CSRF Protection
- Introduction
- How dust-framework protects your application
- Sending the token
- Excluding URIs from protection
- Accepting requests from subdomains
- Testing
Introduction
Cross-site request forgery (CSRF) is an attack in which another website makes a logged-in user's browser send a request to your application. For example, imagine your application has a /user/email route that accepts a POST request to change the user's email address. Without protection, a malicious site could include a form that posts the attacker's own email address to that route, and submit it as soon as the page loads:
<form action="https://your-application.com/user/email" method="POST"> <input type="email" name="email" value="malicious-email@example.com"></form><script> document.forms[0].submit();</script>The user's browser sends their session cookie along with the request. So if the attacker lures one of your users to that page, your application changes the user's email address to the attacker's.
CORS and CSRF protect different things. CORS decides whether JavaScript on another origin may read your responses; CSRF protection decides whether a state-changing request may run at all. A permissive CORS policy doesn't replace CSRF protection, and CSRF protection doesn't stop a script that already has a valid token.
dust-framework protects your application from these requests by default. The web middleware group includes a middleware that checks every request except GET, HEAD, and OPTIONS requests. Since those three methods are never checked, make sure your routes that respond to them don't change any data.
How dust-framework protects your application
The PreventRequestForgery middleware in the web group checks each request in two steps:
- If the browser's
Sec-Fetch-Siteheader says the request comes from your application's own origin, the middleware lets it through. Modern browsers send this header over HTTPS, so this step covers nearly every request from your own pages. - Otherwise, the request must carry the CSRF token stored in the user's session. If the token is missing or doesn't match, the middleware rejects the request with a
419response.
Another site can't read your user's token, so it can't forge a request that carries it. dust-framework also changes the token each time the user logs in or out, and whenever the session ID is regenerated:
| Event | Token |
|---|---|
| The session starts | A token is generated and stored in the session. |
| The user logs in or out | The token is replaced. |
session.regenerate() or session.invalidate() |
The token is replaced. |
session.flush() |
The token is kept, so open forms still submit. |
Because the token changes on login, a page that was open before the user signed in has a stale token. Reloading the page renders the new token.
Sending the token
Most requests from your own pages pass the Sec-Fetch-Site check, so PreventRequestForgery never needs to look at their CSRF token. However, older browsers don't send the Sec-Fetch-Site header, and no browser sends it over plain HTTP, so those requests must carry the token instead. To make sure every request works, send the CSRF token from all of your forms and JavaScript requests.
Forms
An HTML form sends the token in a hidden _token field. You don't need to write the field yourself. In a view, call csrf_field() inside the form, and dust-framework renders the hidden field with the current token:
<form method="POST" action="/profile"> {{ csrf_field() }} <!-- Renders <input type="hidden" name="_token" value="..."> --></form>JavaScript requests
Some clients, such as the browser's built-in fetch, don't read the cookie. For those, send the token in an X-CSRF-TOKEN header instead. First, render the token in a <meta> tag in your layout view with csrf_token():
<meta name="csrf-token" content="{{ csrf_token() }}">Then read the tag each time you send a request, rather than once when the page loads, because the token changes when the user logs in:
fetch("/messages", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content, }, body: JSON.stringify({ body: "Hello!" }),});On every response from a route in the web group, PreventRequestForgery also puts the token in an XSRF-TOKEN cookie. HTTP clients such as Axios read that cookie and send its value back in an X-XSRF-TOKEN header automatically, so a client that already does this needs no <meta> tag.
If a token is missing or stale, the request fails with 419 Page Expired. That usually means the session expired while the page stayed open, so the user needs to reload the form and submit it again.
Excluding URIs from protection
Sometimes you may need to exclude a few URIs from CSRF protection. For example, if you process payments with Stripe and use its webhooks, Stripe's servers post to your application directly, and Stripe has no way of knowing your user's CSRF token. When applicable, verify those requests with the signature the provider sends instead.
A webhook rarely needs the session, so the best place for it is usually src/routes/api.rs, which CSRF protection doesn't cover. If you'd like to keep a webhook in src/routes/web.rs, you may exclude it from PreventRequestForgery instead.
To exclude several URIs at once, such as every webhook route, replace the PreventRequestForgery middleware in src/app.rs with one that lists the URIs to skip. A * matches any part of a URI, so stripe/* excludes /stripe/webhook, /stripe/refunds, and every other URI under /stripe:
use dust::http::middleware::PreventRequestForgery;.with_middleware(|middleware, _| { middleware.replace( PreventRequestForgery::new().except(["stripe/*", "webhooks/*"]), );})To exclude a single route, you may instead call without_middleware on the route's definition in your route file. This keeps the exclusion next to the route it applies to:
use dust::http::middleware::PreventRequestForgery;route .post("/stripe/webhook", webhooks::stripe) .without_middleware::<PreventRequestForgery>();Accepting requests from subdomains
Some applications span several subdomains that post to each other. For example, a page on dashboard.example.com might post a form to example.com. The browser marks that request as coming from the same site rather than the same origin, so PreventRequestForgery checks it for a CSRF token. To let requests from your other subdomains through without a token, replace the middleware in src/app.rs with one that calls allow_same_site:
use dust::http::middleware::PreventRequestForgery;.with_middleware(|middleware, _| { middleware.replace(PreventRequestForgery::new().allow_same_site());})Testing
The test client marks every request as same-origin, so CSRF protection lets test requests through without a token. You don't need to fetch a token or add a _token field to a test form. If you write a test for a route you excluded from protection, the test also passes; to verify the exclusion itself, inspect the middleware configuration or send a request that a browser would mark cross-site.
To learn more about sending requests in tests, check out the testing guide's section on making requests.