dust

Middleware

Introduction

Middleware let you inspect and filter the HTTP requests that enter your application. For example, dust-framework includes a middleware that checks whether the user is logged in. If they aren't, the middleware redirects them to your application's login page. If they are, the middleware lets the request continue on to your handler.

You may write middleware of your own for all kinds of tasks besides authentication. For example, a logging middleware might record every request your application receives, and another might add a header to every response. dust-framework includes several middleware of its own, such as the ones that start the session and protect your forms from cross-site request forgery. Your own middleware usually live in your application's src/http/middleware directory.

Defining middleware

A middleware is an async function marked with #[middleware]. It receives the request and next, which passes the request on to the rest of your application, and it returns the response. You may keep your middleware in src/http/middleware. For example, this middleware only lets a request through when it carries the right API token:

rust
use dust::http::{Next, Request, Response, middleware};#[middleware]pub async fn ensure_token_is_valid(request: Request, next: Next) -> dust::Result<Response> {    if request.header("x-api-token") != Some("my-secret-token") {        dust::abort!(403);    }    Ok(next.run(request).await)}

If the token doesn't match, the middleware stops the request with a 403 error page. Otherwise, next.run(request) passes the request deeper into your application, and the middleware returns the response that comes back. A middleware that never fails may return Response instead of dust::Result<Response>.

[!NOTE] This example only reads a header. dust-framework doesn't read a request's body until something asks for it, so a middleware that needs form or JSON input has to load the body first. To learn more, check out the requests guide's section on input in middleware.

Middleware arguments

A middleware may ask for the same arguments a handler does, such as a service, a configuration section, a route parameter, or the logged-in user. Put these arguments before request. For example, this middleware logs which user made each request:

rust
use dust::auth::Auth;use dust::http::{Next, Request, Response, middleware};#[middleware]pub async fn log_user(    auth: Auth<User>,    request: Request,    next: Next,) -> dust::Result<Response> {    if let Some(user) = auth.user().await? {        tracing::info!(user.id = user.id, path = request.path(), "Handling request");    }    Ok(next.run(request).await)}

Keep in mind that log_user can only find the logged-in user after the session has started, and global middleware run before that happens. So instead of registering a middleware like this globally, attach it to your routes or add it to the web middleware group.

Middleware and responses

Some middleware do their work after the handler, such as adding a header to every response. Code before next.run runs before your handler, and code after it runs once the response is ready. For example, this middleware measures how long the request took, and adds a Server-Timing header to the response:

rust
use std::time::Instant;use dust::http::{Next, Request, Response, middleware};#[middleware]pub async fn add_server_timing(request: Request, next: Next) -> Response {    let started = Instant::now();    let response = next.run(request).await;    response.with_header("server-timing", format!("app;dur={}", started.elapsed().as_millis()))}

Registering middleware

A middleware may run at four scopes. Pick the narrowest one that covers the routes it protects, so unrelated pages don't pay for work they don't need:

Scope Runs for Register it with
Global Every request, including ones that match no route with_middleware in src/app.rs
web or api Every page, or every API route middleware.web(..) or middleware.api(..)
Group The routes in one route group route.middleware(..).group(..)
Route One route route.get(..).middleware(..)

Global middleware run before routing, so they can't read route parameters or the session. A middleware that needs either belongs on a group or a route.

Global middleware

To run a middleware on every HTTP request to your application, such as the add_server_timing middleware above, append it to the global middleware in src/app.rs:

rust
use crate::http::middleware::add_server_timing;Application::configure()    .with_middleware(|middleware, _| {        middleware.append(add_server_timing);    })

append adds the middleware to the end of the global middleware, and prepend adds it to the beginning. The closure's second argument is your application's configuration, so you may add a middleware only in some environments. For example, this adds the timing header only while debug mode is on:

rust
.with_middleware(|middleware, config| {    if config.app.debug {        middleware.append(add_server_timing);    }})

Assigning middleware to routes

Most middleware belong on some routes rather than all of them. To assign middleware to a route or a route group, call middleware in your route file:

rust
use dust::auth::Authenticate;route.get("/profile", profile::show).middleware(Authenticate);route.middleware(Authenticate).group(|route| {    route.get("/settings", settings::show);});

To assign several middleware at once, pass a tuple. dust-framework runs them in the order you list them, so in this example, Authenticate makes sure the user is logged in before RequireVerifiedEmail checks their email address:

