feat: add token introspection endpoint and token test UI (#12702)

* feat: add token introspection endpoint and token test UI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PjsYvuQ2VAhEVRfa9AiGq9

* fix: report effective superadmin rights in token introspection

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PjsYvuQ2VAhEVRfa9AiGq9

* fix: resolve guest tokens and check webhooks by path in token introspection

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PjsYvuQ2VAhEVRfa9AiGq9

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ruben Fiszel
2026-11-27 15:24:00 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 5b3a40b1a4
commit 55aec82102
9 changed files with 933 additions and 64 deletions
@@ -0,0 +1,88 @@
{
"db_name": "PostgreSQL",
"query": "SELECT owner, email, label, token_prefix, created_at, expiration, workspace_id,\n scopes, read_only, super_admin, admin, allowed_ips::text[] AS allowed_ips\n FROM token\n WHERE token_hash = $1 AND (expiration > NOW() OR expiration IS NULL)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "owner",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "email",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "label",
"type_info": "Varchar"
},
{
"ordinal": 3,
"name": "token_prefix",
"type_info": "Varchar"
},
{
"ordinal": 4,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 5,
"name": "expiration",
"type_info": "Timestamptz"
},
{
"ordinal": 6,
"name": "workspace_id",
"type_info": "Varchar"
},
{
"ordinal": 7,
"name": "scopes",
"type_info": "TextArray"
},
{
"ordinal": 8,
"name": "read_only",
"type_info": "Bool"
},
{
"ordinal": 9,
"name": "super_admin",
"type_info": "Bool"
},
{
"ordinal": 10,
"name": "admin",
"type_info": "Bool"
},
{
"ordinal": 11,
"name": "allowed_ips",
"type_info": "TextArray"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
true,
true,
true,
false,
false,
true,
true,
true,
false,
false,
false,
null
]
},
"hash": "bcc9c9a09ecf260a9221037285e0f7d6892b8f91fee8db3563bffe87ab4ed889"
}
+68 -60
View File
@@ -1364,7 +1364,7 @@ pub fn transform_old_scope_to_new_scope(scopes: Option<&mut Vec<String>>) {
}
}
fn maybe_get_workspace_id_from_path(path_vec: &[&str]) -> Option<String> {
pub fn maybe_get_workspace_id_from_path(path_vec: &[&str]) -> Option<String> {
let workspace_id = if path_vec.len() >= 4 && path_vec[0] == "" && path_vec[2] == "w" {
Some(path_vec[3].to_owned())
} else if path_vec.len() >= 5
@@ -1484,66 +1484,18 @@ pub async fn resolve_opt_job_authed(
if let Some(mut opt_job_authed) = resolved {
let path = original_uri.path();
let method = parts.method.as_str();
if workspace_id.is_none() && opt_job_authed.job_id.is_some() {
if let Err(err) = crate::scopes::check_job_token_for_global_route(path, method)
{
return Err((err, parts));
}
}
let own_job_runtime_route = match opt_job_authed.job_id {
Some(job_id) if opt_job_authed.authed.scopes.is_some() => {
crate::scopes::is_own_job_runtime_route(path, method, job_id)
|| match crate::scopes::flow_run_read_route_job(path, method) {
Some(target) => {
job_in_same_flow_run(&cache.db, job_id, target).await
}
None => false,
}
}
_ => false,
};
let authed = &mut opt_job_authed.authed;
if authed.scopes.is_some() && !own_job_runtime_route {
transform_old_scope_to_new_scope(authed.scopes.as_mut());
if let Some(w_id) = workspace_id.as_deref() {
expand_filter_tags_for_dev_workspace(
&cache.db,
w_id,
authed.scopes.as_mut(),
)
.await;
}
if let Err(err) = crate::scopes::check_scopes_for_route(
authed.scopes.as_deref(),
path,
method,
) {
return Err((err, parts));
}
}
if authed.read_only {
// MCP transport runs over POST (streamable HTTP / SSE handshake),
// so the middleware can't safely reject mutating methods on it —
// the MCP runner itself filters out write tools and rejects
// mutating tool calls for read-only tokens. Narrow to the actual
// transport endpoints: anything else under `/api/mcp/*` (OAuth
// approve, token exchange, client registration) must still go
// through the read-only check, otherwise a read-only token
// could approve an OAuth flow that mints a new non-read-only
// token.
let is_mcp_transport = path == "/api/mcp/gateway"
|| path == "/api/mcp"
|| (path.starts_with("/api/mcp/w/")
&& (path.ends_with("/mcp")
|| path.ends_with("/sse")
|| path.ends_with("/list_tools")));
if !is_mcp_transport {
if let Err(err) = crate::scopes::check_read_only_for_route(path, method) {
return Err((err, parts));
}
}
if let Err(err) = check_route_layer(
&cache.db,
&mut opt_job_authed,
workspace_id.as_deref(),
path,
method,
)
.await
{
return Err((err, parts));
}
let authed = &opt_job_authed.authed;
parts.extensions.insert(authed.clone());
Span::current().record("username", &authed.username.as_str());
@@ -1578,6 +1530,62 @@ pub async fn resolve_opt_job_authed(
Err((Error::NotAuthorized("Unauthorized".to_string()), parts))
}
/// The route checks every request passes before its handler runs: job-token confinement,
/// scopes and `read_only`. `workspace_id` is the request's workspace, `None` on a global route.
/// Normalizes `opt_job_authed`'s scopes in place, as handlers then read them. Token
/// introspection calls this to report a verdict, so a check added to the route layer belongs
/// here rather than beside the call in `resolve_opt_job_authed`.
pub async fn check_route_layer(
db: &DB,
opt_job_authed: &mut OptJobAuthed,
workspace_id: Option<&str>,
path: &str,
method: &str,
) -> windmill_common::error::Result<()> {
if workspace_id.is_none() && opt_job_authed.job_id.is_some() {
crate::scopes::check_job_token_for_global_route(path, method)?;
}
let own_job_runtime_route = match opt_job_authed.job_id {
Some(job_id) if opt_job_authed.authed.scopes.is_some() => {
crate::scopes::is_own_job_runtime_route(path, method, job_id)
|| match crate::scopes::flow_run_read_route_job(path, method) {
Some(target) => job_in_same_flow_run(db, job_id, target).await,
None => false,
}
}
_ => false,
};
let authed = &mut opt_job_authed.authed;
if authed.scopes.is_some() && !own_job_runtime_route {
transform_old_scope_to_new_scope(authed.scopes.as_mut());
if let Some(w_id) = workspace_id {
expand_filter_tags_for_dev_workspace(db, w_id, authed.scopes.as_mut()).await;
}
crate::scopes::check_scopes_for_route(authed.scopes.as_deref(), path, method)?;
}
if authed.read_only {
// MCP transport runs over POST (streamable HTTP / SSE handshake),
// so the middleware can't safely reject mutating methods on it —
// the MCP runner itself filters out write tools and rejects
// mutating tool calls for read-only tokens. Narrow to the actual
// transport endpoints: anything else under `/api/mcp/*` (OAuth
// approve, token exchange, client registration) must still go
// through the read-only check, otherwise a read-only token
// could approve an OAuth flow that mints a new non-read-only
// token.
let is_mcp_transport = path == "/api/mcp/gateway"
|| path == "/api/mcp"
|| (path.starts_with("/api/mcp/w/")
&& (path.ends_with("/mcp")
|| path.ends_with("/sse")
|| path.ends_with("/list_tools")));
if !is_mcp_transport {
crate::scopes::check_read_only_for_route(path, method)?;
}
}
Ok(())
}
/// Returns the override and whether it names the token's *label* rather than the entity that
/// fired the request. Callers must not re-derive the second element from the first: the
/// `ephemeral-script-end-user-` arm forwards a `created_by` verbatim, and `created_by` is
+153
View File
@@ -7426,6 +7426,43 @@ paths:
items:
$ref: "#/components/schemas/ScopeDomain"
/tokens/introspect:
get:
summary: describe the token presenting the request
description: |
Reports what the bearer credential of this request is: its row (label, expiry, bound
workspace, scopes, carried admin rights), the identity it acts as in `workspace`, and
whether the route layer would admit it on `method` `path`. Only the presented token is
ever described. Every token may call it, whatever its scopes.
operationId: introspectToken
tags:
- token
parameters:
- name: workspace
description: workspace to resolve the token's identity in
in: query
schema:
type: string
- name: path
description: |
route to check, either a full `/api/...` path or a path relative to
`/api/w/{workspace}/`
in: query
schema:
type: string
- name: method
description: HTTP method of the route to check (GET by default)
in: query
schema:
type: string
responses:
"200":
description: what the token is and may do
content:
application/json:
schema:
$ref: "#/components/schemas/TokenIntrospection"
/users/tokens/create:
post:
summary: create token
@@ -39704,6 +39741,122 @@ components:
- label
- requires_resource_path
TokenIntrospection:
type: object
properties:
kind:
type: string
enum: [session, api_token, jwt, external, superadmin_secret]
email:
type: string
username:
type: string
label:
type: string
token_prefix:
type: string
created_at:
type: string
format: date-time
expiration:
type: string
format: date-time
workspace_id:
description: the one workspace the token is bound to; absent when it is not bound
type: string
workspace_ids:
description: the workspaces a signed token is bound to, when it names several
type: array
items:
type: string
scopes:
description: absent when the token is unrestricted
type: array
items:
type: string
read_only:
type: boolean
admin_withheld:
description: |
the token does not carry its owner's workspace admin rights; the rights it does hold
in a workspace are in `workspace`
type: boolean
super_admin:
description: |
whether the token reaches superadmin routes: its owner is a superadmin, and it is
neither a job token nor one that withholds those rights
type: boolean
allowed_ips:
type: array
items:
type: string
job_id:
type: string
format: uuid
workspace:
$ref: "#/components/schemas/TokenWorkspaceAccess"
route:
$ref: "#/components/schemas/TokenRouteCheck"
required:
- kind
- email
- username
- read_only
- admin_withheld
- super_admin
TokenWorkspaceAccess:
type: object
properties:
workspace_id:
type: string
usable:
description: whether the token is accepted in this workspace at all
type: boolean
is_admin:
type: boolean
is_operator:
type: boolean
groups:
type: array
items:
type: string
folders:
type: array
items:
type: object
properties:
name:
type: string
write:
type: boolean
owner:
type: boolean
required:
- name
- write
- owner
required:
- workspace_id
- usable
TokenRouteCheck:
type: object
properties:
method:
type: string
path:
type: string
allowed:
type: boolean
reason:
description: why the route layer refuses the token, when it does
type: string
required:
- method
- path
- allowed
ScopeDomain:
type: object
properties:
+319 -3
View File
@@ -1,7 +1,20 @@
use axum::{routing::get, Json, Router};
use std::sync::Arc;
use axum::{extract::Query, routing::get, Extension, Json, Router};
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use windmill_common::error::JsonResult;
use windmill_api_auth::{
auth::{check_route_layer, maybe_get_workspace_id_from_path},
check_scopes, AuthCache, OptJobAuthed, Tokened,
};
use windmill_common::{
auth::{hash_token, is_session_label, is_super_admin_email, JWTAuthClaims},
client_ip::ClientIp,
error::{Error, JsonResult},
jwt,
users::SUPERADMIN_SECRET_EMAIL,
DB,
};
#[derive(Default, Serialize, Deserialize, Clone)]
pub struct ScopeOption {
@@ -285,7 +298,294 @@ lazy_static! {
}
pub fn global_service() -> Router {
Router::new().route("/list/scopes", get(get_all_available_scopes))
Router::new()
.route("/list/scopes", get(get_all_available_scopes))
.route("/introspect", get(introspect_token))
}
#[derive(Deserialize)]
struct IntrospectQuery {
workspace: Option<String>,
path: Option<String>,
method: Option<String>,
}
#[derive(Serialize)]
struct TokenIntrospection {
kind: &'static str,
email: String,
username: String,
#[serde(skip_serializing_if = "Option::is_none")]
label: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
token_prefix: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
created_at: Option<chrono::DateTime<chrono::Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
expiration: Option<chrono::DateTime<chrono::Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
workspace_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
workspace_ids: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
scopes: Option<Vec<String>>,
read_only: bool,
/// The token does not carry its owner's workspace admin rights.
admin_withheld: bool,
/// The token reaches superadmin routes: its owner is a superadmin and the token neither
/// withholds that nor is a job's.
super_admin: bool,
#[serde(skip_serializing_if = "Option::is_none")]
allowed_ips: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
job_id: Option<uuid::Uuid>,
#[serde(skip_serializing_if = "Option::is_none")]
workspace: Option<TokenWorkspaceAccess>,
#[serde(skip_serializing_if = "Option::is_none")]
route: Option<TokenRouteCheck>,
}
#[derive(Serialize)]
struct TokenWorkspaceAccess {
workspace_id: String,
usable: bool,
#[serde(skip_serializing_if = "Option::is_none")]
is_admin: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
is_operator: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
groups: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
folders: Option<Vec<FolderAccess>>,
}
#[derive(Serialize)]
struct FolderAccess {
name: String,
write: bool,
owner: bool,
}
#[derive(Serialize)]
struct TokenRouteCheck {
method: String,
path: String,
allowed: bool,
#[serde(skip_serializing_if = "Option::is_none")]
reason: Option<String>,
}
/// The scope a run-by-path endpoint (`windmill-api/src/jobs.rs`) requires of the runnable once
/// the route layer has admitted the token, which only knows that it may run something. Routes
/// added there with their own `check_scopes` belong here too, or the verdict over-reports.
fn run_by_path_scope(path: &str) -> Option<String> {
let (_, suffix) = path.strip_prefix("/api/w/")?.split_once('/')?;
let (endpoint, rest) = suffix.strip_prefix("jobs/")?.split_once('/')?;
if !matches!(
endpoint,
"run" | "run_wait_result" | "run_and_stream" | "run_inline"
) {
return None;
}
let kind = match rest.split_once('/')? {
("p", runnable) => ("scripts", runnable),
("f", runnable) if endpoint != "run_inline" => ("flows", runnable),
_ => return None,
};
Some(format!("jobs:run:{}:{}", kind.0, kind.1))
}
/// Describes only the credential presenting the request (`Tokened`), never one named in the
/// request, so it cannot be used to look up another person's token. It resolves the token
/// itself rather than through `ApiAuthed`: the route layer would refuse a scoped token here,
/// and a workspace-bound token resolves on no route outside its workspace.
async fn introspect_token(
Extension(db): Extension<DB>,
Extension(cache): Extension<Arc<AuthCache>>,
Tokened { token }: Tokened,
ClientIp(client_ip): ClientIp,
Query(q): Query<IntrospectQuery>,
) -> JsonResult<TokenIntrospection> {
let unauthorized = || Error::NotAuthorized("Unauthorized".to_string());
let row = if token.starts_with("jwt_") {
None
} else {
sqlx::query!(
"SELECT owner, email, label, token_prefix, created_at, expiration, workspace_id,
scopes, read_only, super_admin, admin, allowed_ips::text[] AS allowed_ips
FROM token
WHERE token_hash = $1 AND (expiration > NOW() OR expiration IS NULL)",
hash_token(&token)
)
.fetch_optional(&db)
.await?
};
let mut out = if let Some(row) = row {
let allowed =
windmill_api_auth::token_ip_allowlist_oss::load_allowed_ips(row.allowed_ips.clone());
if !windmill_api_auth::client_ip_allowed(allowed.as_deref(), client_ip) {
return Err(unauthorized());
}
let email = row.email.ok_or_else(unauthorized)?;
let is_session = is_session_label(row.label.as_deref());
TokenIntrospection {
kind: if is_session { "session" } else { "api_token" },
username: row
.owner
.as_deref()
.and_then(|o| o.split_once('/'))
.map(|(_, name)| name.to_string())
.unwrap_or_else(|| email.clone()),
email,
label: row.label,
token_prefix: Some(row.token_prefix),
created_at: Some(row.created_at),
expiration: row.expiration,
workspace_id: row.workspace_id,
workspace_ids: None,
scopes: row.scopes,
read_only: row.read_only,
admin_withheld: !row.admin,
// Not withheld yet; whether the owner holds it is settled below. A session
// always stands for the account as it is.
super_admin: row.super_admin || is_session,
// What the build enforces: a CE build ignores a stored list.
allowed_ips: allowed.map(|nets| nets.iter().map(|n| n.to_string()).collect()),
job_id: None,
workspace: None,
route: None,
}
} else {
// A guest JWT resolves only inside its workspace.
let requested = q.workspace.clone().filter(|w| !w.is_empty());
let resolved = match cache.get_opt_job_authed(None, &token, client_ip).await {
Some(resolved) => Some(resolved),
None if requested.is_some() => {
cache.get_opt_job_authed(requested, &token, client_ip).await
}
None => None,
};
let OptJobAuthed { authed, job_id } = resolved.ok_or_else(unauthorized)?;
let mut out = TokenIntrospection {
kind: if authed.email == SUPERADMIN_SECRET_EMAIL {
"superadmin_secret"
} else {
"external"
},
email: authed.email,
username: authed.username,
label: None,
token_prefix: None,
created_at: None,
expiration: None,
workspace_id: None,
workspace_ids: None,
scopes: authed.scopes,
read_only: authed.read_only,
admin_withheld: authed.admin_withheld,
super_admin: !authed.super_admin_withheld,
allowed_ips: None,
job_id,
workspace: None,
route: None,
};
if let Some(jwt) = token
.strip_prefix("jwt_")
.filter(|_| !token.starts_with("jwt_ext_"))
{
out.kind = "jwt";
if let Ok(claims) = jwt::decode_with_internal_secret::<JWTAuthClaims>(jwt).await {
out.label = claims.label;
out.workspace_id = claims.workspace_id;
out.workspace_ids = claims.workspace_ids;
out.expiration = chrono::DateTime::from_timestamp(claims.exp as i64, 0);
}
}
out
};
// The same three conditions `require_super_admin` checks.
out.super_admin =
out.super_admin && out.job_id.is_none() && is_super_admin_email(&db, &out.email).await?;
if let Some(w_id) = q.workspace.as_deref().filter(|w| !w.is_empty()) {
let resolved = cache
.get_opt_job_authed(Some(w_id.to_string()), &token, client_ip)
.await;
out.workspace = Some(match resolved {
Some(OptJobAuthed { authed, .. }) => TokenWorkspaceAccess {
workspace_id: w_id.to_string(),
usable: true,
is_admin: Some(authed.is_admin),
is_operator: Some(authed.is_operator),
groups: Some(authed.groups),
folders: Some(
authed
.folders
.into_iter()
.map(|(name, write, owner)| FolderAccess { name, write, owner })
.collect(),
),
},
None => TokenWorkspaceAccess {
workspace_id: w_id.to_string(),
usable: false,
is_admin: None,
is_operator: None,
groups: None,
folders: None,
},
});
}
if let Some(path) = q.path.as_deref().map(str::trim).filter(|p| !p.is_empty()) {
let path = if path.starts_with("/api/") {
path.to_string()
} else if let Some(w_id) = q.workspace.as_deref().filter(|w| !w.is_empty()) {
format!("/api/w/{w_id}/{}", path.trim_start_matches('/'))
} else {
return Err(Error::BadRequest(
"a relative path needs a workspace; pass a full /api/... path".to_string(),
));
};
let path = path
.split(['?', '#'])
.next()
.unwrap_or_default()
.to_string();
let method = q.method.as_deref().unwrap_or("GET").to_ascii_uppercase();
let path_vec: Vec<&str> = path.split('/').collect();
let route_workspace = maybe_get_workspace_id_from_path(&path_vec);
let resolved = cache
.get_opt_job_authed(route_workspace.clone(), &token, client_ip)
.await;
let verdict = match resolved {
None => Err(match route_workspace.as_deref() {
Some(w_id) => format!("The token cannot be used in workspace {w_id}."),
None => "The token cannot be used outside a workspace.".to_string(),
}),
Some(mut opt_job_authed) => async {
check_route_layer(
&db,
&mut opt_job_authed,
route_workspace.as_deref(),
&path,
&method,
)
.await?;
if let Some(scope) = run_by_path_scope(&path) {
check_scopes(&opt_job_authed.authed, || scope)?;
}
Ok::<_, Error>(())
}
.await
.map_err(|e| e.to_string()),
};
out.route =
Some(TokenRouteCheck { method, path, allowed: verdict.is_ok(), reason: verdict.err() });
}
Ok(Json(out))
}
async fn get_all_available_scopes() -> JsonResult<Vec<ScopeDomain>> {
@@ -296,6 +596,22 @@ async fn get_all_available_scopes() -> JsonResult<Vec<ScopeDomain>> {
mod tests {
use super::*;
#[test]
fn run_by_path_scope_names_the_runnable() {
let scope = |p: &str| run_by_path_scope(p);
assert_eq!(
scope("/api/w/ws/jobs/run_wait_result/p/f/ci/build").as_deref(),
Some("jobs:run:scripts:f/ci/build")
);
assert_eq!(
scope("/api/w/ws/jobs/run/f/u/me/flow").as_deref(),
Some("jobs:run:flows:u/me/flow")
);
assert_eq!(scope("/api/w/ws/jobs/run/h/abc"), None);
assert_eq!(scope("/api/w/ws/jobs/run_inline/f/u/me/flow"), None);
assert_eq!(scope("/api/w/ws/scripts/list"), None);
}
/// The token-scope picker is driven by this catalog, so a scope that is
/// enforced but absent here can't be granted through the supported UI.
#[test]
+6
View File
@@ -36,6 +36,12 @@ 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.
- **`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
route verdict is `check_route_layer` (`windmill-api-auth/src/auth.rs`), the function the auth
extractor runs, plus the runnable scope of the run-by-path endpoints (`run_by_path_scope`); a
handler that checks a scope of its own and is missing there gets an over-reported "allowed".
- **`max_token_expiration_days`** caps `POST /users/tokens/create` and `tokens/impersonate`, by
shortening the stored expiration (`cap_token_expiration`), never by refusing: `wmill user
create-token` and the editor's language-server token pick a lifetime without reading the
@@ -15,6 +15,8 @@
import { listEveryWorkspace, mcpTokenUrlDisabled } from '$lib/mcpAuth'
import { apiBaseUrl } from '$lib/apiBaseUrl.svelte'
import TokenDisplay from './TokenDisplay.svelte'
import TokenInspector from './TokenInspector.svelte'
import CollapseLink from '../CollapseLink.svelte'
import ScopesPicker from './ScopesPicker.svelte'
import { parseMaxTokenExpirationDays } from '$lib/tokenExpiration'
@@ -57,6 +59,8 @@
}: Props = $props()
let newToken = $state<string | undefined>(undefined)
let newTokenTestWorkspace = $state<string | undefined>(undefined)
let newTokenTestOpen = $state(false)
let newMcpToken = $state<string | undefined>(undefined)
let newMcpTokenUrl = $state('')
// What an MCP token may do, as the access picker sets it.
@@ -274,6 +278,8 @@
} else {
newMcpToken = undefined
newToken = `${createdToken}`
newTokenTestWorkspace = tokenWorkspaceId ?? $operatingWorkspace
newTokenTestOpen = false
}
onTokenCreated(`${createdToken}`)
@@ -727,6 +733,13 @@
{#if newToken && displayCreateToken}
<TokenDisplay token={newToken} />
<div class="-mt-4 mb-6">
<CollapseLink text="Check what this token can do" bind:open={newTokenTestOpen}>
{#key newToken}
<TokenInspector token={newToken} workspace={newTokenTestWorkspace} />
{/key}
</CollapseLink>
</div>
{/if}
{#if newMcpToken && displayCreateToken}
@@ -0,0 +1,247 @@
<script lang="ts">
import { untrack } from 'svelte'
import { OpenAPI, type TokenIntrospection } from '$lib/gen'
import { displayDate } from '$lib/utils'
import { Alert, Badge, Button } from '../common'
import TextInput from '../text_input/TextInput.svelte'
import Select from '../select/Select.svelte'
import { Check, ShieldCheck, X } from 'lucide-svelte'
interface Props {
/** The token to inspect. When unset, the user pastes one. */
token?: string
/** Workspace the identity and the route are evaluated in. */
workspace?: string
/** Route to check, relative to `/api/w/{workspace}/`, or a full `/api/...` path. */
defaultPath?: string
defaultMethod?: string
}
let { token, workspace, defaultPath, defaultMethod }: Props = $props()
let pastedToken = $state('')
let effectiveToken = $derived((token ?? pastedToken).trim())
let routeMethod = $state(untrack(() => defaultMethod ?? 'GET'))
let routePath = $state(untrack(() => defaultPath ?? ''))
let result = $state<TokenIntrospection | undefined>(undefined)
let error = $state<string | undefined>(undefined)
let loading = $state(false)
const methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].map((m) => ({ label: m, value: m }))
const kindLabel: Record<TokenIntrospection['kind'], string> = {
session: 'Browser session',
api_token: 'API token',
jwt: 'Signed token (JWT)',
external: 'External issuer',
superadmin_secret: 'Superadmin secret'
}
async function inspect() {
if (!effectiveToken) return
loading = true
error = undefined
result = undefined
try {
const params = new URLSearchParams()
if (workspace) params.set('workspace', workspace)
if (routePath.trim()) {
params.set('path', routePath.trim())
params.set('method', routeMethod)
}
// The route describes only the credential presenting the request, so the token
// must be the bearer credential, not a parameter.
const response = await fetch(`${OpenAPI.BASE}/tokens/introspect?${params}`, {
headers: { Authorization: `Bearer ${effectiveToken}` },
credentials: 'omit'
})
if (response.status === 401) {
error = 'This token is not valid: it does not exist, has expired or was revoked.'
} else if (!response.ok) {
error = (await response.text()) || `Request failed (${response.status})`
} else {
result = await response.json()
}
} catch (e) {
error = e instanceof Error ? e.message : String(e)
} finally {
loading = false
}
}
/** Whether the server read the token's expiry and workspace bounds: it does for its own rows
* and signed tokens, not for an external issuer's or a guest's, whose absence means nothing. */
function metadataKnown(r: TokenIntrospection): boolean {
return r.kind === 'api_token' || r.kind === 'session' || r.expiration != undefined
}
function expiryText(expiration: string | undefined): string {
return expiration ? displayDate(expiration) : 'Never'
}
</script>
<div class="flex flex-col gap-3">
{#if token === undefined}
<div class="flex flex-col gap-1">
<span class="text-xs text-emphasis font-semibold">Token</span>
<TextInput
bind:value={pastedToken}
inputProps={{ type: 'password', placeholder: 'Paste a token to test', autocomplete: 'off' }}
class="w-full"
/>
</div>
{/if}
<div class="flex flex-col gap-1">
<span class="text-xs text-emphasis font-semibold">
Route to check <span class="text-hint font-normal">(optional)</span>
</span>
<div class="flex gap-2 items-center">
<div class="w-28 shrink-0">
<Select items={methods} bind:value={routeMethod} size="sm" />
</div>
<TextInput
bind:value={routePath}
inputProps={{
placeholder: workspace
? 'scripts/list, or a full /api/... path'
: '/api/w/<workspace>/...'
}}
size="sm"
class="w-full"
/>
<Button
variant="accent-secondary"
unifiedSize="sm"
startIcon={{ icon: ShieldCheck }}
disabled={!effectiveToken}
{loading}
onClick={inspect}
>
Test token
</Button>
</div>
</div>
{#if error}
<Alert type="error" title="Could not test the token" size="xs">{error}</Alert>
{/if}
{#if result}
<div class="flex flex-col gap-3 border rounded-md p-3 bg-surface-tertiary text-xs">
<div class="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5">
<span class="text-secondary">Kind</span>
<span class="text-primary">{kindLabel[result.kind] ?? result.kind}</span>
<span class="text-secondary">Acts as</span>
<span class="text-primary">{result.email} ({result.username})</span>
{#if result.label}
<span class="text-secondary">Label</span>
<span class="text-primary">{result.label}</span>
{/if}
{#if result.token_prefix}
<span class="text-secondary">Prefix</span>
<span class="text-primary">{result.token_prefix}****</span>
{/if}
<span class="text-secondary">Expires</span>
<span class="text-primary">
{metadataKnown(result) ? expiryText(result.expiration) : 'Not reported'}
</span>
<span class="text-secondary">Workspaces</span>
<span class="text-primary">
{#if result.workspace_ids?.length}
{result.workspace_ids.join(', ')}
{:else if result.workspace_id}
{result.workspace_id}
{:else if metadataKnown(result)}
Every workspace the owner is a member of
{:else}
Not reported
{/if}
</span>
<span class="text-secondary">Rights</span>
<div class="flex flex-wrap gap-1">
{#if result.super_admin}
<Badge color="red" small>Superadmin</Badge>
{/if}
{#if result.admin_withheld}
<Badge color="gray" small>Admin rights withheld</Badge>
{/if}
{#if result.read_only}
<Badge color="blue" small>Read-only</Badge>
{/if}
{#if result.job_id}
<Badge color="gray" small>Job {result.job_id}</Badge>
{/if}
{#if !result.super_admin && !result.admin_withheld && !result.read_only && !result.job_id}
<span class="text-primary">Owner's member rights</span>
{/if}
</div>
{#if result.allowed_ips?.length}
<span class="text-secondary">Usable from</span>
<span class="text-primary">{result.allowed_ips.join(', ')}</span>
{/if}
<span class="text-secondary">Scopes</span>
<div class="flex flex-wrap gap-1">
{#if result.scopes}
{#each result.scopes as scope (scope)}
<Badge color="gray" small>{scope}</Badge>
{:else}
<span class="text-primary">None</span>
{/each}
{:else}
<span class="text-primary">Unrestricted</span>
{/if}
</div>
</div>
{#if result.workspace}
{@const ws = result.workspace}
<div class="border-t pt-3 grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5">
<span class="text-secondary">In {ws.workspace_id}</span>
{#if ws.usable}
<div class="flex flex-wrap gap-1">
<Badge color={ws.is_admin ? 'indigo' : ws.is_operator ? 'yellow' : 'green'} small>
{ws.is_admin ? 'Admin' : ws.is_operator ? 'Restricted role' : 'Member'}
</Badge>
</div>
<span class="text-secondary">Groups</span>
<span class="text-primary">{ws.groups?.join(', ') || 'None'}</span>
<span class="text-secondary">Folders</span>
<span class="text-primary">
{#if ws.folders?.length}
{ws.folders
.map((f) => `${f.name} (${f.owner ? 'owner' : f.write ? 'write' : 'read'})`)
.join(', ')}
{:else}
None
{/if}
</span>
{:else}
<span class="text-primary">Not usable in this workspace</span>
{/if}
</div>
{/if}
{#if result.route}
{@const route = result.route}
<div class="border-t pt-3 flex flex-col gap-1">
<div class="flex items-start gap-2">
{#if route.allowed}
<Check size={14} class="shrink-0 mt-0.5 text-green-600 dark:text-green-400" />
{:else}
<X size={14} class="shrink-0 mt-0.5 text-red-600 dark:text-red-400" />
{/if}
<span class="text-primary font-mono break-all">{route.method} {route.path}</span>
</div>
{#if route.allowed}
<span class="text-secondary">
The token passes the route checks. The endpoint can still refuse it: a scope that
names a path is matched against the item, and the identity needs permission on it.
</span>
{:else}
<span class="text-secondary">{route.reason}</span>
{/if}
</div>
{/if}
</div>
{/if}
</div>
@@ -2,7 +2,9 @@
import { untrack } from 'svelte'
import TableCustom from '$lib/components/TableCustom.svelte'
import { displayDate } from '$lib/utils'
import { enterpriseLicense } from '$lib/stores'
import { enterpriseLicense, workspaceStore } from '$lib/stores'
import CollapseLink from '../CollapseLink.svelte'
import TokenInspector from './TokenInspector.svelte'
import { UserService, type TruncatedToken } from '$lib/gen'
import { sendUserToast } from '$lib/toast'
import CreateToken from './CreateToken.svelte'
@@ -37,6 +39,7 @@
| undefined
>(undefined)
let editModalOpen = $state(false)
let testOpen = $state(false)
$effect(() => {
listTokens()
@@ -275,6 +278,16 @@
{/if}
</div>
</div>
<div class="mt-4">
<CollapseLink text="Test a token" bind:open={testOpen}>
<div class="text-xs text-secondary mb-2">
See who a token acts as, what it is scoped to and whether it can call a route{$workspaceStore
? ` in ${$workspaceStore}`
: ''}.
</div>
<TokenInspector workspace={$workspaceStore} />
</CollapseLink>
</div>
</div>
<EditTokenScopesModal
@@ -23,6 +23,7 @@
import TextInput from '$lib/components/text_input/TextInput.svelte'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import CollapseLink from '$lib/components/CollapseLink.svelte'
import TokenInspector from '$lib/components/settings/TokenInspector.svelte'
import CopyableCodeBlock from '$lib/components/details/CopyableCodeBlock.svelte'
import { markdown } from 'svelte-highlight/languages'
import {
@@ -86,6 +87,18 @@
}
})
/** The route the token test checks: the by-path form of the one the examples call. A by-hash
* or by-version route is gated by the same runnable scope, which the check only resolves
* from a path. */
const webhookRoutePath = $derived.by(() => {
const base = `/api/w/${wsId}/jobs`
if (agent) return `${base}/run/agent/${path}`
const endpoint =
requestType == 'async' ? 'run' : requestType == 'sync' ? 'run_wait_result' : 'run_and_stream'
return `${base}/${endpoint}/${isFlow ? 'f' : 'p'}/${path}`
})
let tokenTestOpen = $state(false)
let surface = $state('http') as 'http' | 'sdk'
let example = $state('rest') as 'rest' | 'curl' | 'fetch'
let promptOpen = $state(false)
@@ -363,6 +376,18 @@ done`
</Tooltip>
</Button>
</div>
<div class="mt-2">
<CollapseLink text="Test this token" bind:open={tokenTestOpen}>
{#key `${callMethod} ${webhookRoutePath}`}
<TokenInspector
{token}
workspace={wsId}
defaultPath={webhookRoutePath}
defaultMethod={callMethod.toUpperCase()}
/>
{/key}
</CollapseLink>
</div>
</Label>
{/if}