diff --git a/docs/agents/adding-capabilities.md b/docs/agents/adding-capabilities.md index 6614fa924e..5907001bfd 100644 --- a/docs/agents/adding-capabilities.md +++ b/docs/agents/adding-capabilities.md @@ -104,6 +104,11 @@ runs. Missing secrets still fail with the same "secret not found" guidance used elsewhere, and secret-bearing capability inputs still require an authenticated user. +When a secret has an `allowed_capabilities` policy, Kody also checks that the +current capability name is explicitly listed before resolving the placeholder. +An empty `allowed_capabilities` list means no capability is allowed to resolve +the secret until entries are added. + Use this for capabilities that need to accept a secret value as an argument but are not themselves the host-approval boundary. Good fits include: @@ -284,6 +289,8 @@ scope narrow: - annotate only the exact credential fields, not the whole object - prefer this for local persistence or device-side credential flows +- tell users which capability names should be added to a secret's + `allowed_capabilities` policy when a workflow depends on restricted secrets - avoid using it for generic remote API wrappers where fetch-time host approval should remain the enforcement point @@ -295,8 +302,8 @@ Public MCP behavior should be verified through the compact tool surface: ranked results - use `execute` to confirm the capability runs correctly -Prefer E2E tests in `packages/worker/src/mcp/*.mcp-e2e.test.ts` for the real -MCP contract. +Prefer E2E tests in `packages/worker/src/mcp/*.mcp-e2e.test.ts` for the real MCP +contract. Registry invariants (duplicate capability names, domain/capability mismatches, duplicate domain registration) are covered in diff --git a/docs/agents/secret-host-approval.md b/docs/agents/secret-host-approval.md index 1eb51634c4..dcc0b48bde 100644 --- a/docs/agents/secret-host-approval.md +++ b/docs/agents/secret-host-approval.md @@ -5,18 +5,19 @@ secrets. ## Rule -Allowed outbound hosts for a secret are privileged policy, not normal secret +Allowed outbound hosts for a secret and allowed capabilities for direct +capability-input secret resolution are privileged policy, not normal secret metadata. -That policy must not be created, widened, or modified by: +Those policies must not be created, widened, or modified by: - MCP tools - execute-time sandboxed code - generated UI code - capability handlers that serve agent-driven secret creation or update flows -Allowed outbound hosts may only be changed through the authenticated account -admin UI approval flow. +Allowed outbound hosts and allowed capabilities may only be changed through the +authenticated account admin UI. In this repo, that means the user must approve host access through the account secrets experience, such as `/account/secrets` and the focused approval route at @@ -29,7 +30,7 @@ allowlist unless the user has already approved one or more hosts in the admin UI. Saving or updating a secret value does not authorize sending that secret to any -host. +host or passing it into any capability. If an outbound request uses a placeholder such as `{{secret:name}}` and the target host is not already approved for that secret, the correct behavior is: @@ -42,16 +43,22 @@ target host is not already approved for that secret, the correct behavior is: ## What agents must not do Do not design or document any MCP capability, generated UI helper, or client -library that allows agent-controlled writes to a secret's allowed hosts. +library that allows agent-controlled writes to a secret's allowed hosts or +allowed capabilities. Specifically, do not: - add `allowed_hosts` or equivalent fields to MCP-facing secret create/update inputs +- add `allowed_capabilities` or equivalent fields to MCP-facing secret + create/update inputs - imply that a generated UI can self-authorize a host just because it can save a secret +- imply that execute-time capability calls can widen which capabilities may + consume a secret - imply that execute-time code can widen egress permissions -- treat host approval as ordinary secret metadata editing +- treat host approval or capability allowlists as ordinary secret metadata + editing If a workflow would be smoother by auto-approving a host, the fix should be better guidance, helper APIs, or UX around the approval flow, not a new write @@ -62,7 +69,10 @@ path that bypasses the admin UI. When writing capability descriptions or agent-facing docs: - say explicitly that secret save/update does not grant outbound use +- say explicitly that secret save/update does not grant capability access - say explicitly that only the authenticated account admin UI can approve hosts +- say explicitly that only the authenticated account admin UI can restrict which + capabilities may consume a secret directly - tell agents to inspect secret metadata before making a secret-bearing request - tell agents to surface the approval link and stop on deny @@ -84,6 +94,9 @@ That feature is for cases where the capability needs the secret value itself, for example to store credentials on a local connector or pass them into a device-local action. +If a secret has an allowed-capabilities policy, Kody enforces that allowlist by +capability name before resolving the placeholder for the handler. + Use it narrowly: - mark only the exact sensitive fields @@ -105,11 +118,13 @@ Generated UIs may: - save those values as secrets - save and read back non-secret values for public configuration - inspect secret metadata, including current allowed hosts +- inspect secret metadata, including current allowed capabilities - present approval links returned from blocked requests Generated UIs may not: - set allowed hosts directly +- set allowed capabilities directly - bypass the admin approval route - silently retry secret-bearing requests after a deny - use `executeCode(...)` as a general string interpolation mechanism for diff --git a/packages/worker/client/mcp-apps/generated-ui-shell.node.test.ts b/packages/worker/client/mcp-apps/generated-ui-shell.node.test.ts index b9857e9f83..de6274acef 100644 --- a/packages/worker/client/mcp-apps/generated-ui-shell.node.test.ts +++ b/packages/worker/client/mcp-apps/generated-ui-shell.node.test.ts @@ -215,7 +215,6 @@ test('readSavedAppSourceFromHostToolResult preserves host tool errors', () => { errorMessage: 'Saved app not found for this user.', }) }) - test('buildLocalMessageLogRuntimeSource logs sendMessage locally outside hosted contexts', () => { const originalWindow = globalThis.window const originalDocument = globalThis.document diff --git a/packages/worker/client/mcp-apps/generated-ui-shell.ts b/packages/worker/client/mcp-apps/generated-ui-shell.ts index dac6861894..a42711b0f1 100644 --- a/packages/worker/client/mcp-apps/generated-ui-shell.ts +++ b/packages/worker/client/mcp-apps/generated-ui-shell.ts @@ -22,6 +22,7 @@ type SecretMetadata = { description: string app_id: string | null allowed_hosts: Array + allowed_capabilities: Array created_at: string updated_at: string ttl_ms: number | null @@ -772,6 +773,10 @@ function initializeGeneratedUiShell() { (secret.app_id == null || typeof secret.app_id === 'string') && Array.isArray(secret.allowed_hosts) && secret.allowed_hosts.every((host) => typeof host === 'string') && + Array.isArray(secret.allowed_capabilities) && + secret.allowed_capabilities.every( + (capability) => typeof capability === 'string', + ) && typeof secret.created_at === 'string' && typeof secret.updated_at === 'string' && (secret.ttl_ms == null || diff --git a/packages/worker/client/routes/account-secrets.tsx b/packages/worker/client/routes/account-secrets.tsx index e14b4469a8..3e0b16a061 100644 --- a/packages/worker/client/routes/account-secrets.tsx +++ b/packages/worker/client/routes/account-secrets.tsx @@ -42,6 +42,7 @@ type SecretListItem = { appId: string | null appTitle: string | null allowedHosts: Array + allowedCapabilities: Array createdAt: string updatedAt: string ttlMs: number | null @@ -68,6 +69,7 @@ type EditorState = { description: string value: string allowedHosts: Array + allowedCapabilities: Array } type SelectionState = { @@ -108,10 +110,56 @@ function createEmptyEditorState(apps: Array): EditorState { description: '', value: '', allowedHosts: [''], + allowedCapabilities: [''], } } +function coerceStringRows(list: Array): Array { + return list.filter((item): item is string => typeof item === 'string') +} + +/** Matches server `normalizeAllowedHosts` in `#mcp/secrets/allowed-hosts.ts`. */ +function clientNormalizeAllowedHosts(hosts: Array): Array { + return Array.from( + new Set( + hosts + .map((host) => host.trim().toLowerCase()) + .filter((host) => host.length > 0), + ), + ).sort() +} + +/** Matches server `normalizeAllowedCapabilities` in `#mcp/secrets/allowed-capabilities.ts`. */ +function clientNormalizeAllowedCapabilities( + capabilities: Array, +): Array { + return Array.from( + new Set( + capabilities + .map((value) => value.trim()) + .filter((value) => value.length > 0), + ), + ).sort((left, right) => left.localeCompare(right)) +} + +function collectRepeatedTextRows( + form: HTMLFormElement, + listName: 'allowed-hosts' | 'allowed-capabilities', +): Array { + const root = form.querySelector(`[data-repeat-list="${listName}"]`) + if (!root) return [] + const out: Array = [] + for (const row of root.children) { + if (!(row instanceof HTMLElement)) continue + const input = row.querySelector('input[type="text"]') + if (input instanceof HTMLInputElement) out.push(input.value) + } + return out +} + function createEditorStateFromSecret(secret: SecretDetail): EditorState { + const allowedHosts = coerceStringRows(secret.allowedHosts) + const allowedCapabilities = coerceStringRows(secret.allowedCapabilities) return { currentId: secret.id, name: secret.name, @@ -119,7 +167,9 @@ function createEditorStateFromSecret(secret: SecretDetail): EditorState { appId: secret.appId ?? '', description: secret.description, value: secret.value, - allowedHosts: secret.allowedHosts.length > 0 ? secret.allowedHosts : [''], + allowedHosts: allowedHosts.length > 0 ? allowedHosts : [''], + allowedCapabilities: + allowedCapabilities.length > 0 ? allowedCapabilities : [''], } } @@ -255,6 +305,7 @@ function filterSecrets( secret.appTitle ?? '', secret.scope, ...secret.allowedHosts, + ...secret.allowedCapabilities, ] .join(' ') .toLowerCase() @@ -435,11 +486,19 @@ export function AccountSecretsRoute(handle: Handle) { event.preventDefault() if (saveState !== 'idle') return + const form = event.currentTarget as HTMLFormElement + saveState = 'saving' message = null handle.update() try { + const allowedHosts = clientNormalizeAllowedHosts( + collectRepeatedTextRows(form, 'allowed-hosts'), + ) + const allowedCapabilities = clientNormalizeAllowedCapabilities( + collectRepeatedTextRows(form, 'allowed-capabilities'), + ) const response = await fetch(accountSecretsApiPath, { method: 'POST', headers: { @@ -455,7 +514,8 @@ export function AccountSecretsRoute(handle: Handle) { appId: editorState.scope === 'app' ? editorState.appId : null, description: editorState.description, value: editorState.value, - allowedHosts: editorState.allowedHosts, + allowedHosts, + allowedCapabilities, }), }) if (response.status === 401) { @@ -569,6 +629,37 @@ export function AccountSecretsRoute(handle: Handle) { handle.update() } + function updateAllowedCapability(index: number, value: string) { + editorState = { + ...editorState, + allowedCapabilities: editorState.allowedCapabilities.map( + (capabilityName, capabilityIndex) => + capabilityIndex === index ? value : capabilityName, + ), + } + handle.update() + } + + function addAllowedCapability() { + editorState = { + ...editorState, + allowedCapabilities: [...editorState.allowedCapabilities, ''], + } + handle.update() + } + + function removeAllowedCapability(index: number) { + const nextCapabilities = editorState.allowedCapabilities.filter( + (_capabilityName, capabilityIndex) => capabilityIndex !== index, + ) + editorState = { + ...editorState, + allowedCapabilities: + nextCapabilities.length > 0 ? nextCapabilities : [''], + } + handle.update() + } + return () => { const currentHref = getCurrentHref() const selection = getSelectionState(currentHref) @@ -1181,10 +1272,13 @@ export function AccountSecretsRoute(handle: Handle) { a secret can be used.