rust
use dust::auth::{Authenticate, RequireVerifiedEmail};route.get("/billing", billing::show).middleware((Authenticate, RequireVerifiedEmail));

Middleware groups

When several routes share the same set of middleware, such as billing pages that need a logged-in user with a verified email address, you may bundle the middleware into a MiddlewareGroup. Build the group in a function, then attach it to your routes as you would a single middleware:

rust
use dust::auth::{Authenticate, RequireVerifiedEmail};use dust::http::MiddlewareGroup;pub fn verified() -> MiddlewareGroup {    MiddlewareGroup::new().with(Authenticate).with(RequireVerifiedEmail)}pub fn routes(route: &mut Router) {    route.prefix("/billing").middleware(verified()).group(|route| {        // ...    });}

dust-framework also has two groups of its own. Routes in src/routes/web.rs run within the web group, and routes in src/routes/api.rs run within the api group. To add a middleware to either group, call web or api in src/app.rs. Here, every web page gets the timing header, and every API request must carry a valid token:

rust
.with_middleware(|middleware, _| {    middleware.web(|web| {        web.append(add_server_timing);    });    middleware.api(|api| {        api.prepend(ensure_token_is_valid);    });})

Excluding middleware

Sometimes a route shouldn't run one of its group's middleware. For example, Stripe can't send a CSRF token with its webhook requests, so your webhook route needs to skip the web group's CSRF protection. Call without_middleware with the middleware's type:

rust
use dust::http::middleware::PreventRequestForgery;route    .post("/webhooks/stripe", webhooks::stripe)    .without_middleware::<PreventRequestForgery>();

If several routes need the same exception, such as all of your webhooks, call without_middleware before group instead. The routes in nested groups skip the middleware too:

rust
route.prefix("/webhooks").without_middleware::<PreventRequestForgery>().group(|route| {    route.post("/stripe", webhooks::stripe);    route.post("/github", webhooks::github);});

To exclude a middleware you wrote with #[middleware], name its function, as in without_middleware::<ensure_token_is_valid>().

without_middleware can't exclude a global middleware, because global middleware run before dust-framework knows which route matched. To change a global middleware, replace or remove it.

Ordering

When a request reaches a route, its middleware run in this order:

  1. The global middleware, which run on every request.
  2. The web or api middleware group, depending on whether the route is defined in src/routes/web.rs or src/routes/api.rs.
  3. Any middleware you assigned to a route group that contains the route. When groups are nested, the outer group's middleware run before the inner group's.
  4. Any middleware attached directly to the route's definition, such as route.get(..).middleware(Authenticate).

Within each step, middleware run in the order you added them. On the way out, they see the response in the reverse order.

Global middleware run before dust-framework matches a route, so they also run for requests that match no route. They also run before the web group starts the session, so they can't see the session or the logged-in user. A middleware that needs either one belongs on your routes, or in the web group, where it runs after StartSession.

Middleware parameters

Some middleware need a value from the route that uses them, such as the role a user must have to see a page. Put these parameters after next. For example, say each User has a role, and some routes are only for editors or admins:

rust
use dust::auth::Auth;use dust::http::{Next, Request, Response, middleware};#[derive(Clone, Copy, PartialEq)]pub enum Role {    Editor,    Admin,}#[middleware]pub async fn ensure_role(    auth: Auth<User>,    request: Request,    next: Next,    role: Role,) -> dust::Result<Response> {    let user = auth.user().await?;    dust::abort_unless(user.is_some_and(|user| user.role == role), 403)?;    Ok(next.run(request).await)}

To use ensure_role on a route, call it with the role the route requires, such as ensure_role(Role::Admin). You don't pass auth, request, or next yourself, because dust-framework provides those when the request comes in. In this example, editors may update posts, but only admins may delete them:

rust
route.put("/posts/{post}", posts::update).middleware(ensure_role(Role::Editor));route.delete("/posts/{post}", posts::destroy).middleware(ensure_role(Role::Admin));

dust-framework clones the parameters for each request, so their types must implement Clone.

dust-framework's default middleware

A new dust-framework application comes with several middleware already registered. Some run on every request, such as the ones that trim whitespace from form input and answer cross-origin requests to your API. Others run only for routes in the web group, where they start the session, encrypt your cookies, and protect your forms from cross-site request forgery. You don't need to set any of them up yourself, but it helps to know what each one does. They run in the order listed:

Middleware Where What it does
Trusted proxies Before all others Removes X-Forwarded-* headers unless the request came through a trusted proxy.
SecurityHeaders Global Adds security headers to every response.
TrustHosts Global Rejects requests for hosts your application doesn't serve.
HandleCors Global Answers cross-origin requests to your API.
SpoofMethods Global Lets HTML forms send PUT, PATCH, and DELETE requests.
TrimStrings Global Trims whitespace from string input, except passwords.
ConvertEmptyStringsToNull Global Turns empty string input into null.
EncryptCookies web Encrypts the cookies you set, and decrypts them when they come back.
StartSession web Loads the session before the request and saves it after.
PreventRequestForgery web Rejects cross-site requests that change state, as CSRF protection explains.

Customizing the defaults

Sometimes a default middleware needs a different setting, or isn't needed at all. For example, you may want CSRF protection everywhere except your webhooks, keep a secret field from being trimmed, or keep empty strings as strings. replace swaps in a middleware configured differently, in the original's place, and remove takes one out. Both look through the global middleware and the web and api groups. If the middleware appears in more than one of them, such as in both the web and api groups, it's replaced or removed in each:

rust
use dust::http::middleware::{ConvertEmptyStringsToNull, PreventRequestForgery, TrimStrings};.with_middleware(|middleware, _| {    middleware.replace(PreventRequestForgery::new().except(["webhooks/*"]));    middleware.replace(TrimStrings::except(["secret"]));    middleware.remove::<ConvertEmptyStringsToNull>();})

Your with_middleware closure runs after every package adds its middleware, so you may use replace and remove on a package's middleware too.

Trusting proxies

When your application runs behind a load balancer that terminates TLS, the load balancer describes the original request in X-Forwarded-* headers: the client's IP address, and whether it used HTTPS. Any client can send those headers, so dust-framework ignores them unless the request came through a proxy you trust. Without a trusted proxy, request.ip() is your load balancer's address, and URLs start with http://.

List your load balancer's IP addresses or networks in src/app.rs:

rust
.with_middleware(|middleware, _| {    middleware.trust_proxies(["10.0.0.0/8"]);})

If you don't know your load balancer's address, you may trust every proxy with "*". The client's IP address is then the first one in X-Forwarded-For.

On DUST Cloud, you don't need to configure anything. Unless you list proxies yourself, dust-framework trusts every proxy there.

[!WARNING] Trust "*" only when your load balancer replaces any X-Forwarded-For header the client sent. Otherwise, the first address is whatever the client claims.

Trusting hosts

dust-framework builds absolute URLs, such as password reset links, from the request's host, so a forged Host header could point those links at another site. In production, dust-framework answers only requests for the host in your APP_URL and its subdomains, and other hosts get a 400 Bad Request. In the local and testing environments, it doesn't check hosts.

If your application also serves other hosts, list them. The list replaces the default, so include your APP_URL's host too. *.example.com means every subdomain of example.com, but not example.com itself:

rust
.with_middleware(|middleware, _| {    middleware.trust_hosts(["example.com", "*.example.com", "example.org"]);})

Security headers

dust-framework automatically adds two security headers to every response, including error pages and static files in public/, to protect your users against clickjacking and MIME-type sniffing:

Header What it does
X-Frame-Options: SAMEORIGIN Prevents other sites from embedding your pages in an <iframe>, while still allowing framing from your own origin.
X-Content-Type-Options: nosniff Tells browsers to honor the Content-Type header you send instead of guessing a response's type from its content.

If a response already sets either header, dust-framework keeps the value you provided. If your reverse proxy or CDN already manages security headers for you, you may disable SecurityHeaders globally with middleware.remove::<SecurityHeaders>().

Sometimes a specific page needs to be embedded on other sites, such as a public widget. Because SecurityHeaders is global middleware, an individual route can't skip it with without_middleware. Instead, move SecurityHeaders from the global stack into the web group (and api if you'd like API responses to keep the headers) in src/app.rs:

rust
// src/app.rsuse dust::http::middleware::SecurityHeaders;.with_middleware(|middleware, _| {    middleware        .remove::<SecurityHeaders>()        .web(|web| {            web.prepend(SecurityHeaders);        })        .api(|api| {            api.prepend(SecurityHeaders);        });})

Then exclude SecurityHeaders from the embeddable route in src/routes/web.rs:

rust
// src/routes/web.rsroute.get("/widget", widget::show).without_middleware::<SecurityHeaders>();

Keep in mind that moving SecurityHeaders out of global middleware means static files from public/ and 404 responses for unmatched routes will no longer include these headers.

Limits

Every route limits how large a request's body may be, and how long handling the request may take. The defaults suit most routes, but some may need more room, such as a video upload or a large export. Each limit is a middleware, so you may set it globally, on a group, or on a single route. When you set the same limit in more than one place, dust-framework uses the setting closest to the route.

Body size

A body read into memory, such as JSON or a form, may be up to 2 MB. A multipart form, whose files stream to disk, may be up to 16 MB. A larger body gets a 413 Content Too Large response before the route's middleware and handler run, even when nothing reads it. A form may also have at most 1,000 fields and upload at most 20 files, which you may raise with the SERVER_MAX_INPUT_VARS and SERVER_MAX_FILE_UPLOADS environment variables.

LimitBody sets the limit for bodies read into memory, and LimitUploads sets the limit for multipart forms:

rust
use dust::http::middleware::{LimitBody, LimitUploads};route.post("/videos", videos::store).middleware(LimitUploads::megabytes(500));route.post("/imports", imports::store).middleware(LimitBody::megabytes(10));

Both have bytes(..) for an exact size, and none() to remove the limit, such as for a route that streams its body itself. To change the limits for every route, append them to the global middleware in src/app.rs:

rust
.with_middleware(|middleware, _| {    middleware        .append(LimitBody::megabytes(8))        .append(LimitUploads::megabytes(64));})

Timeouts

Handling a request may take up to 30 seconds. A slower request gets a 503 Service Unavailable response. To give a route more time, set a Timeout:

rust
use dust::http::middleware::Timeout;route.get("/reports/export", reports::export).middleware(Timeout::after(2.minutes()));

Timeout::none() removes the limit, such as for a long poll. The timeout stops once your handler returns, so a streamed response may keep streaming past it.

Rate limiting

Some routes are easy to abuse, such as a contact form that sends you an email or an API endpoint that does expensive work. To protect them, you may limit how many requests each client can make by adding a Throttle middleware to the route. Once a client goes over the limit, dust-framework responds with a 429 Too Many Requests until enough time has passed. For example, this route accepts up to 60 messages a minute from each client:

rust
use dust::http::middleware::Throttle;route.post("/messages", messages::store).middleware(Throttle::per_minute(60));

To learn more, including how to limit each user separately and how to choose a limit for each request, check out the rate limiting documentation.

Cache headers

Some pages look the same to every visitor, such as a pricing page. To let browsers and CDNs cache a route's responses, add CacheHeaders to the route or a group. Its methods are the Cache-Control directives: public, private, no_cache, no_store, must_revalidate, immutable, max_age, and s_maxage. With etag, a browser that already has a response's contents gets a 304 Not Modified without the body:

rust
use dust::http::middleware::CacheHeaders;route    .get("/pricing", pages::pricing)    .middleware(CacheHeaders::new().public().max_age(5.minutes()).etag());

CacheHeaders changes only successful responses to GET and HEAD requests, so error pages are never cached.

[!WARNING] The web group sets cookies, such as the session cookie, on its responses, and shared caches shouldn't keep a response that sets cookies. Use public only on routes outside the web group, such as your API's.

Testing middleware

Middleware runs inside a test request, so test it through the route it protects rather than calling the function yourself. Send a request without the header and assert the rejection, then send one with it and assert the handler ran:

rust
use dust::testing::prelude::*;#[dust::test]async fn a_missing_api_token_is_forbidden(app: Application) {    app.get("/api/reports").await.assert_forbidden();}#[dust::test]async fn a_valid_api_token_reaches_the_handler(app: Application) {    app.get("/api/reports")        .header("x-api-token", "my-secret-token")        .await        .assert_ok();}

A middleware that adds a header can be checked on any response with assert_header. When the header's value varies, such as a Server-Timing duration, read it with header(..) and assert on the part that is stable instead of the exact value.

When the middleware needs the logged-in user, use acting_as so the session and the resolved user are in place before it runs. To learn more about the available assertions, check out the testing guide's section on available assertions.

Tower layers

dust-framework is built on Axum, so any Tower layer may be a middleware. Add the layer's crate to your Cargo.toml, such as tower-http with its compression-gzip feature, and wrap the layer with layer:

rust
use dust::http::layer;use tower_http::compression::CompressionLayer;.with_middleware(|middleware, _| {    middleware.append(layer(CompressionLayer::new()));})

To remove a layer you added this way, name the layer's type, as in middleware.remove::<CompressionLayer>().