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 <noreply@anthropic.com>

* perf: refresh folders once per draft listing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep the identity's groups when refreshing draft folders

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ruben Fiszel
2026-12-01 22:27:14 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 9a3fd388ec
commit b0f7573a66
4 changed files with 111 additions and 13 deletions
+54
View File
@@ -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<Postgres>,
) -> 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::<Value>(&body)?, Value::Null);
Ok(())
}
+6 -2
View File
@@ -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
+3 -3
View File
@@ -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<DB>,
Extension(user_db): Extension<UserDB>,
Extension(webhook): Extension<WebhookShared>,
@@ -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,
+48 -8
View File
@@ -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<Json<Option<DraftForUser>>> {
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<Box<serde_json::value::RawValue>>", 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<ApiAuthed> {
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(());
}
}
}
_ => {}
}