From 6faa81644b1f37bc4379fb688866ed8f40ccb5f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 18 Jul 2026 20:56:41 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20fix(cors):=20never=20send=20cred?= =?UTF-8?q?entials=20in=20mirror=20mode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Unset CORS_ALLOWED_ORIGINS reflected any origin AND advertised allow-credentials — a credential-theft hole held shut only by the cookie's SameSite=Lax, two independent switches guarding one door. Mirror mode (dev) now runs uncredentialed; the allowlist branch keeps credentials. cors_layer takes the allowlist as a parameter (env read once in build_router) so tests drive both modes without env races. Boot warns when COOKIE_SECURE is on without an allowlist. Cookie-using browser frontends must list their origin in CORS_ALLOWED_ORIGINS — including cross-port localhost dev setups. --- .env.example | 7 +++--- README.md | 16 +++++++----- src/lib.rs | 57 ++++++++++++++++++++++++++++------------- src/web/auth.rs | 3 +++ tests/integration.rs | 60 +++++++++++++++++++++++++++++++++++++++----- 5 files changed, 111 insertions(+), 32 deletions(-) diff --git a/.env.example b/.env.example index 9662ad1..aa22142 100644 --- a/.env.example +++ b/.env.example @@ -18,9 +18,10 @@ RUST_LOG=info,hezarfen_backend=debug # over HTTPS. Enable in production behind TLS; leave unset for plain-HTTP dev. # COOKIE_SECURE=true -# Comma-separated CORS allowlist for browser clients on other origins. Leave -# unset to reflect the request's Origin (dev-friendly). Credentials (the session -# cookie) are always allowed, so a wildcard `*` is never used. +# Comma-separated CORS allowlist for browser clients on other origins; listed +# origins may send credentials (the session cookie). Leave unset to reflect the +# request's Origin (dev-friendly) — but without credentials, so a cookie-using +# browser frontend must be listed here explicitly. # CORS_ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com # Per-IP rate limits (requests per minute). AUTH covers /auth/login and diff --git a/README.md b/README.md index 9f8b092..52f4c4f 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,9 @@ embedded there is only one service; its data lives in the named volume files (`/data/files`) together, so that one volume persists everything. `HOST` is forced to `0.0.0.0` inside the container so the published port works. Production knobs (`COOKIE_SECURE`, `CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in -`compose.yaml` — uncomment as needed. Works with `docker compose` too. +`compose.yaml` — uncomment as needed. Leaving `CORS_ALLOWED_ORIGINS` unset +means dev mirror mode without credentials; a cookie-using browser frontend +must be allowlisted explicitly. Works with `docker compose` too. Without compose: @@ -153,11 +155,13 @@ directly — the header is client-forged in that case. ## CORS Cookie-authenticated APIs can't use a wildcard `Access-Control-Allow-Origin` -(browsers refuse it on credentialed requests), so the server always advertises -`Access-Control-Allow-Credentials: true` and, by default, reflects the -request's `Origin` — dev-friendly, effectively open. In production set -`CORS_ALLOWED_ORIGINS` to a comma-separated allowlist to restrict which -browser origins may call the API. +(browsers refuse it on credentialed requests), so origins listed in the +comma-separated `CORS_ALLOWED_ORIGINS` allowlist are echoed back with +`Access-Control-Allow-Credentials: true`. When the allowlist is unset the +server reflects the request's `Origin` — dev-friendly — but **without** +credentials: mirroring with credentials would let any website ride a +visitor's session cookie. A browser frontend that needs the session cookie +cross-origin must therefore be allowlisted explicitly. ## Roles & access control diff --git a/src/lib.rs b/src/lib.rs index ccda239..0855471 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -101,6 +101,13 @@ pub fn build_router(state: AppState) -> Router { state.rate_limit.trust_proxy, ); + let cors_allowlist = cors_allowlist_from_env(); + if state.cookie_secure && cors_allowlist.is_empty() { + tracing::warn!( + "COOKIE_SECURE is on but CORS_ALLOWED_ORIGINS is unset: production should list its frontend origins explicitly; mirror mode runs uncredentialed, so browser frontends cannot send the session cookie" + ); + } + router .merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", api)) .with_state(state) @@ -108,16 +115,37 @@ pub fn build_router(state: AppState) -> Router { let limiter = api_limiter.clone(); async move { limiter.enforce(req, next).await } })) - .layer(cors_layer()) + .layer(cors_layer(cors_allowlist)) .layer(TraceLayer::new_for_http()) } +/// Parse the `CORS_ALLOWED_ORIGINS` (comma-separated) allowlist; empty when unset. +fn cors_allowlist_from_env() -> Vec { + std::env::var("CORS_ALLOWED_ORIGINS") + .unwrap_or_default() + .split(',') + .map(str::trim) + .filter(|origin| !origin.is_empty()) + .filter_map(|origin| origin.parse().ok()) + .collect() +} + /// CORS for a cookie-authenticated API. `CorsLayer::permissive()` would send /// `Access-Control-Allow-Origin: *`, which browsers refuse to combine with -/// credentialed (cookie) requests — so instead reflect the caller's origin, or a -/// `CORS_ALLOWED_ORIGINS` (comma-separated) allowlist when set, and advertise -/// `Access-Control-Allow-Credentials: true`. -fn cors_layer() -> CorsLayer { +/// credentialed (cookie) requests — so origins from the `CORS_ALLOWED_ORIGINS` +/// allowlist are echoed back with `Access-Control-Allow-Credentials: true`. +/// +/// With no allowlist (dev) the caller's origin is mirrored, but WITHOUT +/// credentials: mirror + credentials would let any website ride a visitor's +/// session cookie, so the two must NEVER be recombined (the cookie's +/// `SameSite=Lax` in `web/auth.rs` is the only other guard on that door). A +/// cross-origin dev frontend can't send the Lax cookie anyway, so credentials +/// bought nothing in mirror mode; a credentialed browser frontend requires +/// listing its origin in `CORS_ALLOWED_ORIGINS`. +/// +/// Takes the allowlist as a parameter (env read once in `build_router`) so +/// tests can exercise both modes without racing on process-global env vars. +pub fn cors_layer(allowlist: Vec) -> CorsLayer { let layer = CorsLayer::new() .allow_methods([ Method::GET, @@ -126,21 +154,16 @@ fn cors_layer() -> CorsLayer { Method::DELETE, Method::OPTIONS, ]) - .allow_headers([header::CONTENT_TYPE]) - .allow_credentials(true); - - let allowlist: Vec = std::env::var("CORS_ALLOWED_ORIGINS") - .unwrap_or_default() - .split(',') - .map(str::trim) - .filter(|origin| !origin.is_empty()) - .filter_map(|origin| origin.parse().ok()) - .collect(); + .allow_headers([header::CONTENT_TYPE]); if allowlist.is_empty() { - layer.allow_origin(AllowOrigin::mirror_request()) + layer + .allow_origin(AllowOrigin::mirror_request()) + .allow_credentials(false) } else { - layer.allow_origin(AllowOrigin::list(allowlist)) + layer + .allow_origin(AllowOrigin::list(allowlist)) + .allow_credentials(true) } } diff --git a/src/web/auth.rs b/src/web/auth.rs index a460d61..3d7b310 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -117,6 +117,9 @@ async fn login( .path("/") .http_only(true) .secure(st.cookie_secure) + // Lax is part of the CORS defense: it keeps this cookie off cross-site + // requests. Before relaxing toward SameSite=None, first make sure + // `cors_layer` (lib.rs) can never mirror origins with credentials on. .same_site(SameSite::Lax) .max_age(time::Duration::days(SESSION_DURATION_DAYS)) .build(); diff --git a/tests/integration.rs b/tests/integration.rs index 5473e74..c587189 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -4862,6 +4862,13 @@ async fn session_cookie_secure_attribute_follows_config() { !plain.contains("Secure"), "dev cookie must not be Secure: {plain}" ); + // SameSite=Lax is the cookie-side half of the CORS defense: dev mirror + // mode (see `cors_layer`) is only safe as long as this cookie never rides + // cross-site requests. + assert!( + plain.contains("SameSite=Lax"), + "cookie must stay SameSite=Lax: {plain}" + ); // With the flag on: Secure present. let db = database::init_mem().await.unwrap(); @@ -4970,27 +4977,68 @@ async fn patch_null_clears_event_times() { assert!(res.body["ends_at"].is_null()); } -/// #4 — CORS echoes the caller's origin and allows credentials, never `*` -/// (which browsers reject for cookie-bearing requests). +/// #4 — mirror mode (no `CORS_ALLOWED_ORIGINS`) reflects the caller's origin, +/// never `*`, but must NOT advertise credentials: reflecting arbitrary origins +/// with credentials would let any website ride a visitor's session cookie. #[tokio::test] -async fn cors_is_credential_safe_not_wildcard() { +async fn cors_mirror_mode_reflects_origin_without_credentials() { let app = mem_app().await; let req = Request::builder() .method("GET") .uri("/health") - .header("origin", "https://client.example") + .header("origin", "https://evil.example") .body(Body::empty()) .unwrap(); let res = app.oneshot(req).await.unwrap(); let headers = res.headers(); assert_eq!( headers.get("access-control-allow-origin").unwrap(), - "https://client.example", + "https://evil.example", "origin must be reflected, not wildcarded" ); + // tower-http omits the header entirely when credentials are off. + assert!( + headers.get("access-control-allow-credentials").is_none(), + "mirror mode must never send allow-credentials" + ); +} + +/// Allowlist mode: a listed origin gets both the origin echo and +/// `allow-credentials: true`; an unlisted origin gets no origin header at all. +/// `cors_layer` takes the allowlist as a parameter, so this needs no +/// process-global env mutation (which would race other tests). +#[tokio::test] +async fn cors_allowlist_mode_credits_only_listed_origins() { + async fn probe(origin: &str) -> axum::http::HeaderMap { + let app = axum::Router::new() + .route("/ping", axum::routing::get(|| async { "pong" })) + .layer(hezarfen_backend::cors_layer(vec![ + "https://app.example".parse().unwrap(), + ])); + let req = Request::builder() + .method("GET") + .uri("/ping") + .header("origin", origin) + .body(Body::empty()) + .unwrap(); + app.oneshot(req).await.unwrap().headers().clone() + } + + let listed = probe("https://app.example").await; + assert_eq!( + listed.get("access-control-allow-origin").unwrap(), + "https://app.example", + ); assert_eq!( - headers.get("access-control-allow-credentials").unwrap(), + listed.get("access-control-allow-credentials").unwrap(), "true", + "the allowlisted origin must keep credentialed CORS" + ); + + let unlisted = probe("https://evil.example").await; + assert!( + unlisted.get("access-control-allow-origin").is_none(), + "an unlisted origin must not be echoed" ); }