fix: keep withheld admin rights in the tools preview, name what a partial author or the deploy rules hold back

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
hugocasa
2026-12-03 10:31:00 +01:00
co-authored by Claude Opus 5.5
parent 8485bf250a
commit 2efcb9b1d9
11 changed files with 197 additions and 81 deletions
+16
View File
@@ -157,6 +157,22 @@ async fn role_setting_caps_every_token(db: Pool<Postgres>) -> anyhow::Result<()>
.filter_map(|t| t["name"].as_str())
.collect();
assert_eq!(names, ["in_set"], "{preview}");
// A token holding back its owner's admin rights would list scripts only an admin reads.
sqlx::query(
"INSERT INTO token (token_hash, token_prefix, email, label, super_admin, admin)
VALUES (encode(sha256('NOADMIN_TOKEN'::bytea), 'hex'), 'NOADMIN_TO', $1, 'mcp', false, false)",
)
.bind(admin)
.execute(&db)
.await?;
let refused = reqwest::Client::new()
.get(format!(
"http://localhost:{port}/api/mcp/gateway/oauth/server/runnable_tools?workspace_id=test-workspace"
))
.bearer_auth("NOADMIN_TOKEN")
.send()
.await?;
assert!(!refused.status().is_success(), "{}", refused.status());
let call = |url: &'static str, token: &'static str, name: &'static str, args: Value| async move {
mcp(
port,
+5
View File
@@ -42272,6 +42272,11 @@ components:
description: With `run_and_edit`, the kinds the caller's role edits.
items:
type: string
withheld:
type: array
description: With `build_and_run`, what is held back all the same - `scripts`, `flows` or `apps` the role does not author, and `deploy` where the deploy rules block the caller.
items:
type: string
required: [id, name, access, limited]
McpRoleSetting:
-6
View File
@@ -906,11 +906,6 @@ pub async fn add_www_authenticate_header_gateway(
}
}
/// The tools server's runner, for the consent page to list what a connection would get. Set
/// once the MCP server is set up; unset in a process that serves no MCP.
pub(crate) static PREVIEW_RUNNER: std::sync::OnceLock<Runner<WindmillBackend>> =
std::sync::OnceLock::new();
impl From<windmill_mcp::server::Tool> for ToolsetEntry {
fn from(tool: windmill_mcp::server::Tool) -> Self {
ToolsetEntry {
@@ -934,7 +929,6 @@ pub async fn setup_mcp_server(
let backend = WindmillBackend::new(db.clone(), user_db, base_internal_url, auth_cache);
let session_runner = SessionRunner::new(backend.clone());
let runner = Runner::new(backend);
let _ = PREVIEW_RUNNER.set(runner.clone());
let service_config = StreamableHttpServerConfig::default()
.with_sse_keep_alive(Some(Duration::from_secs(15)))
+63 -5
View File
@@ -9,7 +9,7 @@ use windmill_common::{
db::UserDB,
error::{Error, JsonResult},
roles::{self, McpRoleAccess, McpRoleSetting, RoleCapabilities},
workspaces::ProtectionRules,
workspaces::{check_deploy_rules, ProtectionRules, RuleCheckResult},
DB,
};
use windmill_mcp::server::{
@@ -74,6 +74,9 @@ struct MemberAccess {
can_run: bool,
/// With `RunAndEdit`, what the role edits.
edits: Vec<&'static str>,
/// With `BuildAndRun`, what is held back all the same: the kinds the role does not author,
/// and `deploy` where the deploy rules block the member.
withheld: Vec<&'static str>,
}
/// What a connection with `access` gets in each workspace, for `list_workspaces`. Community, where
@@ -147,6 +150,14 @@ async fn accesses(
)
.fetch_all(db)
.await?;
let deployers_only: Vec<String> = sqlx::query_scalar!(
"SELECT DISTINCT workspace_id FROM workspace_protection_rule
WHERE workspace_id = ANY($1) AND rules & $2 <> 0",
&ids,
ProtectionRules::RESTRICT_DEPLOY_TO_DEPLOYERS.bits()
)
.fetch_all(db)
.await?;
let instance = roles::instance_roles(db).await?;
let mut out = HashMap::with_capacity(ids.len());
@@ -155,6 +166,7 @@ async fn accesses(
let mut builds = true;
let mut limit = None;
let mut edits = vec![];
let mut withheld = vec![];
let member = members.iter().find(|m| m.workspace_id == id);
if let Some(m) = member {
// Roles that cannot be read refuse every call there, as `caller_mcp_limit` does.
@@ -178,6 +190,15 @@ async fn accesses(
session = SessionAccess::ReadOnly;
}
builds = caps.is_author();
if !caps.code {
withheld.push("scripts");
}
if caps.flows == roles::AuthorLevel::None {
withheld.push("flows");
}
if caps.apps == roles::AuthorLevel::None {
withheld.push("apps");
}
// Folder rights, not the role, gate these two.
edits.extend(["resources", "variables"]);
if caps.manage_schedules {
@@ -205,8 +226,28 @@ async fn accesses(
(_, SessionAccess::Full) if !builds => WorkspaceMcpAccess::RunAndEdit,
(_, SessionAccess::Full) => WorkspaceMcpAccess::BuildAndRun,
};
// Checked per member, only where a rule keeps deploying to deployers.
if let Some(m) = member
.filter(|_| access == WorkspaceMcpAccess::BuildAndRun && deployers_only.contains(&id))
{
let groups =
windmill_common::auth::get_groups_for_user(&id, &m.username, email, db).await?;
if matches!(
check_deploy_rules(&id, &m.username, &groups, m.is_admin || super_admin, db)
.await?,
RuleCheckResult::Blocked(_)
) {
withheld.push("deploy");
}
}
if access != WorkspaceMcpAccess::BuildAndRun {
withheld.clear();
}
let username = member.map(|m| m.username.clone());
out.insert(id, MemberAccess { access, limit, username, can_run, edits });
out.insert(
id,
MemberAccess { access, limit, username, can_run, edits, withheld },
);
}
Ok(out)
}
@@ -224,6 +265,10 @@ pub struct WorkspaceAccessEntry {
/// With `run_and_edit`, the kinds the caller's role edits.
#[serde(skip_serializing_if = "Vec::is_empty")]
edits: Vec<&'static str>,
/// With `build_and_run`, what is held back all the same: `scripts`, `flows`, `apps` the role
/// does not author, and `deploy` where the deploy rules block the caller.
#[serde(skip_serializing_if = "Vec::is_empty")]
withheld: Vec<&'static str>,
}
#[derive(Deserialize)]
@@ -313,6 +358,7 @@ pub async fn list_workspace_access(
} else {
vec![]
},
withheld: member.withheld.clone(),
id: w.id,
name: w.name,
});
@@ -329,6 +375,8 @@ pub struct RunnableToolsQuery {
/// workspace would list where the caller's role offers them as tools, with their arguments.
pub async fn list_runnable_tools(
Extension(db): Extension<DB>,
Extension(user_db): Extension<UserDB>,
Extension(auth_cache): Extension<std::sync::Arc<crate::auth::AuthCache>>,
authed: ApiAuthed,
Query(query): Query<RunnableToolsQuery>,
) -> JsonResult<Vec<super::core::ToolsetEntry>> {
@@ -341,6 +389,12 @@ pub async fn list_runnable_tools(
"A scope-restricted token cannot list its owner's tools".to_string(),
));
}
// The listing runs with the owner's admin rights, which this token does not carry.
if authed.admin_withheld {
return Err(Error::NotAuthorized(
"A token without its owner's admin rights cannot list its owner's tools".to_string(),
));
}
let w_id = query.workspace_id;
let username = accesses(
&db,
@@ -353,9 +407,13 @@ pub async fn list_runnable_tools(
.remove(&w_id)
.and_then(|m| m.username)
.ok_or_else(|| Error::NotFound(format!("You are not a member of '{w_id}'")))?;
let runner = super::core::PREVIEW_RUNNER
.get()
.ok_or_else(|| Error::BadRequest("This server does not serve MCP".to_string()))?;
// Listing reads the database only, so no internal URL is needed.
let runner = windmill_mcp::server::Runner::new(super::core::WindmillBackend::new(
db.clone(),
user_db,
String::new(),
auth_cache,
));
let there: ApiAuthed = windmill_common::auth::fetch_authed_from_permissioned_as(
&format!("u/{username}"),
&authed.email,
@@ -43,7 +43,9 @@
initialScopes?: string[]
/** Names the level that narrows nothing. */
fullLabel?: string
/** Rendered between the access choice and the tool list. */
/** Rendered right under the access choice, as part of it. */
belowAccess?: Snippet
/** Rendered after the access choice. */
afterAccess?: Snippet
/** Offers the chosen level's tools in a dialog. */
showTools?: boolean
@@ -55,6 +57,7 @@
access = $bindable(),
initialScopes = [],
fullLabel = 'Build and run',
belowAccess,
afterAccess,
showTools = false
}: Props = $props()
@@ -90,18 +93,19 @@
<div class="flex flex-col gap-4">
<div>
<span class="block mb-1 text-emphasis text-xs font-semibold">Access</span>
<div class="mb-1 flex items-center gap-1.5">
<span class="text-emphasis text-xs font-semibold">Access</span>
{#if showTools && toolsetAccess}
<Button variant="default" unifiedSize="xs" onClick={() => (toolsOpen = true)}>
Show tools
</Button>
{/if}
</div>
<Select items={LEVELS} bind:value={() => access, (v) => v && (access = v as McpAccess)} />
{#if access}
<div class="mt-1 flex items-start justify-between gap-2">
<p class="text-2xs text-secondary">{ACCESS_HINTS[access]}</p>
{#if showTools && toolsetAccess}
<Button variant="subtle" unifiedSize="xs" onClick={() => (toolsOpen = true)}>
Show tools
</Button>
{/if}
</div>
<p class="mt-1 text-2xs text-secondary">{ACCESS_HINTS[access]}</p>
{/if}
{@render belowAccess?.()}
</div>
{@render afterAccess?.()}
{#if access === 'selected'}
@@ -97,5 +97,11 @@ describe('narrows', () => {
expect(narrows(ws('a', 'runnables'), 'full')).toBe(true)
expect(narrows(ws('a', 'read_only'), 'selected')).toBe(true)
expect(narrows(ws('a', 'off'), 'read')).toBe(true)
const partial = { ...ws('a', 'build_and_run'), withheld: ['scripts', 'deploy'] }
expect(narrows(partial, 'full')).toBe(true)
expect(restriction(partial, 'full')).toBe(
"Your role can't build scripts. The deploy rules don't let you deploy, so the client saves drafts only."
)
expect(narrows(partial, 'read_run')).toBe(false)
})
})
@@ -53,15 +53,27 @@ export function accessLabel(workspace: McpWorkspaceAccess, picked: McpAccess): s
return LABELS[access]
}
/** How a role that writes no scripts, flows or apps holds back build and run, which keeps the
* label of the level picked. */
const joined = (items: string[], last: string) =>
items.length > 1 ? `${items.slice(0, -1).join(', ')} ${last} ${items.at(-1)}` : (items[0] ?? '')
/** What build and run holds back in a workspace all the same, which keeps the label of the level
* picked: a role writing no scripts, flows or apps, or only some kinds, and deploy rules. */
export function restriction(workspace: McpWorkspaceAccess, picked: McpAccess): string | undefined {
if (workspace.access !== 'run_and_edit' || picked !== 'full') return undefined
const edits = workspace.edits ?? []
const last = edits.at(-1)
const listed = edits.length > 1 ? `${edits.slice(0, -1).join(', ')} and ${last}` : last
const set = workspace.limited ? ' Set by your role.' : ''
return `Your role writes no scripts, flows or apps. The client runs them${listed ? ` and edits ${listed}` : ''}.${set}`
if (picked !== 'full') return undefined
if (workspace.access === 'run_and_edit') {
const edits = joined(workspace.edits ?? [], 'and')
return `Your role writes no scripts, flows or apps. The client runs them${edits ? ` and edits ${edits}` : ''}.`
}
if (workspace.access !== 'build_and_run') return undefined
const withheld = workspace.withheld ?? []
const kinds = withheld.filter((w) => w !== 'deploy')
const parts = [
kinds.length > 0 ? `Your role can't build ${joined(kinds, 'or')}.` : '',
withheld.includes('deploy')
? "The deploy rules don't let you deploy, so the client saves drafts only."
: ''
].filter(Boolean)
return parts.length > 0 ? parts.join(' ') : undefined
}
/** The covered workspaces a connection serves. One set to scripts and flows as tools is served
@@ -73,6 +73,7 @@
let newTokenTestOpen = $state(false)
let newMcpToken = $state<string | undefined>(undefined)
let newMcpTokenUrl = $state('')
let newMcpWorkspaceTokenUrl = $state('')
// What an MCP token may do, as the access picker sets it.
let mcpAccess = $state<McpAccess>('full')
let mcpScopes = $state<string[]>(['mcp:all'])
@@ -291,6 +292,9 @@
newToken = undefined
newMcpToken = `${createdToken}`
newMcpTokenUrl = `${mcpUrl}?token=${createdToken}`
newMcpWorkspaceTokenUrl = workspaceUrlOffered
? `${workspaceMcpUrl(mcpBoundWorkspace!)}?token=${createdToken}`
: ''
} else {
newMcpToken = undefined
newToken = `${createdToken}`
@@ -393,6 +397,8 @@
(w) => (mcpAllWorkspaces || mcpWorkspaces.includes(w.id)) && narrows(w, mcpAccess)
)
)
// The home page's tab also offers the workspace's own URL where `/api/mcp` is the main one.
const workspaceUrlOffered = $derived(lockWorkspace && !mcpAsTools && !!mcpBoundWorkspace)
const mcpUrl = $derived(
mcpAsTools && mcpBoundWorkspace
? workspaceMcpUrl(mcpBoundWorkspace)
@@ -432,6 +438,18 @@
bind:access={() => mcpAccess, setMcpAccess}
showTools
>
{#snippet belowAccess()}
{#if mcpNarrowed}
<div class="mt-2">
<McpWorkspaceAccessList
workspaces={mcpWorkspaceAccess.current ?? []}
covered={mcpWorkspaces}
all={mcpAllWorkspaces}
access={mcpAccess}
/>
</div>
{/if}
{/snippet}
{#snippet afterAccess()}
{#if canCarryAdmin}
{@render adminToggle(mcpSuperAdmin)}
@@ -453,15 +471,6 @@
{/if}
{/snippet}
</McpAccessPicker>
{#if mcpNarrowed}
<McpWorkspaceAccessList
workspaces={mcpWorkspaceAccess.current ?? []}
covered={mcpWorkspaces}
all={mcpAllWorkspaces}
access={mcpAccess}
title="What it gets"
/>
{/if}
{#if !mcpOnly}
<div>
<span class="block mb-1 text-emphasis text-xs font-semibold"
@@ -639,7 +648,7 @@
{/if}
</p>
</div>
{#if lockWorkspace && !mcpAsTools && mcpBoundWorkspace}
{#if workspaceUrlOffered && mcpBoundWorkspace}
<div class="flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">Or only {mcpBoundWorkspace}</span>
<ClipboardPanel content={workspaceMcpUrl(mcpBoundWorkspace)} size="sm" />
@@ -852,6 +861,11 @@
{/if}
{#if newMcpToken && displayCreateToken}
<TokenDisplay token={newMcpToken} mcpUrl={newMcpTokenUrl} />
<TokenDisplay
token={newMcpToken}
mcpUrl={newMcpTokenUrl}
workspaceMcpUrl={newMcpWorkspaceTokenUrl || undefined}
workspace={mcpBoundWorkspace}
/>
{/if}
</div>
@@ -264,17 +264,21 @@
workspaceId={mcpWorkspaceId}
initialScopes={(initialScopes ?? []).filter((s) => !isWorkspaceList(s))}
bind:scopes={mcpScopes}
/>
>
{#snippet belowAccess()}
{#if mcpNarrowed}
<div class="mt-2">
<McpWorkspaceAccessList
workspaces={mcpWorkspaceAccess.current ?? []}
covered={warnsFor}
all={false}
access={mcpAccess}
/>
</div>
{/if}
{/snippet}
</McpAccessPicker>
</div>
{#if mcpNarrowed}
<McpWorkspaceAccessList
workspaces={mcpWorkspaceAccess.current ?? []}
covered={warnsFor}
all={false}
access={mcpAccess}
title="What it gets"
/>
{/if}
{:else}
<ScopesPicker workspaceId={mcpWorkspaceId} {initialScopes} bind:value={pickedScopes} />
{/if}
@@ -8,11 +8,14 @@
interface Props {
token: string
mcpUrl?: string
/** The same token on one workspace's own URL. */
workspaceMcpUrl?: string
workspace?: string
title?: string
onClose?: () => void
}
let { token, mcpUrl, title, onClose }: Props = $props()
let { token, mcpUrl, workspaceMcpUrl, workspace, title, onClose }: Props = $props()
const displayTitle = $derived(
title || (mcpUrl ? 'MCP URL generated successfully' : 'Token created successfully')
@@ -62,6 +65,10 @@
<div class="flex flex-col gap-y-1">
<!-- Token display with proper surface and border styling -->
<CopyableCodeBlock code={tokenOrUrl} language={shell} wrap />
{#if workspaceMcpUrl}
<p class="mt-1 text-xs font-semibold text-emphasis">Or only {workspace}</p>
<CopyableCodeBlock code={workspaceMcpUrl} language={shell} wrap />
{/if}
<!-- Warning alert using existing Alert component -->
<div class="mt-1">
@@ -30,7 +30,6 @@
servedOn,
workspaceMcpUrl
} from '$lib/components/mcp/workspaceAccess'
import ClipboardPanel from '$lib/components/details/ClipboardPanel.svelte'
import {
McpOauthService,
UserService,
@@ -511,7 +510,7 @@
</p>
{:else if toolsAlone}
<div class="flex items-center gap-1">
<p class="text-xs text-primary">{covered[0].name} only</p>
<p class="text-xs text-primary">{covered[0].name}</p>
<Button
variant="subtle"
unifiedSize="xs"
@@ -593,11 +592,7 @@
{/snippet}
{#snippet toolsToggle()}
{#if connectionTools || runnablesHere}
<Button
variant="subtle"
unifiedSize="xs"
onClick={() => (toolsOpen = true)}
>
<Button variant="default" unifiedSize="xs" onClick={() => (toolsOpen = true)}>
Show tools
</Button>
{/if}
@@ -615,10 +610,10 @@
{#if same}
{@const restricted = restriction(first, access)}
<div class="flex flex-wrap items-center gap-x-1.5">
<span class="text-xs text-primary">{accessLabel(first, access)}</span>
{#if restricted}
<Badge color="gray" small>Restricted</Badge>
{/if}
<span class="text-xs text-primary">{accessLabel(first, access)}</span>
<Tooltip small>{restricted ?? accessHint(first, access)}</Tooltip>
{@render pen()}
</div>
@@ -660,30 +655,31 @@
</Button>
{#if leftOutOpen}
<p class="text-xs text-primary">
Scripts and flows as tools need a connection of their own.
Scripts and flows as tools need a connection of their own: add {one
? 'its'
: 'each'} workspace URL to your AI client, or connect it alone here.
</p>
{#each leftOut as w (w.id)}
<div class="flex flex-col gap-3">
<div class="flex flex-col gap-1">
<p class="text-xs font-semibold text-emphasis">
Add {one ? 'its' : `${w.name}'s`} URL to your AI client
</p>
<ClipboardPanel content={workspaceMcpUrl(w.id)} size="sm" />
<div class="flex flex-col gap-1">
{#each leftOut as w (w.id)}
<div class="flex items-center justify-between gap-2">
<span class="text-xs text-emphasis truncate">{w.name}</span>
<div class="flex shrink-0 gap-1">
<Button
variant="default"
unifiedSize="xs"
startIcon={{ icon: Copy }}
title={workspaceMcpUrl(w.id)}
onClick={() => copyToClipboard(workspaceMcpUrl(w.id), true)}
>
Copy workspace URL
</Button>
<Button variant="default" unifiedSize="xs" onClick={() => connectOnly(w.id)}>
Connect only
</Button>
</div>
</div>
<div class="flex flex-col gap-1">
<p class="text-xs font-semibold text-emphasis">Or connect only {w.name} here</p>
<p class="text-2xs text-secondary">In place of the other workspaces.</p>
<Button
variant="default"
unifiedSize="sm"
btnClasses="w-fit"
onClick={() => connectOnly(w.id)}
>
Connect {w.name} only
</Button>
</div>
</div>
{/each}
{/each}
</div>
{/if}
</div>
{/if}