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 <noreply@anthropic.com>
This commit is contained in:
Ruben Fiszel
2026-11-28 18:53:04 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 1a43ff8500
commit 7365bfdf68
6 changed files with 167 additions and 7 deletions
+31 -4
View File
@@ -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);
@@ -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(&[]));
}
}
+5 -2
View File
@@ -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")]
+47
View File
@@ -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<Self> {
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!(
+4
View File
@@ -3530,6 +3530,8 @@ async fn create_resource_type(
Path(w_id): Path<String>,
Json(resource_type): Json<CreateResourceType>,
) -> 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<String> {
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<EditResourceType>,
) -> Result<String> {
check_scopes(&authed, || "resources:write".to_string())?;
use sql_builder::prelude::*;
if let RuleCheckResult::Blocked(msg) = check_deploy_rules(
&w_id,
+5 -1
View File
@@ -85,9 +85,13 @@ pub fn workspaced_service() -> Router {
async fn list_contextual_variables(
Path(w_id): Path<String>,
ApiAuthed { username, email, .. }: ApiAuthed,
authed: ApiAuthed,
Extension(db): Extension<DB>,
) -> JsonResult<Vec<ContextualVariable>> {
// 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(),