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

* fix: load the whole token review at once and pin the risk rules in a test

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

* fix: a job tag filter alone does not narrow a privileged token

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

* fix: flag the rights a token carries, not the rights of its owner

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

* feat: flag tokens that work in every workspace and filter the review by flag

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

* perf: compute token risks in a view and page the review with a cursor

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

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

* fix: leave a day of clock skew on the server-managed token lifetime

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

* feat: make the instance-wide token list and deletion an EE feature

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

* fix: keep the token list EE in the CE image, which builds private

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

* 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 <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
This commit is contained in:
Ruben Fiszel
2026-11-27 16:24:34 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 windmill-internal-app[bot]
parent b2f3986f94
commit 51e9017c67
22 changed files with 1172 additions and 56 deletions
@@ -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"
}
@@ -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"
}
@@ -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"
}
@@ -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"
}
@@ -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"
}
@@ -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"
}
+1 -1
View File
@@ -1 +1 @@
5456ade3c09011206acc20ab026dda49f15f9517
b3c5cbb7edcc42f3db92865896d472cdd8842cf9
@@ -0,0 +1 @@
DROP INDEX IF EXISTS token_email_idx;
@@ -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);
@@ -0,0 +1 @@
DROP VIEW IF EXISTS token_risk;
@@ -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;
@@ -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<Postgres>, 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<Postgres>, 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<Postgres>, prefix: &str) -> Vec<String> {
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<Postgres>) -> 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<Postgres>) -> 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<Postgres>) -> 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(())
}
+138 -20
View File
@@ -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<Vec<String>>,
pub admin: bool,
pub super_admin: bool,
pub risks: Vec<String>,
}
// 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<String>, Option<i64>)>) -> 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<DB>,
ApiAuthed { email, .. }: ApiAuthed,
) -> JsonResult<TokenRiskCounts> {
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<DB>,
authed: ApiAuthed,
) -> JsonResult<TokenRiskCounts> {
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<String>,
pub label: Option<String>,
pub token_prefix: String,
pub expiration: Option<chrono::DateTime<chrono::Utc>>,
pub created_at: chrono::DateTime<chrono::Utc>,
pub last_used_at: chrono::DateTime<chrono::Utc>,
pub scopes: Option<Vec<String>>,
pub workspace_id: Option<String>,
pub read_only: bool,
pub risks: Vec<String>,
}
#[derive(Deserialize)]
pub struct TokenReviewQuery {
/// A risk to narrow to, `all` for every token, or none for any risk.
pub flag: Option<String>,
pub search: Option<String>,
pub per_page: Option<usize>,
/// 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<chrono::DateTime<chrono::Utc>>,
pub after_token_prefix: Option<String>,
}
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<DB>,
authed: ApiAuthed,
Query(query): Query<TokenReviewQuery>,
) -> JsonResult<Vec<TokenForReview>> {
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<DB>,
authed: ApiAuthed,
Path((email, token_prefix)): Path<(String, String)>,
) -> Result<String> {
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`).
@@ -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<Vec<crate::users::TokenForReview>> {
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<String> {
Err(crate::users::token_review_requires_ee())
}
+169
View File
@@ -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
+3
View File
@@ -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.
+2
View File
@@ -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,
+7
View File
@@ -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
@@ -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 @@
<Tab value="ext_jwt" label="External JWTs" />
{/if}
<Tab value="guests" label="Guests" />
<Tab value="tokens" label="Token review" />
</Tabs>
{#if usersListShown}
@@ -800,6 +802,8 @@
loadExtJwtPage(1)
}}
/>
{:else if usersSubTab === 'tokens'}
<TokenReview />
{:else if usersSubTab === 'guests' && !guestList}
{#if guestLoading}
<Skeleton layout={[[2], 1, [8]]} />
@@ -0,0 +1,256 @@
<script lang="ts">
import DataTable from '$lib/components/table/DataTable.svelte'
import Head from '$lib/components/table/Head.svelte'
import Cell from '$lib/components/table/Cell.svelte'
import SettingsPageHeader from '$lib/components/settings/SettingsPageHeader.svelte'
import Select from '$lib/components/select/Select.svelte'
import TextInput from '$lib/components/text_input/TextInput.svelte'
import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte'
import { Alert, Badge, Button } from '$lib/components/common'
import { UserService, type TokenForReview, type TokenRisk, type TokenRiskCounts } from '$lib/gen'
import { displayDate } from '$lib/utils'
import { sendUserToast } from '$lib/toast'
import { Trash } from 'lucide-svelte'
import { Debounced, watch } from 'runed'
import {
tokenRiskSummary,
TOKEN_RISK_INFO,
TOKEN_RISKS
} from '$lib/components/settings/tokenRisks'
import { MCP_SESSION } from '$lib/components/mcp/McpAccessPicker.svelte'
import { enterpriseLicense } from '$lib/stores'
const perPage = 100
let tokens: TokenForReview[] = $state([])
let counts: TokenRiskCounts | undefined = $state(undefined)
let hasMore = $state(false)
let loading = $state(false)
let loadFailed = $state(false)
let flagFilter: TokenRisk | 'any' | 'all' = $state('any')
let search = $state('')
const debouncedSearch = new Debounced(() => search.trim(), 300)
let toDelete: TokenForReview | undefined = $state(undefined)
let deleting = $state(false)
// Drops a response that a newer filter or search has overtaken.
let requestId = 0
// The last row the server returned, which the shown list may have dropped as a repeat: a
// cursor taken from the shown list would stall on a page of repeats.
let cursor: TokenForReview | undefined = undefined
async function loadCounts() {
try {
counts = await UserService.getTokenRiskCountsAsSuperAdmin()
loadFailed = false
} catch (e) {
loadFailed = true
sendUserToast(`Failed to count tokens: ${e}`, true)
}
}
loadCounts()
async function load(more: boolean) {
const id = ++requestId
const last = more ? cursor : undefined
loading = true
try {
const page = await UserService.listTokensAsSuperAdmin({
flag: flagFilter === 'any' ? undefined : flagFilter,
search: debouncedSearch.current || undefined,
perPage,
afterLastUsedAt: last?.last_used_at,
afterTokenPrefix: last?.token_prefix
})
if (id !== requestId) return
if (more) {
// A token used since the previous page moved behind the cursor and comes back.
const seen = new Set(tokens.map((t) => `${t.email}:${t.token_prefix}`))
tokens = [...tokens, ...page.filter((t) => !seen.has(`${t.email}:${t.token_prefix}`))]
} else {
tokens = page
}
if (page.length > 0) cursor = page[page.length - 1]
hasMore = page.length === perPage
} catch (e) {
if (id !== requestId) return
sendUserToast(`Failed to load tokens: ${e}`, true)
} finally {
if (id === requestId) loading = false
}
}
watch([() => $enterpriseLicense, () => flagFilter, () => debouncedSearch.current], () => {
if ($enterpriseLicense) load(false)
})
let riskSummary = $derived(tokenRiskSummary(counts))
let flagItems = $derived([
{ value: 'any', label: 'Any flag' },
...TOKEN_RISKS.map((r) => ({
value: r,
label: counts ? `${TOKEN_RISK_INFO[r].badge} (${counts[r]})` : TOKEN_RISK_INFO[r].badge
})),
{ value: 'all', label: 'All tokens' }
])
function shownScopes(scopes: string[] | undefined): string {
return (scopes ?? []).filter((s) => s !== MCP_SESSION).join(', ')
}
async function confirmDelete() {
const t = toDelete
if (!t?.email) return
deleting = true
try {
await UserService.deleteTokenAsSuperAdmin({ email: t.email, tokenPrefix: t.token_prefix })
tokens = tokens.filter((x) => !(x.email === t.email && x.token_prefix === t.token_prefix))
if (counts) {
const next = { ...counts }
for (const r of t.risks) next[r] = Math.max(0, next[r] - 1)
counts = next
}
sendUserToast(`Deleted token ${t.token_prefix}**** of ${t.email}`)
toDelete = undefined
} catch (e) {
sendUserToast(`Failed to delete token: ${e}`, true)
} finally {
deleting = false
}
}
</script>
<SettingsPageHeader
title="Token review"
description="API tokens of every user on the instance, least recently used first. Tokens the server expires or renews on its own (login sessions, job, app, MCP and impersonation tokens) are left out."
/>
{#if riskSummary.length > 0}
<div class="mb-4">
<Alert type="warning" size="xs" title="Tokens to review across the instance">
<ul class="list-disc pl-4">
{#each riskSummary as line (line)}
<li>{line}</li>
{/each}
</ul>
</Alert>
</div>
{:else if counts && !loadFailed}
<div class="mb-4">
<Alert type="success" size="xs" title="No token needs a review" />
</div>
{/if}
{#if !$enterpriseLicense}
<Alert type="info" size="xs" title="The token list requires Enterprise Edition">
With an Enterprise license, this page lists every user's tokens, filters them by flag, owner
or label, and deletes any of them.
</Alert>
{:else}
<div class="flex flex-row gap-2 items-center mb-2">
<TextInput
inputProps={{ placeholder: 'Search by email or label' }}
bind:value={search}
class="w-60"
/>
<Select items={flagItems} bind:value={flagFilter} class="w-52" />
</div>
<DataTable loading={loading && tokens.length === 0}>
<Head>
<tr>
<Cell head first>Owner</Cell>
<Cell head>Token</Cell>
<Cell head>Flags</Cell>
<Cell head>Workspace</Cell>
<Cell head>Scopes</Cell>
<Cell head>Last used</Cell>
<Cell head>Expiration</Cell>
<Cell head last></Cell>
</tr>
</Head>
<tbody>
{#each tokens as token, i (`${token.email}:${token.token_prefix}`)}
<tr class={i % 2 === 0 ? 'bg-surface-tertiary' : 'bg-surface'}>
<Cell first><span class="text-xs">{token.email ?? '-'}</span></Cell>
<Cell>
<div class="flex flex-col">
<span class="font-mono text-xs">{token.token_prefix}****</span>
<span class="text-2xs text-secondary truncate max-w-40" title={token.label ?? ''}
>{token.label ?? ''}</span
>
</div>
</Cell>
<Cell>
<div class="flex flex-wrap gap-1">
{#if token.read_only}
<Badge color="blue" small>Read-only</Badge>
{/if}
{#each token.risks as risk (risk)}
<span title={TOKEN_RISK_INFO[risk].tooltip}>
<Badge color={TOKEN_RISK_INFO[risk].color} small
>{TOKEN_RISK_INFO[risk].badge}</Badge
>
</span>
{/each}
</div>
</Cell>
<Cell><span class="text-xs">{token.workspace_id ?? 'All'}</span></Cell>
<Cell>
<span class="text-xs truncate max-w-48 block" title={shownScopes(token.scopes)}
>{shownScopes(token.scopes) || '-'}</span
>
</Cell>
<Cell><span class="whitespace-nowrap text-xs">{displayDate(token.last_used_at)}</span></Cell
>
<Cell>
<span class="whitespace-nowrap text-xs"
>{token.expiration ? displayDate(token.expiration) : 'Never'}</span
>
</Cell>
<Cell last>
<Button
variant="subtle"
destructive
unifiedSize="xs"
title="Delete token"
startIcon={{ icon: Trash }}
iconOnly
disabled={!token.email}
onclick={() => (toDelete = token)}
/>
</Cell>
</tr>
{:else}
{#if !loading}
<tr>
<Cell first last colspan={8}>
<span class="text-secondary italic text-xs">
{flagFilter === 'all' ? 'No tokens' : 'No token has this flag'}
</span>
</Cell>
</tr>
{/if}
{/each}
</tbody>
</DataTable>
{#if hasMore}
<div class="flex justify-center mt-2">
<Button variant="default" unifiedSize="sm" {loading} onclick={() => load(true)}>
Load more
</Button>
</div>
{/if}
{/if}
<ConfirmationModal
open={toDelete !== undefined}
title="Delete token"
confirmationText="Delete"
loading={deleting}
onConfirmed={confirmDelete}
onCanceled={() => (toDelete = undefined)}
>
The token {toDelete?.token_prefix}**** {toDelete?.label ? `(${toDelete.label}) ` : ''}of
{toDelete?.email} stops working immediately. Anything authenticating with it will fail.
</ConfirmationModal>
@@ -5,7 +5,7 @@
import { enterpriseLicense, workspaceStore } from '$lib/stores'
import CollapseLink from '../CollapseLink.svelte'
import TokenInspector from './TokenInspector.svelte'
import { UserService, type TruncatedToken } from '$lib/gen'
import { UserService, type TokenRisk, type TokenRiskCounts, type TruncatedToken } from '$lib/gen'
import { sendUserToast } from '$lib/toast'
import CreateToken from './CreateToken.svelte'
import EditTokenScopesModal from './EditTokenScopesModal.svelte'
@@ -14,6 +14,7 @@
import Alert from '../common/alert/Alert.svelte'
import { Pen, Trash } from 'lucide-svelte'
import { MCP_SESSION } from '../mcp/McpAccessPicker.svelte'
import { tokenRiskSummary, TOKEN_RISK_INFO } from './tokenRisks'
// --- Props ---
interface Props {
@@ -101,6 +102,15 @@
}).length
)
// Over all the user's tokens, not only the page shown.
let riskCounts: TokenRiskCounts | undefined = $state(undefined)
let riskSummary = $derived(tokenRiskSummary(riskCounts))
// The access column already shows a token's workspace and rights.
function rowBadgeRisks(risks: TokenRisk[]): TokenRisk[] {
return risks.filter((r) => r === 'never_expires' || r === 'unused')
}
function handleTokenCreated(token: string) {
onTokenCreated(token)
listTokens()
@@ -136,11 +146,10 @@
}
export async function listTokens(): Promise<void> {
tokens = await UserService.listTokens({
excludeEphemeral: true,
page: tokenPage,
perPage: 100
})
;[tokens, riskCounts] = await Promise.all([
UserService.listTokens({ excludeEphemeral: true, page: tokenPage, perPage: 100 }),
UserService.getTokenRiskCounts()
])
}
function handleNextPage() {
@@ -158,6 +167,20 @@
<div class="text-xs text-secondary mb-2">
Authenticate to the Windmill API with access tokens.
</div>
{#if riskSummary.length > 0}
<div class="mb-2">
<Alert type="warning" title="Some of your tokens need a review" size="xs">
<ul class="list-disc pl-4">
{#each riskSummary as line (line)}
<li>{line}</li>
{/each}
</ul>
A leaked token keeps working until it expires or is deleted. Delete tokens you no longer use,
and give the ones you keep an expiration, the narrowest scopes they need and no admin rights
unless they require them.
</Alert>
</div>
{/if}
{#if expiringSoonCount > 0}
<div class="mb-2">
<Alert
@@ -188,11 +211,25 @@
{#snippet body()}
<tbody>
{#if tokens && tokens.length > 0}
{#each tokens as { token_prefix, expiration, label, scopes, workspace_id, read_only, allowed_ips, admin, super_admin } (token_prefix)}
{#each tokens as { token_prefix, expiration, label, scopes, workspace_id, read_only, allowed_ips, admin, super_admin, risks } (token_prefix)}
{@const rowRisks = rowBadgeRisks(risks)}
{@const badge = expirationBadge(expiration, label)}
<tr>
<td class="w-32 text-xs text-primary">{token_prefix}****</td>
<td class="min-w-0 max-w-32 truncate text-xs text-primary">{label ?? ''}</td>
<td class="min-w-0 max-w-40 text-xs text-primary">
<div class="truncate">{label ?? ''}</div>
{#if rowRisks.length > 0}
<div class="flex flex-wrap gap-1 mt-0.5">
{#each rowRisks as risk (risk)}
<span title={TOKEN_RISK_INFO[risk].tooltip}>
<Badge color={TOKEN_RISK_INFO[risk].color} small>
{TOKEN_RISK_INFO[risk].badge}
</Badge>
</span>
{/each}
</div>
{/if}
</td>
<td class="w-40 whitespace-nowrap text-xs text-secondary">
<div class="flex items-center gap-1.5">
{displayDate(expiration ?? '')}
@@ -0,0 +1,60 @@
import type { TokenRisk, TokenRiskCounts } from '$lib/gen'
/** Mirrors the 90 days the `token_risk` view (backend migrations) flags as unused. */
export const STALE_TOKEN_DAYS = 90
/** How each risk the server flags reads, keyed in the order summaries and filters list them. */
export const TOKEN_RISK_INFO: Record<
TokenRisk,
{
badge: string
color: 'red' | 'orange' | 'yellow'
tooltip: string
summary: (n: number) => string
}
> = {
superadmin: {
badge: 'Superadmin',
color: 'red',
tooltip:
'Minted with superadmin rights and not narrowed by scopes: it carries full control of the instance',
summary: (n) =>
n === 1 ? '1 token carries superadmin rights' : `${n} tokens carry superadmin rights`
},
admin: {
badge: 'Admin',
color: 'orange',
tooltip:
'Minted with admin rights and not narrowed by scopes: it carries full control of the workspace',
summary: (n) => (n === 1 ? '1 token carries admin rights' : `${n} tokens carry admin rights`)
},
all_workspaces: {
badge: 'All workspaces',
color: 'orange',
tooltip: 'Not bound to a workspace: it reaches every workspace its owner belongs to',
summary: (n) =>
n === 1 ? '1 token works in every workspace' : `${n} tokens work in every workspace`
},
never_expires: {
badge: 'No expiration',
color: 'orange',
tooltip: 'Stays valid until it is deleted',
summary: (n) => (n === 1 ? '1 token never expires' : `${n} tokens never expire`)
},
unused: {
badge: `Unused ${STALE_TOKEN_DAYS}d+`,
color: 'yellow',
tooltip: `Not used in over ${STALE_TOKEN_DAYS} days`,
summary: (n) =>
n === 1
? `1 token has not been used in over ${STALE_TOKEN_DAYS} days`
: `${n} tokens have not been used in over ${STALE_TOKEN_DAYS} days`
}
}
export const TOKEN_RISKS = Object.keys(TOKEN_RISK_INFO) as TokenRisk[]
export function tokenRiskSummary(counts: TokenRiskCounts | undefined): string[] {
if (!counts) return []
return TOKEN_RISKS.filter((r) => counts[r] > 0).map((r) => TOKEN_RISK_INFO[r].summary(counts[r]))
}