Never send credentials in mirror mode
Browse files at this commit6faa81644b1f37bc4379fb688866ed8f40ccb5f0Parent: 6917977- fix
- never send credentials in mirror mode
5 changed files +111 -32
- .env.example +4 -3
- README.md +10 -6
- src/lib.rs +40 -17
- src/web/auth.rs +3 -0
- tests/integration.rs +54 -6
.env.examplemodified+4 -3
| @@ -18,9 +18,10 @@ RUST_LOG=info,hezarfen_backend=debug | |||
| 18 | # over HTTPS. Enable in production behind TLS; leave unset for plain-HTTP dev. | 18 | # over HTTPS. Enable in production behind TLS; leave unset for plain-HTTP dev. |
| 19 | # COOKIE_SECURE=true | 19 | # COOKIE_SECURE=true |
| 20 | 20 | ||
| 21 | -# Comma-separated CORS allowlist for browser clients on other origins. Leave | 21 | +# Comma-separated CORS allowlist for browser clients on other origins; listed |
| 22 | -# unset to reflect the request's Origin (dev-friendly). Credentials (the session | 22 | +# origins may send credentials (the session cookie). Leave unset to reflect the |
| 23 | -# cookie) are always allowed, so a wildcard `*` is never used. | 23 | +# request's Origin (dev-friendly) — but without credentials, so a cookie-using |
| 24 | +# browser frontend must be listed here explicitly. | ||
| 24 | # CORS_ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com | 25 | # CORS_ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com |
| 25 | 26 | ||
| 26 | # Per-IP rate limits (requests per minute). AUTH covers /auth/login and | 27 | # Per-IP rate limits (requests per minute). AUTH covers /auth/login and |
README.mdmodified+10 -6
| @@ -78,7 +78,9 @@ embedded there is only one service; its data lives in the named volume | |||
| 78 | files (`/data/files`) together, so that one volume persists everything. `HOST` is forced to `0.0.0.0` inside the | 78 | files (`/data/files`) together, so that one volume persists everything. `HOST` is forced to `0.0.0.0` inside the |
| 79 | container so the published port works. Production knobs (`COOKIE_SECURE`, | 79 | container so the published port works. Production knobs (`COOKIE_SECURE`, |
| 80 | `CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in | 80 | `CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in |
| 81 | -`compose.yaml` — uncomment as needed. Works with `docker compose` too. | 81 | +`compose.yaml` — uncomment as needed. Leaving `CORS_ALLOWED_ORIGINS` unset |
| 82 | +means dev mirror mode without credentials; a cookie-using browser frontend | ||
| 83 | +must be allowlisted explicitly. Works with `docker compose` too. | ||
| 82 | 84 | ||
| 83 | Without compose: | 85 | Without compose: |
| 84 | 86 | ||
| @@ -153,11 +155,13 @@ directly — the header is client-forged in that case. | |||
| 153 | ## CORS | 155 | ## CORS |
| 154 | 156 | ||
| 155 | Cookie-authenticated APIs can't use a wildcard `Access-Control-Allow-Origin` | 157 | Cookie-authenticated APIs can't use a wildcard `Access-Control-Allow-Origin` |
| 156 | -(browsers refuse it on credentialed requests), so the server always advertises | 158 | +(browsers refuse it on credentialed requests), so origins listed in the |
| 157 | -`Access-Control-Allow-Credentials: true` and, by default, reflects the | 159 | +comma-separated `CORS_ALLOWED_ORIGINS` allowlist are echoed back with |
| 158 | -request's `Origin` — dev-friendly, effectively open. In production set | 160 | +`Access-Control-Allow-Credentials: true`. When the allowlist is unset the |
| 159 | -`CORS_ALLOWED_ORIGINS` to a comma-separated allowlist to restrict which | 161 | +server reflects the request's `Origin` — dev-friendly — but **without** |
| 160 | -browser origins may call the API. | 162 | +credentials: mirroring with credentials would let any website ride a |
| 163 | +visitor's session cookie. A browser frontend that needs the session cookie | ||
| 164 | +cross-origin must therefore be allowlisted explicitly. | ||
| 161 | 165 | ||
| 162 | ## Roles & access control | 166 | ## Roles & access control |
| 163 | 167 | ||
src/lib.rsmodified+40 -17
| @@ -101,6 +101,13 @@ pub fn build_router(state: AppState) -> Router { | |||
| 101 | state.rate_limit.trust_proxy, | 101 | state.rate_limit.trust_proxy, |
| 102 | ); | 102 | ); |
| 103 | 103 | ||
| 104 | + let cors_allowlist = cors_allowlist_from_env(); | ||
| 105 | + if state.cookie_secure && cors_allowlist.is_empty() { | ||
| 106 | + tracing::warn!( | ||
| 107 | + "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" | ||
| 108 | + ); | ||
| 109 | + } | ||
| 110 | + | ||
| 104 | router | 111 | router |
| 105 | .merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", api)) | 112 | .merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", api)) |
| 106 | .with_state(state) | 113 | .with_state(state) |
| @@ -108,16 +115,37 @@ pub fn build_router(state: AppState) -> Router { | |||
| 108 | let limiter = api_limiter.clone(); | 115 | let limiter = api_limiter.clone(); |
| 109 | async move { limiter.enforce(req, next).await } | 116 | async move { limiter.enforce(req, next).await } |
| 110 | })) | 117 | })) |
| 111 | - .layer(cors_layer()) | 118 | + .layer(cors_layer(cors_allowlist)) |
| 112 | .layer(TraceLayer::new_for_http()) | 119 | .layer(TraceLayer::new_for_http()) |
| 113 | } | 120 | } |
| 114 | 121 | ||
| 122 | +/// Parse the `CORS_ALLOWED_ORIGINS` (comma-separated) allowlist; empty when unset. | ||
| 123 | +fn cors_allowlist_from_env() -> Vec<HeaderValue> { | ||
| 124 | + std::env::var("CORS_ALLOWED_ORIGINS") | ||
| 125 | + .unwrap_or_default() | ||
| 126 | + .split(',') | ||
| 127 | + .map(str::trim) | ||
| 128 | + .filter(|origin| !origin.is_empty()) | ||
| 129 | + .filter_map(|origin| origin.parse().ok()) | ||
| 130 | + .collect() | ||
| 131 | +} | ||
| 132 | + | ||
| 115 | /// CORS for a cookie-authenticated API. `CorsLayer::permissive()` would send | 133 | /// CORS for a cookie-authenticated API. `CorsLayer::permissive()` would send |
| 116 | /// `Access-Control-Allow-Origin: *`, which browsers refuse to combine with | 134 | /// `Access-Control-Allow-Origin: *`, which browsers refuse to combine with |
| 117 | -/// credentialed (cookie) requests — so instead reflect the caller's origin, or a | 135 | +/// credentialed (cookie) requests — so origins from the `CORS_ALLOWED_ORIGINS` |
| 118 | -/// `CORS_ALLOWED_ORIGINS` (comma-separated) allowlist when set, and advertise | 136 | +/// allowlist are echoed back with `Access-Control-Allow-Credentials: true`. |
| 119 | -/// `Access-Control-Allow-Credentials: true`. | 137 | +/// |
| 120 | -fn cors_layer() -> CorsLayer { | 138 | +/// With no allowlist (dev) the caller's origin is mirrored, but WITHOUT |
| 139 | +/// credentials: mirror + credentials would let any website ride a visitor's | ||
| 140 | +/// session cookie, so the two must NEVER be recombined (the cookie's | ||
| 141 | +/// `SameSite=Lax` in `web/auth.rs` is the only other guard on that door). A | ||
| 142 | +/// cross-origin dev frontend can't send the Lax cookie anyway, so credentials | ||
| 143 | +/// bought nothing in mirror mode; a credentialed browser frontend requires | ||
| 144 | +/// listing its origin in `CORS_ALLOWED_ORIGINS`. | ||
| 145 | +/// | ||
| 146 | +/// Takes the allowlist as a parameter (env read once in `build_router`) so | ||
| 147 | +/// tests can exercise both modes without racing on process-global env vars. | ||
| 148 | +pub fn cors_layer(allowlist: Vec<HeaderValue>) -> CorsLayer { | ||
| 121 | let layer = CorsLayer::new() | 149 | let layer = CorsLayer::new() |
| 122 | .allow_methods([ | 150 | .allow_methods([ |
| 123 | Method::GET, | 151 | Method::GET, |
| @@ -126,21 +154,16 @@ fn cors_layer() -> CorsLayer { | |||
| 126 | Method::DELETE, | 154 | Method::DELETE, |
| 127 | Method::OPTIONS, | 155 | Method::OPTIONS, |
| 128 | ]) | 156 | ]) |
| 129 | - .allow_headers([header::CONTENT_TYPE]) | 157 | + .allow_headers([header::CONTENT_TYPE]); |
| 130 | - .allow_credentials(true); | ||
| 131 | - | ||
| 132 | - let allowlist: Vec<HeaderValue> = std::env::var("CORS_ALLOWED_ORIGINS") | ||
| 133 | - .unwrap_or_default() | ||
| 134 | - .split(',') | ||
| 135 | - .map(str::trim) | ||
| 136 | - .filter(|origin| !origin.is_empty()) | ||
| 137 | - .filter_map(|origin| origin.parse().ok()) | ||
| 138 | - .collect(); | ||
| 139 | 158 | ||
| 140 | if allowlist.is_empty() { | 159 | if allowlist.is_empty() { |
| 141 | - layer.allow_origin(AllowOrigin::mirror_request()) | 160 | + layer |
| 161 | + .allow_origin(AllowOrigin::mirror_request()) | ||
| 162 | + .allow_credentials(false) | ||
| 142 | } else { | 163 | } else { |
| 143 | - layer.allow_origin(AllowOrigin::list(allowlist)) | 164 | + layer |
| 165 | + .allow_origin(AllowOrigin::list(allowlist)) | ||
| 166 | + .allow_credentials(true) | ||
| 144 | } | 167 | } |
| 145 | } | 168 | } |
| 146 | 169 | ||
src/web/auth.rsmodified+3 -0
| @@ -117,6 +117,9 @@ async fn login( | |||
| 117 | .path("/") | 117 | .path("/") |
| 118 | .http_only(true) | 118 | .http_only(true) |
| 119 | .secure(st.cookie_secure) | 119 | .secure(st.cookie_secure) |
| 120 | + // Lax is part of the CORS defense: it keeps this cookie off cross-site | ||
| 121 | + // requests. Before relaxing toward SameSite=None, first make sure | ||
| 122 | + // `cors_layer` (lib.rs) can never mirror origins with credentials on. | ||
| 120 | .same_site(SameSite::Lax) | 123 | .same_site(SameSite::Lax) |
| 121 | .max_age(time::Duration::days(SESSION_DURATION_DAYS)) | 124 | .max_age(time::Duration::days(SESSION_DURATION_DAYS)) |
| 122 | .build(); | 125 | .build(); |
tests/integration.rsmodified+54 -6
| @@ -4862,6 +4862,13 @@ async fn session_cookie_secure_attribute_follows_config() { | |||
| 4862 | !plain.contains("Secure"), | 4862 | !plain.contains("Secure"), |
| 4863 | "dev cookie must not be Secure: {plain}" | 4863 | "dev cookie must not be Secure: {plain}" |
| 4864 | ); | 4864 | ); |
| 4865 | + // SameSite=Lax is the cookie-side half of the CORS defense: dev mirror | ||
| 4866 | + // mode (see `cors_layer`) is only safe as long as this cookie never rides | ||
| 4867 | + // cross-site requests. | ||
| 4868 | + assert!( | ||
| 4869 | + plain.contains("SameSite=Lax"), | ||
| 4870 | + "cookie must stay SameSite=Lax: {plain}" | ||
| 4871 | + ); | ||
| 4865 | 4872 | ||
| 4866 | // With the flag on: Secure present. | 4873 | // With the flag on: Secure present. |
| 4867 | let db = database::init_mem().await.unwrap(); | 4874 | let db = database::init_mem().await.unwrap(); |
| @@ -4970,27 +4977,68 @@ async fn patch_null_clears_event_times() { | |||
| 4970 | assert!(res.body["ends_at"].is_null()); | 4977 | assert!(res.body["ends_at"].is_null()); |
| 4971 | } | 4978 | } |
| 4972 | 4979 | ||
| 4973 | -/// #4 — CORS echoes the caller's origin and allows credentials, never `*` | 4980 | +/// #4 — mirror mode (no `CORS_ALLOWED_ORIGINS`) reflects the caller's origin, |
| 4974 | -/// (which browsers reject for cookie-bearing requests). | 4981 | +/// never `*`, but must NOT advertise credentials: reflecting arbitrary origins |
| 4982 | +/// with credentials would let any website ride a visitor's session cookie. | ||
| 4975 | #[tokio::test] | 4983 | #[tokio::test] |
| 4976 | -async fn cors_is_credential_safe_not_wildcard() { | 4984 | +async fn cors_mirror_mode_reflects_origin_without_credentials() { |
| 4977 | let app = mem_app().await; | 4985 | let app = mem_app().await; |
| 4978 | let req = Request::builder() | 4986 | let req = Request::builder() |
| 4979 | .method("GET") | 4987 | .method("GET") |
| 4980 | .uri("/health") | 4988 | .uri("/health") |
| 4981 | - .header("origin", "https://client.example") | 4989 | + .header("origin", "https://evil.example") |
| 4982 | .body(Body::empty()) | 4990 | .body(Body::empty()) |
| 4983 | .unwrap(); | 4991 | .unwrap(); |
| 4984 | let res = app.oneshot(req).await.unwrap(); | 4992 | let res = app.oneshot(req).await.unwrap(); |
| 4985 | let headers = res.headers(); | 4993 | let headers = res.headers(); |
| 4986 | assert_eq!( | 4994 | assert_eq!( |
| 4987 | headers.get("access-control-allow-origin").unwrap(), | 4995 | headers.get("access-control-allow-origin").unwrap(), |
| 4988 | - "https://client.example", | 4996 | + "https://evil.example", |
| 4989 | "origin must be reflected, not wildcarded" | 4997 | "origin must be reflected, not wildcarded" |
| 4990 | ); | 4998 | ); |
| 4999 | + // tower-http omits the header entirely when credentials are off. | ||
| 5000 | + assert!( | ||
| 5001 | + headers.get("access-control-allow-credentials").is_none(), | ||
| 5002 | + "mirror mode must never send allow-credentials" | ||
| 5003 | + ); | ||
| 5004 | +} | ||
| 5005 | + | ||
| 5006 | +/// Allowlist mode: a listed origin gets both the origin echo and | ||
| 5007 | +/// `allow-credentials: true`; an unlisted origin gets no origin header at all. | ||
| 5008 | +/// `cors_layer` takes the allowlist as a parameter, so this needs no | ||
| 5009 | +/// process-global env mutation (which would race other tests). | ||
| 5010 | +#[tokio::test] | ||
| 5011 | +async fn cors_allowlist_mode_credits_only_listed_origins() { | ||
| 5012 | + async fn probe(origin: &str) -> axum::http::HeaderMap { | ||
| 5013 | + let app = axum::Router::new() | ||
| 5014 | + .route("/ping", axum::routing::get(|| async { "pong" })) | ||
| 5015 | + .layer(hezarfen_backend::cors_layer(vec![ | ||
| 5016 | + "https://app.example".parse().unwrap(), | ||
| 5017 | + ])); | ||
| 5018 | + let req = Request::builder() | ||
| 5019 | + .method("GET") | ||
| 5020 | + .uri("/ping") | ||
| 5021 | + .header("origin", origin) | ||
| 5022 | + .body(Body::empty()) | ||
| 5023 | + .unwrap(); | ||
| 5024 | + app.oneshot(req).await.unwrap().headers().clone() | ||
| 5025 | + } | ||
| 5026 | + | ||
| 5027 | + let listed = probe("https://app.example").await; | ||
| 5028 | + assert_eq!( | ||
| 5029 | + listed.get("access-control-allow-origin").unwrap(), | ||
| 5030 | + "https://app.example", | ||
| 5031 | + ); | ||
| 4991 | assert_eq!( | 5032 | assert_eq!( |
| 4992 | - headers.get("access-control-allow-credentials").unwrap(), | 5033 | + listed.get("access-control-allow-credentials").unwrap(), |
| 4993 | "true", | 5034 | "true", |
| 5035 | + "the allowlisted origin must keep credentialed CORS" | ||
| 5036 | + ); | ||
| 5037 | + | ||
| 5038 | + let unlisted = probe("https://evil.example").await; | ||
| 5039 | + assert!( | ||
| 5040 | + unlisted.get("access-control-allow-origin").is_none(), | ||
| 5041 | + "an unlisted origin must not be echoed" | ||
| 4994 | ); | 5042 | ); |
| 4995 | } | 5043 | } |
| 4996 | 5044 | ||