From 680e8d2ba6c3fcd11ac319ff20afc40835d83596 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sat, 28 Nov 2026 18:53:37 +0000 Subject: [PATCH] refactor: consolidate request origin handling Move request origin classification into windmill-api-auth and reuse it for session-authenticated requests; adds SESSION_COOKIE_TRUSTED_ORIGINS. Co-Authored-By: Claude Opus 5.5 --- backend/Cargo.lock | 1 + backend/tests/jobs_cross_site_get.rs | 52 ++- backend/windmill-api-auth/Cargo.toml | 1 + backend/windmill-api-auth/src/auth.rs | 43 ++- backend/windmill-api-auth/src/lib.rs | 1 + backend/windmill-api-auth/src/request_site.rs | 331 ++++++++++++++++++ backend/windmill-api/src/csrf.rs | 201 ++--------- docs/auth-surface.md | 10 + 8 files changed, 451 insertions(+), 189 deletions(-) create mode 100644 backend/windmill-api-auth/src/request_site.rs diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 1098970b7d..38b2a691ad 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -15997,6 +15997,7 @@ dependencies = [ "tokio", "tower-cookies", "tracing", + "url", "uuid", "windmill-audit", "windmill-common", diff --git a/backend/tests/jobs_cross_site_get.rs b/backend/tests/jobs_cross_site_get.rs index 5b6151c328..db602da9a6 100644 --- a/backend/tests/jobs_cross_site_get.rs +++ b/backend/tests/jobs_cross_site_get.rs @@ -14,12 +14,15 @@ //! exempting the parameter would let `?token=junk` reinstate the vector. //! //! This test pins down: -//! - both endpoints refuse a cross-site cookie GET to a Hub script (the core fix), whether -//! `Sec-Fetch-Site` says so or, with no such header (plain http), a cross-host `Referer`, +//! - both endpoints refuse a cookie GET to a Hub script from another site, same-site +//! included, whether `Sec-Fetch-Site` says so or, with no such header (plain http), a +//! cross-host `Referer`, //! - a junk `token` query parameter does not buy a pass, //! - the scope: the same request to a workspace script is not refused, +//! - a POST from another site does not authenticate on the cookie, but does on its own +//! `?token=`, //! - a Hub-script request with its own credential (bearer, or `?token=` and no cookie), or -//! sent as a POST, gets through. +//! sent as a same-origin POST, gets through. //! //! No runnable exists and no Hub is contacted. A request that gets past the guard fails as //! not-found on a workspace path, and for a Hub path on fetching it from a Hub pointed at a @@ -69,6 +72,11 @@ async fn test_cross_site_get_cannot_run_hub_scripts(db: Pool) -> anyho "Sec-Fetch-Site: cross-site", cookie_get(path).header("Sec-Fetch-Site", "cross-site"), ), + // A sibling subdomain gets the `SameSite=Lax` cookie on every request. + ( + "Sec-Fetch-Site: same-site", + cookie_get(path).header("Sec-Fetch-Site", "same-site"), + ), // Plain http gets no `Sec-Fetch-*` at all, so `Referer` is the only signal left. ( "cross-host Referer with no Sec-Fetch-Site", @@ -113,8 +121,32 @@ async fn test_cross_site_get_cannot_run_hub_scripts(db: Pool) -> anyho ); } - // ---- A Hub-script request that carries its own credential, or is a POST, gets through. + // ---- A POST from another site does not authenticate on the cookie. let hub = HUB_GETS[1]; + for (name, headers) in [ + ("same-site", &[("Sec-Fetch-Site", "same-site")][..]), + ( + "Origin on another host", + &[("Origin", "http://sibling.localhost")][..], + ), + ] { + let mut req = client + .post(format!("{base}/{hub}")) + .header("Cookie", "token=SECRET_TOKEN") + .json(&serde_json::json!({})); + for (k, v) in headers { + req = req.header(*k, *v); + } + let (status, body) = send(req).await?; + assert_eq!( + status, + StatusCode::FORBIDDEN, + "POST [{name}] must not use the cookie: {body}" + ); + } + + // ---- A Hub-script request that carries its own credential, or is a same-origin POST, + // gets through. let allowed = [ ( "cross-origin bearer token", @@ -130,11 +162,19 @@ async fn test_cross_site_get_cannot_run_hub_scripts(db: Pool) -> anyho .header("Sec-Fetch-Site", "cross-site"), ), ( - "POST with the cookie", + "same-origin POST with the cookie", client .post(format!("{base}/{hub}")) .header("Cookie", "token=SECRET_TOKEN") - .header("Sec-Fetch-Site", "cross-site") + .header("Sec-Fetch-Site", "same-origin") + .json(&serde_json::json!({})), + ), + ( + "same-site POST with ?token= next to the cookie", + client + .post(format!("{base}/{hub}?token=SECRET_TOKEN")) + .header("Cookie", "token=junk") + .header("Sec-Fetch-Site", "same-site") .json(&serde_json::json!({})), ), ]; diff --git a/backend/windmill-api-auth/Cargo.toml b/backend/windmill-api-auth/Cargo.toml index c2cd3a1674..474b8710ea 100644 --- a/backend/windmill-api-auth/Cargo.toml +++ b/backend/windmill-api-auth/Cargo.toml @@ -29,6 +29,7 @@ serde_json.workspace = true uuid.workspace = true itertools.workspace = true tower-cookies.workspace = true +url.workspace = true tracing.workspace = true chrono.workspace = true quick_cache.workspace = true diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index f1a55f9cf5..7c2893ed46 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -1159,6 +1159,36 @@ async fn pick_live_session_token( picked.map(|i| candidates[i].clone()).or(fallback) } +/// Set on a request whose session cookie [`refuse_foreign_cookie`] set aside, so that the +/// rejection names the reason rather than reading as a plain logged-out 401. +#[derive(Clone, Copy)] +struct ForeignCookieRefused; + +const FOREIGN_COOKIE_REFUSED: &str = "the session cookie is not accepted on a state-changing \ + request sent by a page of another site: pass a token in the `Authorization` header, or, \ + for a site the instance trusts, list it in SESSION_COOKIE_TRUSTED_ORIGINS"; + +/// Whether to set aside the session cookie of a state-changing request sent by a page of +/// another origin (see [`crate::request_site`]). The request then authenticates as if it had no +/// cookie: on its `token` query parameter if it has one, else not at all, so routes that take +/// an optional caller (public apps, approval links, HTTP routes, login callbacks) still serve +/// it anonymously. Safe methods are left to the routes that act on a GET, which check for +/// themselves (`CrossSiteGetGuard`). +fn refuse_foreign_cookie(parts: &mut Parts) -> bool { + if parts.method.is_safe() { + return false; + } + if parts.extensions.get::().is_some() { + return true; + } + let Some(foreign) = crate::request_site::foreign_request(&parts.headers, &parts.uri) else { + return false; + }; + foreign.log("ignoring the session cookie"); + parts.extensions.insert(ForeignCookieRefused); + true +} + pub(crate) async fn extract_token(parts: &mut Parts, state: &S) -> Option { let auth_header = parts .headers @@ -1170,7 +1200,7 @@ pub(crate) async fn extract_token(parts: &mut Parts, state: &S) Some(x) => Some(x.to_owned()), None => { let candidates = session_cookie_values(parts); - if candidates.len() > 1 { + let cookie = if candidates.len() > 1 { pick_live_session_token(parts, state, candidates).await } else { Extension::::from_request_parts(parts, state) @@ -1181,7 +1211,8 @@ pub(crate) async fn extract_token(parts: &mut Parts, state: &S) .get(COOKIE_NAME) .map(|c| c.value_trimmed().to_owned()) }) - } + }; + cookie.filter(|_| !refuse_foreign_cookie(parts)) } }; @@ -1263,6 +1294,8 @@ where let tokened = Self { token: "no_auth".to_string() }; parts.extensions.insert(tokened.clone()); Ok(tokened) + } else if parts.extensions.get::().is_some() { + Err((StatusCode::FORBIDDEN, FOREIGN_COOKIE_REFUSED.to_owned())) } else { BRUTE_FORCE_COUNTER.increment().await; Err((StatusCode::UNAUTHORIZED, "Unauthorized".to_owned())) @@ -1526,6 +1559,12 @@ pub async fn resolve_opt_job_authed( } } } + if parts.extensions.get::().is_some() { + return Err(( + Error::PermissionDenied(FOREIGN_COOKIE_REFUSED.to_string()), + parts, + )); + } BRUTE_FORCE_COUNTER.increment().await; Err((Error::NotAuthorized("Unauthorized".to_string()), parts)) } diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index f75a3fd2d5..0d07bbce6d 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -11,6 +11,7 @@ pub mod composed; #[cfg(feature = "private")] pub mod ee; pub mod ee_oss; +pub mod request_site; pub mod scopes; #[cfg(all(feature = "private", feature = "enterprise"))] mod token_ip_allowlist_ee; diff --git a/backend/windmill-api-auth/src/request_site.rs b/backend/windmill-api-auth/src/request_site.rs new file mode 100644 index 0000000000..733963b41d --- /dev/null +++ b/backend/windmill-api-auth/src/request_site.rs @@ -0,0 +1,331 @@ +/* + * Author: Ruben Fiszel + * Copyright: Windmill Labs, Inc 2026 + * This file and its contents are licensed under the AGPLv3 License. + * Please see the included NOTICE for copyright information and + * LICENSE-AGPL for a copy of the license. + */ + +//! Whether a request was sent by a page of this instance's own origin. +//! +//! The session cookie is `SameSite=Lax`, which a browser attaches to every request from a +//! *same-site* page: any sibling host under the same registrable domain (every +//! `*.windmill.dev` host for a `.windmill.dev` instance, every `*.corp.com` host for +//! `windmill.corp.com`), forms and top-level GETs alike. The cookie is therefore only treated +//! as the caller's intent on requests from the instance's own origin, a bookmark or a typed +//! URL, or a non-browser client. + +use http::{header, HeaderMap, Uri}; +use url::Url; + +/// Hosts, besides the instance's own, whose pages may send requests that authenticate with +/// the session cookie. `*` accepts every site. +pub const TRUSTED_ORIGINS_ENV: &str = "SESSION_COOKIE_TRUSTED_ORIGINS"; + +lazy_static::lazy_static! { + static ref TRUSTED_ORIGINS: TrustedOrigins = TrustedOrigins::parse( + &std::env::var(TRUSTED_ORIGINS_ENV).unwrap_or_default() + ); +} + +#[derive(Debug, Default)] +pub struct TrustedOrigins { + any: bool, + hosts: Vec, +} + +impl TrustedOrigins { + /// A comma-separated list of hosts or origins (`dash.corp.com`, `https://dash.corp.com`). + pub fn parse(value: &str) -> Self { + let mut trusted = TrustedOrigins::default(); + for entry in value.split(',').map(str::trim).filter(|e| !e.is_empty()) { + if entry == "*" { + trusted.any = true; + } else if let Some(host) = Url::parse(entry) + .ok() + .and_then(|u| u.host_str().map(str::to_owned)) + .or_else(|| host_of(entry)) + { + trusted.hosts.push(host); + } else { + tracing::warn!("{TRUSTED_ORIGINS_ENV}: ignoring {entry:?}, not a host or origin"); + } + } + trusted + } + + fn allows(&self, host: &str) -> bool { + self.hosts.iter().any(|h| h.eq_ignore_ascii_case(host)) + } +} + +/// Why a request is taken to come from a page of another origin. +#[derive(Debug)] +pub enum Foreign { + /// `Sec-Fetch-Site` says so (`same-site`, `cross-site`, or a value this code does not know). + Declared(String), + /// No `Sec-Fetch-Site`; `Origin` names another host, or an opaque origin (`null`). + Origin { origin: String, instance_hosts: Vec }, + /// No `Sec-Fetch-Site` and no `Origin`; `Referer` names another host. + Referer { referer: String, instance_hosts: Vec }, +} + +impl Foreign { + /// Logged when a request is refused. The `Origin`/`Referer` legs compare against the hosts + /// the backend can see, so a proxy that rewrites `Host` without setting + /// `X-Forwarded-Host`, with `BASE_URL` naming another host, refuses requests that were + /// same-origin: say so, so it reads as a misconfiguration. + pub fn log(&self, what: &str) { + match self { + Foreign::Declared(site) => { + tracing::info!(sec_fetch_site = %site, "{what}: the request comes from another site") + } + Foreign::Origin { origin: page, instance_hosts } + | Foreign::Referer { referer: page, instance_hosts } => tracing::warn!( + page = %page, + ?instance_hosts, + "{what}: the page that sent the request is on another host; if it was this \ + instance, set `X-Forwarded-Host` on the proxy or configure `BASE_URL`" + ), + } + } +} + +/// [`foreign_signal`] against the configured `BASE_URL` and trusted origins. +pub fn foreign_request(headers: &HeaderMap, uri: &Uri) -> Option { + foreign_signal( + headers, + uri, + windmill_common::BASE_URL.load().as_str(), + &TRUSTED_ORIGINS, + ) +} + +/// `Sec-Fetch-Site` decides when present: only `same-origin` and `none` (a bookmark, a typed +/// URL) are this instance's own. Fetch Metadata rides only on potentially trustworthy URLs, so +/// a plain-http instance (and Safari before 16.4) never gets it; then `Origin`, which a +/// browser sends on every non-GET request, must name an instance host, and failing that +/// `Referer`, the only thing a top-level GET navigation carries. A request with none of them +/// is not from a browser page and is not refused. +/// +/// The `Referer` leg is weak: `strict-origin-when-cross-origin` drops it on an https-to-http +/// downgrade, so an https page pointing at a plain-http instance sends neither header there. +pub fn foreign_signal( + headers: &HeaderMap, + uri: &Uri, + base_url: &str, + trusted: &TrustedOrigins, +) -> Option { + if trusted.any { + return None; + } + let page_host = || { + header_url_host(headers, header::ORIGIN) + .or_else(|| header_url_host(headers, header::REFERER)) + }; + if let Some(site) = headers.get("sec-fetch-site") { + let site = String::from_utf8_lossy(site.as_bytes()).to_ascii_lowercase(); + if site == "same-origin" || site == "none" { + return None; + } + if !trusted.hosts.is_empty() && page_host().is_some_and(|h| trusted.allows(&h)) { + return None; + } + return Some(Foreign::Declared(site)); + } + let is_ours = |host: &str| { + trusted.allows(host) + || instance_hosts(headers, uri, base_url).any(|h| h.eq_ignore_ascii_case(host)) + }; + if let Some(origin) = headers.get(header::ORIGIN) { + if header_url_host(headers, header::ORIGIN).is_some_and(|h| is_ours(&h)) { + return None; + } + return Some(Foreign::Origin { + origin: String::from_utf8_lossy(origin.as_bytes()).into_owned(), + instance_hosts: instance_hosts(headers, uri, base_url).collect(), + }); + } + let referer = header_url_host(headers, header::REFERER)?; + (!is_ours(&referer)).then(|| Foreign::Referer { + referer, + instance_hosts: instance_hosts(headers, uri, base_url).collect(), + }) +} + +/// Every host a same-origin request can name. `Host` alone is not enough: a reverse proxy that +/// forwards without preserving it (nginx `proxy_pass` with no `proxy_set_header Host $host`) +/// hands the backend the upstream's name. A browser page cannot set any of these on a request +/// that carries the cookie (a custom header needs a CORS preflight no route grants with +/// credentials), and `BASE_URL` is instance config. Ports are not compared: the dev frontend +/// and the API differ only by port. +fn instance_hosts<'a>( + headers: &'a HeaderMap, + uri: &'a Uri, + base_url: &'a str, +) -> impl Iterator + 'a { + [ + uri.host() + .map(str::to_owned) + .or_else(|| header_host(headers, header::HOST)), + header_host(headers, "x-forwarded-host"), + Url::parse(base_url) + .ok() + .and_then(|url| url.host_str().map(str::to_owned)), + ] + .into_iter() + .flatten() +} + +fn header_url_host(headers: &HeaderMap, name: header::HeaderName) -> Option { + let value = headers.get(name)?.to_str().ok()?; + Url::parse(value).ok()?.host_str().map(str::to_owned) +} + +fn header_host(headers: &HeaderMap, name: impl header::AsHeaderName) -> Option { + host_of(headers.get(name)?.to_str().ok()?) +} + +/// The host in a `Host`-shaped header value: `host[:port]`, where `host` may be a bracketed +/// IPv6 literal, and where a chain of proxies appends to `X-Forwarded-Host` so only the first +/// entry is the one the browser addressed. +pub fn host_of(value: &str) -> Option { + let host = value.split(',').next()?.trim(); + Url::parse(&format!("http://{host}")) + .ok()? + .host_str() + .map(str::to_owned) +} + +#[cfg(test)] +mod tests { + use super::*; + + const BASE: &str = "https://windmill.example"; + + fn signal_with(headers: &[(&str, &str)], trusted: &TrustedOrigins) -> Option { + let mut map = HeaderMap::new(); + for (name, value) in headers { + map.append( + header::HeaderName::from_bytes(name.as_bytes()).unwrap(), + value.parse().unwrap(), + ); + } + foreign_signal( + &map, + &Uri::from_static("/api/w/ws/jobs/run/p/f"), + BASE, + trusted, + ) + } + + fn signal(headers: &[(&str, &str)]) -> Option { + signal_with(headers, &TrustedOrigins::default()) + } + + #[test] + fn sec_fetch_site_decides_when_present() { + for site in ["same-origin", "none", "Same-Origin"] { + assert!(signal(&[("sec-fetch-site", site)]).is_none(), "{site}"); + } + for site in ["same-site", "cross-site", "unknown"] { + assert!( + matches!( + signal(&[("sec-fetch-site", site)]), + Some(Foreign::Declared(_)) + ), + "{site}" + ); + } + // An `Origin` naming the instance does not outvote the browser's own verdict. + assert!(signal(&[ + ("sec-fetch-site", "same-site"), + ("host", "windmill.example"), + ("origin", "https://windmill.example"), + ]) + .is_some()); + // Nor does a foreign `Referer` outvote `same-origin`. + assert!(signal(&[ + ("sec-fetch-site", "same-origin"), + ("host", "windmill.example"), + ("referer", "https://other.example/page"), + ]) + .is_none()); + } + + #[test] + fn origin_then_referer_stand_in_when_sec_fetch_site_is_absent() { + let host = ("host", "windmill-server.internal:8000"); + assert!(signal(&[host, ("origin", "http://windmill.example")]).is_none()); + assert!(signal(&[ + ("host", "windmill.example:8000"), + ("origin", "http://windmill.example:3000") + ]) + .is_none()); + assert!(signal(&[ + host, + ("x-forwarded-host", "alias.example, proxy.internal"), + ("origin", "http://alias.example") + ]) + .is_none()); + assert!(matches!( + signal(&[host, ("origin", "http://hub.example")]), + Some(Foreign::Origin { .. }) + )); + assert!(matches!( + signal(&[host, ("origin", "null")]), + Some(Foreign::Origin { .. }) + )); + // `Origin` outranks `Referer`. + assert!(signal(&[ + host, + ("origin", "http://hub.example"), + ("referer", "http://windmill.example/") + ]) + .is_some()); + assert!(signal(&[host, ("referer", "http://windmill.example/apps")]).is_none()); + assert!(matches!( + signal(&[host, ("referer", "http://hub.example/x")]), + Some(Foreign::Referer { .. }) + )); + // No browser page named: a script, the CLI, a server-side webhook caller. + assert!(signal(&[host]).is_none()); + } + + #[test] + fn trusted_origins_admit_named_sites() { + let trusted = TrustedOrigins::parse(" https://dash.example , tools.example:8443 ,"); + let from = + |site, origin| signal_with(&[("sec-fetch-site", site), ("origin", origin)], &trusted); + assert!(from("same-site", "https://dash.example").is_none()); + assert!(from("same-site", "https://tools.example").is_none()); + assert!(from("same-site", "https://hub.example").is_some()); + // A top-level navigation has no `Origin`; the `Referer` names the page. + assert!(signal_with( + &[ + ("sec-fetch-site", "same-site"), + ("referer", "https://dash.example/p") + ], + &trusted + ) + .is_none()); + assert!(signal_with(&[("origin", "https://dash.example")], &trusted).is_none()); + let any = TrustedOrigins::parse("*"); + assert!(signal_with(&[("sec-fetch-site", "cross-site")], &any).is_none()); + } + + #[test] + fn host_of_strips_port_brackets_and_proxy_chain() { + assert_eq!( + host_of("windmill.example:8000"), + Some("windmill.example".into()) + ); + assert_eq!(host_of("[::1]:8000"), Some("[::1]".into())); + assert_eq!( + host_of("windmill.example, proxy.internal"), + Some("windmill.example".into()) + ); + assert_eq!(host_of(""), None); + assert_eq!(host_of("not a host"), None); + } +} diff --git a/backend/windmill-api/src/csrf.rs b/backend/windmill-api/src/csrf.rs index 6a8ec4a6fd..a5e1637e86 100644 --- a/backend/windmill-api/src/csrf.rs +++ b/backend/windmill-api/src/csrf.rs @@ -9,21 +9,22 @@ use axum::extract::FromRequestParts; use axum::http::{header, request::Parts, Method}; use axum::Extension; -use url::Url; +use windmill_api_auth::request_site::{self, Foreign}; use windmill_common::error::Error; use windmill_common::users::COOKIE_NAME; use crate::triggers::trigger_helpers::RunnableId; -/// Whether a request is a cross-site GET authenticating on the session cookie alone. A GET -/// handler that runs a script by path resolves it through [`Self::script_runnable`], which -/// refuses a Hub script on such a request. +/// Whether a request is a GET from a page of another origin authenticating on the session +/// cookie alone. A GET handler that runs a script by path resolves it through +/// [`Self::script_runnable`], which refuses a Hub script on such a request. /// -/// The cookie is `SameSite=Lax`, so browsers attach it to cross-site top-level GET -/// navigations. A `hub/` path runs any public Hub script, and an argument written -/// `$var:` or `$res:` is resolved as the caller before the script sees it: such a -/// GET lets any page pick a generic Hub script and hand it the victim's secrets, which the job -/// can then send anywhere. +/// The cookie is `SameSite=Lax`, so browsers attach it to top-level GET navigations from any +/// site, and to every request from a same-site page (a sibling subdomain). A `hub/` path runs +/// any public Hub script, and an argument written `$var:` or `$res:` is resolved as +/// the caller before the script sees it: such a GET lets any page pick a generic Hub script and +/// hand it the victim's secrets, which the job can then send anywhere. What counts as another +/// origin is decided by [`request_site::foreign_request`]. /// /// Workspace scripts and flows are not refused, by choice, so that GET links to them keep /// working. That is a scope decision, not a safety property: they still take attacker-chosen @@ -35,9 +36,10 @@ use crate::triggers::trigger_helpers::RunnableId; /// way to authenticate, since it cannot set headers. The checks run in `extract_token`'s /// order, header before cookie, because that is the order it resolves them in: a request /// carrying both a cookie and `token=` authenticates on the cookie and is therefore still -/// ambient, which is also why a valid `token=` link opened cross-site while signed in is -/// refused. -pub struct CrossSiteGetGuard(Option); +/// ambient, which is also why a valid `token=` link opened from another site while signed in +/// is refused. Other methods never get here with the cookie: `extract_token` sets it aside on +/// a state-changing request from another origin. +pub struct CrossSiteGetGuard(Option); impl CrossSiteGetGuard { pub fn script_runnable( @@ -48,24 +50,12 @@ impl CrossSiteGetGuard { let (Some(signal), RunnableId::HubScript(_)) = (&self.0, &runnable_id) else { return Ok(runnable_id); }; - // The `Referer` leg is the one that can misfire, on a request that really was - // same-host: it compares against the hosts the backend can see, and a proxy that - // rewrites `Host` without setting `X-Forwarded-Host` leaves none of them matching - // what the browser addressed. Name the comparison so that shows up as a - // misconfiguration rather than as an unexplained 403. - if let CrossSite::RefererMismatch { referer, instance_hosts } = signal { - tracing::warn!( - referer_host = %referer, - ?instance_hosts, - "refusing a cross-site GET Hub script run inferred from Referer; if the request \ - was same-host, set `X-Forwarded-Host` on the proxy or configure `BASE_URL`" - ); - } + signal.log("refusing a GET Hub script run on the session cookie"); Err(Error::PermissionDenied( - "a cross-site GET request cannot run a Hub script with the session cookie, which takes \ - precedence over a `token` query parameter: pass the token in the `Authorization` \ - header, or open the link from the instance itself or from a browser with no Windmill \ - session" + "a GET request from another site cannot run a Hub script with the session cookie, \ + which takes precedence over a `token` query parameter: pass the token in the \ + `Authorization` header, or open the link from the instance itself or from a browser \ + with no Windmill session" .to_string(), )) } @@ -81,7 +71,7 @@ impl FromRequestParts for CrossSiteGetGuard { if parts.method != Method::GET { return Ok(CrossSiteGetGuard(None)); } - let Some(signal) = cross_site_signal(parts) else { + let Some(signal) = request_site::foreign_request(&parts.headers, &parts.uri) else { return Ok(CrossSiteGetGuard(None)); }; @@ -101,154 +91,3 @@ impl FromRequestParts for CrossSiteGetGuard { Ok(CrossSiteGetGuard(has_session_cookie.then_some(signal))) } } - -enum CrossSite { - Declared, - RefererMismatch { referer: String, instance_hosts: Vec }, -} - -fn cross_site_signal(parts: &Parts) -> Option { - if let Some(site) = parts.headers.get("sec-fetch-site") { - return site - .as_bytes() - .eq_ignore_ascii_case(b"cross-site") - .then_some(CrossSite::Declared); - } - // Fetch Metadata rides only on potentially trustworthy URLs, so an instance served - // over plain http never receives `Sec-Fetch-Site` (nor does Safari before 16.4) while - // the cookie, not being `Secure` there either, still arrives. `Referer` is the only - // other thing a top-level GET navigation carries — `Origin` is not sent on one — so it - // is all that is left there, and it is weak: the default `strict-origin-when-cross- - // origin` policy already drops `Referer` on an https-to-http downgrade, so an https - // attacker page pointing a victim at a plain-http instance sends neither header. This - // leg catches an http-served attacker page and pre-16.4 Safari on https; the guard is - // load-bearing on https and best-effort at best on plain http. An absent `Referer` - // reads as not cross-site, matching how `Sec-Fetch-Site: none` (a bookmark, a typed - // URL) is treated. - let referer = referer_host(parts)?; - let instance_hosts: Vec = instance_hosts(parts).collect(); - (!instance_hosts - .iter() - .any(|host| host.eq_ignore_ascii_case(&referer))) - .then_some(CrossSite::RefererMismatch { referer, instance_hosts }) -} - -/// Every host a legitimate same-host request can name. `Host` alone is not enough: a -/// reverse proxy that forwards without preserving it (nginx `proxy_pass` with no -/// `proxy_set_header Host $host`) hands the backend the upstream's name, which no browser -/// `Referer` will ever match. None of these is browser-settable on a navigation — a -/// navigation carries no custom headers, and `BASE_URL` is instance config — so widening -/// the accepted set costs nothing. -fn instance_hosts(parts: &Parts) -> impl Iterator { - let base_url = windmill_common::BASE_URL.load(); - [ - request_host(parts), - header_host(parts, "x-forwarded-host"), - Url::parse(base_url.as_str()) - .ok() - .and_then(|url| url.host_str().map(str::to_owned)), - ] - .into_iter() - .flatten() -} - -fn referer_host(parts: &Parts) -> Option { - let referer = parts.headers.get(header::REFERER)?.to_str().ok()?; - Url::parse(referer).ok()?.host_str().map(str::to_owned) -} - -fn request_host(parts: &Parts) -> Option { - if let Some(host) = parts.uri.host() { - return Some(host.to_owned()); - } - header_host(parts, header::HOST) -} - -fn header_host(parts: &Parts, name: impl header::AsHeaderName) -> Option { - host_of(parts.headers.get(name)?.to_str().ok()?) -} - -/// The host in a `Host`-shaped header value: `host[:port]`, where `host` may be a bracketed -/// IPv6 literal, and where a chain of proxies appends to `X-Forwarded-Host` so only the -/// first entry is the one the browser addressed. The port is split off by the URL parser -/// rather than by hand-rolling the bracket rules. -fn host_of(value: &str) -> Option { - let host = value.split(',').next()?.trim(); - Url::parse(&format!("http://{host}")) - .ok()? - .host_str() - .map(str::to_owned) -} - -#[cfg(test)] -mod tests { - use super::{cross_site_signal, host_of, CrossSite}; - use axum::http::{request::Parts, Request}; - - fn parts(headers: &[(&str, &str)]) -> Parts { - let mut req = Request::get("/api/w/ws/jobs/run_wait_result/p/hub/1/x"); - for (name, value) in headers { - req = req.header(*name, *value); - } - req.body(()).unwrap().into_parts().0 - } - - #[test] - fn sec_fetch_site_decides_when_present() { - let declared = |site| cross_site_signal(&parts(&[("sec-fetch-site", site)])); - assert!(matches!(declared("cross-site"), Some(CrossSite::Declared))); - for site in ["same-origin", "same-site", "none"] { - assert!(declared(site).is_none(), "{site} is not cross-site"); - } - // The header outranks a `Referer` that disagrees with it. - let with_referer = parts(&[ - ("sec-fetch-site", "same-origin"), - ("host", "windmill.example"), - ("referer", "https://attacker.example/page"), - ]); - assert!(cross_site_signal(&with_referer).is_none()); - } - - #[test] - fn referer_stands_in_when_sec_fetch_site_is_absent() { - let signal = |headers: &[(&str, &str)]| cross_site_signal(&parts(headers)); - assert!(matches!( - signal(&[ - ("host", "windmill.example"), - ("referer", "https://attacker.example/p") - ]), - Some(CrossSite::RefererMismatch { .. }) - )); - // Ports differ between the frontend and the API, and do not make a request cross-site. - assert!(signal(&[ - ("host", "windmill.example:8000"), - ("referer", "http://windmill.example:3000/apps"), - ]) - .is_none()); - // A proxy that rewrote `Host` but forwarded the public name. - assert!(signal(&[ - ("host", "windmill-server.internal"), - ("x-forwarded-host", "windmill.example"), - ("referer", "https://windmill.example/apps"), - ]) - .is_none()); - assert!(signal(&[("host", "windmill.example")]).is_none()); - } - - #[test] - fn host_of_strips_port_brackets_and_proxy_chain() { - assert_eq!(host_of("windmill.example"), Some("windmill.example".into())); - assert_eq!( - host_of("windmill.example:8000"), - Some("windmill.example".into()) - ); - assert_eq!(host_of("[::1]:8000"), Some("[::1]".into())); - assert_eq!(host_of("[::1]"), Some("[::1]".into())); - assert_eq!( - host_of("windmill.example, proxy.internal"), - Some("windmill.example".into()) - ); - assert_eq!(host_of(""), None); - assert_eq!(host_of("not a host"), None); - } -} diff --git a/docs/auth-surface.md b/docs/auth-surface.md index 87a92717d9..e80f59761a 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -5,6 +5,16 @@ Symbols, not line numbers, are cited: they drift less. - **Credential precedence** (`windmill-api-auth/src/auth.rs` `extract_token`): `Authorization: Bearer` → `token` cookie → `?token=` query param. A URL with `?token=` is a credential on every route, but an existing cookie silently wins over it. +- **The cookie counts only on requests from the instance's own origin** + (`windmill-api-auth/src/request_site.rs`). On a non-GET/HEAD/OPTIONS request `extract_token` + sets the cookie aside unless `Sec-Fetch-Site` is `same-origin` or `none`; without that header + (plain http, old Safari), `Origin`, then `Referer`, must name the request's `Host`, + `X-Forwarded-Host` or `BASE_URL` host (ports ignored); with none of the three the request is + not from a browser page and keeps the cookie. A set-aside request authenticates as if it had + no cookie: on its `?token=` if any, else anonymously on optional-auth routes, else 403. GETs + are not covered except by `CrossSiteGetGuard` (Hub script runs). `same-site` is foreign: the + `SameSite=Lax` cookie reaches every sibling subdomain. `SESSION_COOKIE_TRUSTED_ORIGINS` + (comma-separated hosts or origins, `*` for all) admits named sites for both checks. - **`AUTH_CACHE`** caches a token's identity for 120 s. Deleting a token row purges it only for some rows: the delete trigger (`notify_token_invalidation`, last replaced in `migrations/20261106141303_mcp_oauth_token_delete_revokes_grant.up.sql`) notifies every