forge
Explore
Log in

Don't you dare go Hollow

Never send credentials in mirror mode

Browse files at this commit

6faa81644b1f37bc4379fb688866ed8f40ccb5f0Ahmet Kaan GümüşParent: 6917977
  • fix
    • never send credentials in mirror mode
Show full message
🔒 fix(cors): never send credentials in mirror mode

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.examplemodified+4 -3
@@ -18,9 +18,10 @@ RUST_LOG=info,hezarfen_backend=debug
1818 # over HTTPS. Enable in production behind TLS; leave unset for plain-HTTP dev.
1919 # COOKIE_SECURE=true
2020
21-# Comma-separated CORS allowlist for browser clients on other origins. Leave
22-# unset to reflect the request's Origin (dev-friendly). Credentials (the session
23-# cookie) are always allowed, so a wildcard `*` is never used.
21+# Comma-separated CORS allowlist for browser clients on other origins; listed
22+# origins may send credentials (the session cookie). Leave unset to reflect the
23+# request's Origin (dev-friendly) — but without credentials, so a cookie-using
24+# browser frontend must be listed here explicitly.
2425 # CORS_ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com
2526
2627 # 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
7878 files (`/data/files`) together, so that one volume persists everything. `HOST` is forced to `0.0.0.0` inside the
7979 container so the published port works. Production knobs (`COOKIE_SECURE`,
8080 `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.
8284
8385 Without compose:
8486
@@ -153,11 +155,13 @@ directly — the header is client-forged in that case.
153155 ## CORS
154156
155157 Cookie-authenticated APIs can't use a wildcard `Access-Control-Allow-Origin`
156-(browsers refuse it on credentialed requests), so the server always advertises
157-`Access-Control-Allow-Credentials: true` and, by default, reflects the
158-request's `Origin` — dev-friendly, effectively open. In production set
159-`CORS_ALLOWED_ORIGINS` to a comma-separated allowlist to restrict which
160-browser origins may call the API.
158+(browsers refuse it on credentialed requests), so origins listed in the
159+comma-separated `CORS_ALLOWED_ORIGINS` allowlist are echoed back with
160+`Access-Control-Allow-Credentials: true`. When the allowlist is unset the
161+server reflects the request's `Origin` — dev-friendly — but **without**
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.
161165
162166 ## Roles & access control
163167
src/lib.rsmodified+40 -17
@@ -101,6 +101,13 @@ pub fn build_router(state: AppState) -> Router {
101101 state.rate_limit.trust_proxy,
102102 );
103103
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+
104111 router
105112 .merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", api))
106113 .with_state(state)
@@ -108,16 +115,37 @@ pub fn build_router(state: AppState) -> Router {
108115 let limiter = api_limiter.clone();
109116 async move { limiter.enforce(req, next).await }
110117 }))
111- .layer(cors_layer())
118+ .layer(cors_layer(cors_allowlist))
112119 .layer(TraceLayer::new_for_http())
113120 }
114121
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+
115133 /// CORS for a cookie-authenticated API. `CorsLayer::permissive()` would send
116134 /// `Access-Control-Allow-Origin: *`, which browsers refuse to combine with
117-/// credentialed (cookie) requests — so instead reflect the caller's origin, or a
118-/// `CORS_ALLOWED_ORIGINS` (comma-separated) allowlist when set, and advertise
119-/// `Access-Control-Allow-Credentials: true`.
120-fn cors_layer() -> CorsLayer {
135+/// credentialed (cookie) requests — so origins from the `CORS_ALLOWED_ORIGINS`
136+/// allowlist are echoed back with `Access-Control-Allow-Credentials: true`.
137+///
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 {
121149 let layer = CorsLayer::new()
122150 .allow_methods([
123151 Method::GET,
@@ -126,21 +154,16 @@ fn cors_layer() -> CorsLayer {
126154 Method::DELETE,
127155 Method::OPTIONS,
128156 ])
129- .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();
157+ .allow_headers([header::CONTENT_TYPE]);
139158
140159 if allowlist.is_empty() {
141- layer.allow_origin(AllowOrigin::mirror_request())
160+ layer
161+ .allow_origin(AllowOrigin::mirror_request())
162+ .allow_credentials(false)
142163 } else {
143- layer.allow_origin(AllowOrigin::list(allowlist))
164+ layer
165+ .allow_origin(AllowOrigin::list(allowlist))
166+ .allow_credentials(true)
144167 }
145168 }
146169
src/web/auth.rsmodified+3 -0
@@ -117,6 +117,9 @@ async fn login(
117117 .path("/")
118118 .http_only(true)
119119 .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.
120123 .same_site(SameSite::Lax)
121124 .max_age(time::Duration::days(SESSION_DURATION_DAYS))
122125 .build();
tests/integration.rsmodified+54 -6
@@ -4862,6 +4862,13 @@ async fn session_cookie_secure_attribute_follows_config() {
48624862 !plain.contains("Secure"),
48634863 "dev cookie must not be Secure: {plain}"
48644864 );
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+ );
48654872
48664873 // With the flag on: Secure present.
48674874 let db = database::init_mem().await.unwrap();
@@ -4970,27 +4977,68 @@ async fn patch_null_clears_event_times() {
49704977 assert!(res.body["ends_at"].is_null());
49714978 }
49724979
4973-/// #4 — CORS echoes the caller's origin and allows credentials, never `*`
4974-/// (which browsers reject for cookie-bearing requests).
4980+/// #4 — mirror mode (no `CORS_ALLOWED_ORIGINS`) reflects the caller's origin,
4981+/// never `*`, but must NOT advertise credentials: reflecting arbitrary origins
4982+/// with credentials would let any website ride a visitor's session cookie.
49754983 #[tokio::test]
4976-async fn cors_is_credential_safe_not_wildcard() {
4984+async fn cors_mirror_mode_reflects_origin_without_credentials() {
49774985 let app = mem_app().await;
49784986 let req = Request::builder()
49794987 .method("GET")
49804988 .uri("/health")
4981- .header("origin", "https://client.example")
4989+ .header("origin", "https://evil.example")
49824990 .body(Body::empty())
49834991 .unwrap();
49844992 let res = app.oneshot(req).await.unwrap();
49854993 let headers = res.headers();
49864994 assert_eq!(
49874995 headers.get("access-control-allow-origin").unwrap(),
4988- "https://client.example",
4996+ "https://evil.example",
49894997 "origin must be reflected, not wildcarded"
49904998 );
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+ );
49915032 assert_eq!(
4992- headers.get("access-control-allow-credentials").unwrap(),
5033+ listed.get("access-control-allow-credentials").unwrap(),
49935034 "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"
49945042 );
49955043 }
49965044