From 371139cde3540bccabb9e86958bf227676617c56 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Thu, 19 Nov 2026 19:27:36 -0500 Subject: [PATCH] fix(csrf): require Origin to match Host without an allow-list and default to SameSite=Lax Without allowed_origins, the cross-site check let a same-site request from a sibling subdomain through, and passed a request without fetch metadata whatever Origin it carried. Now, with no allow-list, a same-site request or one without Sec-Fetch-Site that carries an Origin needs that Origin's host[:port] to equal the request's Host header (or the HTTP/2 authority), a default port aside. A Sec-Fetch-Site value the check does not know is treated as cross-site. Refusals keep answering 403 cross_site_request_blocked. Cookies now default to SameSite=Lax instead of None. The reference app pins SameSite=None, which the conformance contract expects. Closes #42 BREAKING CHANGE: auth cookies default to SameSite=Lax (was None when Secure). A frontend on another site that calls the adapter with credentials must set same_site(SameSite::None). Without allowed_origins, an unsafe request whose Origin does not name the request's own Host is refused with 403 cross_site_request_blocked; behind a proxy that rewrites Host, or for a frontend on another origin, set allowed_origins. --- README.md | 17 +++--- conformance/refapp/main.rs | 6 ++- src/adapter.rs | 3 +- src/guard.rs | 3 +- src/options.rs | 15 +++--- src/origin.rs | 67 ++++++++++++++++++----- src/tests/adapter.rs | 106 +++++++++++++++++++++++++++++++++++-- src/tests/guard.rs | 4 +- src/tests/origin.rs | 39 +++++++++++++- 9 files changed, 221 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index 2405643..41ac296 100644 --- a/README.md +++ b/README.md @@ -92,12 +92,15 @@ applies whatever the cookies' `SameSite` setting (a sibling subdomain is same-si - A `null` `Origin` (in any case) is refused first, whatever `Sec-Fetch-Site` and `allowed_origins` say. -- `Sec-Fetch-Site: cross-site` is refused, and `same-origin` (or `none`) passes. -- `Sec-Fetch-Site: same-site` also covers a sibling subdomain, so when `allowed_origins` is set - the `Origin` must be on it, and a request with no `Origin` is refused. Without - `allowed_origins` it passes. +- `Sec-Fetch-Site: same-origin` (or `none`) passes. `cross-site`, and any value this check does + not know, is refused. +- `Sec-Fetch-Site: same-site` also covers a sibling subdomain, so the `Origin` must be trusted, and + a request with no `Origin` is refused. - With no `Sec-Fetch-Site` (an older browser or a server), a request with no `Origin` passes, and - when `allowed_origins` is set the `Origin` must be on it. + one with an `Origin` needs it trusted. +- A trusted `Origin` is one on `allowed_origins` when that is set. Without it, only the request's + own host is trusted: the `Origin`'s `host[:port]` must equal the `Host` header (or the HTTP/2 + authority), a default port aside. Behind a proxy that rewrites `Host`, set `allowed_origins`. - An empty `allowed_origins` is still set: it allows no cross-origin caller. A bearer token is never attached by a browser, so it is not checked. @@ -275,8 +278,8 @@ API cannot be reached. | `jwks_kid` | `dev-main` | `kid` header on service tokens | | `cookie_domain` | none | Cookie `Domain` | | `insecure_cookies` | `false` | Drops `Secure`, for local development over HTTP, and allows example secrets | -| `same_site` | `None`, or `Lax` with `insecure_cookies` | Cookie `SameSite` | -| `allowed_origins` | none | The only cross-origin (including same-site) callers allowed to change state; an empty list allows none | +| `same_site` | `Lax` | Cookie `SameSite`; a frontend on another site needs `None` | +| `allowed_origins` | none (only the request's own `Host`) | The only cross-origin (including same-site) callers allowed to change state; an empty list allows none | | `session_cookie_names` | `seamless-access`, `seamless-refresh` | Session cookie names | | `flow_cookie_names` | `seamless-ephemeral` | Sign-in flow cookie names | | `deliver` | none | Sends OTP codes and magic links through your own transports | diff --git a/conformance/refapp/main.rs b/conformance/refapp/main.rs index f3df2b4..fe33ffc 100644 --- a/conformance/refapp/main.rs +++ b/conformance/refapp/main.rs @@ -10,7 +10,9 @@ use std::sync::{Arc, Mutex}; use axum::extract::Path; use axum::routing::get; use axum::{Json, Router}; -use seamless_auth::{Adapter, Delivery, PermissionRule, StepUp, TokenUser, User, Verifier}; +use seamless_auth::{ + Adapter, Delivery, PermissionRule, SameSite, StepUp, TokenUser, User, Verifier, +}; use serde_json::{Value, json}; type Captured = Arc>>; @@ -25,6 +27,8 @@ async fn main() { .cookie_secret(env("COOKIE_SIGNING_KEY")) .service_secret(env("SEAMLESS_SERVICE_TOKEN")) .jwks_kid(env("JWKS_KID")) + // The conformance contract pins SameSite=None, which is no longer the default. + .same_site(SameSite::None) .deliver(move |d: Delivery| { let sink = sink.clone(); async move { diff --git a/src/adapter.rs b/src/adapter.rs index 17ff24d..3b04189 100644 --- a/src/adapter.rs +++ b/src/adapter.rs @@ -188,7 +188,8 @@ impl Inner { async fn serve(self: Arc, req: Request) -> Response { let (parts, body) = req.into_parts(); - if let Some(blocked) = check_origin(&self.config, &parts.method, &parts.headers) { + if let Some(blocked) = check_origin(&self.config, &parts.method, &parts.uri, &parts.headers) + { return self.write(blocked, false); } diff --git a/src/guard.rs b/src/guard.rs index 2311e7d..779fe13 100644 --- a/src/guard.rs +++ b/src/guard.rs @@ -542,7 +542,8 @@ where // A cookie session gets the same cross-site check as the auth // routes, or a form on another site could act as the user. Ok((_, true)) - if check_origin(&adapter.config, req.method(), req.headers()).is_some() => + if check_origin(&adapter.config, req.method(), req.uri(), req.headers()) + .is_some() => { json_response( StatusCode::FORBIDDEN, diff --git a/src/options.rs b/src/options.rs index 8320e64..7e6c79b 100644 --- a/src/options.rs +++ b/src/options.rs @@ -212,17 +212,18 @@ impl Builder { self } - /// The cookie `SameSite` attribute. Defaults to `None`, or `Lax` with - /// [`insecure_cookies`](Self::insecure_cookies). + /// The cookie `SameSite` attribute. Defaults to `Lax`. A frontend on another + /// site that calls the adapter with credentials needs `None`. pub fn same_site(mut self, same_site: SameSite) -> Self { self.same_site = Some(same_site); self } - /// The only cross-origin callers allowed to change state. With it set, a + /// The only cross-origin callers allowed to change state. A /// `Sec-Fetch-Site: same-site` request (which includes a sibling subdomain), /// or a request without fetch metadata that carries an `Origin`, needs that - /// `Origin` on the list. An empty list allows no cross-origin caller. + /// `Origin` on the list. Without the list that `Origin` must name the request's + /// own `Host`. An empty list allows no cross-origin caller. pub fn allowed_origins(mut self, origins: I) -> Self where I: IntoIterator, @@ -385,11 +386,7 @@ impl Builder { ); "dev-main".to_string() }); - let same_site = self.same_site.unwrap_or(if self.insecure_cookies { - SameSite::Lax - } else { - SameSite::None - }); + let same_site = self.same_site.unwrap_or(SameSite::Lax); let http_client = match self.http_client { Some(client) => client, diff --git a/src/origin.rs b/src/origin.rs index 87b3d03..ca0b19d 100644 --- a/src/origin.rs +++ b/src/origin.rs @@ -1,11 +1,16 @@ -use axum::http::{HeaderMap, Method, StatusCode}; +use axum::http::{HeaderMap, Method, StatusCode, Uri}; use crate::adapter::Reply; use crate::options::Config; /// Blocks cross-site state changes whatever the cookies' `SameSite` setting: a /// sibling subdomain is same-site, so `Lax` and `Strict` cookies still reach it. -pub(crate) fn check_origin(config: &Config, method: &Method, headers: &HeaderMap) -> Option { +pub(crate) fn check_origin( + config: &Config, + method: &Method, + uri: &Uri, + headers: &HeaderMap, +) -> Option { if matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS) { return None; } @@ -26,32 +31,33 @@ pub(crate) fn check_origin(config: &Config, method: &Method, headers: &HeaderMap return blocked(); } + let trusted = |origin: &[u8]| match &config.allowed_origins { + Some(allowed) => is_allowed(allowed, origin), + None => is_own_host(origin, uri, headers), + }; + if let Some(site) = headers.get("sec-fetch-site") { let site = site.as_bytes(); - if site.eq_ignore_ascii_case(b"cross-site") { - return blocked(); + if site.eq_ignore_ascii_case(b"same-origin") || site.eq_ignore_ascii_case(b"none") { + return None; } + // Anything else, a value this check does not know included, is treated + // as cross-site unless it is same-site from a trusted Origin. if !site.eq_ignore_ascii_case(b"same-site") { - return None; + return blocked(); } - let Some(allowed) = &config.allowed_origins else { - return None; - }; return match headers.get("origin") { - Some(origin) if is_allowed(allowed, origin.as_bytes()) => None, + Some(origin) if trusted(origin.as_bytes()) => None, _ => blocked(), }; } let origin = headers.get("origin")?; // An Origin a browser would never send is not one to trust. - if origin.to_str().is_err() { + if origin.to_str().is_err() || !trusted(origin.as_bytes()) { return blocked(); } - match &config.allowed_origins { - Some(allowed) if !is_allowed(allowed, origin.as_bytes()) => blocked(), - _ => None, - } + None } /// Whether an Origin is on the allowlist. An Origin, or an allowlist entry, that @@ -67,6 +73,39 @@ fn is_allowed(allowed: &[String], origin: &[u8]) -> bool { .any(|allowed| allowed == origin) } +/// Whether the Origin names the host this request was sent to: the `Host` +/// header, or the URI authority an HTTP/2 request carries instead. A default +/// port written on either side does not count against a match. +fn is_own_host(origin: &[u8], uri: &Uri, headers: &HeaderMap) -> bool { + let Some(origin) = std::str::from_utf8(origin).ok().and_then(normalize_origin) else { + return false; + }; + let Some(host) = headers + .get("host") + .and_then(|host| host.to_str().ok()) + .or_else(|| uri.authority().map(|authority| authority.as_str())) + else { + return false; + }; + let host = host.trim().to_ascii_lowercase(); + if host.is_empty() || host.contains(['@', '/', '?', '#']) { + return false; + } + let (scheme, authority) = origin.split_once("://").unwrap_or_default(); + let default_port = match scheme { + "https" => ":443", + "http" => ":80", + _ => "", + }; + let strip = |authority: &str| { + authority + .strip_suffix(default_port) + .unwrap_or(authority) + .to_string() + }; + strip(authority) == strip(&host) +} + /// `scheme://host[:port]`, lowercased, or `None` for anything that is not one. fn normalize_origin(origin: &str) -> Option { let origin = origin.trim(); diff --git a/src/tests/adapter.rs b/src/tests/adapter.rs index 8b97238..f69b4fe 100644 --- a/src/tests/adapter.rs +++ b/src/tests/adapter.rs @@ -53,7 +53,7 @@ async fn login_stores_the_pre_auth_token_and_picks_the_body() { let cookie = &r.cookies["seamless-ephemeral"]; assert_eq!(attribute(cookie, "Max-Age"), Some("300")); assert_eq!(attribute(cookie, "Path"), Some("/")); - assert_eq!(attribute(cookie, "SameSite"), Some("None")); + assert_eq!(attribute(cookie, "SameSite"), Some("Lax")); assert!( flag(cookie, "HttpOnly") && flag(cookie, "Secure"), "{cookie}" @@ -685,7 +685,7 @@ async fn the_origin_guard_follows_sec_fetch_site() { &'a [(&'a str, &'a str)], bool, ); - let cases: [Case; 17] = [ + let cases: [Case; 27] = [ ( "cross-site", &open, @@ -708,12 +708,112 @@ async fn the_origin_guard_follows_sec_fetch_site() { false, ), ( - "same-site without an allowlist", + "same-site without an allowlist or Origin", &open, "POST", &[("sec-fetch-site", "same-site")], + true, + ), + ( + "same-site without an allowlist, from a sibling", + &open, + "POST", + &[ + ("sec-fetch-site", "same-site"), + ("host", "auth.example.com"), + ("origin", "https://app.example.com"), + ], + true, + ), + ( + "same-site without an allowlist, from the Host", + &open, + "POST", + &[ + ("sec-fetch-site", "same-site"), + ("host", "auth.example.com"), + ("origin", "https://AUTH.example.com"), + ], false, ), + ( + "an unknown Sec-Fetch-Site", + &open, + "POST", + &[ + ("sec-fetch-site", "same-planet"), + ("host", "auth.example.com"), + ("origin", "https://auth.example.com"), + ], + true, + ), + ( + "no Sec-Fetch-Site, an Origin and no allowlist", + &open, + "POST", + &[ + ("host", "auth.example.com"), + ("origin", "https://evil.example"), + ], + true, + ), + ( + "no Sec-Fetch-Site, an Origin and no Host", + &open, + "POST", + &[("origin", "https://auth.example.com")], + true, + ), + ( + "no Sec-Fetch-Site, the Host's Origin", + &open, + "POST", + &[ + ("host", "auth.example.com"), + ("origin", "https://auth.example.com"), + ], + false, + ), + ( + "no Sec-Fetch-Site, the Host's Origin with the default port", + &open, + "POST", + &[ + ("host", "auth.example.com:443"), + ("origin", "https://auth.example.com"), + ], + false, + ), + ( + "no Sec-Fetch-Site, the Host on another port", + &open, + "POST", + &[ + ("host", "auth.example.com:8443"), + ("origin", "https://auth.example.com"), + ], + true, + ), + ( + "no Sec-Fetch-Site, a scheme's default port on another scheme", + &open, + "POST", + &[ + ("host", "auth.example.com:80"), + ("origin", "https://auth.example.com"), + ], + true, + ), + ( + "no Sec-Fetch-Site, a Host with userinfo", + &open, + "POST", + &[ + ("host", "evil@auth.example.com"), + ("origin", "https://auth.example.com"), + ], + true, + ), ("none", &open, "POST", &[("sec-fetch-site", "none")], false), ("server to server", &open, "POST", &[], false), ("null Origin", &open, "POST", &[("origin", "null")], true), diff --git a/src/tests/guard.rs b/src/tests/guard.rs index 2fc7519..b8165d2 100644 --- a/src/tests/guard.rs +++ b/src/tests/guard.rs @@ -497,13 +497,15 @@ async fn a_cookie_session_from_a_sibling_subdomain_needs_an_allowlisted_origin() ); assert_eq!(post(&listed, None).await.status, 403); + // Without an allowlist only the request's own Host counts as a trusted Origin. let unlisted = api.adapter(|b| b); assert_eq!( post(&unlisted, Some("https://evil.example.com")) .await .status, - 200 + 403 ); + assert_eq!(post(&unlisted, None).await.status, 403); } fn bearer(token: &str) -> String { diff --git a/src/tests/origin.rs b/src/tests/origin.rs index 6c0b9c9..474f421 100644 --- a/src/tests/origin.rs +++ b/src/tests/origin.rs @@ -32,11 +32,13 @@ async fn a_same_site_form_post_under_lax_cookies_is_refused() { let r = form_post() .header("sec-fetch-site", "same-site") + .header("host", "auth.example.com") .header("origin", "https://evil.example.com") .to(&adapter) .await; - assert_eq!(r.status, 415, "{}", r.text); + assert_eq!(r.status, 403, "{}", r.text); + assert_eq!(r.body, json!({ "error": "cross_site_request_blocked" })); assert!(api.calls_to("POST", "/recovery-codes").is_empty()); } @@ -46,14 +48,47 @@ async fn a_form_post_without_fetch_metadata_is_refused() { let adapter = api.adapter(|b| b.same_site(SameSite::Lax)); let r = form_post() + .header("host", "auth.example.com") .header("origin", "https://evil.example") .to(&adapter) .await; - assert_eq!(r.status, 415, "{}", r.text); + assert_eq!(r.status, 403, "{}", r.text); + assert_eq!(r.body, json!({ "error": "cross_site_request_blocked" })); assert!(api.calls_to("POST", "/recovery-codes").is_empty()); } +#[tokio::test] +async fn without_an_allowlist_an_origin_must_match_the_host() { + let api = started().await; + let adapter = api.adapter(|b| b); + + // A form on the same host still meets the content-type gate. + let r = form_post() + .header("host", "auth.example.com") + .header("origin", "https://auth.example.com") + .to(&adapter) + .await; + assert_eq!(r.status, 415, "{}", r.text); + + let r = form_post() + .header("host", "auth.example.com") + .header("origin", "https://auth.example.com") + .header("content-type", "application/json") + .to(&adapter) + .await; + assert_eq!(r.status, 200, "{}", r.text); + + // An HTTP/2 request names its host in the URI authority, not a Host header. + let r = call("POST", "https://auth.example.com/recovery-codes") + .cookie(&access()) + .header("origin", "https://auth.example.com") + .header("content-type", "application/json") + .to(&adapter) + .await; + assert_eq!(r.status, 200, "authority: {}", r.text); +} + #[tokio::test] async fn the_origin_check_runs_whatever_the_same_site_setting() { let api = started().await;