diff --git a/docs/native-oauth.md b/docs/native-oauth.md index 5fe416b5..862df8ce 100644 --- a/docs/native-oauth.md +++ b/docs/native-oauth.md @@ -61,6 +61,20 @@ On every request the server: is still authorized by the API. - **Requests and streams** end when the exchanged token expires (at most five minutes); clients reconnect with a fresh request. +- **Permissions** are chosen by the person who connects, on the authorization + server's consent page. The protected-resource metadata lists no + `scopes_supported`, so clients request no scopes and that page decides. + When the exchanged token names actions, toolsets none of them can use are + left out of the tool list and `get_connection_context` reports them under + `granted`. A token that names no action lists every toolset. Either way the + API authorizes each call. + - API key and workload identity tools are never listed for a token that + names actions: a sign-in cannot hold those permissions. + - The vault and search tools also depend on the organization's entitlements, + which the server reads with the connection's own token. Without + `organizations:read` (on the consent page, "view plan entitlements and + limits") that read is refused and both toolsets are left out, whatever + else was granted. ## Configuration diff --git a/src/app/[transport]/route.test.ts b/src/app/[transport]/route.test.ts index 18cb884a..ac3e4015 100644 --- a/src/app/[transport]/route.test.ts +++ b/src/app/[transport]/route.test.ts @@ -261,6 +261,64 @@ describe("native OAuth credentials", () => { expect(issuer.requests).toHaveLength(2); }); + // The JSON a get_connection_context call returned. + async function connectionContext(response: Response) { + expect(response.status).toBe(200); + const text = await response.text(); + const event = text.split("\n").find((line) => line.startsWith("data: ")); + const message = JSON.parse(event ? event.slice(6) : text); + return JSON.parse(message.result.content[0].text); + } + + test("list only the toolsets the token's actions can use", async () => { + issuer.respondWith({ projects: ["proj_a", "proj_b"] }); + const limited = await issuer.parent({ + scope: "openid browsers:use profiles:read", + }); + let response = await POST(mcpRequest(limited)); + expect(response.status).toBe(200); + const listed = await response.text(); + for (const tool of [ + "manage_browsers", + "computer_action", + "manage_profiles", + ]) + expect(listed).toContain(`"name":"${tool}"`); + for (const tool of ["manage_proxies", "manage_api_keys", "manage_apps"]) + expect(listed).not.toContain(`"name":"${tool}"`); + + response = await POST( + mcpRequest(limited, "tools/call", { + name: "get_connection_context", + arguments: {}, + }), + ); + expect((await connectionContext(response)).granted).toEqual({ + permissions: ["browsers:use", "profiles:read"], + projects: ["proj_a", "proj_b"], + }); + + // A token that names no action holds its whole grant; nothing is hidden. + issuer.respondWith({}); + response = await POST(mcpRequest(await refreshed())); + const everything = await response.text(); + expect(everything).toContain('"name":"manage_proxies"'); + expect(everything).toContain('"name":"manage_api_keys"'); + }); + + test("report granted projects for a token that names no action", async () => { + issuer.respondWith({ projects: ["proj_a"] }); + const response = await POST( + mcpRequest(await refreshed(), "tools/call", { + name: "get_connection_context", + arguments: {}, + }), + ); + expect((await connectionContext(response)).granted).toEqual({ + projects: ["proj_a"], + }); + }); + test("reuse the entitlements snapshot across rotated tokens", async () => { for (let n = 0; n < 2; n++) { const response = await POST(mcpRequest(await refreshed())); diff --git a/src/app/[transport]/route.ts b/src/app/[transport]/route.ts index 74a313c3..ce871b2f 100644 --- a/src/app/[transport]/route.ts +++ b/src/app/[transport]/route.ts @@ -184,6 +184,7 @@ const handler = createMcpHandler(({ authInfo }) => { mcpApps: authInfo?.extra?.mcpApps === true, vaults: authInfo?.extra?.vaults === true, search: authInfo?.extra?.search === true, + permissions: authInfo?.extra?.permissions as string[] | undefined, }); return server; }); @@ -191,6 +192,10 @@ const handler = createMcpHandler(({ authInfo }) => { type AuthInfoExtra = { userId: string | null; clerkToken: string | null; + // The actions a Kernel-issued credential names and, when its grant is + // limited to some, the projects it may use. + permissions?: string[]; + projects?: string[]; }; // A refused connection never reaches the instrumented server, so this @@ -342,6 +347,10 @@ async function handleAuthenticatedRequest( if (native.status !== "ok") return refuseConnection(req, "authentication", "native_oauth", native); const { credential } = native; + // Action scopes name a resource kind and a verb; identity scopes do not. + // A token that names no action holds its whole grant, which it does not + // list, so nothing is known about what it may do. + const actions = credential.scopes.filter((scope) => scope.includes(":")); // The exchanged token rotates; identity is the verified subject, and the // request ends when the exchanged token does, streams included. return await handleMcpRequestWithIdentity({ @@ -357,7 +366,12 @@ async function handleAuthenticatedRequest( userId: credential.subject, }), scopes: credential.scopes, - authInfoExtra: { userId: credential.subject, clerkToken: null }, + authInfoExtra: { + userId: credential.subject, + clerkToken: null, + permissions: actions.length > 0 ? actions : undefined, + projects: credential.projects, + }, credentialType: "native_oauth", transportSessionId, entitlementsCacheCredential: credential.grantId, diff --git a/src/lib/mcp/register.test.ts b/src/lib/mcp/register.test.ts index f68fe6d2..746dcf7f 100644 --- a/src/lib/mcp/register.test.ts +++ b/src/lib/mcp/register.test.ts @@ -281,6 +281,83 @@ describe("MCP toolset allowlist", () => { }); }); +describe("MCP toolsets by granted permission", () => { + async function toolsFor(permissions?: string[]) { + const mcp = await connectTestMcp((server) => { + registerMcpCapabilities(server, { + mcpApps: true, + vaults: true, + search: true, + permissions, + }); + }, {}); + try { + return (await mcp.client.listTools()).tools.map((tool) => tool.name); + } finally { + await mcp.close(); + } + } + + test("lists everything when the credential names no action", async () => { + expect(await toolsFor()).toEqual( + expect.arrayContaining([ + "manage_browsers", + "manage_api_keys", + "manage_workload_identity", + "manage_tasks", + "manage_proxies", + "manage_vaults", + "web_search", + "open_auth_login", + ]), + ); + }); + + test("leaves out toolsets no granted action can use", async () => { + const tools = await toolsFor([ + "browsers:use", + "profiles:read", + "invocations:read", + ]); + expect(tools).toEqual( + expect.arrayContaining([ + "get_connection_context", + "search_docs", + "manage_browsers", + "computer_action", + "execute_playwright_code", + "manage_replays", + "manage_profiles", + "manage_apps", + ]), + ); + for (const hidden of [ + "manage_api_keys", + "manage_workload_identity", + "manage_tasks", + "manage_proxies", + "manage_vaults", + "manage_credentials", + "manage_auth_connections", + "open_auth_login", + "web_search", + ]) + expect(tools).not.toContain(hidden); + }); + + test("lists the task tools for a task action", async () => { + expect(await toolsFor(["tasks:read"])).toContain("manage_tasks"); + }); + + test("an entitled toolset still needs a granted action", async () => { + expect(await toolsFor(["vaults:read"])).toContain("manage_vaults"); + expect(await toolsFor(["searches:read"])).toContain("web_search"); + expect(await toolsFor(["auth_connections:use"])).toEqual( + expect.arrayContaining(["manage_auth_connections", "open_auth_login"]), + ); + }); +}); + describe("project selection registration", () => { const projectScopedTools = [ "manage_profiles", diff --git a/src/lib/mcp/register.ts b/src/lib/mcp/register.ts index f305f4fb..312a0338 100644 --- a/src/lib/mcp/register.ts +++ b/src/lib/mcp/register.ts @@ -36,6 +36,10 @@ type McpRegistrationOptions = { mcpApps?: boolean; vaults?: boolean; search?: boolean; + // The actions a Kernel-issued credential names. Toolsets it cannot use at + // all are left out. Undefined means the credential names none (an API key, + // or a token that holds its whole grant), and every toolset is listed. + permissions?: readonly string[]; dependencies?: McpDependencies; }; type RegisterMcpToolset = (server: McpServer, options: McpToolOptions) => void; @@ -74,6 +78,72 @@ const mcpToolRegistrations = [ type McpToolset = (typeof mcpToolRegistrations)[number][0]; +// The KERNEL API resource kinds the toolsets act on; an action is named +// ":". +type McpResourceKind = + | "auth_connections" + | "browser_pools" + | "browsers" + | "config_registry" + | "credential_providers" + | "credentials" + | "deployments" + | "extensions" + | "invocations" + | "profiles" + | "projects" + | "proxies" + | "searches" + | "tasks" + | "vault_provider_configs" + | "vaults"; + +// What a credential that names its actions needs for each toolset to be +// listed: any action on one of the listed resource kinds, nothing ("any"), or +// a permission no such credential can hold ("never"). The API still +// authorizes every call. +const mcpToolsetRequirements: Record< + McpToolset, + readonly McpResourceKind[] | "any" | "never" +> = { + profiles: ["profiles"], + tasks: ["tasks"], + docs: "any", + browsers: ["browsers"], + projects: ["projects"], + api_keys: "never", + workload_identity: "never", + browser_pools: ["browser_pools"], + config_registry: ["config_registry"], + browser_curl: ["browsers"], + browser_files: ["browsers"], + proxies: ["proxies"], + extensions: ["extensions"], + apps: ["deployments", "invocations"], + computer: ["browsers"], + shell: ["browsers"], + playwright: ["browsers"], + repl: ["browsers"], + webmcp: ["browsers"], + replays: ["browsers"], + auth_connections: ["auth_connections"], + credentials: ["credentials"], + credential_providers: ["credential_providers"], + vaults: ["vaults", "vault_provider_configs"], + search: ["searches"], +}; + +function toolsetPermitted( + permissions: readonly string[] | undefined, + toolset: McpToolset, +) { + const required = mcpToolsetRequirements[toolset]; + if (permissions === undefined || required === "any") return true; + if (required === "never") return false; + const kinds: readonly string[] = required; + return permissions.some((action) => kinds.includes(action.split(":")[0])); +} + const mcpToolsets = mcpToolRegistrations.map(([toolset]) => toolset); const mcpToolsetSet: ReadonlySet = new Set(mcpToolsets); @@ -200,6 +270,7 @@ export function registerMcpCapabilities( mcpApps = false, vaults = false, search = false, + permissions, dependencies = defaultMcpDependencies, }: McpRegistrationOptions = {}, ) { @@ -215,7 +286,8 @@ export function registerMcpCapabilities( if ( (toolset !== "vaults" || vaults) && (toolset !== "search" || search) && - toolsetEnabled(enabledToolsets, disabledToolsets, toolset) + toolsetEnabled(enabledToolsets, disabledToolsets, toolset) && + toolsetPermitted(permissions, toolset) ) { registerToolset(server, dependencies); } @@ -226,7 +298,8 @@ export function registerMcpCapabilities( // resource) without replacing or narrowing manage_auth_connections. if ( mcpApps && - toolsetEnabled(enabledToolsets, disabledToolsets, "auth_connections") + toolsetEnabled(enabledToolsets, disabledToolsets, "auth_connections") && + toolsetPermitted(permissions, "auth_connections") ) { registerAuthLoginApp(server); } diff --git a/src/lib/mcp/tools/connection-context.ts b/src/lib/mcp/tools/connection-context.ts index d14d1ef0..a8f3cee9 100644 --- a/src/lib/mcp/tools/connection-context.ts +++ b/src/lib/mcp/tools/connection-context.ts @@ -8,7 +8,7 @@ export function registerConnectionContextTool(server: McpServer) { "get_connection_context", { description: - "inspect the authenticated KERNEL principal, organization, credential and effective scope, and current effective policy before an operation. service-account principals may also include sanitized workload_identity provenance; no credential secrets or original identity-provider claims are returned. connection_scope.kind=organization may omit project for organization-wide reads and default-project creates, or pass a project name or id. connection_scope.kind=project is fixed to connection_scope.project_id.", + "inspect the authenticated KERNEL principal, organization, credential and effective scope, and current effective policy before an operation. service-account principals may also include sanitized workload_identity provenance; no credential secrets or original identity-provider claims are returned. connection_scope.kind=organization may omit project for organization-wide reads and default-project creates, or pass a project name or id. connection_scope.kind=project is fixed to connection_scope.project_id. when the person who connected chose what this connection may do, granted.permissions lists the allowed actions and granted.projects the only projects it may use (absent means every project); with one granted project, omit project to use it: KERNEL runs a request that names no project in that project.", inputSchema: z.object({}), annotations: { title: "get KERNEL connection context", @@ -23,8 +23,12 @@ export function registerConnectionContextTool(server: McpServer) { const { authContext, scope } = connectionContextFromAuthInfo( ctx.http.authInfo, ); + const { permissions, projects } = ctx.http.authInfo.extra ?? {}; return jsonResponse({ ...authContext, + ...((permissions !== undefined || projects !== undefined) && { + granted: { permissions, projects }, + }), connection_scope: { kind: scope.kind, organization_id: scope.organizationId, diff --git a/src/lib/native-oauth.ts b/src/lib/native-oauth.ts index a036318f..05a63945 100644 --- a/src/lib/native-oauth.ts +++ b/src/lib/native-oauth.ts @@ -27,7 +27,7 @@ const ACCESS_TOKEN_URN = "urn:ietf:params:oauth:token-type:access_token"; const JWKS_PATH = "/.well-known/jwks.json"; const EXCHANGE_TIMEOUT_MS = 5_000; const CACHE_READ_TIMEOUT_MS = 500; -const CACHE_KEY_INFO = "kernel-mcp native exchange cache v1"; +const CACHE_KEY_INFO = "kernel-mcp native exchange cache v2"; // An exchanged token is reused only while at least this much of its lifetime // remains, so every request gets a usable window and clock skew is covered. @@ -56,11 +56,13 @@ const exchangeSchema = z.object({ issued_token_type: z.literal(ACCESS_TOKEN_URN), expires_in: z.number().int().nonnegative(), scope: z.string().min(1), + projects: z.array(z.string()).optional(), }); const cachedExchangeSchema = z.object({ token: z.string().min(1).max(MAX_TOKEN_BYTES), expiresAt: z.number(), + projects: z.array(z.string()).optional(), }); export type NativeCredential = { @@ -69,6 +71,8 @@ export type NativeCredential = { subject: string; grantId: string; scopes: string[]; + // The projects the grant is limited to; absent when it covers every project. + projects?: string[]; // When the exchanged token stops being valid, in local time. expiresAt: number; }; @@ -400,7 +404,12 @@ async function exchange( const exchanged = exchangeSchema.safeParse(body); if (!exchanged.success) throw serverFault("native exchange response is not RFC 8693"); - const { access_token: derivedToken, expires_in, scope } = exchanged.data; + const { + access_token: derivedToken, + expires_in, + scope, + projects, + } = exchanged.data; const derived = await verifyExchangedToken(derivedToken, parent, config); if (derived.scope !== scope) throw serverFault("exchanged token lineage mismatch: scope"); @@ -418,6 +427,7 @@ async function exchange( subject: parent.sub, grantId: parent.grant_id, scopes: scope.split(" "), + projects, expiresAt, }; } @@ -454,6 +464,7 @@ function sealExchange( const plaintext = JSON.stringify({ token: credential.token, expiresAt: credential.expiresAt, + projects: credential.projects, }); const sealed = Buffer.concat([ iv, @@ -515,6 +526,7 @@ async function cachedExchange( subject: parent.sub, grantId: parent.grant_id, scopes: derived.scope.split(" "), + projects: cached.projects, expiresAt: Math.min(cached.expiresAt, derived.exp * 1000), }; } catch (error) { diff --git a/src/lib/oauth-discovery-route.test.ts b/src/lib/oauth-discovery-route.test.ts index d860c8d0..a601f0e0 100644 --- a/src/lib/oauth-discovery-route.test.ts +++ b/src/lib/oauth-discovery-route.test.ts @@ -31,7 +31,6 @@ describe("/.well-known/oauth-protected-resource/mcp", () => { authorization_endpoint: `${issuer}/authorize`, token_endpoint: `${issuer}/token`, registration_endpoint: `${issuer}/register`, - scopes_supported: ["openid"], resource_name: "KERNEL", resource_documentation: "https://www.kernel.sh/docs", }); diff --git a/src/lib/oauth-discovery.test.ts b/src/lib/oauth-discovery.test.ts index c0f374a0..d91c6a24 100644 --- a/src/lib/oauth-discovery.test.ts +++ b/src/lib/oauth-discovery.test.ts @@ -55,7 +55,6 @@ describe("OAuth protected-resource discovery", () => { authorization_endpoint: "https://auth.onkernel.com/authorize", token_endpoint: "https://auth.onkernel.com/token", registration_endpoint: "https://auth.onkernel.com/register", - scopes_supported: ["openid"], resource_name: "KERNEL", resource_documentation: "https://www.kernel.sh/docs", }); diff --git a/src/lib/oauth-discovery.ts b/src/lib/oauth-discovery.ts index 04a9b527..ca7144ac 100644 --- a/src/lib/oauth-discovery.ts +++ b/src/lib/oauth-discovery.ts @@ -62,7 +62,6 @@ export function oauthResourceMetadata( authorization_endpoint: `${authorizationServer}/authorize`, token_endpoint: `${authorizationServer}/token`, registration_endpoint: `${authorizationServer}/register`, - scopes_supported: ["openid"], resource_name: "KERNEL", resource_documentation: "https://www.kernel.sh/docs", };