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

Cookies with tower-cookies

Read, set and sign cookies from a handler with the tower-cookies layer and a Host<Cookies> extractor.

A handler reads and writes cookies through a Cookies handle that CookieManagerLayer places in the request's extensions. The layer collects the changes and writes the set-cookie headers when the handler returns.

The recipe builds on examples/17-http-pre-dispatch. It compiled and ran on port 0 against tower-cookies 0.11.0 with the signed feature.

tower-cookies = { version = "0.11", features = ["signed"] }

The code

use tower_cookies::{Cookie, CookieManagerLayer, Cookies, Key};
use ulo::{App, AppBuilder, Dep, Module, ModuleDef, ModuleIdentity, controller, handlers, module};
use ulo_http::{Host, PreDispatch};

pub struct CookieModule;

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

    fn register(&self, m: &mut ModuleDef<'_>) {
        m.value(Key::generate());
        m.export::<Key>();
        m.meta::<PreDispatch>().layer(CookieManagerLayer::new()).adopt::<Cookies>();
    }
}

#[controller]
pub struct PrefsController {
    key: Dep<Key>,
}

#[handlers]
impl PrefsController {
    #[ulo_http::get("/theme")]
    fn theme(&self, Host(cookies): Host<Cookies>) -> String {
        match cookies.get("theme") {
            Some(cookie) => format!("theme is {}", cookie.value()),
            None => {
                let mut cookie = Cookie::new("theme", "dark");
                cookie.set_path("/");
                cookie.set_http_only(true);
                cookie.set_same_site(tower_cookies::cookie::SameSite::Lax);
                cookies.add(cookie);
                "theme set".to_owned()
            }
        }
    }

    #[ulo_http::get("/signed")]
    fn signed(&self, Host(cookies): Host<Cookies>) -> String {
        let jar = cookies.signed(&self.key);
        match jar.get("uid") {
            Some(cookie) => format!("uid {}", cookie.value()),
            None => {
                jar.add(Cookie::new("uid", "42"));
                "uid set".to_owned()
            }
        }
    }
}

#[module(imports = [CookieModule], controllers = [PrefsController])]
pub struct AppModule;

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

What each seam does

CookieManagerLayer::new() parses the cookie request header and, after the inner service answers, writes every added or removed cookie as set-cookie. Cookies is Clone + Send + Sync, which .adopt::<Cookies>() requires. Adopting makes it available as Ext<Cookies> to guards and execution-scoped services. A handler takes it as Host<Cookies>, the extractor for a value a layer put in the request.

The signing Key is a singleton the module registers with m.value(..) and exports. PrefsController injects it as Dep<Key>, and cookies.signed(&key) returns a jar whose add signs and whose get verifies.

Observed with curl -c jar -b jar:

RequestAnswer
GET /theme, no cookietheme set, set-cookie: theme=dark; HttpOnly; SameSite=Lax; Path=/
GET /theme, with the cookietheme is dark, no set-cookie
GET /signed, no cookieuid set, set-cookie: uid=W4EGU6bLZUVa+AZSiakmHqOC9ShL3wgVR38Gdf0mAhA=42
GET /signed, with that cookieuid 42
GET /signed, Cookie: uid=99 (unsigned)uid set: the forged value does not verify, so it reads as absent

Failure modes

Key::generate() changes on every start. Cookies signed before a restart no longer verify and read as absent. Build the key from a configured secret with Key::from(&bytes) and register that. Key::from panics on fewer than 64 bytes (read in the cookie source, not run). See secrets.

A cookie without Path is scoped to the request's directory. The signed cookie above carries no Path, so browsers send it back only to paths under /. For a request to /signed that is /, but a handler at /a/b/c would scope it to /a/b. Set Path=/, as /theme does.

Host<Cookies> without the layer is a 500. Host<T> answers HostMissing when nothing put a T in the request's extensions, which renders 500 with the message withheld (read in the Host documentation, not run).

Set the attributes explicitly. Cookie::new sets none of HttpOnly, Secure or SameSite. The /theme handler sets HttpOnly and SameSite=Lax, and the cookie it produced carried exactly those and Path=/.

Reference

  • Middleware: layer, adopt and handing a value to a handler as Host<T>.
  • Built-in extractors: Host, Header and the typed headers crate extractors.
  • Secrets: where a signing key comes from.

Sessions with tower-sessions

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

Request IDs

Give every request an x-request-id and echo it on the response with the tower-http SetRequestIdLayer and PropagateRequestIdLayer.

On this page

The codeWhat each seam doesFailure modesReference