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:
| Request | Answer |
|---|---|
GET /theme, no cookie | theme set, set-cookie: theme=dark; HttpOnly; SameSite=Lax; Path=/ |
GET /theme, with the cookie | theme is dark, no set-cookie |
GET /signed, no cookie | uid set, set-cookie: uid=W4EGU6bLZUVa+AZSiakmHqOC9ShL3wgVR38Gdf0mAhA=42 |
GET /signed, with that cookie | uid 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,adoptand handing a value to a handler asHost<T>. - Built-in extractors:
Host,Headerand the typedheaderscrate extractors. - Secrets: where a signing key comes from.