mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-30 00:07:30 +00:00
feat: edit token expiration and allowed IPs, widen only as far as mintable (#12703)
* feat: edit token expiry and allowed IPs, widening only as far as mintable Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: correct the job-token guard comments on app token mints Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: evict an edited token's cached identity on every API server Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: audit a token's full grant on creation and before/after values on edits Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
f52c117e76
commit
b2f3986f94
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "INSERT INTO notify_event (channel, payload) VALUES ('notify_token_invalidation', $1)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "16003c729b74440f86fe511461f6c091cf865d1a6e877fe69104d59db0e13c61"
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE token t SET label = $1\n FROM token old\n WHERE old.token_hash = t.token_hash\n AND t.email = $2 AND t.token_prefix = $3\n AND (t.label IS NULL OR (\n t.label <> 'session'\n AND t.label <> 'guest_session'\n AND lower(t.label) NOT LIKE 'ephemeral%'\n AND t.label <> 'debugger-token'\n AND t.label NOT LIKE 'mcp-oauth-%'\n AND NOT starts_with(t.label, 'embed_app:')\n AND NOT starts_with(t.label, 'sdk_app:')\n AND NOT starts_with(t.label, 'impersonation:')\n AND NOT starts_with(t.label, 'cli-login:')\n AND NOT starts_with(t.label, 'remote-deploy:')\n ))\n RETURNING t.token_prefix, old.label AS previous_label",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "token_prefix",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "previous_label",
|
||||
"type_info": "Varchar"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Varchar",
|
||||
"Text",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "6141c832d916e87dfb353ac73ae4d06088cbdbac4f1a8e7859adfed4c6f64dac"
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT token_hash, label, scopes, super_admin, admin,\n allowed_ips::text[] AS allowed_ips, expiration, workspace_id\n FROM token\n WHERE email = $1 AND token_prefix = $2\n AND (expiration IS NULL OR expiration > now())\n FOR UPDATE",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "token_hash",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "label",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "scopes",
|
||||
"type_info": "TextArray"
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "super_admin",
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "admin",
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"ordinal": 5,
|
||||
"name": "allowed_ips",
|
||||
"type_info": "TextArray"
|
||||
},
|
||||
{
|
||||
"ordinal": 6,
|
||||
"name": "expiration",
|
||||
"type_info": "Timestamptz"
|
||||
},
|
||||
{
|
||||
"ordinal": 7,
|
||||
"name": "workspace_id",
|
||||
"type_info": "Varchar"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
null,
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "8f7b47cc91a6d520cf40787382f5d511eb8c9f096a7ef0fd9c13db8a88be0cf9"
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE token SET expiration = $1, allowed_ips = $2::text[]::cidr[]\n WHERE token_hash = $3",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Timestamptz",
|
||||
"TextArray",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "a2d0fb45dde296b7011a0cf8a9ae83f33736266736c0f0dd8113f0363db984b2"
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE token SET label = $1\n WHERE email = $2 AND token_prefix = $3\n AND (label IS NULL OR (\n label <> 'session'\n AND label <> 'guest_session'\n AND lower(label) NOT LIKE 'ephemeral%'\n AND label <> 'debugger-token'\n AND label NOT LIKE 'mcp-oauth-%'\n AND NOT starts_with(label, 'embed_app:')\n AND NOT starts_with(label, 'sdk_app:')\n AND NOT starts_with(label, 'impersonation:')\n AND NOT starts_with(label, 'cli-login:')\n AND NOT starts_with(label, 'remote-deploy:')\n ))\n RETURNING token_prefix",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "token_prefix",
|
||||
"type_info": "Varchar"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Varchar",
|
||||
"Text",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "b30fb28004897cd1d201a416cdabf124a055eb44b3c5892fd18ff7baf6010ae9"
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "DELETE FROM token_expiry_notification WHERE token_hash = $1",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "cc6a29cd0de33c439c5e966138fc38fb53dbdbc731fc4441049294ae10958881"
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE token SET scopes = $1\n WHERE email = $2 AND token_prefix = $3\n AND (label IS NULL OR label <> 'guest_session')\n RETURNING token_prefix",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "token_prefix",
|
||||
"type_info": "Varchar"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"TextArray",
|
||||
"Text",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "d17645b5001d7f8da1dc451c5d35ea3c9346271b8404863256071cfdf884036a"
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE token SET scopes = $1 WHERE token_hash = $2",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"TextArray",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "ef655ad80f51c7b5ac50090db46c96e9143a2867c8ac50e6dd8937e24fefb38e"
|
||||
}
|
||||
@@ -615,7 +615,16 @@ pub fn ensure_scopes_within_caller(
|
||||
authed: &ApiAuthed,
|
||||
requested_scopes: Option<&[String]>,
|
||||
) -> error::Result<()> {
|
||||
if let Some(caller_restrictions) = scope_restrictions(authed.scopes.as_deref()) {
|
||||
ensure_scopes_within(authed.scopes.as_deref(), requested_scopes)
|
||||
}
|
||||
|
||||
/// Whether a credential holding `holder_scopes` covers `requested_scopes`, by the rules of
|
||||
/// [`ensure_scopes_within_caller`].
|
||||
pub fn ensure_scopes_within(
|
||||
holder_scopes: Option<&[String]>,
|
||||
requested_scopes: Option<&[String]>,
|
||||
) -> error::Result<()> {
|
||||
if let Some(caller_restrictions) = scope_restrictions(holder_scopes) {
|
||||
let Some(requested_restrictions) = scope_restrictions(requested_scopes) else {
|
||||
return Err(Error::PermissionDenied(
|
||||
"A scope-restricted token cannot create or update a token with broader (unscoped) \
|
||||
@@ -682,7 +691,7 @@ pub fn ensure_scopes_within_caller(
|
||||
// not be able to mint or rescope a credential that drops or widens the fence
|
||||
// — even if the caller has no other scope restrictions (filter_tags-only
|
||||
// tokens otherwise look "unscoped" to `scope_restrictions`).
|
||||
if let Some(caller_tags) = first_filter_tags(authed.scopes.as_deref()) {
|
||||
if let Some(caller_tags) = first_filter_tags(holder_scopes) {
|
||||
let Some(requested_tags) = first_filter_tags(requested_scopes) else {
|
||||
return Err(Error::PermissionDenied(
|
||||
"A token restricted by if_jobs:filter_tags cannot mint or rescope a token that \
|
||||
@@ -704,6 +713,54 @@ pub fn ensure_scopes_within_caller(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What a stored token grants, as a token edit leaves it.
|
||||
pub struct TokenGrant<'a> {
|
||||
pub scopes: Option<&'a [String]>,
|
||||
pub super_admin: bool,
|
||||
pub admin: bool,
|
||||
pub allowed_ips: Option<&'a [IpNet]>,
|
||||
}
|
||||
|
||||
/// Refuse a token edit that widens the token beyond what `authed` could mint through
|
||||
/// `tokens/create` right now. Widening a token in place is then never stronger than minting a
|
||||
/// new one: the scopes, the admin and superadmin rights and the IP allowlist are each held to
|
||||
/// the caller's, as minting holds them.
|
||||
pub fn ensure_grant_within_caller(authed: &ApiAuthed, grant: &TokenGrant) -> error::Result<()> {
|
||||
ensure_scopes_within_caller(authed, grant.scopes)?;
|
||||
let caller_scoped = authed
|
||||
.scopes
|
||||
.as_deref()
|
||||
.is_some_and(|s| s.iter().any(|x| !x.starts_with("if_jobs:filter_tags:")));
|
||||
if grant.super_admin && (caller_scoped || authed.super_admin_withheld) {
|
||||
return Err(Error::NotAuthorized(
|
||||
"Only an unscoped token carrying superadmin rights can widen a superadmin token"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
if grant.admin && authed.admin_withheld {
|
||||
return Err(Error::NotAuthorized(
|
||||
"A token withholding workspace admin rights cannot widen a token carrying them"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
if let Some(caller) = authed.allowed_ips.as_deref() {
|
||||
if !ip_nets_within(caller, grant.allowed_ips) {
|
||||
return Err(Error::PermissionDenied(
|
||||
"A token restricted to IP addresses cannot widen a token beyond the networks it \
|
||||
may be used from itself"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether every network of `inner` lies within `outer`. `None` (usable from anywhere) lies
|
||||
/// within no list.
|
||||
pub fn ip_nets_within(outer: &[IpNet], inner: Option<&[IpNet]>) -> bool {
|
||||
inner.is_some_and(|nets| nets.iter().all(|n| outer.iter().any(|o| o.contains(n))))
|
||||
}
|
||||
|
||||
/// Tags from the first `if_jobs:filter_tags:<a,b,...>` scope, matching the
|
||||
/// semantics of [`get_scope_tags`] (which is what the job runtime consults).
|
||||
/// Returns `None` if no such scope is present.
|
||||
@@ -1415,6 +1472,17 @@ pub async fn create_token_internal(
|
||||
)
|
||||
.await;
|
||||
|
||||
let grant = TokenAuditGrant {
|
||||
label: token_config.label.as_deref(),
|
||||
expiration: token_config.expiration,
|
||||
scopes: token_config.scopes.as_deref(),
|
||||
workspace_id: token_config.workspace_id.as_deref(),
|
||||
read_only: token_config.read_only.unwrap_or(false),
|
||||
allowed_ips: allowed_ips.as_deref(),
|
||||
admin: carries_admin,
|
||||
super_admin: is_super_admin,
|
||||
}
|
||||
.params();
|
||||
audit_log(
|
||||
&mut *tx,
|
||||
authed,
|
||||
@@ -1422,7 +1490,7 @@ pub async fn create_token_internal(
|
||||
ActionKind::Create,
|
||||
&"global",
|
||||
Some(t_prefix),
|
||||
None,
|
||||
Some(audit_params(&grant)),
|
||||
)
|
||||
.instrument(tracing::info_span!("token", email = &authed.email))
|
||||
.await?;
|
||||
@@ -1460,6 +1528,59 @@ pub async fn register_token_expiry_notification(
|
||||
}
|
||||
}
|
||||
|
||||
/// What a minted token row holds, recorded on its creation's audit entry. Token edits record
|
||||
/// their fields' values before and after, so a token's history can be replayed from this.
|
||||
pub struct TokenAuditGrant<'a> {
|
||||
pub label: Option<&'a str>,
|
||||
pub expiration: Option<chrono::DateTime<chrono::Utc>>,
|
||||
pub scopes: Option<&'a [String]>,
|
||||
pub workspace_id: Option<&'a str>,
|
||||
pub read_only: bool,
|
||||
pub allowed_ips: Option<&'a [String]>,
|
||||
pub admin: bool,
|
||||
pub super_admin: bool,
|
||||
}
|
||||
|
||||
impl TokenAuditGrant<'_> {
|
||||
/// Each value JSON-encoded, so a `null` (none, never, anywhere) stays distinct from `""`.
|
||||
pub fn params(&self) -> Vec<(&'static str, String)> {
|
||||
let j = |v: serde_json::Value| v.to_string();
|
||||
vec![
|
||||
("label", j(serde_json::json!(self.label))),
|
||||
("expiration", j(serde_json::json!(self.expiration))),
|
||||
("scopes", j(serde_json::json!(self.scopes))),
|
||||
("workspace_id", j(serde_json::json!(self.workspace_id))),
|
||||
("read_only", j(serde_json::json!(self.read_only))),
|
||||
("allowed_ips", j(serde_json::json!(self.allowed_ips))),
|
||||
("admin", j(serde_json::json!(self.admin))),
|
||||
("super_admin", j(serde_json::json!(self.super_admin))),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// Audit parameters from owned values, as `audit_log` takes them.
|
||||
pub fn audit_params<'a>(params: &'a [(&'a str, String)]) -> HashMap<&'a str, &'a str> {
|
||||
params.iter().map(|(k, v)| (*k, v.as_str())).collect()
|
||||
}
|
||||
|
||||
/// Replace a token's pending expiry notification after its expiration changed, so a token
|
||||
/// extended after its warning went out is warned again before the new date.
|
||||
pub async fn reset_token_expiry_notification(
|
||||
tx: &mut sqlx::PgConnection,
|
||||
token_hash: &str,
|
||||
label: Option<&str>,
|
||||
expiration: Option<chrono::DateTime<chrono::Utc>>,
|
||||
) -> Result<()> {
|
||||
sqlx::query!(
|
||||
"DELETE FROM token_expiry_notification WHERE token_hash = $1",
|
||||
token_hash
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
register_token_expiry_notification(tx, token_hash, label, expiration).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ------------ Permission helpers ------------
|
||||
|
||||
pub fn get_perm_in_extra_perms_for_authed(
|
||||
@@ -1624,6 +1745,24 @@ pub fn require_path_read_access_for_preview(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ip_nets_within_holds_lists_to_the_outer_networks() {
|
||||
let nets = |v: &[&str]| v.iter().map(|x| x.parse().unwrap()).collect::<Vec<IpNet>>();
|
||||
let outer = nets(&["10.0.0.0/8", "192.168.1.0/24"]);
|
||||
assert!(ip_nets_within(
|
||||
&outer,
|
||||
Some(&nets(&["10.1.2.3/32", "192.168.1.0/25"]))
|
||||
));
|
||||
assert!(!ip_nets_within(&outer, Some(&nets(&["10.0.0.0/7"]))));
|
||||
assert!(!ip_nets_within(
|
||||
&outer,
|
||||
Some(&nets(&["10.1.0.0/16", "172.16.0.0/12"]))
|
||||
));
|
||||
// Usable from anywhere lies within no list.
|
||||
assert!(!ip_nets_within(&outer, None));
|
||||
assert!(!ip_nets_within(&[], Some(&nets(&["10.0.0.1/32"]))));
|
||||
}
|
||||
|
||||
fn authed_with_scopes(scopes: Option<Vec<&str>>) -> ApiAuthed {
|
||||
ApiAuthed {
|
||||
scopes: scopes.map(|v| v.into_iter().map(String::from).collect()),
|
||||
|
||||
@@ -77,7 +77,7 @@ async fn test_user_endpoints(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
|
||||
// --- tokens/create ---
|
||||
let resp = authed(client().post(format!("{global_base}/tokens/create")))
|
||||
.json(&json!({"label": "ephemeral-test-token"}))
|
||||
.json(&json!({"label": "test-token"}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1709,3 +1709,120 @@ async fn test_list_tokens_reports_carried_rights(db: Pool<Postgres>) -> anyhow::
|
||||
assert_eq!(rights("SECRET_TOKEN").await?, (Some(false), Some(false)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
|
||||
async fn test_token_edits_widen_only_as_far_as_the_caller_could_mint(
|
||||
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 post = |token: String, path: String, body: serde_json::Value| {
|
||||
let url = format!("{base}/{path}");
|
||||
async move {
|
||||
let resp = client()
|
||||
.post(url)
|
||||
.header("Authorization", format!("Bearer {token}"))
|
||||
.json(&body)
|
||||
.send()
|
||||
.await?;
|
||||
let status = resp.status().as_u16();
|
||||
anyhow::Ok((status, resp.text().await?))
|
||||
}
|
||||
};
|
||||
let mint = |body: serde_json::Value| {
|
||||
let post = post.clone();
|
||||
async move {
|
||||
let (status, token) = post("SECRET_TOKEN".into(), "create".into(), body).await?;
|
||||
anyhow::ensure!(status == 201, "create: {token}");
|
||||
anyhow::Ok(token)
|
||||
}
|
||||
};
|
||||
let prefix = |t: &str| t[..10].to_string();
|
||||
let in_days = |d: u64| {
|
||||
(sqlx::types::chrono::Utc::now() + std::time::Duration::from_secs(d * 86400)).to_rfc3339()
|
||||
};
|
||||
|
||||
let target = prefix(&mint(json!({"label": "target", "expiration": in_days(10)})).await?);
|
||||
let scoped = mint(json!({"label": "scoped", "scopes": ["users:write"]})).await?;
|
||||
|
||||
// A scoped caller may shorten an unscoped token, never extend it: it could not mint one.
|
||||
let limits = format!("update_limits/{target}");
|
||||
let (s, body) = post(
|
||||
scoped.clone(),
|
||||
limits.clone(),
|
||||
json!({"expiration": in_days(5)}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(s, 200, "{body}");
|
||||
let (s, body) = post(
|
||||
scoped.clone(),
|
||||
limits.clone(),
|
||||
json!({"expiration": in_days(20)}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(s, 403, "{body}");
|
||||
let (s, body) = post(scoped.clone(), limits.clone(), json!({"expiration": null})).await?;
|
||||
assert_eq!(s, 403, "{body}");
|
||||
let (s, body) = post(
|
||||
"SECRET_TOKEN".into(),
|
||||
limits,
|
||||
json!({"expiration": in_days(20)}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(s, 200, "{body}");
|
||||
// Other API servers evict their cached copy of the edited token.
|
||||
let evicted: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM notify_event
|
||||
WHERE channel = 'notify_token_invalidation' AND payload = $1)",
|
||||
)
|
||||
.bind(&target)
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
assert!(evicted);
|
||||
|
||||
// Widening the scopes of a superadmin token needs a caller that could mint superadmin.
|
||||
let sa = prefix(
|
||||
&mint(
|
||||
json!({"label": "sa", "super_admin": true, "scopes": ["scripts:read", "users:write"]}),
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
let scoped2 =
|
||||
mint(json!({"label": "s2", "scopes": ["scripts:read", "scripts:write", "users:write"]}))
|
||||
.await?;
|
||||
let rescope = format!("update_scopes/{sa}");
|
||||
let widen = json!({"scopes": ["scripts:write", "users:write"]});
|
||||
let (s, body) = post(scoped2.clone(), rescope.clone(), widen.clone()).await?;
|
||||
assert_eq!(s, 401, "{body}");
|
||||
let (s, body) = post(scoped2, rescope.clone(), json!({"scopes": ["users:write"]})).await?;
|
||||
assert_eq!(s, 200, "{body}");
|
||||
let (s, body) = post("SECRET_TOKEN".into(), rescope, widen).await?;
|
||||
assert_eq!(s, 200, "{body}");
|
||||
|
||||
// A system-labelled token only narrows, and keeps its server-managed lifetime.
|
||||
let embed = prefix(&mint(json!({"label": "embed_app:x", "scopes": ["scripts:read"]})).await?);
|
||||
let rescope = format!("update_scopes/{embed}");
|
||||
let (s, body) = post(
|
||||
"SECRET_TOKEN".into(),
|
||||
rescope.clone(),
|
||||
json!({"scopes": null}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(s, 400, "{body}");
|
||||
let (s, body) = post(
|
||||
"SECRET_TOKEN".into(),
|
||||
rescope,
|
||||
json!({"scopes": ["scripts:read:f/x"]}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(s, 200, "{body}");
|
||||
let (s, body) = post(
|
||||
"SECRET_TOKEN".into(),
|
||||
format!("update_limits/{embed}"),
|
||||
json!({"expiration": in_days(1)}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(s, 400, "{body}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -141,6 +141,10 @@ pub fn global_service() -> Router {
|
||||
"/tokens/update_scopes/{token_prefix}",
|
||||
post(update_token_scopes),
|
||||
)
|
||||
.route(
|
||||
"/tokens/update_limits/{token_prefix}",
|
||||
post(update_token_limits),
|
||||
)
|
||||
.route(
|
||||
"/tokens/update_label/{token_prefix}",
|
||||
post(update_token_label),
|
||||
@@ -3556,6 +3560,18 @@ async fn impersonate(
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut params = windmill_api_auth::TokenAuditGrant {
|
||||
label: new_token.label.as_deref(),
|
||||
expiration,
|
||||
scopes: None,
|
||||
workspace_id: new_token.workspace_id.as_deref(),
|
||||
read_only: false,
|
||||
allowed_ips: allowed_ips.as_deref(),
|
||||
admin: new_token.admin == Some(true),
|
||||
super_admin: is_super_admin,
|
||||
}
|
||||
.params();
|
||||
params.push(("impersonated", impersonated.clone()));
|
||||
audit_log(
|
||||
&mut *tx,
|
||||
&authed,
|
||||
@@ -3563,7 +3579,7 @@ async fn impersonate(
|
||||
ActionKind::Delete,
|
||||
&"global",
|
||||
Some(t_prefix),
|
||||
Some([("impersonated", &format!("{impersonated}")[..])].into()),
|
||||
Some(windmill_api_auth::audit_params(¶ms)),
|
||||
)
|
||||
.instrument(tracing::info_span!("token", email = &impersonated))
|
||||
.await?;
|
||||
@@ -4263,37 +4279,62 @@ async fn update_token_scopes(
|
||||
Path(token_prefix): Path<String>,
|
||||
Json(req): Json<UpdateTokenScopesRequest>,
|
||||
) -> Result<String> {
|
||||
// Widening is what makes a narrowly-scoped mint (app embed, raw-app SDK, MCP
|
||||
// OAuth) recoverable as a general credential: a job token is unscoped, so the
|
||||
// caller check below would let it clear the scopes of any token sharing its
|
||||
// email (GHSA-hfh4-cx4h-3fcr).
|
||||
forbid_elevated_job_token(&db, &authed.email, authed.job_id).await?;
|
||||
// A job token is unscoped, so the caller checks below would let it widen any token
|
||||
// sharing its email (GHSA-hfh4-cx4h-3fcr), and narrowing one breaks whatever holds it.
|
||||
forbid_job_token_account_destruction(&authed)?;
|
||||
windmill_api_auth::ensure_scopes_within_caller(&authed, req.scopes.as_deref())?;
|
||||
|
||||
let mut tx = db.begin().await?;
|
||||
|
||||
let token = lock_owned_token(&mut tx, &authed.email, &token_prefix).await?;
|
||||
// A guest-labelled token is never rescoped: its scopes are its whole confinement,
|
||||
// and after promotion the same email owns an account that could otherwise strip
|
||||
// them from the still-valid guest credential. Same shape as the relabel guard.
|
||||
let updated: Option<String> = sqlx::query_scalar!(
|
||||
"UPDATE token SET scopes = $1
|
||||
WHERE email = $2 AND token_prefix = $3
|
||||
AND (label IS NULL OR label <> 'guest_session')
|
||||
RETURNING token_prefix",
|
||||
req.scopes.as_deref(),
|
||||
&authed.email,
|
||||
&token_prefix,
|
||||
)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
let prefix = updated.ok_or_else(|| {
|
||||
Error::NotFound(format!(
|
||||
// them from the still-valid guest credential.
|
||||
if windmill_common::auth::is_guest_session_label(token.label.as_deref()) {
|
||||
return Err(Error::NotFound(format!(
|
||||
"token {token_prefix} not found, not owned by user, or not rescopable"
|
||||
))
|
||||
})?;
|
||||
)));
|
||||
}
|
||||
let widens =
|
||||
windmill_api_auth::ensure_scopes_within(token.scopes.as_deref(), req.scopes.as_deref())
|
||||
.is_err();
|
||||
if widens {
|
||||
// A system token is minted narrow for one purpose and handed wherever that purpose
|
||||
// needs it (an app's viewers, the editor, a deploy), so widening it in place makes a
|
||||
// general credential of a secret its owner never held. A sign-in the owner approved
|
||||
// for an MCP client is theirs to widen.
|
||||
let label = token.label.as_deref();
|
||||
if !windmill_common::auth::is_user_token(label)
|
||||
&& !label.is_some_and(|l| l.starts_with("mcp-oauth-"))
|
||||
{
|
||||
return Err(Error::BadRequest(
|
||||
"the scopes of a token the server minted can only be narrowed".to_string(),
|
||||
));
|
||||
}
|
||||
let allowed_ips =
|
||||
windmill_api_auth::token_ip_allowlist_oss::load_allowed_ips(token.allowed_ips.clone());
|
||||
windmill_api_auth::ensure_grant_within_caller(
|
||||
&authed,
|
||||
&windmill_api_auth::TokenGrant {
|
||||
scopes: req.scopes.as_deref(),
|
||||
super_admin: token.super_admin,
|
||||
admin: token.admin,
|
||||
allowed_ips: allowed_ips.as_deref(),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"UPDATE token SET scopes = $1 WHERE token_hash = $2",
|
||||
req.scopes.as_deref(),
|
||||
&token.token_hash,
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let prefix = token_prefix;
|
||||
|
||||
let scopes_json = serde_json::to_string(&req.scopes).unwrap_or_default();
|
||||
let previous_json = serde_json::to_string(&token.scopes).unwrap_or_default();
|
||||
audit_log(
|
||||
&mut *tx,
|
||||
&authed,
|
||||
@@ -4301,7 +4342,13 @@ async fn update_token_scopes(
|
||||
ActionKind::Update,
|
||||
&"global",
|
||||
Some(&prefix),
|
||||
Some([("scopes", scopes_json.as_str())].into()),
|
||||
Some(
|
||||
[
|
||||
("scopes", scopes_json.as_str()),
|
||||
("previous_scopes", previous_json.as_str()),
|
||||
]
|
||||
.into(),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -4312,6 +4359,210 @@ async fn update_token_scopes(
|
||||
Ok(format!("updated scopes for token {prefix}"))
|
||||
}
|
||||
|
||||
/// The grant of a token row a token edit compares the requested change against.
|
||||
struct OwnedToken {
|
||||
token_hash: String,
|
||||
label: Option<String>,
|
||||
scopes: Option<Vec<String>>,
|
||||
super_admin: bool,
|
||||
admin: bool,
|
||||
allowed_ips: Option<Vec<String>>,
|
||||
expiration: Option<chrono::DateTime<chrono::Utc>>,
|
||||
workspace_id: Option<String>,
|
||||
}
|
||||
|
||||
async fn lock_owned_token(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
email: &str,
|
||||
token_prefix: &str,
|
||||
) -> Result<OwnedToken> {
|
||||
sqlx::query_as!(
|
||||
OwnedToken,
|
||||
r#"SELECT token_hash, label, scopes, super_admin, admin,
|
||||
allowed_ips::text[] AS allowed_ips, expiration, workspace_id
|
||||
FROM token
|
||||
WHERE email = $1 AND token_prefix = $2
|
||||
AND (expiration IS NULL OR expiration > now())
|
||||
FOR UPDATE"#,
|
||||
email,
|
||||
token_prefix,
|
||||
)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
Error::NotFound(format!(
|
||||
"token {token_prefix} not found or not owned by user"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Deserializes a field that is present into `Some`, so `Option<Option<T>>` tells an absent
|
||||
/// field (`None`, leave as is) from an explicit `null` (`Some(None)`, clear it).
|
||||
fn present<'de, D, T>(d: D) -> std::result::Result<Option<T>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
T::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct UpdateTokenLimitsRequest {
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
expiration: Option<Option<chrono::DateTime<chrono::Utc>>>,
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
allowed_ips: Option<Option<Vec<String>>>,
|
||||
}
|
||||
|
||||
/// Change when a token expires and which networks it may be used from. Tightening either is
|
||||
/// always allowed; widening only to what the caller could mint through `tokens/create` now.
|
||||
async fn update_token_limits(
|
||||
Extension(db): Extension<DB>,
|
||||
authed: ApiAuthed,
|
||||
Path(token_prefix): Path<String>,
|
||||
Json(req): Json<UpdateTokenLimitsRequest>,
|
||||
) -> Result<String> {
|
||||
forbid_job_token_account_destruction(&authed)?;
|
||||
if req.expiration.is_none() && req.allowed_ips.is_none() {
|
||||
return Err(Error::BadRequest(
|
||||
"nothing to update: pass expiration or allowed_ips".to_string(),
|
||||
));
|
||||
}
|
||||
if let Some(Some(expiration)) = req.expiration {
|
||||
if expiration <= chrono::Utc::now() {
|
||||
return Err(Error::BadRequest(
|
||||
"expiration must be in the future; delete the token to revoke it".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
// Validated and normalized as on create, the caller's own networks applied below.
|
||||
let requested_ips = match &req.allowed_ips {
|
||||
None => None,
|
||||
Some(None) => Some(None),
|
||||
Some(Some(list)) => Some(windmill_api_auth::token_ip_allowlist(None, Some(list))?),
|
||||
};
|
||||
|
||||
let mut tx = db.begin().await?;
|
||||
let token = lock_owned_token(&mut tx, &authed.email, &token_prefix).await?;
|
||||
// System tokens' lifetimes and reach are the server's to manage (sessions are refreshed,
|
||||
// app and SDK tokens live as long as the open app, OAuth grants follow their refresh).
|
||||
if !windmill_common::auth::is_user_token(token.label.as_deref()) {
|
||||
return Err(Error::BadRequest(
|
||||
"only the expiration and allowed IPs of a token you created can be changed".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
use windmill_api_auth::token_ip_allowlist_oss::load_allowed_ips;
|
||||
let stored_ips = load_allowed_ips(token.allowed_ips.clone());
|
||||
let new_ips_text = match &requested_ips {
|
||||
None => token.allowed_ips.clone(),
|
||||
Some(ips) => ips.clone(),
|
||||
};
|
||||
let new_ips = load_allowed_ips(new_ips_text.clone());
|
||||
let widens_ips = requested_ips.is_some()
|
||||
&& stored_ips
|
||||
.as_deref()
|
||||
.is_some_and(|old| !windmill_api_auth::ip_nets_within(old, new_ips.as_deref()));
|
||||
|
||||
let (expiration, widens_expiration) = match req.expiration {
|
||||
None => (token.expiration, false),
|
||||
Some(requested) => {
|
||||
let widens = match (token.expiration, requested) {
|
||||
(None, _) => false,
|
||||
(Some(_), None) => true,
|
||||
(Some(old), Some(new)) => new > old,
|
||||
};
|
||||
let expiration = if widens {
|
||||
cap_token_expiration(&db, &authed.email, token.workspace_id.as_deref(), requested)
|
||||
.await?
|
||||
} else {
|
||||
requested
|
||||
};
|
||||
(expiration, widens)
|
||||
}
|
||||
};
|
||||
|
||||
if widens_ips || widens_expiration {
|
||||
windmill_api_auth::ensure_grant_within_caller(
|
||||
&authed,
|
||||
&windmill_api_auth::TokenGrant {
|
||||
scopes: token.scopes.as_deref(),
|
||||
super_admin: token.super_admin,
|
||||
admin: token.admin,
|
||||
allowed_ips: new_ips.as_deref(),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"UPDATE token SET expiration = $1, allowed_ips = $2::text[]::cidr[]
|
||||
WHERE token_hash = $3",
|
||||
expiration,
|
||||
new_ips_text.as_deref(),
|
||||
&token.token_hash,
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
// Other API servers drop their cached identity, which carries the old list, on this
|
||||
// event; `invalidate_token_from_cache` below only reaches this process.
|
||||
sqlx::query!(
|
||||
"INSERT INTO notify_event (channel, payload) VALUES ('notify_token_invalidation', $1)",
|
||||
&token_prefix,
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if expiration != token.expiration {
|
||||
windmill_api_auth::reset_token_expiry_notification(
|
||||
&mut *tx,
|
||||
&token.token_hash,
|
||||
token.label.as_deref(),
|
||||
expiration,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
let j = |v: serde_json::Value| v.to_string();
|
||||
let changed: Vec<&str> = [
|
||||
req.expiration.is_some().then_some("expiration"),
|
||||
req.allowed_ips.is_some().then_some("allowed_ips"),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect();
|
||||
let mut params = vec![
|
||||
("changed", j(serde_json::json!(changed))),
|
||||
("expiration", j(serde_json::json!(expiration))),
|
||||
(
|
||||
"previous_expiration",
|
||||
j(serde_json::json!(token.expiration)),
|
||||
),
|
||||
("allowed_ips", j(serde_json::json!(new_ips_text))),
|
||||
(
|
||||
"previous_allowed_ips",
|
||||
j(serde_json::json!(token.allowed_ips)),
|
||||
),
|
||||
];
|
||||
// Shortened by `max_token_expiration_days`.
|
||||
if let Some(requested) = req.expiration.filter(|r| *r != expiration) {
|
||||
params.push(("requested_expiration", j(serde_json::json!(requested))));
|
||||
}
|
||||
audit_log(
|
||||
&mut *tx,
|
||||
&authed,
|
||||
"users.token.update_limits",
|
||||
ActionKind::Update,
|
||||
&"global",
|
||||
Some(&token_prefix),
|
||||
Some(windmill_api_auth::audit_params(¶ms)),
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
|
||||
windmill_api_auth::invalidate_token_from_cache(&token_prefix);
|
||||
|
||||
Ok(format!("updated limits for token {token_prefix}"))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct UpdateTokenLabelRequest {
|
||||
label: Option<String>,
|
||||
@@ -4354,34 +4605,38 @@ async fn update_token_label(
|
||||
// load-bearing labels described above. This SQL mirrors the canonical
|
||||
// `windmill_common::auth::is_user_token`; keep the two in sync (note the
|
||||
// case-insensitive `ephemeral` match).
|
||||
let updated: Option<String> = sqlx::query_scalar!(
|
||||
"UPDATE token SET label = $1
|
||||
WHERE email = $2 AND token_prefix = $3
|
||||
AND (label IS NULL OR (
|
||||
label <> 'session'
|
||||
AND label <> 'guest_session'
|
||||
AND lower(label) NOT LIKE 'ephemeral%'
|
||||
AND label <> 'debugger-token'
|
||||
AND label NOT LIKE 'mcp-oauth-%'
|
||||
AND NOT starts_with(label, 'embed_app:')
|
||||
AND NOT starts_with(label, 'sdk_app:')
|
||||
AND NOT starts_with(label, 'impersonation:')
|
||||
AND NOT starts_with(label, 'cli-login:')
|
||||
AND NOT starts_with(label, 'remote-deploy:')
|
||||
// `old` is the row as it stood before this statement, for the audit entry.
|
||||
let updated = sqlx::query!(
|
||||
"UPDATE token t SET label = $1
|
||||
FROM token old
|
||||
WHERE old.token_hash = t.token_hash
|
||||
AND t.email = $2 AND t.token_prefix = $3
|
||||
AND (t.label IS NULL OR (
|
||||
t.label <> 'session'
|
||||
AND t.label <> 'guest_session'
|
||||
AND lower(t.label) NOT LIKE 'ephemeral%'
|
||||
AND t.label <> 'debugger-token'
|
||||
AND t.label NOT LIKE 'mcp-oauth-%'
|
||||
AND NOT starts_with(t.label, 'embed_app:')
|
||||
AND NOT starts_with(t.label, 'sdk_app:')
|
||||
AND NOT starts_with(t.label, 'impersonation:')
|
||||
AND NOT starts_with(t.label, 'cli-login:')
|
||||
AND NOT starts_with(t.label, 'remote-deploy:')
|
||||
))
|
||||
RETURNING token_prefix",
|
||||
RETURNING t.token_prefix, old.label AS previous_label",
|
||||
req.label.as_deref(),
|
||||
&authed.email,
|
||||
&token_prefix,
|
||||
)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
let prefix = updated.ok_or_else(|| {
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
Error::NotFound(format!(
|
||||
"token {token_prefix} not found, not owned by user, or not editable"
|
||||
))
|
||||
})?;
|
||||
let prefix = updated.token_prefix;
|
||||
let previous_label = updated.previous_label.unwrap_or_default();
|
||||
|
||||
audit_log(
|
||||
&mut *tx,
|
||||
@@ -4390,7 +4645,13 @@ async fn update_token_label(
|
||||
ActionKind::Update,
|
||||
&"global",
|
||||
Some(&prefix),
|
||||
Some([("label", req.label.as_deref().unwrap_or(""))].into()),
|
||||
Some(
|
||||
[
|
||||
("label", req.label.as_deref().unwrap_or("")),
|
||||
("previous_label", previous_label.as_str()),
|
||||
]
|
||||
.into(),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
|
||||
|
||||
@@ -7888,6 +7888,49 @@ paths:
|
||||
schema:
|
||||
type: string
|
||||
|
||||
/users/tokens/update_limits/{token_prefix}:
|
||||
post:
|
||||
summary: update expiration and allowed IPs of an existing token (owner only)
|
||||
description: |
|
||||
Tightening (an earlier expiration, a narrower IP list) is always allowed on a token you
|
||||
created. Widening is allowed only as far as the calling token could mint a new token
|
||||
with the same rights, and a later expiration is capped by `max_token_expiration_days`.
|
||||
operationId: updateTokenLimits
|
||||
tags:
|
||||
- user
|
||||
parameters:
|
||||
- name: token_prefix
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
requestBody:
|
||||
description: fields left out are unchanged, null clears
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
expiration:
|
||||
type: string
|
||||
format: date-time
|
||||
nullable: true
|
||||
description: new expiration (null = never expires)
|
||||
allowed_ips:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
nullable: true
|
||||
description: IPs or CIDRs the token may be used from (null = anywhere)
|
||||
responses:
|
||||
"200":
|
||||
description: limits updated
|
||||
content:
|
||||
text/plain:
|
||||
schema:
|
||||
type: string
|
||||
|
||||
/users/tokens/update_label/{token_prefix}:
|
||||
post:
|
||||
summary: update label of an existing token (owner only)
|
||||
|
||||
@@ -1604,8 +1604,8 @@ async fn mint_raw_app_sdk_token(
|
||||
) -> Result<(String, chrono::DateTime<chrono::Utc>)> {
|
||||
// This credential outlives the request, so an ephemeral job token must not be
|
||||
// able to launder itself into one — the reason `users/tokens/create` refuses.
|
||||
// The minted scopes do not contain it: `users/tokens/update_scopes` can widen
|
||||
// any token of the same email.
|
||||
// The minted scopes do not contain it: they only bound what the token reaches,
|
||||
// not the identity it carries without the job's provenance.
|
||||
forbid_elevated_job_token(db, &authed.email, job_id).await?;
|
||||
// An embed token represents untrusted app JS; it must not bootstrap a
|
||||
// broader SDK credential (same guard as `mint_app_embed_token`).
|
||||
@@ -1877,9 +1877,9 @@ pub async fn mint_app_embed_token(
|
||||
job_id: Option<uuid::Uuid>,
|
||||
) -> Result<EmbedTokenResponse> {
|
||||
let token_and_exp = if let Some(authed) = opt_authed {
|
||||
// This credential outlives the request and its narrow scopes are not the
|
||||
// boundary — `users/tokens/update_scopes` can widen any same-email token —
|
||||
// so an elevated job token must not mint one (GHSA-hfh4-cx4h-3fcr).
|
||||
// This credential outlives the request and carries the job's identity without
|
||||
// the job's provenance, so an elevated job token must not mint one, whatever
|
||||
// its scopes (GHSA-hfh4-cx4h-3fcr).
|
||||
forbid_elevated_job_token(db, &authed.email, job_id).await?;
|
||||
// An app embed token represents untrusted app JS in the sandboxed iframe; it
|
||||
// must never reach this mint path to renew itself. The 12h expiry is the
|
||||
|
||||
@@ -116,6 +116,21 @@ Symbols, not line numbers, are cited: they drift less.
|
||||
stores the `super_admin` request on its code and refresh rows, and each exchange re-checks
|
||||
`password`. A new path minting a token must ask the same questions, or it reaches a different
|
||||
set of workspaces than the others.
|
||||
- **Editing a token widens it only as far as the caller could mint it**
|
||||
(`tokens/update_scopes`, `tokens/update_limits` for expiration and `allowed_ips`). Narrowing is
|
||||
always allowed; a change that widens any of them (scopes outside the stored ones, a later or
|
||||
removed expiration, networks outside the stored list or none) must leave a token
|
||||
`ensure_grant_within_caller` accepts: scopes within the caller's, no superadmin unless the caller
|
||||
is unscoped and carries it, no admin the caller withholds, networks within the caller's. A later
|
||||
expiration goes through `cap_token_expiration`, and changing it re-registers the expiry warning.
|
||||
Only user tokens (`is_user_token`) take limit edits, and only they or an MCP OAuth sign-in widen
|
||||
scopes: a system token is minted narrow for wherever it is handed. Every job token is refused,
|
||||
since `$WM_TOKEN` is unscoped and narrowing breaks whatever holds the token.
|
||||
- **A token's history replays from the audit log.** `users.token.create` and `users.impersonate`
|
||||
record everything the row holds (`TokenAuditGrant`), and each edit records its fields before and
|
||||
after (`update_limits` also which fields were asked for, and the requested expiration when the
|
||||
ceiling shortened it). A new token path or column must keep both, or the chain breaks. Not
|
||||
audited: the superadmin-demotion trigger, the expired-token sweep, and refused edits.
|
||||
- **Every superadmin route refuses a job token**: `require_super_admin`
|
||||
(`windmill-api-auth/src/lib.rs`) errors on `authed.job_id.is_some()`. A script that needs
|
||||
`users/create`, `tokens/impersonate`, `set_login_type`, … must use a dedicated superadmin user
|
||||
|
||||
@@ -12,7 +12,9 @@
|
||||
mcpAccessOf
|
||||
} from '../mcp/McpAccessPicker.svelte'
|
||||
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
|
||||
import { usersWorkspaceStore } from '$lib/stores'
|
||||
import { enterpriseLicense, usersWorkspaceStore } from '$lib/stores'
|
||||
import Select from '../select/Select.svelte'
|
||||
import { displayDate } from '$lib/utils'
|
||||
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
|
||||
@@ -20,10 +22,13 @@
|
||||
open: boolean
|
||||
tokenPrefix?: string
|
||||
initialLabel?: string
|
||||
/** When false, the label is shown read-only (system tokens — see `isUserToken`). */
|
||||
/** When false, the label, expiration and allowed IPs are read-only (system tokens — see
|
||||
* `isUserToken`). */
|
||||
labelEditable?: boolean
|
||||
initialScopes?: string[]
|
||||
tokenWorkspaceId?: string
|
||||
initialExpiration?: string
|
||||
initialAllowedIps?: string[]
|
||||
onSaved?: () => void
|
||||
}
|
||||
|
||||
@@ -34,9 +39,32 @@
|
||||
labelEditable = true,
|
||||
initialScopes,
|
||||
tokenWorkspaceId,
|
||||
initialExpiration,
|
||||
initialAllowedIps,
|
||||
onSaved
|
||||
}: Props = $props()
|
||||
|
||||
const DAY_SECS = 24 * 60 * 60
|
||||
type ExpirationChoice = 'keep' | 'never' | number
|
||||
const expirationItems: { label: string; value: ExpirationChoice }[] = [
|
||||
{ label: 'Keep current', value: 'keep' },
|
||||
{ label: '1 hour from now', value: 60 * 60 },
|
||||
{ label: '1 day from now', value: DAY_SECS },
|
||||
{ label: '7 days from now', value: 7 * DAY_SECS },
|
||||
{ label: '30 days from now', value: 30 * DAY_SECS },
|
||||
{ label: '90 days from now', value: 90 * DAY_SECS },
|
||||
{ label: '180 days from now', value: 180 * DAY_SECS },
|
||||
{ label: '365 days from now', value: 365 * DAY_SECS },
|
||||
{ label: 'Never', value: 'never' }
|
||||
]
|
||||
let expirationChoice = $state<ExpirationChoice>('keep')
|
||||
let allowedIpsText = $state('')
|
||||
const parseIps = (text: string) =>
|
||||
text
|
||||
.split(/[\s,]+/)
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.length > 0)
|
||||
|
||||
// Treat as MCP only when *all* existing scopes are mcp:* — mixed-scope or
|
||||
// null-scope tokens fall back to the standard picker so non-MCP scopes are
|
||||
// never silently dropped.
|
||||
@@ -99,6 +127,8 @@
|
||||
untrack(() => {
|
||||
labelValue = initialLabel ?? ''
|
||||
mcpTouched = false
|
||||
expirationChoice = 'keep'
|
||||
allowedIpsText = (initialAllowedIps ?? []).join(', ')
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -131,7 +161,22 @@
|
||||
requestBody: { scopes: scopesToSave }
|
||||
})
|
||||
}
|
||||
if (labelChanged || scopesChanged) {
|
||||
const limits: { expiration?: string | null; allowed_ips?: string[] | null } = {}
|
||||
if (labelEditable && expirationChoice !== 'keep') {
|
||||
limits.expiration =
|
||||
expirationChoice === 'never'
|
||||
? null
|
||||
: new Date(Date.now() + expirationChoice * 1000).toISOString()
|
||||
}
|
||||
const ips = parseIps(allowedIpsText)
|
||||
if (labelEditable && $enterpriseLicense && !scopesEqual(ips, initialAllowedIps ?? [])) {
|
||||
limits.allowed_ips = ips.length > 0 ? ips : null
|
||||
}
|
||||
const limitsChanged = Object.keys(limits).length > 0
|
||||
if (limitsChanged) {
|
||||
await UserService.updateTokenLimits({ tokenPrefix, requestBody: limits })
|
||||
}
|
||||
if (labelChanged || scopesChanged || limitsChanged) {
|
||||
sendUserToast('Token updated')
|
||||
}
|
||||
onSaved?.()
|
||||
@@ -164,6 +209,33 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if labelEditable}
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="text-xs font-semibold text-emphasis">Expiration</span>
|
||||
<span class="text-2xs text-secondary">
|
||||
Currently {initialExpiration ? displayDate(initialExpiration) : 'never expires'}
|
||||
</span>
|
||||
<Select bind:value={expirationChoice} inputClass="w-full" items={expirationItems} />
|
||||
<p class="text-2xs text-hint">
|
||||
A later expiration is shortened to this instance's maximum token lifetime, if it has one.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{#if $enterpriseLicense}
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="text-xs font-semibold text-emphasis">Allowed IPs</span>
|
||||
<TextInput
|
||||
inputProps={{ type: 'text', placeholder: '203.0.113.4, 10.0.0.0/8' }}
|
||||
bind:value={allowedIpsText}
|
||||
class="w-full"
|
||||
/>
|
||||
<p class="text-2xs text-hint">
|
||||
IP addresses or CIDR ranges, separated by commas. Leave empty to allow any.
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
{#if !isMcp}
|
||||
<span class="text-xs font-semibold text-emphasis">Scopes</span>
|
||||
|
||||
@@ -35,6 +35,8 @@
|
||||
label: string | undefined
|
||||
scopes: string[] | undefined
|
||||
workspaceId: string | undefined
|
||||
expiration: string | undefined
|
||||
allowedIps: string[] | undefined
|
||||
}
|
||||
| undefined
|
||||
>(undefined)
|
||||
@@ -118,13 +120,17 @@
|
||||
tokenPrefix: string,
|
||||
tokenLabel: string | undefined,
|
||||
tokenScopes: string[] | undefined,
|
||||
tokenWorkspaceId: string | undefined
|
||||
tokenWorkspaceId: string | undefined,
|
||||
tokenExpiration: string | undefined,
|
||||
tokenAllowedIps: string[] | undefined
|
||||
) {
|
||||
editingToken = {
|
||||
prefix: tokenPrefix,
|
||||
label: tokenLabel,
|
||||
scopes: tokenScopes,
|
||||
workspaceId: tokenWorkspaceId
|
||||
workspaceId: tokenWorkspaceId,
|
||||
expiration: tokenExpiration,
|
||||
allowedIps: tokenAllowedIps
|
||||
}
|
||||
editModalOpen = true
|
||||
}
|
||||
@@ -241,7 +247,9 @@
|
||||
token_prefix,
|
||||
label ?? undefined,
|
||||
scopes ?? undefined,
|
||||
workspace_id ?? undefined
|
||||
workspace_id ?? undefined,
|
||||
expiration ?? undefined,
|
||||
allowed_ips ?? undefined
|
||||
)}
|
||||
size="xs"
|
||||
startIcon={{ icon: Pen }}
|
||||
@@ -297,5 +305,7 @@
|
||||
labelEditable={isUserToken(editingToken?.label)}
|
||||
initialScopes={editingToken?.scopes}
|
||||
tokenWorkspaceId={editingToken?.workspaceId}
|
||||
initialExpiration={editingToken?.expiration}
|
||||
initialAllowedIps={editingToken?.allowedIps}
|
||||
onSaved={listTokens}
|
||||
/>
|
||||
|
||||
Reference in New Issue
Block a user