mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-20 16:09:26 +00:00
fix: revoke MCP OAuth grants when their token or user goes away (#12282)
* fix: revoke an MCP OAuth refresh grant when its access token is deleted Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: lock the access token before the refresh grant, evict expired mcp tokens Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: revoke all MCP OAuth grants when a user is disabled, deleted or removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: take the mcp grant lock before writing a user's tokens Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: lock the user's password row as the mcp grant lock Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: revoke tokens before grants, lock the account before the membership Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: update ee-repo-ref to 968437f1f4e912b26b828f88f41dfcfa9bfac6f5 This commit updates the EE repository reference after PR #969 was merged in windmill-ee-private. Previous ee-repo-ref: 65642604e613c7c71cbb74c4f7a38589ac943ed3 New ee-repo-ref: 968437f1f4e912b26b828f88f41dfcfa9bfac6f5 Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com> Co-authored-by: Ruben Fiszel <ruben@windmill.dev>
This commit is contained in:
co-authored by
Claude Opus 5.5
windmill-internal-app[bot]
Ruben Fiszel
parent
e4671f7d3f
commit
0c87c651f4
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "DELETE FROM token WHERE email = $1 AND label LIKE 'mcp-oauth-%'\n AND ($2::varchar IS NULL OR workspace_id = $2)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Varchar"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "02ee3702cfe687d4e69cffb816201ae3910c8573f553156fdec8ff391f73f67a"
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "DELETE FROM mcp_oauth_refresh_token WHERE user_email = $1\n AND ($2::varchar IS NULL OR workspace_id = $2)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Varchar"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "2db37efe8087ff8c384e03ef92f4a3ad095a0d698d70a30e8054213c9193c1de"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT 1 AS locked FROM token WHERE token_hash =\n (SELECT access_token_hash FROM mcp_oauth_refresh_token WHERE refresh_token = $1)\n FOR UPDATE",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "locked",
|
||||
"type_info": "Int4"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "844c90d8519b26e8517231d7be34c5b2daf31f242df5820478c7f80440f682bf"
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "DELETE FROM mcp_oauth_server_code WHERE user_email = $1\n AND ($2::varchar IS NULL OR workspace_id = $2)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Varchar"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "8a81c05028d4edd3179c5ee35911bb2821eaf6c16ae17b8b2f635d4618ec1982"
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "WITH revoked AS (\n DELETE FROM token WHERE email = $1 AND label LIKE 'mcp-oauth-%' RETURNING token_prefix\n ), refresh AS (\n DELETE FROM mcp_oauth_refresh_token WHERE user_email = $1\n ), code AS (\n DELETE FROM mcp_oauth_server_code WHERE user_email = $1\n )\n INSERT INTO notify_event (channel, payload)\n SELECT 'notify_token_invalidation', token_prefix FROM revoked",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "b7c7384b335a51f7d1abd2c627ea62ec651c5c6eee947540e7ee5dcea4780b37"
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
747a8896c7bd2490063ccfe0c0796aa14b57ab67
|
||||
968437f1f4e912b26b828f88f41dfcfa9bfac6f5
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
DROP INDEX IF EXISTS idx_mcp_oauth_refresh_token_access_token_hash;
|
||||
|
||||
CREATE OR REPLACE FUNCTION notify_token_invalidation()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
IF OLD.label = 'session' AND OLD.email IS NOT NULL THEN
|
||||
INSERT INTO notify_event (channel, payload)
|
||||
VALUES ('notify_token_invalidation', OLD.token_prefix);
|
||||
END IF;
|
||||
RETURN OLD;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql SECURITY DEFINER;
|
||||
@@ -0,0 +1,22 @@
|
||||
-- An expired MCP OAuth token keeps its refresh grant: the expiry sweep deletes it, and its
|
||||
-- client must still be able to refresh.
|
||||
CREATE OR REPLACE FUNCTION notify_token_invalidation()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
IF OLD.label = 'session' AND OLD.email IS NOT NULL THEN
|
||||
INSERT INTO notify_event (channel, payload)
|
||||
VALUES ('notify_token_invalidation', OLD.token_prefix);
|
||||
ELSIF OLD.label LIKE 'mcp-oauth-%' THEN
|
||||
IF COALESCE(OLD.expiration > now(), true) THEN
|
||||
UPDATE mcp_oauth_refresh_token SET revoked = TRUE
|
||||
WHERE access_token_hash = OLD.token_hash;
|
||||
END IF;
|
||||
INSERT INTO notify_event (channel, payload)
|
||||
VALUES ('notify_token_invalidation', OLD.token_prefix);
|
||||
END IF;
|
||||
RETURN OLD;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql SECURITY DEFINER;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_mcp_oauth_refresh_token_access_token_hash
|
||||
ON mcp_oauth_refresh_token(access_token_hash);
|
||||
@@ -0,0 +1,134 @@
|
||||
//! Deleting an MCP OAuth access token revokes its refresh grant, and only that one; an access
|
||||
//! token removed by the expiry sweep keeps its grant refreshable, until its user is disabled.
|
||||
#![cfg(feature = "mcp")]
|
||||
|
||||
use serde_json::json;
|
||||
use sqlx::{Pool, Postgres};
|
||||
|
||||
use windmill_test_utils::*;
|
||||
|
||||
const VERIFIER: &str = "e2e-pkce-verifier-0123456789-0123456789-abcdef";
|
||||
const CHALLENGE: &str = "q9x8Sam6B6iSaQRwyLQdPrK3Ob2wfH1sNsUhYehHwh8";
|
||||
const REDIRECT: &str = "http://localhost:9/cb";
|
||||
|
||||
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
|
||||
async fn test_deleted_mcp_token_cannot_refresh(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
set_jwt_secret().await;
|
||||
let server = ApiServer::start_mcp(db.clone()).await?;
|
||||
let base = format!("http://localhost:{}/api", server.addr.port());
|
||||
let http = reqwest::Client::new();
|
||||
let (http, base) = (&http, &base);
|
||||
|
||||
// Connects a fresh client as the bearer's user; returns (client_id, access, refresh).
|
||||
let connect = |bearer: &'static str| async move {
|
||||
let client_id = http
|
||||
.post(format!("{base}/mcp/oauth/server/register"))
|
||||
.json(&json!({ "client_name": "test", "redirect_uris": [REDIRECT] }))
|
||||
.send()
|
||||
.await?
|
||||
.json::<serde_json::Value>()
|
||||
.await?["client_id"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let code = http
|
||||
.post(format!("{base}/mcp/gateway/oauth/server/approve"))
|
||||
.bearer_auth(bearer)
|
||||
.json(&json!({
|
||||
"client_id": client_id, "redirect_uri": REDIRECT, "scope": "mcp:all", "state": "",
|
||||
"code_challenge": CHALLENGE, "code_challenge_method": "S256", "all_workspaces": true,
|
||||
}))
|
||||
.send()
|
||||
.await?
|
||||
.json::<serde_json::Value>()
|
||||
.await?["code"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let issued = http
|
||||
.post(format!("{base}/mcp/gateway/oauth/server/token"))
|
||||
.form(&[
|
||||
("grant_type", "authorization_code"),
|
||||
("code", &code),
|
||||
("client_id", &client_id),
|
||||
("redirect_uri", REDIRECT),
|
||||
("code_verifier", VERIFIER),
|
||||
])
|
||||
.send()
|
||||
.await?
|
||||
.json::<serde_json::Value>()
|
||||
.await?;
|
||||
anyhow::Ok((
|
||||
client_id,
|
||||
issued["access_token"].as_str().unwrap().to_string(),
|
||||
issued["refresh_token"].as_str().unwrap().to_string(),
|
||||
))
|
||||
};
|
||||
let refresh = |client_id: &str, refresh_token: &str| {
|
||||
http.post(format!("{base}/mcp/gateway/oauth/server/token"))
|
||||
.form(&[
|
||||
("grant_type", "refresh_token"),
|
||||
("refresh_token", refresh_token),
|
||||
("client_id", client_id),
|
||||
])
|
||||
.send()
|
||||
};
|
||||
let expire_and_sweep = |access: String| {
|
||||
let db = db.clone();
|
||||
async move {
|
||||
sqlx::query(
|
||||
"UPDATE token SET expiration = now() - interval '1 second'
|
||||
WHERE token_hash = encode(sha256($1::bytea), 'hex')",
|
||||
)
|
||||
.bind(access.as_bytes())
|
||||
.execute(&db)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM token WHERE expiration <= now()")
|
||||
.execute(&db)
|
||||
.await?;
|
||||
anyhow::Ok(())
|
||||
}
|
||||
};
|
||||
|
||||
let (deleted_client, deleted_access, deleted_refresh) = connect("SECRET_TOKEN").await?;
|
||||
let (idle_client, idle_access, idle_refresh) = connect("SECRET_TOKEN_2").await?;
|
||||
|
||||
let resp = http
|
||||
.delete(format!(
|
||||
"{base}/users/tokens/delete/{}",
|
||||
&deleted_access[..10]
|
||||
))
|
||||
.bearer_auth("SECRET_TOKEN")
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
let resp = refresh(&deleted_client, &deleted_refresh).await?;
|
||||
assert_eq!(resp.status(), 400);
|
||||
assert_eq!(
|
||||
resp.json::<serde_json::Value>().await?["error"],
|
||||
"invalid_grant"
|
||||
);
|
||||
|
||||
expire_and_sweep(idle_access).await?;
|
||||
let resp = refresh(&idle_client, &idle_refresh).await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
let rotated = resp.json::<serde_json::Value>().await?;
|
||||
|
||||
expire_and_sweep(rotated["access_token"].as_str().unwrap().to_string()).await?;
|
||||
let resp = http
|
||||
.post(format!("{base}/users/update/test2@windmill.dev"))
|
||||
.bearer_auth("SECRET_TOKEN")
|
||||
.json(&json!({ "disabled": true }))
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
let resp = refresh(&idle_client, rotated["refresh_token"].as_str().unwrap()).await?;
|
||||
assert_eq!(
|
||||
resp.status(),
|
||||
400,
|
||||
"a disabled user's idle client still refreshes"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1077,7 +1077,7 @@ async fn test_set_password_revokes_mcp_oauth_grants(db: Pool<Postgres>) -> anyho
|
||||
// A refresh in flight: it holds the grant lock and writes its rotated tokens while the
|
||||
// password change is waiting on that lock.
|
||||
let mut grant = db.begin().await?;
|
||||
sqlx::query("SELECT pg_advisory_xact_lock_shared(hashtext('mcp_oauth_grant:' || $1))")
|
||||
sqlx::query("SELECT 1 FROM password WHERE email = $1 FOR SHARE")
|
||||
.bind("test2@windmill.dev")
|
||||
.execute(&mut *grant)
|
||||
.await?;
|
||||
@@ -1092,8 +1092,8 @@ async fn test_set_password_revokes_mcp_oauth_grants(db: Pool<Postgres>) -> anyho
|
||||
let mut waiting = false;
|
||||
for _ in 0..100 {
|
||||
waiting = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM pg_locks WHERE locktype = 'advisory' AND NOT granted
|
||||
AND database = (SELECT oid FROM pg_database WHERE datname = current_database()))",
|
||||
"SELECT EXISTS(SELECT 1 FROM pg_stat_activity
|
||||
WHERE wait_event_type = 'Lock' AND datname = current_database())",
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
|
||||
@@ -46,7 +46,9 @@ use tracing::Instrument;
|
||||
use windmill_audit::audit_oss::audit_log;
|
||||
use windmill_audit::ActionKind;
|
||||
use windmill_common::audit::AuditAuthor;
|
||||
use windmill_common::auth::{hash_token, safe_token_prefix, TOKEN_PREFIX_LEN};
|
||||
use windmill_common::auth::{
|
||||
hash_token, lock_mcp_oauth_grants, safe_token_prefix, TOKEN_PREFIX_LEN,
|
||||
};
|
||||
use windmill_common::global_settings::{
|
||||
load_value_from_global_settings, parse_max_token_expiration_days,
|
||||
AUTOMATE_USERNAME_CREATION_SETTING, MAX_TOKEN_EXPIRATION_DAYS_SETTING,
|
||||
@@ -1696,6 +1698,7 @@ async fn update_user(
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if d {
|
||||
revoke_mcp_oauth_grants(&mut *tx, &email_to_update, None).await?;
|
||||
// Delete all tokens for immediate session revocation
|
||||
sqlx::query!("DELETE FROM token WHERE email = $1", &email_to_update)
|
||||
.execute(&mut *tx)
|
||||
@@ -1727,6 +1730,7 @@ async fn delete_user(
|
||||
forbid_superadmin_job_token(&db, &authed.email, job_id).await?;
|
||||
let mut tx = db.begin().await?;
|
||||
|
||||
revoke_mcp_oauth_grants(&mut *tx, &email_to_delete, None).await?;
|
||||
sqlx::query!("DELETE FROM token WHERE email = $1", &email_to_delete)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
@@ -2564,6 +2568,7 @@ pub async fn delete_workspace_user_internal(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
authed: Option<&ApiAuthed>, // None for system operations
|
||||
) -> Result<()> {
|
||||
revoke_mcp_oauth_grants(&mut **tx, email_to_delete, Some(w_id)).await?;
|
||||
// Same reasoning as the `extra_perms` sweep below: a freed username must not stay named
|
||||
// anywhere that grants access, tenant lists included.
|
||||
windmill_common::workspaces::remove_datatable_tenant_in_workspace(
|
||||
@@ -2738,6 +2743,19 @@ async fn delete_workspace_user(
|
||||
) -> Result<String> {
|
||||
let mut tx = db.begin().await?;
|
||||
|
||||
// The account row before the membership row, the order `delete_user` takes them in, since
|
||||
// the revoke in `delete_workspace_user_internal` locks it (`lock_mcp_oauth_grants`).
|
||||
if let Some(email) = sqlx::query_scalar!(
|
||||
"SELECT email FROM usr WHERE username = $1 AND workspace_id = $2",
|
||||
username_to_delete,
|
||||
&w_id,
|
||||
)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
{
|
||||
lock_mcp_oauth_grants(&mut *tx, &email, true).await?;
|
||||
}
|
||||
|
||||
// Locked so that the authorization below and the delete it guards see the same row.
|
||||
let target = sqlx::query!(
|
||||
"SELECT email, is_admin FROM usr where username = $1 AND workspace_id = $2 FOR UPDATE",
|
||||
@@ -3992,6 +4010,44 @@ async fn list_tokens(
|
||||
Ok(Json(rows))
|
||||
}
|
||||
|
||||
/// Ends a user's MCP OAuth connections (only those bound to `workspace_id` when given),
|
||||
/// including idle ones whose access token is already gone and codes not yet exchanged.
|
||||
/// Lock the user's `password` row before writing their tokens (see `lock_mcp_oauth_grants`).
|
||||
pub async fn revoke_mcp_oauth_grants(
|
||||
conn: &mut sqlx::PgConnection,
|
||||
email: &str,
|
||||
workspace_id: Option<&str>,
|
||||
) -> Result<()> {
|
||||
lock_mcp_oauth_grants(&mut *conn, email, true).await?;
|
||||
// Separate statements, tokens first: a token delete's trigger locks its token row, then its
|
||||
// grant, and the sibling CTEs of a single statement run in no fixed order.
|
||||
sqlx::query!(
|
||||
"DELETE FROM token WHERE email = $1 AND label LIKE 'mcp-oauth-%'
|
||||
AND ($2::varchar IS NULL OR workspace_id = $2)",
|
||||
email,
|
||||
workspace_id,
|
||||
)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
sqlx::query!(
|
||||
"DELETE FROM mcp_oauth_refresh_token WHERE user_email = $1
|
||||
AND ($2::varchar IS NULL OR workspace_id = $2)",
|
||||
email,
|
||||
workspace_id,
|
||||
)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
sqlx::query!(
|
||||
"DELETE FROM mcp_oauth_server_code WHERE user_email = $1
|
||||
AND ($2::varchar IS NULL OR workspace_id = $2)",
|
||||
email,
|
||||
workspace_id,
|
||||
)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete_token(
|
||||
Extension(db): Extension<DB>,
|
||||
authed: ApiAuthed,
|
||||
@@ -4022,6 +4078,9 @@ async fn delete_token(
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
if !tokens_deleted.is_empty() {
|
||||
windmill_api_auth::invalidate_token_from_cache(&token_prefix);
|
||||
}
|
||||
|
||||
Ok(format!(
|
||||
"deleted {} tokens {:?} with prefix {}",
|
||||
|
||||
@@ -428,7 +428,7 @@ pub async fn oauth_token(
|
||||
};
|
||||
let mut tx = db.begin().await.map_err(db_error)?;
|
||||
if let Some(email) = &owner {
|
||||
crate::users::lock_mcp_oauth_grants(&mut tx, email, false)
|
||||
windmill_common::auth::lock_mcp_oauth_grants(&mut tx, email, false)
|
||||
.await
|
||||
.map_err(db_error)?;
|
||||
}
|
||||
@@ -594,6 +594,21 @@ async fn handle_refresh_token_grant(
|
||||
return Err(OAuthTokenError::invalid_request("client_id is required"));
|
||||
}
|
||||
|
||||
// Deleting the access token revokes this grant from a trigger, locking the token row and
|
||||
// then this one; take them in that same order, or a concurrent delete deadlocks.
|
||||
sqlx::query!(
|
||||
"SELECT 1 AS locked FROM token WHERE token_hash =
|
||||
(SELECT access_token_hash FROM mcp_oauth_refresh_token WHERE refresh_token = $1)
|
||||
FOR UPDATE",
|
||||
refresh_token_value
|
||||
)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("Database error locking MCP access token: {}", e);
|
||||
OAuthTokenError::server_error("Database error")
|
||||
})?;
|
||||
|
||||
// Atomically claim the refresh token by setting used_at in a single UPDATE.
|
||||
let token_row = match sqlx::query_as!(
|
||||
RefreshTokenRow,
|
||||
|
||||
@@ -635,6 +635,7 @@ pub(crate) async fn offboard_global_user(
|
||||
}
|
||||
|
||||
if req.delete_user {
|
||||
windmill_api_users::users::revoke_mcp_oauth_grants(&mut *tx, &email, None).await?;
|
||||
sqlx::query!("DELETE FROM token WHERE email = $1", &email)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
@@ -26,6 +26,7 @@ use serde::Deserialize;
|
||||
use windmill_api_auth::{
|
||||
forbid_elevated_job_token, forbid_superadmin_job_token, require_super_admin,
|
||||
};
|
||||
use windmill_api_users::users::revoke_mcp_oauth_grants;
|
||||
use windmill_audit::audit_oss::audit_log;
|
||||
use windmill_audit::ActionKind;
|
||||
use windmill_common::audit::AuditAuthor;
|
||||
@@ -198,41 +199,6 @@ async fn list_guests(
|
||||
Ok(Json(GuestList { usage, guests }))
|
||||
}
|
||||
|
||||
/// Shared while issuing an MCP OAuth grant, exclusive while revoking: no grant outlives a revoke.
|
||||
pub(crate) async fn lock_mcp_oauth_grants(
|
||||
conn: &mut sqlx::PgConnection,
|
||||
email: &str,
|
||||
exclusive: bool,
|
||||
) -> std::result::Result<(), sqlx::Error> {
|
||||
let q = if exclusive {
|
||||
"SELECT pg_advisory_xact_lock(hashtext('mcp_oauth_grant:' || $1))"
|
||||
} else {
|
||||
"SELECT pg_advisory_xact_lock_shared(hashtext('mcp_oauth_grant:' || $1))"
|
||||
};
|
||||
sqlx::query(q).bind(email).execute(conn).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn revoke_mcp_oauth_grants(tx: &mut sqlx::PgConnection, email: &str) -> Result<()> {
|
||||
lock_mcp_oauth_grants(&mut *tx, email, true).await?;
|
||||
// The token trigger only notifies for sessions, so evict deleted MCP access tokens explicitly.
|
||||
sqlx::query!(
|
||||
"WITH revoked AS (
|
||||
DELETE FROM token WHERE email = $1 AND label LIKE 'mcp-oauth-%' RETURNING token_prefix
|
||||
), refresh AS (
|
||||
DELETE FROM mcp_oauth_refresh_token WHERE user_email = $1
|
||||
), code AS (
|
||||
DELETE FROM mcp_oauth_server_code WHERE user_email = $1
|
||||
)
|
||||
INSERT INTO notify_event (channel, payload)
|
||||
SELECT 'notify_token_invalidation', token_prefix FROM revoked",
|
||||
email
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_password(
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(argon2): Extension<Arc<Argon2<'_>>>,
|
||||
@@ -255,7 +221,7 @@ async fn set_password(
|
||||
.execute(&db)
|
||||
.await?;
|
||||
let mut tx = db.begin().await?;
|
||||
revoke_mcp_oauth_grants(&mut *tx, &email).await?;
|
||||
revoke_mcp_oauth_grants(&mut *tx, &email, None).await?;
|
||||
tx.commit().await?;
|
||||
Ok(res)
|
||||
}
|
||||
@@ -278,7 +244,7 @@ async fn set_password_of_user(
|
||||
.execute(&db)
|
||||
.await?;
|
||||
let mut tx = db.begin().await?;
|
||||
revoke_mcp_oauth_grants(&mut *tx, &email).await?;
|
||||
revoke_mcp_oauth_grants(&mut *tx, &email, None).await?;
|
||||
tx.commit().await?;
|
||||
Ok(res)
|
||||
}
|
||||
@@ -1147,7 +1113,7 @@ async fn reset_password(
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
revoke_mcp_oauth_grants(&mut *tx, &email).await?;
|
||||
revoke_mcp_oauth_grants(&mut *tx, &email, None).await?;
|
||||
|
||||
// Audit log
|
||||
let audit_author = AuditAuthor {
|
||||
|
||||
@@ -83,6 +83,24 @@ pub const CLI_LOGIN_TOKEN_LABEL_PREFIX: &str = "cli-login:";
|
||||
/// through `/users/tokens/create`.
|
||||
pub const REMOTE_DEPLOY_TOKEN_LABEL_PREFIX: &str = "remote-deploy:";
|
||||
|
||||
/// Shared while issuing an MCP OAuth grant, exclusive while revoking: no grant outlives a revoke.
|
||||
/// The lock is the user's `password` row because every path that changes a user locks that row
|
||||
/// before their tokens, the order a refresh takes them in (this row, then its access-token row,
|
||||
/// then its grant). A separate lock taken anywhere in that sequence would deadlock with some path.
|
||||
pub async fn lock_mcp_oauth_grants(
|
||||
conn: &mut sqlx::PgConnection,
|
||||
email: &str,
|
||||
exclusive: bool,
|
||||
) -> std::result::Result<(), sqlx::Error> {
|
||||
let q = if exclusive {
|
||||
"SELECT 1 FROM password WHERE email = $1 FOR UPDATE"
|
||||
} else {
|
||||
"SELECT 1 FROM password WHERE email = $1 FOR SHARE"
|
||||
};
|
||||
sqlx::query(q).bind(email).execute(conn).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `label` belongs to a namespace only the server mints, and which therefore must be
|
||||
/// rejected by `create_token`. Narrower than [`is_user_token`], which also drives label
|
||||
/// editability and expiry notifications and can afford to reserve more: `Ephemeral lsp token`,
|
||||
|
||||
+20
-3
@@ -5,9 +5,26 @@ Symbols, not line numbers, are cited: they drift less.
|
||||
- **Credential precedence** (`windmill-api-auth/src/auth.rs` `extract_token`): `Authorization: Bearer`
|
||||
→ `token` cookie → `?token=` query param. A URL with `?token=` is a credential on every route, but
|
||||
an existing cookie silently wins over it.
|
||||
- **`AUTH_CACHE`** caches a token's identity for 120 s. Deleting a token row does not purge it: the
|
||||
DB trigger (`migrations/20260316000001_token_hash_pk_swap.up.sql`) notifies only for
|
||||
`label = 'session'` rows, and `delete_token` never calls `invalidate_token_from_cache`.
|
||||
- **`AUTH_CACHE`** caches a token's identity for 120 s. Deleting a token row purges it only for
|
||||
some rows: the delete trigger (`notify_token_invalidation`, last replaced in
|
||||
`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.
|
||||
- **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
|
||||
expiry sweep deletes it and its client must still refresh. A client idle past its access
|
||||
token's 7 days therefore has no row left to delete: what ends a user's access calls
|
||||
`revoke_mcp_oauth_grants` (`windmill-api-users`), which also deletes grants without a live
|
||||
token and codes not yet exchanged — a password change or reset, disabling or deleting the
|
||||
account, offboarding, SCIM deactivation and removal, and (for the grants bound to that
|
||||
workspace) removal from a workspace. The grant lock (`lock_mcp_oauth_grants`) is the user's
|
||||
`password` row, shared while issuing a grant and exclusive while revoking, because every path
|
||||
that changes a user locks that row before their tokens: a refresh takes it, then its
|
||||
access-token row, then its grant, the order the trigger also follows. A new path that writes a
|
||||
user's tokens and may revoke must lock that row first too. `leave_workspace` and `leave_instance`
|
||||
delete no tokens and revoke nothing.
|
||||
- **Sessions** are `token` rows with `label='session'` plus the HttpOnly `token` cookie, minted only
|
||||
by `create_session_token` (`windmill-api-users/src/users.rs`). `GET /api/users/refresh_token`
|
||||
mints one for any non-job token but returns plain text, no redirect.
|
||||
|
||||
Reference in New Issue
Block a user