Angel3 Security
Angel3 middleware designed to enhance application security by patching common Web security holes.
Installation
In your pubspec.yaml:
dependencies:
angel3_security: ^10.0.0
Usage
CSRF protection
CsrfFilter refuses cross-site requests that change state (all but GET, HEAD, OPTIONS and TRACE) with a 403. Such a request must:
- come from an allowed origin:
Sec-Fetch-Site: same-origin, or else anOrigin(orReferer) inallowedOrigins; - send back the token, which is the value of the
XSRF-TOKENcookie, in theX-XSRF-TOKENheader (as axios and Angular do) or the_csrfform field.
The cookie is signed with a CookieSigner and bound to the session, so another site can neither forge it nor read it. A form shown before its session expired is refused; the next page gets a new token.
var signer = CookieSigner.fromStringKey(keyFromConfiguration);
var csrf = CsrfFilter(signer, allowedOrigins: {'https://example.com'});
app.fallback(csrf.handleRequest);
app.get('/form', (req, res) {
// The token of the request, for a hidden `_csrf` field.
var token = req.container!.make<CsrfToken>().value;
// ...
});
Requests that do not use cookies to authenticate, such as those with a bearer token, can be exempted with skip. See example/csrf.dart.
Rate limiting
InMemoryRateLimiter limits each user, here by IP address, to a number of requests in a window, and answers the others with a 429 Too Many Requests. See example/rate_limit_redis.dart for a limiter whose windows several instances share.
var rateLimiter = InMemoryRateLimiter(
5,
const Duration(seconds: 30),
(req, res) => req.ip,
);
app.fallback(rateLimiter.handleRequest);
Migrating from 9.x to 10.0.0
The breaking changes of each release are listed in the CHANGELOG. Those of 10.0.0 that may need changes in an app:
RateLimiter.handleRequestreturns whatrejectRequestreturns, as documented, where it always returnedfalse. The defaultrejectRequeststill throws a429; arejectRequestof your own that returnstruelets the request go on.