ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

Integrations

RecipesServe static filesCompress responsesSecurity headers and CSRFSessions with tower-sessionsCookies with tower-cookiesRequest IDsAccess logError reporting with SentryLocalised responses with FluentA client as a providerA MongoDB ODM over the injected clientExplicit transactions with SQLxA mailer over lettreObject storage over the AWS SDKA CLI command with clapMocks with mockallFeature flags with OpenFeatureAuthorization with CedarMoving from axum or actix-web

Operating

Reference

Recipes

Security headers and CSRF

A helmet-style header set from SetResponseHeaderLayer, and a Fetch Metadata and Origin check as a pre-dispatch middleware.

Every response carries a fixed set of browser-hardening headers, and a state-changing request a browser marks as cross-site is refused before routing. The headers are SetResponseHeaderLayer entries and the CSRF check is a small hand-written Middleware, both declared in one PreDispatch.

The recipe builds on examples/17-http-pre-dispatch, whose apply_value(TagTenant) has the same shape as FetchMetadata. It compiled and ran on port 0 against tower-http 0.7.1 (feature set-header).

tower-http = { version = "0.7", features = ["set-header"] }

The code

use tower_http::set_header::SetResponseHeaderLayer;
use ulo::{App, AppBuilder, BoxError, Module, ModuleDef, ModuleIdentity, controller, handlers, module};
use ulo_http::middleware::Next;
use ulo_http::{CallError, ErrorKind, HeaderValue, Method, Middleware, PreDispatch, Request, Response};

const HEADERS: [(&str, &str); 9] = [
    ("content-security-policy", "default-src 'self'; frame-ancestors 'self'; object-src 'none'"),
    ("cross-origin-opener-policy", "same-origin"),
    ("cross-origin-resource-policy", "same-origin"),
    ("referrer-policy", "no-referrer"),
    ("strict-transport-security", "max-age=15552000; includeSubDomains"),
    ("x-content-type-options", "nosniff"),
    ("x-dns-prefetch-control", "off"),
    ("x-frame-options", "SAMEORIGIN"),
    ("origin-agent-cluster", "?1"),
];

/// Refuses a state-changing request a browser marks as cross-site.
pub struct FetchMetadata;

impl Middleware for FetchMetadata {
    async fn handle(&self, req: Request, next: Next<'_>) -> Result<Response, BoxError> {
        if matches!(*req.method(), Method::GET | Method::HEAD | Method::OPTIONS) {
            return next.run(req).await;
        }
        let headers = req.headers();
        let header = |name: &str| headers.get(name).and_then(|value| value.to_str().ok());
        let same_site = match (header("sec-fetch-site"), header("origin")) {
            (Some(site), _) => matches!(site, "same-origin" | "none"),
            (None, Some(origin)) => {
                let authority = origin.split_once("://").map_or(origin, |(_, rest)| rest);
                header("host") == Some(authority)
            }
            // Neither header: not a browser, so not a cross-site form post.
            (None, None) => true,
        };
        if !same_site {
            return Err(CallError::new(ErrorKind::Forbidden, "cross-site request refused").into());
        }
        next.run(req).await
    }
}

pub struct SecurityModule;

impl Module for SecurityModule {
    fn identity(&self) -> ModuleIdentity {
        ModuleIdentity::of_type::<Self>()
    }

    fn register(&self, m: &mut ModuleDef<'_>) {
        let stage = m.meta::<PreDispatch>();
        for (name, value) in HEADERS {
            stage.layer(SetResponseHeaderLayer::if_not_present(
                ulo_http::http::HeaderName::from_static(name),
                HeaderValue::from_static(value),
            ));
        }
        stage.apply_value(FetchMetadata);
    }
}

#[controller]
pub struct TransfersController;

#[handlers]
impl TransfersController {
    #[ulo_http::get("/")]
    fn index(&self) -> &'static str {
        "form"
    }

    #[ulo_http::post("/transfer")]
    fn transfer(&self) -> &'static str {
        "moved"
    }
}

#[module(imports = [SecurityModule], controllers = [TransfersController])]
pub struct AppModule;

pub fn builder() -> AppBuilder {
    App::builder(AppModule)
}

What each seam does

SetResponseHeaderLayer::if_not_present(name, value) adds one header when the response has none of that name, so a handler that sets its own content-security-policy keeps it (read in the tower-http source, not run). The loop declares one layer for each pair in HEADERS. overriding and appending are the other two modes.

FetchMetadata decides from request headers a browser sets and a page's script cannot change:

  • GET, HEAD and OPTIONS pass.
  • sec-fetch-site: same-origin or none passes and any other value (same-site, cross-site) is refused.
  • Without sec-fetch-site, an Origin header must name the request's Host. Origin: null is refused.
  • With neither header the caller is not a browser, so the request passes.

The refusal is CallError::new(ErrorKind::Forbidden, ..) returned as the middleware's Err. The application's error handlers shape it. When no handler claims it, the refusal renders as a 403 problem document.

Observed with curl against GET /, GET /nowhere and a POST /transfer handler:

RequestAnswer
GET /200 with all nine headers below
GET /nowhere404 with the same nine headers
POST /transfer, no browser headers200 moved
POST /transfer, Sec-Fetch-Site: same-origin200 moved
POST /transfer, Sec-Fetch-Site: cross-site403, cross-site request refused, with the nine headers
POST /transfer, Origin: https://evil.example, Host: bank.example403
POST /transfer, Origin: https://bank.example, Host: bank.example200 moved
POST /transfer, Origin: null403
content-security-policy: default-src 'self'; frame-ancestors 'self'; object-src 'none'
cross-origin-opener-policy: same-origin
cross-origin-resource-policy: same-origin
referrer-policy: no-referrer
strict-transport-security: max-age=15552000; includeSubDomains
x-content-type-options: nosniff
x-dns-prefetch-control: off
x-frame-options: SAMEORIGIN
origin-agent-cluster: ?1

Because the header layers are declared before the middleware, they wrap it, and the 403 carries them as well. A layer declared after FetchMetadata would not decorate its refusal.

Failure modes

The Origin comparison is by authority. The page compares the scheme-less Origin to Host, port included. Behind a proxy that rewrites Host, compare against a configured public host instead.

strict-transport-security over plain HTTP. Browsers ignore the header on an http response. Send it from the deployment that terminates TLS, or keep it here and rely on the browser's rule.

The content security policy is a starting point. default-src 'self' blocks inline scripts and third-party assets. Loosen it per route by setting content-security-policy in the handler, which if_not_present leaves alone (read in the tower-http documentation, not run).

Fetch Metadata is one defence. A browser old enough to send neither header is treated as a non-browser and passes. A site that must cover such browsers needs a token the form carries.

Reference

  • Middleware: the Middleware trait, apply_value, and scoping a check to a path pattern with apply_for.
  • CORS: the shipped Cors middleware, which answers preflights.
  • Error handling: how a middleware's Err becomes a response.

Compress responses

Gzip response bodies for every route with the tower-http CompressionLayer in the pre-dispatch stage.

Sessions with tower-sessions

Server-side sessions from tower-sessions, read in a handler as Ext<Session> through an adopt entry.

On this page

The codeWhat each seam doesFailure modesReference