From 7365bfdf68a3cdb42c25f6a0b7053eec22f64752 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sat, 28 Nov 2026 18:53:04 +0000 Subject: [PATCH] fix: token scope matching cleanups Scope matching and a few missing scope checks on resource and variable routes. Co-Authored-By: Claude Opus 5.5 --- backend/windmill-api-auth/src/lib.rs | 35 ++++++++- .../windmill-api/src/explicit_credential.rs | 75 +++++++++++++++++++ backend/windmill-api/src/lib.rs | 7 +- backend/windmill-common/src/scopes.rs | 47 ++++++++++++ backend/windmill-store/src/resources.rs | 4 + backend/windmill-store/src/variables.rs | 6 +- 6 files changed, 167 insertions(+), 7 deletions(-) create mode 100644 backend/windmill-api/src/explicit_credential.rs diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index e75732202a..f75a3fd2d5 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -465,7 +465,7 @@ where { if let Some(scopes) = authed.scopes.as_ref() { let mut is_scoped_token = false; - let required_scope = ScopeDefinition::from_scope_string(&required())?; + let required_scope = ScopeDefinition::from_required_scope_string(&required())?; for scope in scopes { if !scope.starts_with("if_jobs:filter_tags:") { if !is_scoped_token { @@ -473,7 +473,7 @@ where } match ScopeDefinition::from_scope_string(scope) { - Ok(scope) if scope.includes(&required_scope) => return Ok(()), + Ok(scope) if scope.grants(&required_scope) => return Ok(()), _ => {} } } @@ -807,11 +807,11 @@ pub fn build_scope_path_predicate( return true; } let required = - match ScopeDefinition::from_scope_string(&format!("{}:{}:{}", domain, action, path)) { + match ScopeDefinition::from_required_scope_string(&format!("{domain}:{action}:{path}")) { Ok(r) => r, Err(_) => return false, }; - parsed.iter().any(|s| s.includes(&required)) + parsed.iter().any(|s| s.grants(&required)) } } @@ -1944,6 +1944,33 @@ mod tests { assert!(require_owner_of_path(&alice, "u/alice/script").is_ok()); } + #[test] + fn check_scopes_reads_the_required_path_literally() { + let authed = authed_with_scopes(Some(vec![ + "jobs:run:scripts:u/alice/ping", + "resources:read:f/team/*", + ])); + assert!(check_scopes(&authed, || "jobs:run:scripts:u/alice/ping".into()).is_ok()); + assert!(check_scopes(&authed, || "resources:read:f/team/db".into()).is_ok()); + for required in [ + "jobs:run:scripts:hub/1/x,u/alice/ping", + "jobs:run:scripts:hub/1/x,*", + "jobs:run:scripts:*", + "jobs:run:scripts:u/*", + "resources:read:CUSTOM_INSTANCE_DB/x,f/team/db", + "resources:read:*", + "resources:read:f/*", + ] { + assert!( + check_scopes(&authed, || required.to_string()).is_err(), + "{required}" + ); + } + let allowed = build_scope_path_predicate(&authed, "resources", "read"); + assert!(!allowed("x,f/team/db")); + assert!(!allowed("*")); + } + #[test] fn predicate_no_scopes_allows_all() { let authed = authed_with_scopes(None); diff --git a/backend/windmill-api/src/explicit_credential.rs b/backend/windmill-api/src/explicit_credential.rs new file mode 100644 index 0000000000..13fb95df99 --- /dev/null +++ b/backend/windmill-api/src/explicit_credential.rs @@ -0,0 +1,75 @@ +/* + * 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. + */ + +use axum::http::header; +use windmill_common::error::Error; +use windmill_common::users::COOKIE_NAME; + +/// For a GET route that acts (posts a message, signs a link) rather than reads: refuses a +/// request that would authenticate on the session cookie, which a browser attaches to a +/// cross-site navigation. Its callers are jobs and scripts, which send a bearer header. +pub async fn require_explicit_credential( + req: axum::extract::Request, + next: axum::middleware::Next, +) -> axum::response::Response { + use axum::response::IntoResponse; + if authenticates_on_session_cookie(req.headers()) { + return Error::PermissionDenied( + "this route does not accept the session cookie: pass a token in the \ + `Authorization` header" + .to_string(), + ) + .into_response(); + } + next.run(req).await +} + +/// Mirrors `extract_token`: a bearer header wins, and otherwise a session cookie is used +/// before any `token` query parameter. +fn authenticates_on_session_cookie(headers: &axum::http::HeaderMap) -> bool { + let has_bearer = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.starts_with("Bearer ")); + !has_bearer + && headers + .get_all(header::COOKIE) + .iter() + .filter_map(|h| h.to_str().ok()) + .flat_map(|h| h.split(';')) + .filter_map(|c| tower_cookies::Cookie::parse_encoded(c.trim()).ok()) + .any(|c| c.name() == COOKIE_NAME) +} + +#[cfg(test)] +mod tests { + use super::authenticates_on_session_cookie; + use axum::http::HeaderMap; + + fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap { + let mut map = HeaderMap::new(); + for (k, v) in pairs { + map.append(*k, v.parse().unwrap()); + } + map + } + + #[test] + fn session_cookie_is_refused_unless_a_bearer_header_wins() { + let cookie = + |pairs: &[(&'static str, &str)]| authenticates_on_session_cookie(&headers(pairs)); + assert!(cookie(&[("cookie", "a=b; token=abc")])); + assert!(!cookie(&[ + ("cookie", "token=abc"), + ("authorization", "Bearer xyz") + ])); + assert!(!cookie(&[("cookie", "other=abc")])); + assert!(!cookie(&[("authorization", "Bearer xyz")])); + assert!(!cookie(&[])); + } +} diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index e3d5b2a717..7794653bf5 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -90,6 +90,7 @@ mod azure_proxy_oss; mod capture; mod concurrency_groups; mod csrf; +mod explicit_credential; mod db; mod db_health; mod dbt; @@ -1058,11 +1059,13 @@ pub async fn run_server( }) .route( "/w/{workspace_id}/jobs/slack_approval/{job_id}", - get(slack_approvals::request_slack_approval), + get(slack_approvals::request_slack_approval) + .route_layer(axum::middleware::from_fn(explicit_credential::require_explicit_credential)), ) .route( "/w/{workspace_id}/jobs/teams_approval/{job_id}", - get(teams_approvals_oss::request_teams_approval), + get(teams_approvals_oss::request_teams_approval) + .route_layer(axum::middleware::from_fn(explicit_credential::require_explicit_credential)), ) .nest("/w/{workspace_id}/github_app", { #[cfg(feature = "enterprise")] diff --git a/backend/windmill-common/src/scopes.rs b/backend/windmill-common/src/scopes.rs index 8549e673ba..bf834a9968 100644 --- a/backend/windmill-common/src/scopes.rs +++ b/backend/windmill-common/src/scopes.rs @@ -93,6 +93,24 @@ impl ScopeDefinition { } } + /// Parses the scope an operation on one item needs. Its path is taken whole: a `,` or + /// `*` in a request path is part of the name, not a list or a pattern, so it must not be + /// read with the grant grammar of [`Self::from_scope_string`]. + pub fn from_required_scope_string(scope: &str) -> Result { + let mut def = Self::from_scope_string(scope)?; + if def.resource.is_some() { + let path = scope.rsplit(':').next().unwrap_or_default(); + def.resource = Some(vec![path.to_string()]); + } + Ok(def) + } + + /// Whether this grant covers `required`, a scope parsed with + /// [`Self::from_required_scope_string`]. Only the grant side is read as a pattern. + pub fn grants(&self, required: &ScopeDefinition) -> bool { + scope_contains(self, required) + } + pub fn as_string(&self) -> String { match (&self.kind, &self.resource) { (Some(kind), Some(resource)) => { @@ -514,6 +532,15 @@ pub fn scope_contains(caller: &ScopeDefinition, requested: &ScopeDefinition) -> } match (&caller.resource, &requested.resource) { + // A `resources:` pattern also resolves the variables it matches + // (`check_resource_var_ref_scope`), which a pathless `resources:` scope does not, + // so the pattern is not narrower than it. + (None, Some(requested_resources)) + if caller.domain == "resources" + && requested_resources.iter().any(|r| r.contains('*')) => + { + false + } // Caller is unrestricted on resources: covers everything. (None, _) => true, // Caller is resource-restricted but the request is not: broader, unless the @@ -726,6 +753,26 @@ mod job_token_scopes_tests { ); } + #[test] + fn pathless_resources_scope_does_not_contain_patterns() { + let s = |x: &str| ScopeDefinition::from_scope_string(x).unwrap(); + let contains = |caller: &str, requested: &str| scope_contains(&s(caller), &s(requested)); + for requested in ["resources:read:*", "resources:read:f/a/*"] { + assert!(!contains("resources:read", requested)); + assert!(!contains("resources:write", requested)); + } + assert!(contains("resources:read", "resources:read:f/a/b")); + assert!(contains("resources:write:*", "resources:read:f/a/*")); + assert!(contains("variables:read", "variables:read:f/a/*")); + assert_eq!( + intersect_job_token_scopes( + Some(&v(&["resources:read"])), + Some(&v(&["resources:read:*"])) + ), + Some(v(&["resources:read"])) + ); + } + #[test] fn empty_effective_scopes_mint_a_scoped_token() { assert_eq!( diff --git a/backend/windmill-store/src/resources.rs b/backend/windmill-store/src/resources.rs index 01ff46bd1d..fd5ae7958c 100644 --- a/backend/windmill-store/src/resources.rs +++ b/backend/windmill-store/src/resources.rs @@ -3530,6 +3530,8 @@ async fn create_resource_type( Path(w_id): Path, Json(resource_type): Json, ) -> Result<(StatusCode, String)> { + // Resource types are shared by the whole workspace, so a path-scoped token cannot write them. + check_scopes(&authed, || "resources:write".to_string())?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( &w_id, AuditAuthorable::username(&authed), @@ -3641,6 +3643,7 @@ async fn delete_resource_type( Path((w_id, name)): Path<(String, String)>, ) -> Result { require_admin(authed.is_admin, &authed.username)?; + check_scopes(&authed, || "resources:write".to_string())?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( &w_id, AuditAuthorable::username(&authed), @@ -3705,6 +3708,7 @@ async fn update_resource_type( Path((w_id, name)): Path<(String, String)>, Json(ns): Json, ) -> Result { + check_scopes(&authed, || "resources:write".to_string())?; use sql_builder::prelude::*; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( &w_id, diff --git a/backend/windmill-store/src/variables.rs b/backend/windmill-store/src/variables.rs index aff754e3c1..dafef639a7 100644 --- a/backend/windmill-store/src/variables.rs +++ b/backend/windmill-store/src/variables.rs @@ -85,9 +85,13 @@ pub fn workspaced_service() -> Router { async fn list_contextual_variables( Path(w_id): Path, - ApiAuthed { username, email, .. }: ApiAuthed, + authed: ApiAuthed, Extension(db): Extension, ) -> JsonResult> { + // The list carries the workspace's environment variables with their values, which + // belong to no single path. + check_scopes(&authed, || "variables:read".to_string())?; + let ApiAuthed { username, email, .. } = authed; Ok(Json( get_reserved_variables( &db.into(),