From 51e9017c67481e334c529387db442be2002a287c Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Fri, 27 Nov 2026 15:24:34 +0000 Subject: [PATCH] feat: flag risky tokens and add a superadmin token review (#12693) * feat: flag risky tokens in the tokens drawer and add a superadmin token review Co-Authored-By: Claude Opus 5.5 * fix: load the whole token review at once and pin the risk rules in a test Co-Authored-By: Claude Opus 5.5 * fix: a job tag filter alone does not narrow a privileged token Co-Authored-By: Claude Opus 5.5 * fix: flag the rights a token carries, not the rights of its owner Co-Authored-By: Claude Opus 5.5 * feat: flag tokens that work in every workspace and filter the review by flag Co-Authored-By: Claude Opus 5.5 * perf: compute token risks in a view and page the review with a cursor Co-Authored-By: Claude Opus 5.5 * fix: trust only reserved labels or short lifetimes as server-managed, keep the review cursor on raw rows Co-Authored-By: Claude Opus 5.5 * fix: leave a day of clock skew on the server-managed token lifetime Co-Authored-By: Claude Opus 5.5 * feat: make the instance-wide token list and deletion an EE feature Co-Authored-By: Claude Opus 5.5 * fix: keep the token list EE in the CE image, which builds private Co-Authored-By: Claude Opus 5.5 * chore: update ee-repo-ref to b3c5cbb7edcc42f3db92865896d472cdd8842cf9 This commit updates the EE repository reference after PR #1020 was merged in windmill-ee-private. Previous ee-repo-ref: 51a2425e60989d727d40330bdfa7b2d302224c9c New ee-repo-ref: b3c5cbb7edcc42f3db92865896d472cdd8842cf9 Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: windmill-internal-app[bot] --- ...fe226bf276cac01b052dac82a6e21b00ac833.json | 80 ++++++ ...0c43946b7440bd427d045b8d8b83ba7a3ab26.json | 28 ++ ...ef01f3c1737a1ff5f86c37211ff4aa3290b66.json | 26 ++ ...a09252f353124ddad863100f3598f6241fb1.json} | 32 ++- ...39141ff05981a14029714318b80ae97cc4fa.json} | 32 ++- ...f3d12945450fdfbd9f52e59617660ea20c4c3.json | 23 ++ backend/ee-repo-ref.txt | 2 +- .../20261127105444_token_email_index.down.sql | 1 + .../20261127105444_token_email_index.up.sql | 8 + .../20261127105445_token_risk_view.down.sql | 1 + .../20261127105445_token_risk_view.up.sql | 65 +++++ .../tests/token_risk.rs | 196 ++++++++++++++ backend/windmill-api-users/src/users.rs | 158 +++++++++-- backend/windmill-api-users/src/users_oss.rs | 20 ++ backend/windmill-api/openapi.yaml | 169 ++++++++++++ backend/windmill-api/src/db.rs | 3 + backend/windmill-common/src/auth.rs | 2 + docs/auth-surface.md | 7 + .../components/SuperadminSettingsInner.svelte | 6 +- .../instanceSettings/TokenReview.svelte | 256 ++++++++++++++++++ .../components/settings/TokensTable.svelte | 53 +++- .../src/lib/components/settings/tokenRisks.ts | 60 ++++ 22 files changed, 1172 insertions(+), 56 deletions(-) create mode 100644 backend/.sqlx/query-027dbff1397b96a6fb1cfe9aaaffe226bf276cac01b052dac82a6e21b00ac833.json create mode 100644 backend/.sqlx/query-34854f8d651562512ac522db1dc0c43946b7440bd427d045b8d8b83ba7a3ab26.json create mode 100644 backend/.sqlx/query-58bb4c7646404beae1f2183b13aef01f3c1737a1ff5f86c37211ff4aa3290b66.json rename backend/.sqlx/{query-441afa3ca7cd24ac9239b05fadb9ac74f53ba3c4077d67cf1d912062b95a4b85.json => query-7c70080e4d6248c9593ebfe8c3c3a09252f353124ddad863100f3598f6241fb1.json} (57%) rename backend/.sqlx/{query-4b65e9af266188dcd5b464cabc3456bbff59b7c51131bad4929304f63f2cfa02.json => query-96611797b0867dc967ab5076005e39141ff05981a14029714318b80ae97cc4fa.json} (58%) create mode 100644 backend/.sqlx/query-9f1e9d7657c78e014792be95b6bf3d12945450fdfbd9f52e59617660ea20c4c3.json create mode 100644 backend/migrations/20261127105444_token_email_index.down.sql create mode 100644 backend/migrations/20261127105444_token_email_index.up.sql create mode 100644 backend/migrations/20261127105445_token_risk_view.down.sql create mode 100644 backend/migrations/20261127105445_token_risk_view.up.sql create mode 100644 backend/windmill-api-integration-tests/tests/token_risk.rs create mode 100644 frontend/src/lib/components/instanceSettings/TokenReview.svelte create mode 100644 frontend/src/lib/components/settings/tokenRisks.ts diff --git a/backend/.sqlx/query-027dbff1397b96a6fb1cfe9aaaffe226bf276cac01b052dac82a6e21b00ac833.json b/backend/.sqlx/query-027dbff1397b96a6fb1cfe9aaaffe226bf276cac01b052dac82a6e21b00ac833.json new file mode 100644 index 0000000000..446ec94a16 --- /dev/null +++ b/backend/.sqlx/query-027dbff1397b96a6fb1cfe9aaaffe226bf276cac01b052dac82a6e21b00ac833.json @@ -0,0 +1,80 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT email, label, token_prefix AS \"token_prefix!\", expiration,\n created_at AS \"created_at!\", last_used_at AS \"last_used_at!\", scopes, workspace_id,\n read_only AS \"read_only!\", risks AS \"risks!\"\n FROM token_risk\n WHERE NOT self_managed\n AND CASE WHEN $1::text IS NULL THEN cardinality(risks) > 0\n WHEN $1 = 'all' THEN true\n ELSE $1 = ANY(risks) END\n AND ($2::text IS NULL OR strpos(lower(email), $2) > 0\n OR strpos(lower(COALESCE(label, '')), $2) > 0)\n AND ($3::timestamptz IS NULL OR (last_used_at, token_prefix) > ($3, $4::text))\n ORDER BY last_used_at, token_prefix\n LIMIT $5", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "label", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "token_prefix!", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "expiration", + "type_info": "Timestamptz" + }, + { + "ordinal": 4, + "name": "created_at!", + "type_info": "Timestamptz" + }, + { + "ordinal": 5, + "name": "last_used_at!", + "type_info": "Timestamptz" + }, + { + "ordinal": 6, + "name": "scopes", + "type_info": "TextArray" + }, + { + "ordinal": 7, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 8, + "name": "read_only!", + "type_info": "Bool" + }, + { + "ordinal": 9, + "name": "risks!", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Timestamptz", + "Text", + "Int8" + ] + }, + "nullable": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ] + }, + "hash": "027dbff1397b96a6fb1cfe9aaaffe226bf276cac01b052dac82a6e21b00ac833" +} diff --git a/backend/.sqlx/query-34854f8d651562512ac522db1dc0c43946b7440bd427d045b8d8b83ba7a3ab26.json b/backend/.sqlx/query-34854f8d651562512ac522db1dc0c43946b7440bd427d045b8d8b83ba7a3ab26.json new file mode 100644 index 0000000000..3e3d3cce46 --- /dev/null +++ b/backend/.sqlx/query-34854f8d651562512ac522db1dc0c43946b7440bd427d045b8d8b83ba7a3ab26.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT r AS risk, count(*) AS n FROM token_risk, unnest(risks) r WHERE email = $1 GROUP BY r", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "risk", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "n", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null, + null + ] + }, + "hash": "34854f8d651562512ac522db1dc0c43946b7440bd427d045b8d8b83ba7a3ab26" +} diff --git a/backend/.sqlx/query-58bb4c7646404beae1f2183b13aef01f3c1737a1ff5f86c37211ff4aa3290b66.json b/backend/.sqlx/query-58bb4c7646404beae1f2183b13aef01f3c1737a1ff5f86c37211ff4aa3290b66.json new file mode 100644 index 0000000000..2c01dc53c0 --- /dev/null +++ b/backend/.sqlx/query-58bb4c7646404beae1f2183b13aef01f3c1737a1ff5f86c37211ff4aa3290b66.json @@ -0,0 +1,26 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT r AS risk, count(*) AS n FROM token_risk, unnest(risks) r GROUP BY r", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "risk", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "n", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null, + null + ] + }, + "hash": "58bb4c7646404beae1f2183b13aef01f3c1737a1ff5f86c37211ff4aa3290b66" +} diff --git a/backend/.sqlx/query-441afa3ca7cd24ac9239b05fadb9ac74f53ba3c4077d67cf1d912062b95a4b85.json b/backend/.sqlx/query-7c70080e4d6248c9593ebfe8c3c3a09252f353124ddad863100f3598f6241fb1.json similarity index 57% rename from backend/.sqlx/query-441afa3ca7cd24ac9239b05fadb9ac74f53ba3c4077d67cf1d912062b95a4b85.json rename to backend/.sqlx/query-7c70080e4d6248c9593ebfe8c3c3a09252f353124ddad863100f3598f6241fb1.json index 98e809837e..984e733192 100644 --- a/backend/.sqlx/query-441afa3ca7cd24ac9239b05fadb9ac74f53ba3c4077d67cf1d912062b95a4b85.json +++ b/backend/.sqlx/query-7c70080e4d6248c9593ebfe8c3c3a09252f353124ddad863100f3598f6241fb1.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT t.label, t.token_prefix, t.expiration, t.created_at, t.last_used_at, t.scopes, t.workspace_id, t.read_only, t.allowed_ips::text[] AS allowed_ips, (t.admin AND EXISTS (SELECT 1 FROM usr u WHERE u.email = t.email AND u.is_admin AND NOT u.disabled AND (t.workspace_id IS NULL OR u.workspace_id = t.workspace_id))) AS \"admin!\", ((t.super_admin OR COALESCE(t.label = 'session', false)) AND COALESCE((SELECT p.super_admin FROM password p WHERE p.email = t.email), false)) AS \"super_admin!\" FROM token t WHERE t.email = $1 AND (t.label != 'ephemeral-script' OR t.label IS NULL)\n ORDER BY t.created_at DESC LIMIT $2 OFFSET $3", + "query": "SELECT label, token_prefix AS \"token_prefix!\", expiration,\n created_at AS \"created_at!\", last_used_at AS \"last_used_at!\", scopes, workspace_id,\n read_only AS \"read_only!\", allowed_ips::text[] AS allowed_ips,\n admin AS \"admin!\", super_admin AS \"super_admin!\", risks AS \"risks!\"\n FROM token_risk WHERE email = $1 AND (label != 'ephemeral-script' OR label IS NULL)\n ORDER BY created_at DESC LIMIT $2 OFFSET $3", "describe": { "columns": [ { @@ -10,7 +10,7 @@ }, { "ordinal": 1, - "name": "token_prefix", + "name": "token_prefix!", "type_info": "Varchar" }, { @@ -20,12 +20,12 @@ }, { "ordinal": 3, - "name": "created_at", + "name": "created_at!", "type_info": "Timestamptz" }, { "ordinal": 4, - "name": "last_used_at", + "name": "last_used_at!", "type_info": "Timestamptz" }, { @@ -40,7 +40,7 @@ }, { "ordinal": 7, - "name": "read_only", + "name": "read_only!", "type_info": "Bool" }, { @@ -57,6 +57,11 @@ "ordinal": 10, "name": "super_admin!", "type_info": "Bool" + }, + { + "ordinal": 11, + "name": "risks!", + "type_info": "TextArray" } ], "parameters": { @@ -68,17 +73,18 @@ }, "nullable": [ true, - false, - true, - false, - false, true, true, - false, + true, + true, + true, + true, + true, null, - null, - null + true, + true, + true ] }, - "hash": "441afa3ca7cd24ac9239b05fadb9ac74f53ba3c4077d67cf1d912062b95a4b85" + "hash": "7c70080e4d6248c9593ebfe8c3c3a09252f353124ddad863100f3598f6241fb1" } diff --git a/backend/.sqlx/query-4b65e9af266188dcd5b464cabc3456bbff59b7c51131bad4929304f63f2cfa02.json b/backend/.sqlx/query-96611797b0867dc967ab5076005e39141ff05981a14029714318b80ae97cc4fa.json similarity index 58% rename from backend/.sqlx/query-4b65e9af266188dcd5b464cabc3456bbff59b7c51131bad4929304f63f2cfa02.json rename to backend/.sqlx/query-96611797b0867dc967ab5076005e39141ff05981a14029714318b80ae97cc4fa.json index ddb63a7bd8..cf37e33bc4 100644 --- a/backend/.sqlx/query-4b65e9af266188dcd5b464cabc3456bbff59b7c51131bad4929304f63f2cfa02.json +++ b/backend/.sqlx/query-96611797b0867dc967ab5076005e39141ff05981a14029714318b80ae97cc4fa.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT t.label, t.token_prefix, t.expiration, t.created_at, t.last_used_at, t.scopes, t.workspace_id, t.read_only, t.allowed_ips::text[] AS allowed_ips, (t.admin AND EXISTS (SELECT 1 FROM usr u WHERE u.email = t.email AND u.is_admin AND NOT u.disabled AND (t.workspace_id IS NULL OR u.workspace_id = t.workspace_id))) AS \"admin!\", ((t.super_admin OR COALESCE(t.label = 'session', false)) AND COALESCE((SELECT p.super_admin FROM password p WHERE p.email = t.email), false)) AS \"super_admin!\" FROM token t WHERE t.email = $1\n ORDER BY t.created_at DESC LIMIT $2 OFFSET $3", + "query": "SELECT label, token_prefix AS \"token_prefix!\", expiration,\n created_at AS \"created_at!\", last_used_at AS \"last_used_at!\", scopes, workspace_id,\n read_only AS \"read_only!\", allowed_ips::text[] AS allowed_ips,\n admin AS \"admin!\", super_admin AS \"super_admin!\", risks AS \"risks!\"\n FROM token_risk WHERE email = $1\n ORDER BY created_at DESC LIMIT $2 OFFSET $3", "describe": { "columns": [ { @@ -10,7 +10,7 @@ }, { "ordinal": 1, - "name": "token_prefix", + "name": "token_prefix!", "type_info": "Varchar" }, { @@ -20,12 +20,12 @@ }, { "ordinal": 3, - "name": "created_at", + "name": "created_at!", "type_info": "Timestamptz" }, { "ordinal": 4, - "name": "last_used_at", + "name": "last_used_at!", "type_info": "Timestamptz" }, { @@ -40,7 +40,7 @@ }, { "ordinal": 7, - "name": "read_only", + "name": "read_only!", "type_info": "Bool" }, { @@ -57,6 +57,11 @@ "ordinal": 10, "name": "super_admin!", "type_info": "Bool" + }, + { + "ordinal": 11, + "name": "risks!", + "type_info": "TextArray" } ], "parameters": { @@ -68,17 +73,18 @@ }, "nullable": [ true, - false, - true, - false, - false, true, true, - false, + true, + true, + true, + true, + true, null, - null, - null + true, + true, + true ] }, - "hash": "4b65e9af266188dcd5b464cabc3456bbff59b7c51131bad4929304f63f2cfa02" + "hash": "96611797b0867dc967ab5076005e39141ff05981a14029714318b80ae97cc4fa" } diff --git a/backend/.sqlx/query-9f1e9d7657c78e014792be95b6bf3d12945450fdfbd9f52e59617660ea20c4c3.json b/backend/.sqlx/query-9f1e9d7657c78e014792be95b6bf3d12945450fdfbd9f52e59617660ea20c4c3.json new file mode 100644 index 0000000000..475628940f --- /dev/null +++ b/backend/.sqlx/query-9f1e9d7657c78e014792be95b6bf3d12945450fdfbd9f52e59617660ea20c4c3.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM token WHERE email = $1 AND token_prefix = $2 RETURNING token_prefix", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "token_prefix", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "9f1e9d7657c78e014792be95b6bf3d12945450fdfbd9f52e59617660ea20c4c3" +} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index f564d218cc..c30483151d 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -5456ade3c09011206acc20ab026dda49f15f9517 +b3c5cbb7edcc42f3db92865896d472cdd8842cf9 diff --git a/backend/migrations/20261127105444_token_email_index.down.sql b/backend/migrations/20261127105444_token_email_index.down.sql new file mode 100644 index 0000000000..899c5e0252 --- /dev/null +++ b/backend/migrations/20261127105444_token_email_index.down.sql @@ -0,0 +1 @@ +DROP INDEX IF EXISTS token_email_idx; diff --git a/backend/migrations/20261127105444_token_email_index.up.sql b/backend/migrations/20261127105444_token_email_index.up.sql new file mode 100644 index 0000000000..45c51e2d85 --- /dev/null +++ b/backend/migrations/20261127105444_token_email_index.up.sql @@ -0,0 +1,8 @@ +-- Serves every per-user token listing (`list_tokens`, the token risk counts), which otherwise +-- scans the whole table, sessions and job tokens included. +-- Dropped before it is built because the OVERRIDDEN_MIGRATIONS rewrite in +-- windmill-api/src/db.rs runs both CONCURRENTLY: an interrupted concurrent build leaves an +-- invalid index that IF NOT EXISTS would skip rebuilding. +DROP INDEX IF EXISTS token_email_idx; + +CREATE INDEX IF NOT EXISTS token_email_idx ON token (email); diff --git a/backend/migrations/20261127105445_token_risk_view.down.sql b/backend/migrations/20261127105445_token_risk_view.down.sql new file mode 100644 index 0000000000..8de051cb6f --- /dev/null +++ b/backend/migrations/20261127105445_token_risk_view.down.sql @@ -0,0 +1 @@ +DROP VIEW IF EXISTS token_risk; diff --git a/backend/migrations/20261127105445_token_risk_view.up.sql b/backend/migrations/20261127105445_token_risk_view.up.sql new file mode 100644 index 0000000000..903796f220 --- /dev/null +++ b/backend/migrations/20261127105445_token_risk_view.up.sql @@ -0,0 +1,65 @@ +-- The risks a token review flags, computed once for the user's token list and the superadmin +-- review (windmill-api-users/src/users.rs). `self_managed` marks a token the server mints and +-- expires or renews on its own, which nobody manages by hand; its `risks` are empty. The 90 days +-- are mirrored by STALE_TOKEN_DAYS in frontend/src/lib/components/settings/tokenRisks.ts, +-- which only words them. `admin` and `super_admin` are the rights the token carries, as +-- `tokens/list` reports them: minted with them (a session always is) and still held by the owner. +CREATE OR REPLACE VIEW token_risk AS +SELECT + t.email, + t.label, + t.token_prefix, + t.expiration, + t.created_at, + t.last_used_at, + t.scopes, + t.workspace_id, + t.read_only, + t.allowed_ips, + r.admin, + r.super_admin, + m.self_managed, + CASE WHEN m.self_managed THEN ARRAY[]::text[] ELSE array_remove(ARRAY[ + -- Scopes or read-only mode narrow a token's rights; a job tag filter alone does not + -- (windmill-api-auth/src/scopes.rs). + CASE WHEN m.unrestricted AND r.super_admin THEN 'superadmin' END, + CASE WHEN m.unrestricted AND NOT r.super_admin AND r.admin THEN 'admin' END, + CASE WHEN t.workspace_id IS NULL THEN 'all_workspaces' END, + CASE WHEN t.expiration IS NULL THEN 'never_expires' END, + CASE WHEN t.last_used_at < now() - interval '90 days' THEN 'unused' END + ], NULL) END AS risks +FROM token t +LEFT JOIN ( + SELECT email, array_agg(workspace_id) AS admin_of + FROM usr WHERE is_admin AND NOT disabled GROUP BY email +) a ON a.email = t.email +LEFT JOIN password p ON p.email = t.email +CROSS JOIN LATERAL ( + SELECT + t.admin AND a.admin_of IS NOT NULL + AND (t.workspace_id IS NULL OR t.workspace_id = ANY(a.admin_of)) AS admin, + (t.super_admin OR t.label = 'session') IS TRUE AND COALESCE(p.super_admin, false) + AS super_admin +) r +CROSS JOIN LATERAL ( + SELECT + -- A job token, or a label only the server can mint (`is_server_minted_label`). + (t.job IS NOT NULL + OR t.label IN ('session', 'guest_session', 'ephemeral-script') + OR starts_with(t.label, 'ephemeral-webhook-') + OR starts_with(t.label, 'ephemeral-script-end-user-') + OR starts_with(t.label, 'mcp-oauth-') + -- `tokens/create` accepts these labels too, so only a lifetime as short as the + -- system's own (72h for the editor's language server at most, plus a day for the + -- browser's clock, which sets it) proves the token is one of those rather than a + -- long-lived token borrowing the label. + OR ((t.label = 'debugger-token' + OR lower(t.label) LIKE 'ephemeral%' + OR starts_with(t.label, 'embed_app:') + OR starts_with(t.label, 'sdk_app:') + OR starts_with(t.label, 'impersonation:')) + AND t.expiration <= t.created_at + interval '4 days')) IS TRUE AS self_managed, + NOT t.read_only + AND NOT EXISTS (SELECT 1 FROM unnest(t.scopes) s WHERE NOT starts_with(s, 'if_jobs:filter_tags:')) + AS unrestricted +) m; diff --git a/backend/windmill-api-integration-tests/tests/token_risk.rs b/backend/windmill-api-integration-tests/tests/token_risk.rs new file mode 100644 index 0000000000..c2c2ae6634 --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/token_risk.rs @@ -0,0 +1,196 @@ +//! The `token_risk` view flags what a token review looks at, and the superadmin review (EE) +//! pages through it with a cursor, so a token used between two pages is not skipped. Without +//! `enterprise` (the CE image builds `private` alone), only its counts are served. + +use sqlx::{Pool, Postgres, Row}; +use windmill_test_utils::*; + +/// A token with no risk: bound to test-workspace, expiring, just used, minted without rights. +async fn insert_token(db: &Pool, prefix: &str, email: &str) { + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, email, label, expiration, workspace_id, \ + super_admin, admin) \ + VALUES (md5($1), $1, $2, $1, now() + interval '30 days', 'test-workspace', false, false)", + ) + .bind(prefix) + .bind(email) + .execute(db) + .await + .unwrap(); +} + +async fn update(db: &Pool, prefix: &str, set: &str) { + sqlx::query(&format!("UPDATE token SET {set} WHERE token_prefix = $1")) + .bind(prefix) + .execute(db) + .await + .unwrap(); +} + +async fn risks(db: &Pool, prefix: &str) -> Vec { + sqlx::query("SELECT risks FROM token_risk WHERE token_prefix = $1") + .bind(prefix) + .fetch_one(db) + .await + .unwrap() + .get("risks") +} + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_token_risk_rules(db: Pool) -> anyhow::Result<()> { + // test@ is an admin of test-workspace, test2@ only a member. + let admin = "test@windmill.dev"; + let member = "test2@windmill.dev"; + let cases: &[(&str, &str, &str, &[&str])] = &[ + ("clean", admin, "read_only = false", &[]), + ("never", admin, "expiration = NULL", &["never_expires"]), + ("unbound", admin, "workspace_id = NULL", &["all_workspaces"]), + ( + "stale", + admin, + "last_used_at = now() - interval '91 days'", + &["unused"], + ), + ( + "recent", + admin, + "last_used_at = now() - interval '89 days'", + &[], + ), + ( + "sa", + admin, + "super_admin = true, admin = true", + &["superadmin"], + ), + ("adm", admin, "admin = true", &["admin"]), + // Rights the owner does not hold are not flagged, nor rights the token was minted without. + ("member", member, "admin = true", &[]), + // Scopes or read-only mode narrow the rights; a job tag filter alone does not. + ("scoped", admin, "admin = true, scopes = '{jobs:read}'", &[]), + ("ro", admin, "admin = true, read_only = true", &[]), + ( + "tags", + admin, + "admin = true, scopes = '{if_jobs:filter_tags:prod}'", + &["admin"], + ), + ]; + for (prefix, email, set, expected) in cases { + insert_token(&db, prefix, email).await; + update(&db, prefix, set).await; + assert_eq!(&risks(&db, prefix).await, expected, "{prefix}"); + } + + // Tokens the server manages on its own carry no flag, however risky they look: a label + // only the server mints, or a system label `tokens/create` also accepts on a token as + // short-lived as the system's own. The same label on a long-lived token proves nothing. + let managed: &[(&str, &str, bool)] = &[ + ("session", "expiration = NULL", true), + ("ephemeral-script", "expiration = NULL", true), + ("mcp-oauth-x", "expiration = NULL", true), + ("impersonation:a", "expiration = created_at + interval '24 hours'", true), + ("Ephemeral lsp token", "expiration = created_at + interval '72 hours'", true), + ("debugger-token", "expiration = NULL", false), + ("sdk_app:f", "expiration = created_at + interval '30 days'", false), + ]; + for (i, (label, expiration, exempt)) in managed.iter().enumerate() { + let prefix = format!("managed-{i}"); + insert_token(&db, &prefix, admin).await; + update( + &db, + &prefix, + &format!("label = '{label}', {expiration}, workspace_id = NULL, super_admin = true"), + ) + .await; + assert_eq!(risks(&db, &prefix).await.is_empty(), *exempt, "{label}"); + } + Ok(()) +} + +#[cfg(feature = "enterprise")] +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_token_review_cursor_survives_use(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let url = format!( + "http://localhost:{}/api/users/tokens/list_as_super_admin", + server.addr.port() + ); + let http = reqwest::Client::new(); + + // Flagged (no expiration) and staler than the fixture's tokens, in this order. + for (prefix, days) in [("page-a", 12), ("page-b", 11), ("page-c", 10)] { + insert_token(&db, prefix, "test@windmill.dev").await; + update( + &db, + prefix, + &format!("expiration = NULL, last_used_at = now() - interval '{days} days'"), + ) + .await; + } + + let first: serde_json::Value = http + .get(&url) + .bearer_auth("SECRET_TOKEN") + .query(&[("per_page", "1")]) + .send() + .await? + .json() + .await?; + let a = &first[0]; + assert_eq!(a["token_prefix"], "page-a"); + + // page-a is used before the next page is read, which moves it to the end of the order: + // an offset would now skip page-b. + update(&db, "page-a", "last_used_at = now()").await; + + let next: serde_json::Value = http + .get(&url) + .bearer_auth("SECRET_TOKEN") + .query(&[ + ("per_page", "1"), + ("after_last_used_at", a["last_used_at"].as_str().unwrap()), + ("after_token_prefix", "page-a"), + ]) + .send() + .await? + .json() + .await?; + assert_eq!(next[0]["token_prefix"], "page-b"); + Ok(()) +} + +#[cfg(not(feature = "enterprise"))] +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_token_review_list_is_ee(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base = format!("http://localhost:{}/api/users/tokens", server.addr.port()); + let http = reqwest::Client::new(); + insert_token(&db, "victim", "test2@windmill.dev").await; + + let counts = http + .get(format!("{base}/risk_counts_as_super_admin")) + .bearer_auth("SECRET_TOKEN") + .send() + .await?; + assert_eq!(counts.status(), 200); + let list = http + .get(format!("{base}/list_as_super_admin")) + .bearer_auth("SECRET_TOKEN") + .send() + .await?; + assert_eq!(list.status(), 400); + let delete = http + .delete(format!("{base}/delete_as_super_admin/test2@windmill.dev/victim")) + .bearer_auth("SECRET_TOKEN") + .send() + .await?; + assert_eq!(delete.status(), 400); + let left: i64 = sqlx::query_scalar("SELECT count(*) FROM token WHERE token_prefix = 'victim'") + .fetch_one(&db) + .await?; + assert_eq!(left, 1); + Ok(()) +} diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index 5bad41664e..6c78b510ec 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -150,6 +150,19 @@ pub fn global_service() -> Router { post(update_token_label), ) .route("/tokens/list", get(list_tokens)) + .route("/tokens/risk_counts", get(token_risk_counts)) + .route( + "/tokens/risk_counts_as_super_admin", + get(token_risk_counts_as_super_admin), + ) + .route( + "/tokens/list_as_super_admin", + get(list_tokens_as_super_admin), + ) + .route( + "/tokens/delete_as_super_admin/{email}/{token_prefix}", + delete(delete_token_as_super_admin), + ) .route("/tokens/impersonate", post(impersonate)) .route("/login_links", post(create_login_link)) .route( @@ -342,6 +355,7 @@ pub struct TruncatedToken { pub allowed_ips: Option>, pub admin: bool, pub super_admin: bool, + pub risks: Vec, } // NewToken is re-exported from windmill-api-auth above @@ -4149,16 +4163,12 @@ async fn list_tokens( let rows = if query.exclude_ephemeral.unwrap_or(false) { sqlx::query_as!( TruncatedToken, - "SELECT t.label, t.token_prefix, t.expiration, t.created_at, t.last_used_at, t.scopes, \ - t.workspace_id, t.read_only, t.allowed_ips::text[] AS allowed_ips, \ - (t.admin AND EXISTS (SELECT 1 FROM usr u WHERE u.email = t.email AND u.is_admin \ - AND NOT u.disabled AND (t.workspace_id IS NULL OR u.workspace_id = t.workspace_id))) \ - AS \"admin!\", \ - ((t.super_admin OR COALESCE(t.label = 'session', false)) \ - AND COALESCE((SELECT p.super_admin FROM password p WHERE p.email = t.email), false)) \ - AS \"super_admin!\" \ - FROM token t WHERE t.email = $1 AND (t.label != 'ephemeral-script' OR t.label IS NULL) - ORDER BY t.created_at DESC LIMIT $2 OFFSET $3", + r#"SELECT label, token_prefix AS "token_prefix!", expiration, + created_at AS "created_at!", last_used_at AS "last_used_at!", scopes, workspace_id, + read_only AS "read_only!", allowed_ips::text[] AS allowed_ips, + admin AS "admin!", super_admin AS "super_admin!", risks AS "risks!" + FROM token_risk WHERE email = $1 AND (label != 'ephemeral-script' OR label IS NULL) + ORDER BY created_at DESC LIMIT $2 OFFSET $3"#, email, per_page as i64, offset as i64, @@ -4168,16 +4178,12 @@ async fn list_tokens( } else { sqlx::query_as!( TruncatedToken, - "SELECT t.label, t.token_prefix, t.expiration, t.created_at, t.last_used_at, t.scopes, \ - t.workspace_id, t.read_only, t.allowed_ips::text[] AS allowed_ips, \ - (t.admin AND EXISTS (SELECT 1 FROM usr u WHERE u.email = t.email AND u.is_admin \ - AND NOT u.disabled AND (t.workspace_id IS NULL OR u.workspace_id = t.workspace_id))) \ - AS \"admin!\", \ - ((t.super_admin OR COALESCE(t.label = 'session', false)) \ - AND COALESCE((SELECT p.super_admin FROM password p WHERE p.email = t.email), false)) \ - AS \"super_admin!\" \ - FROM token t WHERE t.email = $1 - ORDER BY t.created_at DESC LIMIT $2 OFFSET $3", + r#"SELECT label, token_prefix AS "token_prefix!", expiration, + created_at AS "created_at!", last_used_at AS "last_used_at!", scopes, workspace_id, + read_only AS "read_only!", allowed_ips::text[] AS allowed_ips, + admin AS "admin!", super_admin AS "super_admin!", risks AS "risks!" + FROM token_risk WHERE email = $1 + ORDER BY created_at DESC LIMIT $2 OFFSET $3"#, email, per_page as i64, offset as i64, @@ -4188,6 +4194,118 @@ async fn list_tokens( Ok(Json(rows)) } +/// How many tokens carry each risk of the `token_risk` view. +#[derive(Serialize, Default)] +pub struct TokenRiskCounts { + pub superadmin: i64, + pub admin: i64, + pub all_workspaces: i64, + pub never_expires: i64, + pub unused: i64, +} + +impl TokenRiskCounts { + fn from_rows(rows: Vec<(Option, Option)>) -> Self { + let mut c = Self::default(); + for (risk, n) in rows { + let n = n.unwrap_or(0); + match risk.as_deref() { + Some("superadmin") => c.superadmin = n, + Some("admin") => c.admin = n, + Some("all_workspaces") => c.all_workspaces = n, + Some("never_expires") => c.never_expires = n, + Some("unused") => c.unused = n, + _ => {} + } + } + c + } +} + +/// The caller's own counts, over all their tokens rather than one page of `tokens/list`. +async fn token_risk_counts( + Extension(db): Extension, + ApiAuthed { email, .. }: ApiAuthed, +) -> JsonResult { + let rows = sqlx::query!( + "SELECT r AS risk, count(*) AS n FROM token_risk, unnest(risks) r WHERE email = $1 GROUP BY r", + email, + ) + .fetch_all(&db) + .await?; + Ok(Json(TokenRiskCounts::from_rows( + rows.into_iter().map(|r| (r.risk, r.n)).collect(), + ))) +} + +/// Instance-wide counts, for the token review's summary. +async fn token_risk_counts_as_super_admin( + Extension(db): Extension, + authed: ApiAuthed, +) -> JsonResult { + require_super_admin(&db, &authed).await?; + let rows = + sqlx::query!("SELECT r AS risk, count(*) AS n FROM token_risk, unnest(risks) r GROUP BY r") + .fetch_all(&db) + .await?; + Ok(Json(TokenRiskCounts::from_rows( + rows.into_iter().map(|r| (r.risk, r.n)).collect(), + ))) +} + +#[derive(FromRow, Serialize)] +pub struct TokenForReview { + pub email: Option, + pub label: Option, + pub token_prefix: String, + pub expiration: Option>, + pub created_at: chrono::DateTime, + pub last_used_at: chrono::DateTime, + pub scopes: Option>, + pub workspace_id: Option, + pub read_only: bool, + pub risks: Vec, +} + +#[derive(Deserialize)] +pub struct TokenReviewQuery { + /// A risk to narrow to, `all` for every token, or none for any risk. + pub flag: Option, + pub search: Option, + pub per_page: Option, + /// The last row of the previous page. A cursor rather than an offset, since the order + /// moves as tokens are used: an offset would skip rows that move behind it. + pub after_last_used_at: Option>, + pub after_token_prefix: Option, +} + +pub(crate) fn token_review_requires_ee() -> Error { + Error::BadRequest( + "Listing and deleting every user's tokens requires a valid Windmill Enterprise Edition license" + .to_string(), + ) +} + +async fn list_tokens_as_super_admin( + Extension(db): Extension, + authed: ApiAuthed, + Query(query): Query, +) -> JsonResult> { + require_super_admin(&db, &authed).await?; + Ok(Json( + crate::users_oss::list_tokens_as_super_admin(&db, query).await?, + )) +} + +async fn delete_token_as_super_admin( + Extension(db): Extension, + authed: ApiAuthed, + Path((email, token_prefix)): Path<(String, String)>, +) -> Result { + require_super_admin(&db, &authed).await?; + crate::users_oss::delete_token_as_super_admin(&db, &authed, &email, &token_prefix).await +} + /// 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`). diff --git a/backend/windmill-api-users/src/users_oss.rs b/backend/windmill-api-users/src/users_oss.rs index a1eedd8563..f33cb0a3b7 100644 --- a/backend/windmill-api-users/src/users_oss.rs +++ b/backend/windmill-api-users/src/users_oss.rs @@ -36,3 +36,23 @@ pub(crate) async fn portal_cloud_trial_login( .to_string(), )) } + +// The CE image builds with `private` but not `enterprise`, so these, not `users_ee`'s, serve +// it: the instance-wide token list stays EE. +#[cfg(not(all(feature = "private", feature = "enterprise")))] +pub(crate) async fn list_tokens_as_super_admin( + _db: &windmill_common::DB, + _query: crate::users::TokenReviewQuery, +) -> windmill_common::error::Result> { + Err(crate::users::token_review_requires_ee()) +} + +#[cfg(not(all(feature = "private", feature = "enterprise")))] +pub(crate) async fn delete_token_as_super_admin( + _db: &windmill_common::DB, + _authed: &windmill_api_auth::ApiAuthed, + _email: &str, + _token_prefix: &str, +) -> windmill_common::error::Result { + Err(crate::users::token_review_requires_ee()) +} diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index b12a85c8d9..d58f46610c 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -7985,6 +7985,104 @@ paths: items: $ref: "#/components/schemas/TruncatedToken" + /users/tokens/risk_counts: + get: + summary: count the caller's tokens carrying each risk + operationId: getTokenRiskCounts + tags: + - user + responses: + "200": + description: count per risk, over all the caller's tokens + content: + application/json: + schema: + $ref: "#/components/schemas/TokenRiskCounts" + + /users/tokens/risk_counts_as_super_admin: + get: + summary: count every user's tokens carrying each risk (superadmin only) + operationId: getTokenRiskCountsAsSuperAdmin + tags: + - user + responses: + "200": + description: count per risk, over the whole instance + content: + application/json: + schema: + $ref: "#/components/schemas/TokenRiskCounts" + + /users/tokens/list_as_super_admin: + get: + summary: list every user's tokens, least recently used first (superadmin only, EE) + description: > + Tokens the server expires or renews on its own are left out. Pages are read with a cursor: + pass the last row's `last_used_at` and `token_prefix` to get the next page. + operationId: listTokensAsSuperAdmin + tags: + - user + parameters: + - name: flag + description: a risk to narrow to, `all` for every token, or omitted for tokens with any risk + in: query + schema: + type: string + enum: [all, superadmin, admin, all_workspaces, never_expires, unused] + - name: search + description: case-insensitive substring of the owner's email or the token's label + in: query + schema: + type: string + - name: per_page + description: rows per page, 100 by default, at most 1000 + in: query + schema: + type: integer + - name: after_last_used_at + in: query + schema: + type: string + format: date-time + - name: after_token_prefix + in: query + schema: + type: string + responses: + "200": + description: one page of tokens + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/TokenForReview" + + /users/tokens/delete_as_super_admin/{email}/{token_prefix}: + delete: + summary: delete another user's token (superadmin only, EE) + operationId: deleteTokenAsSuperAdmin + tags: + - user + parameters: + - name: email + in: path + required: true + schema: + type: string + - name: token_prefix + in: path + required: true + schema: + type: string + responses: + "200": + description: delete token + content: + text/plain: + schema: + type: string + /oidc/signing_status: get: summary: what signs OIDC tokens and the keys the JWKS serves (ee only, superadmin) @@ -34412,11 +34510,82 @@ components: description: | The token carries superadmin rights: it was minted with them (a session always is) and its owner is a superadmin. Set by /users/tokens/list. + risks: + type: array + description: what a token review flags on this token; empty for a token the server manages on its own + items: + $ref: "#/components/schemas/TokenRisk" required: - token_prefix - created_at - last_used_at - read_only + - risks + + TokenRisk: + type: string + description: > + superadmin / admin: minted with those rights (and the owner still an admin where the token + reaches), not narrowed by scopes or read-only mode. all_workspaces: not bound to a workspace. + never_expires: no expiration. unused: not used in over 90 days. + enum: [superadmin, admin, all_workspaces, never_expires, unused] + + TokenRiskCounts: + type: object + properties: + superadmin: + type: integer + admin: + type: integer + all_workspaces: + type: integer + never_expires: + type: integer + unused: + type: integer + required: + - superadmin + - admin + - all_workspaces + - never_expires + - unused + + TokenForReview: + type: object + properties: + email: + type: string + label: + type: string + expiration: + type: string + format: date-time + token_prefix: + type: string + created_at: + type: string + format: date-time + last_used_at: + type: string + format: date-time + scopes: + type: array + items: + type: string + workspace_id: + type: string + read_only: + type: boolean + risks: + type: array + items: + $ref: "#/components/schemas/TokenRisk" + required: + - token_prefix + - created_at + - last_used_at + - read_only + - risks ExternalJwtToken: type: object diff --git a/backend/windmill-api/src/db.rs b/backend/windmill-api/src/db.rs index 56524011fe..c691acf608 100644 --- a/backend/windmill-api/src/db.rs +++ b/backend/windmill-api/src/db.rs @@ -126,6 +126,9 @@ lazy_static::lazy_static! { (20261106050615, include_str!( "../../migrations/20261106050615_concurrency_key_place_index.up.sql" ).replace("CREATE INDEX", "CREATE INDEX CONCURRENTLY").replace("DROP INDEX", "DROP INDEX CONCURRENTLY")), + (20261127105444, include_str!( + "../../migrations/20261127105444_token_email_index.up.sql" + ).replace("CREATE INDEX", "CREATE INDEX CONCURRENTLY").replace("DROP INDEX", "DROP INDEX CONCURRENTLY")), // The widening fails every query the previous release's still-running // servers prepared on the column; `variables::widen_variable_value` does it // once they are gone. diff --git a/backend/windmill-common/src/auth.rs b/backend/windmill-common/src/auth.rs index 1500194056..db56fdbf6c 100644 --- a/backend/windmill-common/src/auth.rs +++ b/backend/windmill-common/src/auth.rs @@ -30,6 +30,8 @@ use crate::{ /// - the `update_token_label` editability guard (SQL `WHERE`) in /// windmill-api-users/src/users.rs /// - `isUserToken` in frontend/src/lib/components/settings/TokensTable.svelte +/// - `self_managed` in the `token_risk` view (a migration), for a label the server also expires or +/// renews on its own pub fn is_user_token(label: Option<&str>) -> bool { match label { None => true, diff --git a/docs/auth-surface.md b/docs/auth-surface.md index f823ed66e2..fd1ab6d1be 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -54,6 +54,13 @@ Symbols, not line numbers, are cited: they drift less. expiry or another login changes or drops it. A session revoked server-side keeps its hint, so until `whoami` answers that browser still renders as its own last user. - **`tokens/impersonate`** (superadmin) returns a multi-use token and sets no cookie. +- **Token risk flags** (rights the token was minted with and no scope narrows, not bound to a + workspace, no expiration, unused 90 days) are computed once, by the `token_risk` view, which also + marks the tokens the server expires or renews on its own (`self_managed`, no flags). The user's + `tokens/list` and `tokens/risk_counts` and the superadmin review read it: its counts + (`tokens/risk_counts_as_super_admin`) in CE, its list (`tokens/list_as_super_admin`, cursor-paged + on `(last_used_at, token_prefix)`) and `tokens/delete_as_super_admin/{email}/{prefix}` in EE + (`users_ee.rs`); `frontend/src/lib/components/settings/tokenRisks.ts` only words the flags. - **`GET /api/tokens/introspect`** describes the credential presenting it, never one named in the request, and resolves it in the handler rather than through `ApiAuthed`: the route layer would refuse a scoped token there, and a workspace-bound one resolves on no global route. Its diff --git a/frontend/src/lib/components/SuperadminSettingsInner.svelte b/frontend/src/lib/components/SuperadminSettingsInner.svelte index 3fba7e887e..8924d2af77 100644 --- a/frontend/src/lib/components/SuperadminSettingsInner.svelte +++ b/frontend/src/lib/components/SuperadminSettingsInner.svelte @@ -57,6 +57,7 @@ import InstanceAISettings from './instanceSettings/InstanceAISettings.svelte' import ExternalJwtTokens from './instanceSettings/ExternalJwtTokens.svelte' import GuestActivityList from './instanceSettings/GuestActivityList.svelte' + import TokenReview from './instanceSettings/TokenReview.svelte' import { Alert, Skeleton } from '$lib/components/common' let filter = $state('') @@ -106,7 +107,7 @@ listUsers(activeOnly) }) - let usersSubTab: 'users' | 'ext_jwt' | 'guests' = $state('users') + let usersSubTab: 'users' | 'ext_jwt' | 'guests' | 'tokens' = $state('users') let guestList: GuestList | undefined = $state(undefined) let guestHasMore = $state(true) let guestLoading = $state(false) @@ -382,6 +383,7 @@ {/if} + {#if usersListShown} @@ -800,6 +802,8 @@ loadExtJwtPage(1) }} /> + {:else if usersSubTab === 'tokens'} + {:else if usersSubTab === 'guests' && !guestList} {#if guestLoading} diff --git a/frontend/src/lib/components/instanceSettings/TokenReview.svelte b/frontend/src/lib/components/instanceSettings/TokenReview.svelte new file mode 100644 index 0000000000..42f1948296 --- /dev/null +++ b/frontend/src/lib/components/instanceSettings/TokenReview.svelte @@ -0,0 +1,256 @@ + + + + +{#if riskSummary.length > 0} +
+ +
    + {#each riskSummary as line (line)} +
  • {line}
  • + {/each} +
+
+
+{:else if counts && !loadFailed} +
+ +
+{/if} + +{#if !$enterpriseLicense} + + With an Enterprise license, this page lists every user's tokens, filters them by flag, owner + or label, and deletes any of them. + +{:else} +
+ +