-
+
{editorState.allowedHosts.map((host, index) => (
updateAllowedHost( @@ -1228,6 +1322,72 @@ export function AccountSecretsRoute(handle: Handle) {
+
+
+ Allowed capabilities +

+ Only capabilities listed here can resolve this secret + when used with an + x-kody-secret + input. +

+
+
+ {editorState.allowedCapabilities.map( + (capabilityName, index) => ( +
+ + updateAllowedCapability( + index, + event.currentTarget.value, + ), + }} + css={inputCss} + /> + +
+ ), + )} +
+
+ +
+
+ {selectedSecret ? (
@@ -39,6 +41,7 @@ type AccountSecretListItem = { appId: string | null appTitle: string | null allowedHosts: Array + allowedCapabilities: Array createdAt: string updatedAt: string ttlMs: number | null @@ -335,6 +338,7 @@ function toAccountSecretListItem( description: string appId: string | null allowedHosts: Array + allowedCapabilities: Array createdAt: string updatedAt: string ttlMs: number | null @@ -358,6 +362,7 @@ function toAccountSecretListItem( appId: secret.appId, appTitle: secret.appId ? (appTitles.get(secret.appId) ?? null) : null, allowedHosts: secret.allowedHosts, + allowedCapabilities: secret.allowedCapabilities, createdAt: secret.createdAt, updatedAt: secret.updatedAt, ttlMs: secret.ttlMs, @@ -446,6 +451,9 @@ async function handleSaveAction(input: { const allowedHosts = normalizeAllowedHosts( readStringArray(input.body, 'allowedHosts'), ) + const allowedCapabilities = normalizeAllowedCapabilities( + readStringArray(input.body, 'allowedCapabilities'), + ) if (!name) { return jsonResponse({ ok: false, error: 'Secret name is required.' }, 400) @@ -523,6 +531,17 @@ async function handleSaveAction(input: { appId, }), }) + await setSecretAllowedCapabilities({ + env: input.env, + userId: input.user.mcpUser.userId, + name, + scope, + allowedCapabilities, + storageContext: getSecretContextForAccountSecret({ + scope, + appId, + }), + }) if (currentSecret && currentSecret.id !== nextId) { await deleteSecret({ diff --git a/packages/worker/src/app/saved-ui-hosted-html.ts b/packages/worker/src/app/saved-ui-hosted-html.ts index b0e69c712c..9b9586d6d8 100644 --- a/packages/worker/src/app/saved-ui-hosted-html.ts +++ b/packages/worker/src/app/saved-ui-hosted-html.ts @@ -469,6 +469,10 @@ async function listSecretsWithHttp(scope) { (secret.app_id == null || typeof secret.app_id === 'string') && Array.isArray(secret.allowed_hosts) && secret.allowed_hosts.every((host) => typeof host === 'string') && + Array.isArray(secret.allowed_capabilities) && + secret.allowed_capabilities.every( + (capability) => typeof capability === 'string', + ) && typeof secret.created_at === 'string' && typeof secret.updated_at === 'string' && (secret.ttl_ms == null || diff --git a/packages/worker/src/mcp/capabilities/secrets/secret-list.ts b/packages/worker/src/mcp/capabilities/secrets/secret-list.ts index f34dc351e1..977ed8b133 100644 --- a/packages/worker/src/mcp/capabilities/secrets/secret-list.ts +++ b/packages/worker/src/mcp/capabilities/secrets/secret-list.ts @@ -12,7 +12,7 @@ export const secretListCapability = defineDomainCapability( { name: 'secret_list', description: - 'List available secret references for the signed-in user without revealing secret values. When scope is omitted, results include every accessible scope in precedence order. Use `codemode.secret_list({ scope })` inside execute-time code when you want the same metadata, including allowed hosts, from the sandbox.', + 'List available secret references for the signed-in user without revealing secret values. When scope is omitted, results include every accessible scope in precedence order. Use `codemode.secret_list({ scope })` inside execute-time code when you want the same metadata, including allowed hosts and allowed capabilities, from the sandbox.', keywords: ['secret', 'list', 'discovery', 'metadata', 'credentials'], readOnly: true, idempotent: true, @@ -46,6 +46,7 @@ export const secretListCapability = defineDomainCapability( description: secret.description, app_id: secret.appId, allowed_hosts: secret.allowedHosts, + allowed_capabilities: secret.allowedCapabilities, created_at: secret.createdAt, updated_at: secret.updatedAt, ttl_ms: secret.ttlMs, diff --git a/packages/worker/src/mcp/capabilities/secrets/shared.ts b/packages/worker/src/mcp/capabilities/secrets/shared.ts index d0b9834393..d56d21358c 100644 --- a/packages/worker/src/mcp/capabilities/secrets/shared.ts +++ b/packages/worker/src/mcp/capabilities/secrets/shared.ts @@ -7,6 +7,7 @@ export const secretMetadataSchema = z.object({ description: z.string(), app_id: z.string().nullable(), allowed_hosts: z.array(z.string()), + allowed_capabilities: z.array(z.string()), created_at: z.string(), updated_at: z.string(), ttl_ms: z.number().int().nonnegative().nullable(), diff --git a/packages/worker/src/mcp/executor.node.test.ts b/packages/worker/src/mcp/executor.node.test.ts new file mode 100644 index 0000000000..27eeead139 --- /dev/null +++ b/packages/worker/src/mcp/executor.node.test.ts @@ -0,0 +1,54 @@ +import { expect, test } from 'vitest' +import { + createCapabilitySecretAccessDeniedMessage, + createMissingSecretMessage, +} from '#mcp/secrets/errors.ts' +import { formatExecutionOutput, getExecutionErrorDetails } from './executor.ts' + +test('getExecutionErrorDetails returns concrete guidance for capability access denial', () => { + const error = new Error( + createCapabilitySecretAccessDeniedMessage( + 'cloudflareToken', + 'cloudflare_rest', + ), + ) + + expect(getExecutionErrorDetails(error)).toEqual({ + kind: 'secret_capability_access_required', + message: + 'Secret "cloudflareToken" is not allowed for capability "cloudflare_rest". If this capability should be able to use the secret, ask the user whether to add "cloudflare_rest" to the secret\'s allowed capabilities in the account secrets UI, then retry after they approve that policy change.', + nextStep: + "Ask the user whether this capability should be allowed to use the secret. If they approve, help them add this capability name to the secret's allowed capabilities in the account secrets UI, then retry.", + secretNames: ['cloudflareToken'], + capabilityName: 'cloudflare_rest', + suggestedAction: { + type: 'edit_secret_policy', + policyField: 'allowed_capabilities', + }, + }) +}) + +test('formatExecutionOutput includes capability access next step', () => { + const result = { + error: new Error( + createCapabilitySecretAccessDeniedMessage( + 'cloudflareToken', + 'cloudflare_rest', + ), + ), + } as const + + expect(formatExecutionOutput(result)).toContain( + "Next step: Ask the user whether this capability should be allowed to use the secret. If they approve, help them add this capability name to the secret's allowed capabilities in the account secrets UI, then retry.", + ) +}) + +test('formatExecutionOutput keeps missing secret guidance intact', () => { + const result = { + error: new Error(createMissingSecretMessage('missingToken')), + } as const + + expect(formatExecutionOutput(result)).toContain( + 'Open a generated UI so the user can provide and save this secret', + ) +}) diff --git a/packages/worker/src/mcp/executor.ts b/packages/worker/src/mcp/executor.ts index e437c6bb7b..4499737c6d 100644 --- a/packages/worker/src/mcp/executor.ts +++ b/packages/worker/src/mcp/executor.ts @@ -4,6 +4,7 @@ type WorkerLoopbackExports = Exclude import { type FetchGatewayProps } from '#mcp/fetch-gateway.ts' import { isSecretAuthRequiredMessage, + parseCapabilityAccessRequiredMessage, parseHostApprovalRequiredMessage, parseMissingSecretMessage, } from '#mcp/secrets/errors.ts' @@ -44,6 +45,17 @@ export type ExecutionErrorDetails = type: 'approve_secret_host' } } + | { + kind: 'secret_capability_access_required' + message: string + nextStep: string + secretNames: Array + capabilityName: string + suggestedAction: { + type: 'edit_secret_policy' + policyField: 'allowed_capabilities' + } + } | { kind: 'secret_required' message: string @@ -84,6 +96,22 @@ export function getExecutionErrorDetails( } } + const capabilityAccessDetails = parseCapabilityAccessRequiredMessage(message) + if (capabilityAccessDetails) { + return { + kind: 'secret_capability_access_required', + message, + nextStep: + "Ask the user whether this capability should be allowed to use the secret. If they approve, help them add this capability name to the secret's allowed capabilities in the account secrets UI, then retry.", + secretNames: [capabilityAccessDetails.secretName], + capabilityName: capabilityAccessDetails.capabilityName, + suggestedAction: { + type: 'edit_secret_policy', + policyField: 'allowed_capabilities', + }, + } + } + const missingSecretDetails = parseMissingSecretMessage(message) if (missingSecretDetails) { return { diff --git a/packages/worker/src/mcp/generated-ui-api.ts b/packages/worker/src/mcp/generated-ui-api.ts index cf80d55e4a..06b572c526 100644 --- a/packages/worker/src/mcp/generated-ui-api.ts +++ b/packages/worker/src/mcp/generated-ui-api.ts @@ -299,6 +299,7 @@ function createGeneratedUiSecretsHandler(env: Env) { description: secret.description, app_id: secret.appId, allowed_hosts: secret.allowedHosts, + allowed_capabilities: secret.allowedCapabilities, created_at: secret.createdAt, updated_at: secret.updatedAt, ttl_ms: secret.ttlMs, @@ -338,6 +339,7 @@ function createGeneratedUiSecretsHandler(env: Env) { description: saved.description, app_id: saved.appId, allowed_hosts: saved.allowedHosts, + allowed_capabilities: saved.allowedCapabilities, created_at: saved.createdAt, updated_at: saved.updatedAt, ttl_ms: saved.ttlMs, diff --git a/packages/worker/src/mcp/index.ts b/packages/worker/src/mcp/index.ts index 43d968276f..d69660f876 100644 --- a/packages/worker/src/mcp/index.ts +++ b/packages/worker/src/mcp/index.ts @@ -80,10 +80,10 @@ How to use execute - Each capability call returns that capability's raw structured result value. - When chaining calls, read fields from the previous result using its outputSchema. - Chain multiple calls, use conditionals, and return structured results. -- Use \`await codemode.secret_list({})\` or \`await codemode.secret_list({ scope: 'app' })\` when you need secret metadata such as names, descriptions, scopes, and allowed hosts from the sandbox. +- Use \`await codemode.secret_list({})\` or \`await codemode.secret_list({ scope: 'app' })\` when you need secret metadata such as names, descriptions, scopes, allowed hosts, and allowed capabilities from the sandbox. - Use \`await codemode.value_get({ name })\` or \`await codemode.value_list({ scope })\` for readable non-secret configuration that generated UI code should be able to store and read back later. - Use normal \`fetch(...)\` for outbound HTTP. To inject a stored secret, place a placeholder such as \`{{secret:cloudflareToken}}\` or \`{{secret:cloudflareToken|scope=user}}\` in the URL, headers, or request body; the host resolves it server-side and blocks unapproved destinations. -- Some capability input fields also accept secret placeholders. When an input schema marks a string field with \`x-kody-secret: true\`, you may pass \`{{secret:name}}\` or \`{{secret:name|scope=user}}\` there instead of a raw value. +- Some capability input fields also accept secret placeholders. When an input schema marks a string field with \`x-kody-secret: true\`, you may pass \`{{secret:name}}\` or \`{{secret:name|scope=user}}\` there instead of a raw value. If that secret has an allowed-capabilities policy, the current capability name must be on the allowlist. - Secret placeholders are not general-purpose string interpolation. Do not use \`execute\` to build a string or object that merely returns \`{{secret:...}}\`; those placeholders only resolve in secret-aware fetch paths or capability inputs that explicitly opt into \`x-kody-secret\`. - Saving or updating a secret does not authorize sending it anywhere. If a fetch fails because a host is not approved for that secret, ask the user whether to open the approval link and approve that host in the web app. - Secrets are intentionally not readable or updatable through \`codemode\`. Never ask the user to paste a secret into chat; use generated UI flows such as \`saveSecret(...)\` when the user needs to provide or rotate a value, and use \`codemode.secret_delete(...)\` only when removing a stored secret reference. diff --git a/packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts b/packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts index 86a95fae9a..10617f0cb4 100644 --- a/packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts +++ b/packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts @@ -1337,6 +1337,7 @@ test('generated ui sessions support secret storage, execute-time resolution, and description: 'Session-only verification code', app_id: null, allowed_hosts: [], + allowed_capabilities: [], created_at: expect.any(String), updated_at: expect.any(String), ttl_ms: expect.any(Number), @@ -1401,6 +1402,7 @@ test('generated ui sessions support secret storage, execute-time resolution, and description: 'App-scoped Cloudflare deployment token', app_id: appId, allowed_hosts: [], + allowed_capabilities: [], created_at: expect.any(String), updated_at: expect.any(String), ttl_ms: null, diff --git a/packages/worker/src/mcp/run-codemode-registry.node.test.ts b/packages/worker/src/mcp/run-codemode-registry.node.test.ts index b00ff29609..165e4ad58c 100644 --- a/packages/worker/src/mcp/run-codemode-registry.node.test.ts +++ b/packages/worker/src/mcp/run-codemode-registry.node.test.ts @@ -1,6 +1,7 @@ -import { expect, test } from 'vitest' +import { expect, test, vi } from 'vitest' import { createMcpCallerContext } from '#mcp/context.ts' import { buildCodemodeFns } from './run-codemode-registry.ts' +import * as secretService from '#mcp/secrets/service.ts' test('buildCodemodeFns resolves annotated home capability secret placeholders', async () => { let toolArguments: Record | null = null @@ -72,10 +73,12 @@ test('buildCodemodeFns resolves annotated home capability secret placeholders', env, createMcpCallerContext({ baseUrl: 'https://heykody.dev', + user: { userId: 'user-123' }, homeConnectorId: 'default', }), { - resolveSecretValue: async (secret) => `${secret.name}-resolved`, + resolveSecretValue: async (secret, capabilityName) => + `${secret.name}-${capabilityName}-resolved`, }, ) @@ -87,7 +90,93 @@ test('buildCodemodeFns resolves annotated home capability secret placeholders', expect(toolArguments).toEqual({ processorId: 'lutron-192-168-0-41', - username: 'lutronUsername-resolved', - password: 'lutronPassword-resolved', + username: 'lutronUsername-home_lutron_set_credentials-resolved', + password: 'lutronPassword-home_lutron_set_credentials-resolved', }) }) + +test('buildCodemodeFns denies capability secret placeholders for disallowed capabilities', async () => { + const resolveSecretSpy = vi + .spyOn(secretService, 'resolveSecret') + .mockResolvedValue({ + found: true, + value: 'lutronUsername-resolved', + scope: 'user', + allowedHosts: [], + allowedCapabilities: ['some_other_capability'], + }) + const env = { + HOME_CONNECTOR_SESSION: { + idFromName(name: string) { + return name + }, + get() { + return { + async fetch(input: string | URL | Request) { + const url = new URL( + typeof input === 'string' + ? input + : input instanceof URL + ? input.toString() + : input.url, + ) + if (url.pathname.endsWith('/snapshot')) { + return Response.json({ + connectorId: 'default', + connectedAt: '2026-03-27T00:00:00.000Z', + lastSeenAt: '2026-03-27T00:00:01.000Z', + tools: [ + { + name: 'lutron_set_credentials', + title: 'Set Lutron Credentials', + description: 'Store Lutron credentials.', + inputSchema: { + type: 'object', + properties: { + username: { + type: 'string', + 'x-kody-secret': true, + }, + }, + required: ['username'], + }, + }, + ], + }) + } + + throw new Error(`Unexpected fetch to ${url.pathname}`) + }, + } + }, + }, + } as unknown as Env + + const codemode = await buildCodemodeFns( + env, + createMcpCallerContext({ + baseUrl: 'https://heykody.dev', + user: { userId: 'user-123' }, + homeConnectorId: 'default', + }), + ) + + try { + await expect( + codemode.home_lutron_set_credentials({ + username: '{{secret:lutronUsername|scope=user}}', + }), + ).rejects.toThrow( + 'Secret "lutronUsername" is not allowed for capability "home_lutron_set_credentials"', + ) + expect(resolveSecretSpy).toHaveBeenCalledWith( + expect.objectContaining({ + name: 'lutronUsername', + scope: 'user', + userId: 'user-123', + }), + ) + } finally { + resolveSecretSpy.mockRestore() + } +}) diff --git a/packages/worker/src/mcp/run-codemode-registry.ts b/packages/worker/src/mcp/run-codemode-registry.ts index 13ea393355..6de7aec390 100644 --- a/packages/worker/src/mcp/run-codemode-registry.ts +++ b/packages/worker/src/mcp/run-codemode-registry.ts @@ -8,6 +8,7 @@ import { type McpCallerContext } from '@kody-internal/shared/chat.ts' import { resolveCapabilityInputSecrets } from '#mcp/secrets/capability-inputs.ts' import { capabilityInputSecretAuthRequiredMessage, + createCapabilitySecretAccessDeniedMessage, createMissingSecretMessage, } from '#mcp/secrets/errors.ts' import { resolveSecret } from '#mcp/secrets/service.ts' @@ -19,24 +20,32 @@ export async function buildCodemodeFns( env: Env, callerContext: McpCallerContext, options?: { - resolveSecretValue?: (secret: ReferencedSecret) => Promise + resolveSecretValue?: ( + secret: ReferencedSecret, + capabilityName: string, + ) => Promise }, ) { const { capabilityMap } = await getCapabilityRegistryForContext({ env, callerContext, }) - const resolveSecretValue = - options?.resolveSecretValue ?? - createCapabilityInputSecretResolver(env, callerContext) return Object.fromEntries( Object.values(capabilityMap).map((capability) => [ capability.name, async (args: unknown) => { + const resolveSecretValue = + options?.resolveSecretValue ?? + createCapabilityInputSecretResolver( + env, + callerContext, + capability.name, + ) const resolvedArgs = await resolveCapabilityInputSecrets({ schema: capability.inputSchema, value: (args ?? {}) as Record, - resolveSecretValue, + resolveSecretValue: (secret) => + resolveSecretValue(secret, capability.name), }) return capability.handler(resolvedArgs as Record, { env, @@ -69,8 +78,9 @@ export async function buildCodemodeProvider( function createCapabilityInputSecretResolver( env: Env, callerContext: McpCallerContext, + capabilityName: string, ) { - return async (secret: ReferencedSecret) => { + return async (secret: ReferencedSecret, _currentCapabilityName: string) => { const userId = callerContext.user?.userId ?? null if (!userId) { throw new Error(capabilityInputSecretAuthRequiredMessage) @@ -90,6 +100,11 @@ function createCapabilityInputSecretResolver( if (!resolved.found || typeof resolved.value !== 'string') { throw new Error(createMissingSecretMessage(secret.name)) } + if (!resolved.allowedCapabilities.includes(capabilityName)) { + throw new Error( + createCapabilitySecretAccessDeniedMessage(secret.name, capabilityName), + ) + } return resolved.value } } diff --git a/packages/worker/src/mcp/secrets/account-secret-save-body.node.test.ts b/packages/worker/src/mcp/secrets/account-secret-save-body.node.test.ts new file mode 100644 index 0000000000..3def7cfcb1 --- /dev/null +++ b/packages/worker/src/mcp/secrets/account-secret-save-body.node.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' + +/** + * Mirrors account-secrets handler readStringArray: non-strings are dropped. + * JSON.stringify turns array holes/undefined entries into null, so a client + * that serializes ['a', undefined] sends ["a",null] and the server keeps + * only 'a' after filtering — matching the UI bug where a row looked filled + * (stale DOM) but only one capability persisted. + */ +function readStringArray(body: Record, key: string) { + const value = body[key] + if (!Array.isArray(value)) return [] + return value.filter((item): item is string => typeof item === 'string') +} + +describe('account secret save body parsing', () => { + it('drops null elements produced from JSON undefined serialization', () => { + const body = JSON.parse( + JSON.stringify({ + allowedCapabilities: ['cloudflare_rest', undefined], + }), + ) as Record + expect(body.allowedCapabilities).toEqual(['cloudflare_rest', null]) + expect(readStringArray(body, 'allowedCapabilities')).toEqual([ + 'cloudflare_rest', + ]) + }) + + it('keeps both capabilities when both are strings', () => { + const body = { + allowedCapabilities: ['cloudflare_rest', 'home_lutron_set_credentials'], + } + expect(readStringArray(body, 'allowedCapabilities')).toEqual([ + 'cloudflare_rest', + 'home_lutron_set_credentials', + ]) + }) +}) diff --git a/packages/worker/src/mcp/secrets/allowed-capabilities.ts b/packages/worker/src/mcp/secrets/allowed-capabilities.ts new file mode 100644 index 0000000000..c979308c0b --- /dev/null +++ b/packages/worker/src/mcp/secrets/allowed-capabilities.ts @@ -0,0 +1,24 @@ +export function normalizeAllowedCapabilities(input: Array) { + return Array.from( + new Set( + input.map((value) => value.trim()).filter((value) => value.length > 0), + ), + ).sort((left, right) => left.localeCompare(right)) +} + +export function parseAllowedCapabilities(value: string | null | undefined) { + if (!value) return [] + try { + const parsed = JSON.parse(value) + if (!Array.isArray(parsed)) return [] + return normalizeAllowedCapabilities( + parsed.filter((entry): entry is string => typeof entry === 'string'), + ) + } catch { + return [] + } +} + +export function stringifyAllowedCapabilities(input: Array) { + return JSON.stringify(normalizeAllowedCapabilities(input)) +} diff --git a/packages/worker/src/mcp/secrets/errors.node.test.ts b/packages/worker/src/mcp/secrets/errors.node.test.ts index dcc789e3cc..ed6286ffe9 100644 --- a/packages/worker/src/mcp/secrets/errors.node.test.ts +++ b/packages/worker/src/mcp/secrets/errors.node.test.ts @@ -1,9 +1,11 @@ import { expect, test } from 'vitest' import { capabilityInputSecretAuthRequiredMessage, + createCapabilitySecretAccessDeniedMessage, createMissingSecretMessage, fetchSecretAuthRequiredMessage, isSecretAuthRequiredMessage, + parseCapabilityAccessRequiredMessage, parseHostApprovalRequiredMessage, parseMissingSecretMessage, } from './errors.ts' @@ -35,3 +37,17 @@ test('parseHostApprovalRequiredMessage extracts secret name and host', () => { }) expect(parseHostApprovalRequiredMessage('Host approval failed')).toBeNull() }) + +test('parseCapabilitySecretAccessDeniedMessage extracts secret and capability', () => { + const message = createCapabilitySecretAccessDeniedMessage( + 'cloudflareToken', + 'cloudflare_rest', + ) + expect(parseCapabilityAccessRequiredMessage(message)).toEqual({ + secretName: 'cloudflareToken', + capabilityName: 'cloudflare_rest', + }) + expect( + parseCapabilityAccessRequiredMessage('Capability approval failed'), + ).toBeNull() +}) diff --git a/packages/worker/src/mcp/secrets/errors.ts b/packages/worker/src/mcp/secrets/errors.ts index 5bd0cffd59..585a2adcb9 100644 --- a/packages/worker/src/mcp/secrets/errors.ts +++ b/packages/worker/src/mcp/secrets/errors.ts @@ -1,5 +1,7 @@ const hostApprovalRequiredRegex = /^Secret "([^"]+)" is not allowed for host "([^"]+)"/ +const capabilityAccessRequiredRegex = + /^Secret "([^"]+)" is not allowed for capability "([^"]+)"/ const missingSecretRegex = /^Secret "([^"]+)" was not found\.$/ export const fetchSecretAuthRequiredMessage = @@ -17,6 +19,13 @@ export function createMissingSecretMessage(secretName: string) { return `Secret "${secretName}" was not found.` } +export function createCapabilitySecretAccessDeniedMessage( + secretName: string, + capabilityName: string, +) { + return `Secret "${secretName}" is not allowed for capability "${capabilityName}". If this capability should be able to use the secret, ask the user whether to add "${capabilityName}" to the secret's allowed capabilities in the account secrets UI, then retry after they approve that policy change.` +} + export function parseMissingSecretMessage(message: string) { const match = message.match(missingSecretRegex) if (!match?.[1]) return null @@ -34,6 +43,15 @@ export function parseHostApprovalRequiredMessage(message: string) { } } +export function parseCapabilityAccessRequiredMessage(message: string) { + const match = message.match(capabilityAccessRequiredRegex) + if (!match?.[1] || !match?.[2]) return null + return { + secretName: match[1], + capabilityName: match[2], + } +} + export function isSecretAuthRequiredMessage(message: string) { return secretAuthRequiredMessages.has(message) } diff --git a/packages/worker/src/mcp/secrets/repo.ts b/packages/worker/src/mcp/secrets/repo.ts index c815bb6f85..0e5c395950 100644 --- a/packages/worker/src/mcp/secrets/repo.ts +++ b/packages/worker/src/mcp/secrets/repo.ts @@ -10,6 +10,7 @@ type SecretMetadataRow = { name: string description: string allowed_hosts: string + allowed_capabilities: string created_at: string updated_at: string expires_at: string | null @@ -73,7 +74,7 @@ export async function getSecretEntry(input: { }): Promise { const row = await input.db .prepare( - `SELECT bucket_id, name, description, encrypted_value, allowed_hosts, created_at, updated_at + `SELECT bucket_id, name, description, encrypted_value, allowed_hosts, allowed_capabilities, created_at, updated_at FROM secret_entries WHERE bucket_id = ? AND name = ? LIMIT 1`, @@ -94,13 +95,14 @@ export async function upsertSecretEntry(input: { await input.db .prepare( `INSERT INTO secret_entries ( - bucket_id, name, description, encrypted_value, allowed_hosts, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?) + bucket_id, name, description, encrypted_value, allowed_hosts, allowed_capabilities, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(bucket_id, name) DO UPDATE SET description = excluded.description, encrypted_value = excluded.encrypted_value, allowed_hosts = excluded.allowed_hosts, + allowed_capabilities = excluded.allowed_capabilities, updated_at = excluded.updated_at`, ) .bind( @@ -109,6 +111,7 @@ export async function upsertSecretEntry(input: { input.row.description, input.row.encrypted_value, input.row.allowed_hosts, + input.row.allowed_capabilities, input.row.created_at ?? now, input.row.updated_at ?? now, ) @@ -133,7 +136,7 @@ export async function listSecretMetadataForBucket(input: { }): Promise> { const { results } = await input.db .prepare( - `SELECT ? AS scope, ? AS binding_key, name, description, allowed_hosts, created_at, updated_at, ? AS expires_at + `SELECT ? AS scope, ? AS binding_key, name, description, allowed_hosts, allowed_capabilities, created_at, updated_at, ? AS expires_at FROM secret_entries WHERE bucket_id = ? ORDER BY name ASC`, @@ -156,7 +159,7 @@ export async function listUserScopeSecretMetadata(input: { const now = input.now ?? new Date().toISOString() const { results } = await input.db .prepare( - `SELECT b.scope, b.binding_key, e.name, e.description, e.allowed_hosts, e.created_at, e.updated_at, b.expires_at + `SELECT b.scope, b.binding_key, e.name, e.description, e.allowed_hosts, e.allowed_capabilities, e.created_at, e.updated_at, b.expires_at FROM secret_buckets b JOIN secret_entries e ON e.bucket_id = b.id WHERE b.user_id = ? AND b.scope = 'user' @@ -179,7 +182,7 @@ export async function listAppScopeSecretMetadata(input: { const placeholders = input.appIds.map(() => '?').join(', ') const { results } = await input.db .prepare( - `SELECT b.scope, b.binding_key, e.name, e.description, e.allowed_hosts, e.created_at, e.updated_at, b.expires_at + `SELECT b.scope, b.binding_key, e.name, e.description, e.allowed_hosts, e.allowed_capabilities, e.created_at, e.updated_at, b.expires_at FROM secret_buckets b JOIN secret_entries e ON e.bucket_id = b.id WHERE b.user_id = ? AND b.scope = 'app' @@ -211,6 +214,7 @@ function mapSecretEntryRow(row: Record): SecretEntryRow { description: String(row['description']), encrypted_value: String(row['encrypted_value']), allowed_hosts: String(row['allowed_hosts']), + allowed_capabilities: String(row['allowed_capabilities']), created_at: String(row['created_at']), updated_at: String(row['updated_at']), } @@ -223,6 +227,7 @@ function mapSecretMetadataRow(row: Record): SecretMetadataRow { name: String(row['name']), description: String(row['description']), allowed_hosts: String(row['allowed_hosts']), + allowed_capabilities: String(row['allowed_capabilities']), created_at: String(row['created_at']), updated_at: String(row['updated_at']), expires_at: row['expires_at'] == null ? null : String(row['expires_at']), diff --git a/packages/worker/src/mcp/secrets/service.ts b/packages/worker/src/mcp/secrets/service.ts index 0bd8aa11a7..9fcd0a8d19 100644 --- a/packages/worker/src/mcp/secrets/service.ts +++ b/packages/worker/src/mcp/secrets/service.ts @@ -1,3 +1,8 @@ +import { + normalizeAllowedCapabilities, + parseAllowedCapabilities, + stringifyAllowedCapabilities, +} from './allowed-capabilities.ts' import { normalizeAllowedHosts, normalizeHost, @@ -66,6 +71,7 @@ export type ResolvedSecret = { value: string | null scope: SecretScope | null allowedHosts: Array + allowedCapabilities: Array } export async function saveSecret( @@ -101,6 +107,7 @@ export async function saveSecret( description, encrypted_value: await encryptSecretValue(input.env, value), allowed_hosts: existingEntry?.allowed_hosts ?? '[]', + allowed_capabilities: existingEntry?.allowed_capabilities ?? '[]', created_at: existingEntry?.created_at ?? now, updated_at: now, }, @@ -113,6 +120,9 @@ export async function saveSecret( allowedHosts: existingEntry ? parseAllowedHosts(existingEntry.allowed_hosts) : [], + allowedCapabilities: existingEntry + ? parseAllowedCapabilities(existingEntry.allowed_capabilities) + : [], createdAt: existingEntry?.created_at ?? now, updatedAt: now, expiresAt: bucket.expires_at, @@ -143,6 +153,7 @@ export async function listSecrets( description: row.description, appId: row.scope === 'app' ? row.binding_key : null, allowedHosts: parseAllowedHosts(row.allowed_hosts), + allowedCapabilities: parseAllowedCapabilities(row.allowed_capabilities), createdAt: row.created_at, updatedAt: row.updated_at, expiresAt: row.expires_at, @@ -175,6 +186,7 @@ export async function resolveSecret( value: await decryptSecretValue(input.env, entry.encrypted_value), scope, allowedHosts: parseAllowedHosts(entry.allowed_hosts), + allowedCapabilities: parseAllowedCapabilities(entry.allowed_capabilities), } } return { @@ -182,6 +194,7 @@ export async function resolveSecret( value: null, scope: null, allowedHosts: [], + allowedCapabilities: [], } } @@ -247,6 +260,7 @@ export async function updateSecret( ? await encryptSecretValue(input.env, nextValue!) : existingEntry.encrypted_value, allowed_hosts: existingEntry.allowed_hosts, + allowed_capabilities: existingEntry.allowed_capabilities, created_at: existingEntry.created_at, updated_at: now, }, @@ -257,6 +271,9 @@ export async function updateSecret( description: nextDescription, appId: input.scope === 'app' ? bucket.binding_key : null, allowedHosts: parseAllowedHosts(existingEntry.allowed_hosts), + allowedCapabilities: parseAllowedCapabilities( + existingEntry.allowed_capabilities, + ), createdAt: existingEntry.created_at, updatedAt: now, expiresAt: bucket.expires_at, @@ -301,6 +318,7 @@ export async function listAppSecretsByAppIds(input: { description: row.description, appId, allowedHosts: parseAllowedHosts(row.allowed_hosts), + allowedCapabilities: parseAllowedCapabilities(row.allowed_capabilities), createdAt: row.created_at, updatedAt: row.updated_at, expiresAt: row.expires_at, @@ -415,6 +433,7 @@ function toSecretMetadata(input: { description: string appId: string | null allowedHosts: Array + allowedCapabilities: Array createdAt: string updatedAt: string expiresAt: string | null @@ -425,6 +444,9 @@ function toSecretMetadata(input: { description: input.description, appId: input.appId, allowedHosts: normalizeAllowedHosts(input.allowedHosts), + allowedCapabilities: normalizeAllowedCapabilities( + input.allowedCapabilities, + ), createdAt: input.createdAt, updatedAt: input.updatedAt, ttlMs: @@ -478,6 +500,62 @@ export async function setSecretAllowedHosts(input: { description: existingEntry.description, appId: input.scope === 'app' ? bucket.binding_key : null, allowedHosts: input.allowedHosts, + allowedCapabilities: parseAllowedCapabilities( + existingEntry.allowed_capabilities, + ), + createdAt: existingEntry.created_at, + updatedAt: now, + expiresAt: bucket.expires_at, + }) +} + +export async function setSecretAllowedCapabilities(input: { + env: Pick + userId: string + name: string + scope: SecretScope + allowedCapabilities: Array + storageContext?: StorageContext | null +}) { + const name = input.name.trim() + if (!name) { + throw new Error('Secret name is required.') + } + const bucket = await getExistingBucketForScope({ + db: input.env.APP_DB, + userId: input.userId, + scope: input.scope, + storageContext: input.storageContext ?? null, + }) + if (!bucket) { + throw new Error('Secret not found for this scope.') + } + const existingEntry = await getSecretEntry({ + db: input.env.APP_DB, + bucketId: bucket.id, + name, + }) + if (!existingEntry) { + throw new Error('Secret not found for this scope.') + } + const now = new Date().toISOString() + await upsertSecretEntry({ + db: input.env.APP_DB, + row: { + ...existingEntry, + allowed_capabilities: stringifyAllowedCapabilities( + input.allowedCapabilities, + ), + updated_at: now, + }, + }) + return toSecretMetadata({ + name, + scope: input.scope, + description: existingEntry.description, + appId: input.scope === 'app' ? bucket.binding_key : null, + allowedHosts: parseAllowedHosts(existingEntry.allowed_hosts), + allowedCapabilities: input.allowedCapabilities, createdAt: existingEntry.created_at, updatedAt: now, expiresAt: bucket.expires_at, diff --git a/packages/worker/src/mcp/secrets/types.ts b/packages/worker/src/mcp/secrets/types.ts index da8f53f9f1..8d7c8b06f1 100644 --- a/packages/worker/src/mcp/secrets/types.ts +++ b/packages/worker/src/mcp/secrets/types.ts @@ -24,6 +24,7 @@ export type SecretEntryRow = { description: string encrypted_value: string allowed_hosts: string + allowed_capabilities: string created_at: string updated_at: string } @@ -34,6 +35,7 @@ export type SecretMetadata = { description: string appId: string | null allowedHosts: Array + allowedCapabilities: Array createdAt: string updatedAt: string ttlMs: number | null diff --git a/packages/worker/src/mcp/tools/execute.ts b/packages/worker/src/mcp/tools/execute.ts index d89e90c165..62bcfe1995 100644 --- a/packages/worker/src/mcp/tools/execute.ts +++ b/packages/worker/src/mcp/tools/execute.ts @@ -48,12 +48,13 @@ Network access: - To inject a saved secret into a request, use a placeholder string such as \`{{secret:cloudflareToken}}\` or \`{{secret:cloudflareToken|scope=user}}\` in the URL, headers, or request body. - Secret placeholders only work for hosts that the user has already approved for that secret. - Some capability input fields also accept secret placeholders. When a capability's input schema marks a string field with \`x-kody-secret: true\`, you may pass \`{{secret:name}}\` there instead of a raw credential. +- Capability-input secret placeholders also respect any per-secret allowed capability names. If a secret has a non-empty allowed-capabilities list, only those exact capability names may resolve it. - If a request is blocked because the host is not approved, do not retry blindly. Ask the user whether they want to approve that host, then provide the approval link from the error message. - Saving or updating a secret does not authorize outbound use automatically. Host approval happens separately in the app. Secrets: - Never ask the user to paste secrets, tokens, API keys, passwords, OAuth codes, client secrets, or other credentials into chat. If a workflow needs a secret value that is not already stored, use generated UI to collect and save it instead. -- Use \`await codemode.secret_list({})\` to inspect available secret metadata before building a request. The result is metadata only and does not reveal secret values. +- Use \`await codemode.secret_list({})\` to inspect available secret metadata before building a request. The result is metadata only and does not reveal secret values; it includes allowed hosts and allowed capability names. - Pass \`scope\` to narrow results, for example \`await codemode.secret_list({ scope: 'app' })\`. - Do not expect \`codemode.secret_get(...)\`, \`codemode.secret_require(...)\`, or any injected \`secrets\` helper to be available in execute-time code.