fix: clear cached identities of a deleted workspace on every server

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
hugocasa
2026-12-03 17:50:07 +01:00
co-authored by Claude Opus 5.5
parent 9eda2e1c0c
commit ffc71e1bc8
7 changed files with 97 additions and 4 deletions
@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO notify_event (channel, payload) VALUES ('notify_workspace_auth_reset', $1)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text"
]
},
"nullable": []
},
"hash": "ab0f9cd4e6eaf060d7b05ec7a1deaffa916dd2500f01eda594213207ec864062"
}
+4
View File
@@ -1862,6 +1862,10 @@ async fn process_notify_event(
);
windmill_api::auth::invalidate_token_from_cache(payload);
}
"notify_workspace_auth_reset" => {
tracing::info!("Workspace id {payload} freed, dropping its cached identities");
windmill_api::auth::invalidate_workspace_from_cache(payload);
}
"notify_user_email_change" => {
// `<workspace_id>:<username>`, or `*:<username>` from a `password` change, which
// knows the name but no workspace. Workspace ids can't contain ':'.
+8
View File
@@ -152,6 +152,14 @@ pub fn invalidate_token_from_cache(token_prefix: &str) {
);
}
/// Drops every identity resolved under `w_id`, in this process. Call it when the id is freed:
/// an entry describes the caller in the workspace that held the id, and must not carry over to
/// the next workspace created under it. `notify_workspace_auth_reset` reaches the other servers.
pub fn invalidate_workspace_from_cache(w_id: &str) {
AUTH_CACHE.retain(|(workspace_id, _), _| workspace_id != w_id);
crate::API_AUTHED_CACHE.retain(|(workspace_id, _, _), _| workspace_id != w_id);
}
#[derive(Clone)]
pub struct ExpiringAuthCache {
pub authed: ApiAuthed,
@@ -1362,3 +1362,57 @@ async fn archiving_a_workspace_makes_its_public_apps_private(
);
Ok(())
}
/// A deleted workspace's id can be created again at once. What a token was resolved to in the
/// deleted workspace must not apply to the new one.
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
async fn recreated_workspace_id_does_not_inherit_cached_identity(
db: Pool<Postgres>,
) -> anyhow::Result<()> {
initialize_tracing().await;
sqlx::query("UPDATE password SET username = 'test-user-2' WHERE email = 'test2@windmill.dev'")
.execute(&db)
.await?;
let server = ApiServer::start(db.clone()).await?;
let api = format!("http://localhost:{}/api", server.addr.port());
let w_id = "reused-id-auth-cache";
let create_with_member = |is_admin: bool| {
let api = api.clone();
async move {
let resp = authed(client().post(format!("{api}/workspaces/create")))
.json(&json!({"id": w_id, "name": w_id}))
.send()
.await?;
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
let resp = authed(client().post(format!("{api}/w/{w_id}/workspaces/add_user")))
.json(&json!({"email": "test2@windmill.dev", "is_admin": is_admin, "operator": false}))
.send()
.await?;
assert_eq!(resp.status(), 201, "{}", resp.text().await?);
anyhow::Ok(())
}
};
let member_is_admin = || async {
let whoami: serde_json::Value = client()
.get(format!("{api}/w/{w_id}/users/whoami"))
.header("Authorization", "Bearer SECRET_TOKEN_2")
.send()
.await?
.error_for_status()?
.json()
.await?;
anyhow::Ok(whoami["is_admin"].as_bool().unwrap())
};
create_with_member(true).await?;
assert!(member_is_admin().await?);
let resp = authed(client().delete(format!("{api}/workspaces/delete/{w_id}")))
.send()
.await?;
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
create_with_member(false).await?;
assert!(!member_is_admin().await?);
Ok(())
}
@@ -1451,7 +1451,17 @@ pub(crate) async fn delete_workspace(
None,
)
.await?;
// The id is free once this commits, and a workspace created under it next must not inherit
// what callers were resolved to here: every server drops those identities. A rename does not
// free the old id, which stays archived until deleted here.
sqlx::query!(
"INSERT INTO notify_event (channel, payload) VALUES ('notify_workspace_auth_reset', $1)",
&w_id
)
.execute(&mut *tx)
.await?;
tx.commit().await?;
windmill_api_auth::auth::invalidate_workspace_from_cache(&w_id);
// Physical ducklake-namespace cleanup, post-commit, from the pre-read snapshot: fork
// namespaces are deterministic from (id, lake), so an orphan would silently REATTACH to a
+3 -3
View File
@@ -1,5 +1,5 @@
pub use windmill_api_auth::auth::{
get_end_user_email, invalidate_token_from_cache, list_tokens_internal,
transform_old_scope_to_new_scope, AuthCache, ExpiringAuthCache, OptTokened, Tokened,
TruncatedTokenWithEmail,
get_end_user_email, invalidate_token_from_cache, invalidate_workspace_from_cache,
list_tokens_internal, transform_old_scope_to_new_scope, AuthCache, ExpiringAuthCache,
OptTokened, Tokened, TruncatedTokenWithEmail,
};
+4 -1
View File
@@ -20,7 +20,10 @@ Symbols, not line numbers, are cited: they drift less.
`migrations/20261106141303_mcp_oauth_token_delete_revokes_grant.up.sql`) notifies every
instance for `session` and `mcp-oauth-*` rows, within the notify poll (≤10 s), and
`delete_token` also evicts at once on the instance serving it. Other labels deleted by other
paths stay cached until the TTL, which ignores the token's own expiration.
paths stay cached until the TTL, which ignores the token's own expiration. Deleting a workspace
drops every entry under its id (and `API_AUTHED_CACHE`'s), at once on the instance serving it
and elsewhere through `notify_workspace_auth_reset` within the poll, since the id can be created
again. A rename frees no id: the old one stays archived until deleted.
- **Deleting a live MCP OAuth access token revokes its refresh grant**, by whatever path: the same
trigger marks the `mcp_oauth_refresh_token` row issued with it (`access_token_hash`) revoked, so
only that client's connection ends. A token past its expiration keeps its grant, since the