From b0f7573a66876423e856ea96f606e4830a32d3c5 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Tue, 1 Dec 2026 22:27:14 +0000 Subject: [PATCH] fix: read drafts in a folder just created through another token (#12778) * fix: read drafts in a folder just created through another token Co-Authored-By: Claude Opus 5.5 * perf: refresh folders once per draft listing Co-Authored-By: Claude Opus 5.5 * fix: keep the identity's groups when refreshing draft folders Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- backend/tests/drafts_new_folder_read.rs | 54 +++++++++++++++++++++ backend/windmill-api-auth/src/auth.rs | 8 +++- backend/windmill-api-groups/src/folders.rs | 6 +-- backend/windmill-api/src/drafts.rs | 56 ++++++++++++++++++---- 4 files changed, 111 insertions(+), 13 deletions(-) create mode 100644 backend/tests/drafts_new_folder_read.rs diff --git a/backend/tests/drafts_new_folder_read.rs b/backend/tests/drafts_new_folder_read.rs new file mode 100644 index 0000000000..a7ad63f7c9 --- /dev/null +++ b/backend/tests/drafts_new_folder_read.rs @@ -0,0 +1,54 @@ +//! A draft read in a folder the caller just created works at once, from any of their tokens. +//! +//! The AI session tools create the folder through one token (a JWT minted per tool call) and +//! read the draft through another, whose identity was cached before the folder existed. The +//! folder has no deployed item yet, so nothing but the caller's folder set can admit the read. + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base"))] +async fn test_draft_read_in_folder_created_through_another_token( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::query( + "INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin) + VALUES (encode(sha256('SECOND_TOKEN_2'::bytea), 'hex'), 'SECOND_TOK', 'SECOND_TOKEN_2', + 'test2@windmill.dev', 'second token', false)", + ) + .execute(&db) + .await?; + let server = ApiServer::start(db.clone()).await?; + let base = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + let client = reqwest::Client::new(); + let read = || { + client + .get(format!("{base}/drafts/get_own/script/f/fresh/hello")) + .header("Authorization", "Bearer SECOND_TOKEN_2") + .send() + }; + + // Caches the second token's identity, without the folder. + assert_eq!(read().await?.status(), 404); + + let resp = client + .post(format!("{base}/folders/create")) + .header("Authorization", "Bearer SECRET_TOKEN_2") + .json(&json!({ "name": "fresh" })) + .send() + .await?; + assert!(resp.status().is_success(), "{}", resp.text().await?); + + let resp = read().await?; + let status = resp.status(); + let body = resp.text().await?; + assert_eq!(status, 200, "draft read in the new folder refused: {body}"); + assert_eq!(serde_json::from_str::(&body)?, Value::Null); + Ok(()) +} diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index 9362c3b9f1..86cd21adb2 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -206,8 +206,12 @@ impl AuthCache { } } - pub async fn invalidate(&self, w_id: &str, token: String) { - AUTH_CACHE.remove(&(w_id.to_string(), token)); + /// Drops every cached identity of `email`, whatever token it was resolved from. A change + /// to what the user can reach must reach all of them: the AI session tools act through a + /// JWT minted from the caller's cached identity, so the token presenting the change is + /// not the one that will present the next request. + pub fn invalidate_user(&self, email: &str) { + AUTH_CACHE.retain(|_, cached| cached.authed.email != email); } /// `client_ip` is the address of the request presenting `token` (`ClientIp`), `None` outside diff --git a/backend/windmill-api-groups/src/folders.rs b/backend/windmill-api-groups/src/folders.rs index ddf121b4d8..36a26f9cd1 100644 --- a/backend/windmill-api-groups/src/folders.rs +++ b/backend/windmill-api-groups/src/folders.rs @@ -17,7 +17,7 @@ use lazy_static::lazy_static; use regex::Regex; use windmill_api_auth::{ build_scope_path_filter, build_scope_path_predicate, check_scopes, ApiAuthed, AuthCache, - ScopePathFilter, Tokened, + ScopePathFilter, }; use windmill_audit::audit_oss::{audit_log, AuditAuthorable}; use windmill_audit::ActionKind; @@ -263,7 +263,6 @@ lazy_static! { async fn create_folder( authed: ApiAuthed, - Tokened { token }: Tokened, Extension(db): Extension, Extension(user_db): Extension, Extension(webhook): Extension, @@ -295,7 +294,6 @@ async fn create_folder( ))); } check_name_conflict(&mut tx, &w_id, &ng.name).await?; - cache.invalidate(&w_id, token).await; let owner = username_to_permissioned_as(&authed.username); let owners = ng.owners.unwrap_or_else(|| vec![owner.clone()]); let owners = if owners.contains(&owner) { @@ -394,6 +392,8 @@ async fn create_folder( .await?; tx.commit().await?; + // After the commit: a request resolving the identity in between would cache the old folders. + cache.invalidate_user(&authed.email); handle_deployment_metadata( &authed.email, diff --git a/backend/windmill-api/src/drafts.rs b/backend/windmill-api/src/drafts.rs index 2a9bc2a28b..ea46c93e7f 100644 --- a/backend/windmill-api/src/drafts.rs +++ b/backend/windmill-api/src/drafts.rs @@ -154,6 +154,19 @@ async fn list_drafts( // otherwise the broadened listing would disclose the path/summary/authors // of items the caller can't see. Unreadable rows are dropped, mirroring the // `require_can_read_path` gate on `/drafts/get`. + // The folder set is refreshed once here, so the per-row read checks need not each + // refresh it for every draft in a folder the caller cannot read. + let unknown_folder = rows.iter().find(|row| { + !row.mine + && row.path.strip_prefix("f/").is_some_and(|rest| { + let folder = rest.split('/').next().unwrap_or_default(); + !authed.folders.iter().any(|(name, _, _)| name == folder) + }) + }); + let authed = match unknown_folder { + Some(_) => with_current_folders(authed, &w_id, &db).await?, + None => authed, + }; let mut out = Vec::with_capacity(rows.len()); for mut row in rows { if row.mine { @@ -177,7 +190,7 @@ async fn list_drafts( // `require_can_read_path` denies with `NotFound` (it hides existence) // and, for some paths, `NotAuthorized` — both mean "not visible to the // caller", so drop the row. Any other error is a real failure. - match require_can_read_path(&authed, &user_db, &w_id, row.kind, &row.path).await { + match require_can_read_path(&authed, None, &user_db, &w_id, row.kind, &row.path).await { Ok(()) => { row.can_write = false; out.push(row); @@ -574,7 +587,9 @@ async fn update_draft( // answer whether an item was moved away from a path they only guessed at. Err(Error::NotAuthorized(e)) if moved_to.is_some() => { return Err(Error::NotAuthorized( - match require_can_read_path(&authed, &user_db, &w_id, kind, url_path).await { + match require_can_read_path(&authed, Some(&db), &user_db, &w_id, kind, url_path) + .await + { Ok(()) => { "this draft's item was moved to a path you cannot write".to_string() } @@ -734,7 +749,9 @@ async fn update_draft( // module. Without it, discarding at a guessed path reads `draft_move`. let disclosed = match moved_to { Some(dest) => { - match require_can_read_path(&authed, &user_db, &w_id, kind, &dest).await { + match require_can_read_path(&authed, Some(&db), &user_db, &w_id, kind, &dest) + .await + { Ok(()) => Some(dest), Err(Error::NotFound(_)) | Err(Error::NotAuthorized(_)) @@ -1518,7 +1535,7 @@ async fn get_draft_for_user( "drafts for this item kind are private to their owner".to_string(), )); } - require_can_read_path(&authed, &user_db, &w_id, kind, path).await?; + require_can_read_path(&authed, Some(&db), &user_db, &w_id, kind, path).await?; // Username -> email, scoped to the workspace. None signals "fetch the // legacy NULL-email row" (distinct from a username with no draft, which @@ -1577,7 +1594,7 @@ async fn get_own_draft( Path((w_id, kind, path)): Path<(String, UserDraftItemKind, windmill_common::utils::StripPath)>, ) -> Result>> { let path = path.to_path(); - require_can_read_path(&authed, &user_db, &w_id, kind, path).await?; + require_can_read_path(&authed, Some(&db), &user_db, &w_id, kind, path).await?; let row = sqlx::query_as!( DraftForUser, r#"SELECT value as "value!: sqlx::types::Json>", created_at @@ -1654,8 +1671,7 @@ pub(crate) async fn require_can_write_path( if has_write(authed) { return Ok(()); } - let refreshed = - windmill_api_auth::maybe_refresh_folders(path, w_id, authed.clone(), db).await; + let refreshed = with_current_folders(authed.clone(), w_id, db).await?; if has_write(&refreshed) { return Ok(()); } @@ -1700,6 +1716,17 @@ pub(crate) async fn require_can_write_path( ))) } +/// `authed` with its folder set re-read, for a folder created since the identity was cached. +/// Its groups are kept, not re-read: they can be narrower than the stored memberships (an +/// external IdP token carries only the managed groups it names), and folders reached through a +/// stored group the identity does not hold must stay out. +async fn with_current_folders(authed: ApiAuthed, w_id: &str, db: &DB) -> Result { + let folders = + windmill_common::auth::get_folders_for_user(w_id, &authed.username, &authed.groups, db) + .await?; + Ok(ApiAuthed { folders, ..authed }) +} + /// Resolves to `Ok(())` if `authed` can read at `path`. Three layers: /// 1. admin → always. /// 2. Path-prefix match against own `u/{username}`, a group in `authed.groups`, or any @@ -1714,8 +1741,12 @@ pub(crate) async fn require_can_write_path( /// deployed content, so an operator can view a collaborator's draft for the /// cross-user kinds they can already read, while never writing one. Drawer /// kinds never reach this (`get_draft_for_user` rejects them up front). +/// +/// `refresh_from` re-reads the folder set when `path`'s folder is missing from it; a caller +/// checking many paths passes `None` after refreshing `authed` once itself. async fn require_can_read_path( authed: &ApiAuthed, + refresh_from: Option<&DB>, user_db: &UserDB, w_id: &str, kind: UserDraftItemKind, @@ -1734,9 +1765,18 @@ async fn require_can_read_path( "g" if authed.groups.iter().any(|g| g == parts[1]) => return Ok(()), "f" => { let folder = parts[1]; - if authed.folders.iter().any(|(name, _, _)| name == folder) { + let can_read = |a: &ApiAuthed| a.folders.iter().any(|(name, _, _)| name == folder); + if can_read(authed) { return Ok(()); } + // As `require_can_write_path` does: a folder created since the identity was + // cached has no deployed row for the probe below, so only a refresh finds it. + if let Some(db) = refresh_from { + let refreshed = with_current_folders(authed.clone(), w_id, db).await?; + if can_read(&refreshed) { + return Ok(()); + } + } } _ => {} }