From d08e11f9723f5c502489018ca9949e0ba0e6a3d9 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Thu, 19 Nov 2026 23:21:25 +0000 Subject: [PATCH] Let MCP connections name themselves and owners edit their permissions --- packages/api-client/src/schema.d.ts | 72 +++++++++ .../0065_oauth_connection_settings.sql | 5 + packages/api/src/access-tokens.ts | 4 +- packages/api/src/agent-api.ts | 29 ++-- packages/api/src/api-contract.ts | 6 +- packages/api/src/consent-api.ts | 2 +- packages/api/src/flow-service.ts | 46 +++++- packages/api/src/oauth-connection-settings.ts | 11 ++ packages/api/src/postgres/schema.ts | 2 + packages/api/src/protected-api.ts | 15 +- packages/api/src/settings-contracts.ts | 10 +- packages/api/test/api-boundary.test.ts | 1 + .../test/report-run-error-boundary.test.ts | 1 + .../features/settings/authorized-clients.tsx | 6 +- .../features/settings/client-permissions.tsx | 50 +++++++ packages/app/test/settings.browser.test.mjs | 31 ++++ packages/docs/integrations/oauth.mdx | 4 +- packages/docs/llms-full.txt | 5 +- packages/docs/mcp/tools.mdx | 1 + packages/docs/openapi.yaml | 139 ++++++++++++++++++ scripts/agent-api-runtime.test.mjs | 10 ++ scripts/oauth-runtime.test.mjs | 25 ++++ 22 files changed, 443 insertions(+), 32 deletions(-) create mode 100644 packages/api/migrations/0065_oauth_connection_settings.sql create mode 100644 packages/api/src/oauth-connection-settings.ts create mode 100644 packages/app/src/features/settings/client-permissions.tsx diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index bf514e7c..b5114302 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1232,6 +1232,28 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/access/authorizations/{grantId}/permissions": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Edit an OAuth connection’s scopes and integration access + * @description Requires the jobs:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + put: operations["put_api_v1_access_authorizations_grantId_permissions"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/access/authorizations/{grantId}": { parameters: { query?: never; @@ -6067,6 +6089,12 @@ export interface operations { }; content: { "application/json": { + availableScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write" | "proxy:use" | "vm:grant")[]; + /** @description Integration ID to approved epoch-bound scope, or false to block. */ + integrationOverrides: { + [key: string]: string | false; + }; + revision: number; grantId: string; clientId: string; clientName: string; @@ -6199,6 +6227,50 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + put_api_v1_access_authorizations_grantId_permissions: { + parameters: { + query?: never; + header?: never; + path: { + grantId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + disabledScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write" | "proxy:use" | "vm:grant")[]; + /** @description Integration ID to approved epoch-bound scope, or false to block. */ + integrationOverrides: { + [key: string]: string | false; + }; + expectedRevision?: number; + }; + }; + }; + responses: { + /** @description Permissions saved */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ok: boolean; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; delete_api_v1_access_authorizations_grantId: { parameters: { query?: never; diff --git a/packages/api/migrations/0065_oauth_connection_settings.sql b/packages/api/migrations/0065_oauth_connection_settings.sql new file mode 100644 index 00000000..582941b5 --- /dev/null +++ b/packages/api/migrations/0065_oauth_connection_settings.sql @@ -0,0 +1,5 @@ +ALTER TABLE app.agent_identities + ADD COLUMN display_name text, + ADD COLUMN disabled_scopes text[] NOT NULL DEFAULT '{}', + ADD COLUMN integration_overrides jsonb NOT NULL DEFAULT '{}', + ADD COLUMN permissions_revision integer NOT NULL DEFAULT 0; diff --git a/packages/api/src/access-tokens.ts b/packages/api/src/access-tokens.ts index 5f6e2f8c..1f8bfb7e 100644 --- a/packages/api/src/access-tokens.ts +++ b/packages/api/src/access-tokens.ts @@ -4,7 +4,7 @@ import { databaseFor } from "./postgres/database"; import { AccessTokenRepository } from "./postgres/access-token-repository"; export const ACCESS_SCOPES = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:start", "runs:cancel", "runs:write", "integrations:read", "integrations:write", "skills:read", "skills:write"] as const; -export const AGENT_SCOPES: readonly string[] = [...ACCESS_SCOPES, "proxy:use", "vm:grant"]; +export const AGENT_SCOPES = [...ACCESS_SCOPES, "proxy:use", "vm:grant"] as const; export type AccessScope = typeof ACCESS_SCOPES[number]; export type LegacyScope = "flows:read" | "flows:write"; @@ -15,7 +15,7 @@ export function normalizeScopes(scopes: readonly string[]): string[] { if (scope === "flows:read") ["projects:read", "jobs:read", "integrations:read"].forEach(value => result.add(value)); else if (scope === "flows:write") ["projects:write", "jobs:write", "integrations:write"].forEach(value => result.add(value)); else if (scope === "runs:write") ["runs:read", "runs:invoke", "runs:cancel", "runs:write"].forEach(value => result.add(value)); - else if (AGENT_SCOPES.includes(scope) || isIntegrationScope(scope)) result.add(scope); + else if ((AGENT_SCOPES as readonly string[]).includes(scope) || isIntegrationScope(scope)) result.add(scope); } return [...result]; } diff --git a/packages/api/src/agent-api.ts b/packages/api/src/agent-api.ts index 01bbd559..32785d85 100644 --- a/packages/api/src/agent-api.ts +++ b/packages/api/src/agent-api.ts @@ -14,6 +14,12 @@ export class AgentApiError extends Error { } export type AgentIntegration = {id: string; kind: "bearer" | "model" | "github" | "linear" | "fly" | "exe" | "amp" | "clickup" | "x"; credential_id: string; name: string; description: string | null; available: boolean; policy: "baseline" | "requestable" | "disabled"; epoch: number; revision: number}; export const requiredIntegrationScope = (row: AgentIntegration) => `integration:${row.id}:${row.epoch}`; +type ConnectionPolicy = { integration_overrides: Record; disabled_scopes: string[] }; +function connectionAccess(row: AgentIntegration, scopes: string[], policy: ConnectionPolicy) { + const scope = requiredIntegrationScope(row); + if (policy.disabled_scopes.includes("proxy:use") || policy.integration_overrides[row.id] === false || row.policy === "disabled" || !row.available) return "blocked"; + return row.policy === "baseline" || policy.integration_overrides[row.id] === scope || scopes.includes(scope) ? "granted" : "requestable"; +} const STORAGE_BLOCK_BYTES = 1024 * 1024; const forbidden = () => new AgentApiError(403, "forbidden", "This integration is not authorized."); const invalidIdentity = () => new AgentApiError(401, "invalid_token", "The agent authorization is no longer active."); @@ -71,24 +77,23 @@ export class AgentApiService { config = row.execution_config; } else if (auth.authMethod === "vm_grant" && auth.vmGrantId) { kind = "vm"; subject = auth.vmGrantId; - const grant = (await this.database.pool.query(`SELECT g.permissions, g.parent_scopes FROM app.vm_grants g + const grant = (await this.database.pool.query(`SELECT g.permissions, g.parent_scopes, parent.integration_overrides, parent.disabled_scopes, to_jsonb(provider) AS provider FROM app.vm_grants g JOIN app.agent_identities parent ON parent.tenant_id=g.tenant_id AND parent.id=g.parent_id JOIN app.agent_integrations provider ON provider.tenant_id=g.tenant_id AND provider.id=g.provider_id WHERE g.tenant_id=$1 AND g.id=$2 AND parent.user_id=$3 AND parent.session_version=$4 AND parent.revoked_at IS NULL AND g.issuer IS NOT NULL AND g.revoked_at IS NULL AND g.expires_at>now() - AND provider.available AND provider.epoch=g.provider_epoch AND (provider.policy='baseline' OR - (provider.policy='requestable' AND g.parent_scopes @> to_jsonb(ARRAY['integration:' || provider.id::text || ':' || provider.epoch::text])))`, + AND provider.available AND provider.epoch=g.provider_epoch`, [auth.tenantId, subject, auth.userId, auth.sessionVersion])).rows[0]; - if (!grant) throw invalidIdentity(); + if (!grant || grant.disabled_scopes.includes("vm:grant") || connectionAccess(grant.provider, grant.parent_scopes, grant as ConnectionPolicy) !== "granted") throw invalidIdentity(); config = grant; } else if (auth.authMethod === "oauth" && auth.oauthGrantId && auth.oauthClientId && auth.oauthExpiresAt && auth.oauthExpiresAt > Date.now()/1000) { kind = "oauth"; subject = auth.oauthGrantId; } else throw invalidIdentity(); - const row = (await this.database.pool.query<{id: string; user_id: string; session_version: number; revoked_at: Date | null}>(`INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version) + const row = (await this.database.pool.query(`INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version) VALUES($1,$2,$3,$4,$5) ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET subject=excluded.subject - RETURNING id,user_id,session_version,revoked_at`, [auth.tenantId, kind, subject, auth.userId, auth.sessionVersion])).rows[0]!; + RETURNING id,user_id,session_version,revoked_at,integration_overrides,disabled_scopes`, [auth.tenantId, kind, subject, auth.userId, auth.sessionVersion])).rows[0]!; if (row.revoked_at || row.user_id !== auth.userId || row.session_version !== auth.sessionVersion) throw invalidIdentity(); - return {id: row.id, kind, config}; + return {id: row.id, kind, config, policy: row}; } private selected(row: AgentIntegration, config: Record) { switch(row.kind) { @@ -107,15 +112,15 @@ export class AgentApiService { if (!row) throw forbidden(); if (identity.kind === "vm") { const grant = identity.config!; - if (grant.permissions[row.id] !== row.epoch || !row.available || row.policy === "disabled" - || (row.policy !== "baseline" && !grant.parent_scopes.includes(requiredIntegrationScope(row)))) throw forbidden(); + if (grant.permissions[row.id] !== row.epoch || connectionAccess(row, grant.parent_scopes, grant as ConnectionPolicy) !== "granted") throw forbidden(); } else if (identity.kind === "run") { if (!this.selected(row, identity.config!)) throw forbidden(); const revoked = await this.database.pool.query("SELECT 1 FROM app.run_credential_revocations WHERE tenant_id=$1 AND run_id=$2 AND kind=$3 AND credential_id=$4", [this.auth.tenantId, this.auth.runId, row.kind, row.credential_id]); if (revoked.rowCount || !row.available) throw forbidden(); } else { - if (row.policy === "disabled" || !row.available) throw forbidden(); - if (row.policy !== "baseline" && !this.auth.scopes.includes(requiredIntegrationScope(row))) throw new AgentApiError(403, "insufficient_scope", "Approve this integration before making the request.", requiredIntegrationScope(row)); + const access = connectionAccess(row, this.auth.scopes, identity.policy); + if (access === "blocked") throw forbidden(); + if (access === "requestable") throw new AgentApiError(403, "insufficient_scope", "Approve this integration before making the request.", requiredIntegrationScope(row)); } return {identity, integration: row}; } @@ -132,7 +137,7 @@ export class AgentApiService { } result.push({...publicIntegration(row), access, ...(row.kind === "exe" && identity.kind === "oauth" && access === "granted" ? {vmGrantProvider: "exe.dev" as const} : {}), instructions: row.kind === "x" ? "Use the HTTP request endpoint with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use the HTTP request endpoint with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use the HTTP request endpoint with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use the HTTP request endpoint with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use the HTTP request endpoint with a path relative to /api/v2." : row.kind === "fly" ? "Use the HTTP request endpoint with a Fly Machines API path, such as /v1/apps." : row.kind === "model" ? "Use the HTTP request endpoint with an OpenAI-compatible path relative to /v1." : "Use the HTTP request endpoint with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions."}); } - return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(this.auth.scopes), proxy: { + return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(this.auth.scopes).filter(scope => !identity.policy.disabled_scopes.includes(scope)), proxy: { requestUrl: this.env.APP_ORIGIN + "/api/v1/agent/requests", readResponseUrl: this.env.APP_ORIGIN + "/api/v1/agent/responses/read", authentication: identity.kind === "run" ? "Use your run identity helper." : "POST JSON with integration, method, and path. Use the agent OAuth credential with proxy:use. With the Factorize device launcher, curl -H @\"$FACTORIZE_AGENT_AUTH_FILE\" reads the authorization header.", diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index c4796791..06f6a7d7 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -5,7 +5,7 @@ import { queryOf } from "./query-params"; import { launchPayloadResponse } from "./launch-payload"; import { searchResponse } from "./search-contracts"; import { consentPreviewInput, consentPreviewResponse, consentDecisionInput, consentDecisionResponse } from "./consent-api"; -import { exeConnection, integrationStatus, authorizedClient, accessToken, createdAccessToken, savedExe, testedExe, savedAmp, savedTail, okResult } from "./settings-contracts"; +import { exeConnection, integrationStatus, clientPermissionsInput, authorizedClient, accessToken, createdAccessToken, savedExe, testedExe, savedAmp, savedTail, okResult } from "./settings-contracts"; import { triggerAvailabilityResponse, namedOption, providerOptions, githubInstallation, githubRepository, tailIntegration } from "./editor-contracts"; import { runSummaryResponse, runPageResponse, runStatusResponse, fullRunResponse, revisionTracePage, revisionTraceQuery, runtimeContextResponse, runtimeIntegrationsResponse } from "./run-read-contracts"; import { jobPageQuery, jobSummaryPage, jobSelectorPage, jobResponse, jobUpdateInput } from "./job-contracts"; @@ -675,6 +675,10 @@ export const API_ROUTES: RouteContract[] = [ (service, { params }) => service.revokeAccessToken(params.tokenId), { ownerSession: true }, ), + route("PUT", "/api/v1/access/authorizations/{grantId}/permissions", "jobs:write", { + summary: "Edit an OAuth connection’s scopes and integration access", + responses: {"200": {description: "Permissions saved", content: {"application/json": {schema: jsonSchema(okResult, "output")}}}}, + }, (service, {params, body}) => service.updateClientPermissions(params.grantId, body), {ownerSession: true, body: clientPermissionsInput}), route("DELETE", "/api/v1/access/authorizations/{grantId}", "jobs:write", {summary:"Revoke one isolated OAuth connection", description:"Other connections, including copies of the same client, retain their approvals.",responses:{"200":{description:"Authorization revoked",content:{"application/json":{schema:jsonSchema(z.object({revoked:z.number().int()}),"output")}}}}}, (service,{params})=>service.revokeOAuthAuthorization(params.grantId), {ownerSession:true}), route( "DELETE", diff --git a/packages/api/src/consent-api.ts b/packages/api/src/consent-api.ts index e9401dcb..b1cee8f2 100644 --- a/packages/api/src/consent-api.ts +++ b/packages/api/src/consent-api.ts @@ -54,7 +54,7 @@ export async function consentDecision(env: Env, session: Session, input: z.infer const legacyRequest = parsed.scope.some(scope => scope === "flows:read" || scope === "flows:write"); const selected = normalizeScopes(input.scopes); const issuedScopes = legacyRequest ? input.scopes : selected; - if (input.scopes.some(scope => !allowed.has(scope) && !allowed.has(normalizeScopes([scope])[0] ?? "") ) || selected.some(scope => !AGENT_SCOPES.includes(scope) && !isIntegrationScope(scope))) return null; + if (input.scopes.some(scope => !allowed.has(scope) && !allowed.has(normalizeScopes([scope])[0] ?? "") ) || selected.some(scope => !(AGENT_SCOPES as readonly string[]).includes(scope) && !isIntegrationScope(scope))) return null; return databaseFor(env).transaction(async transaction => { const preview = await transaction.query("UPDATE app.oauth_consent_previews SET used_at=now() WHERE id=$1 AND used_at IS NULL AND expires_at>clock_timestamp() RETURNING id", [envelope.nonce]); if (!preview.rows.length) return null; diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 794df3f8..ce1e35a8 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -12,7 +12,7 @@ import { apiPolicyInput, integrationRef, requestApiInput, readApiResponseInput } import { DEFAULT_RUN_SCOPES } from "./run-scopes"; import { launchPayloadResponse } from "./launch-payload"; import { searchResponse } from "./search-contracts"; -import { integrationStatus, exeConnection, accessToken, createdAccessToken, authorizedClient } from "./settings-contracts"; +import { integrationStatus, exeConnection, accessToken, createdAccessToken, clientPermissionsInput, clientNameInput, authorizedClient } from "./settings-contracts"; import { namedOption, providerOptions, githubRepository, githubInstallation, tailIntegration } from "./editor-contracts"; import { z } from "zod"; import { runPageResponse, fullRunResponse, runtimeContextResponse, runtimeIntegrationsResponse } from "./run-read-contracts"; @@ -377,7 +377,7 @@ export class ApiService { async previewJobPrompt(input: unknown) { await this.authorize("skills:read"); const parsed = previewSkillInput.parse(input); const repository = this.skills(); const skills = await Promise.all(parsed.skillIds.map(async id => { const skill = await repository.get(id); if (!skill) throw new ServiceError(400, "invalid_request", "A selected skill is unavailable."); return skill; })); return { prompt: composePrompt(skills.map(skill => ({ body: skill.body ?? "" })), parsed.jobContext), skills: skills.map(skill => ({ id: skill.id, key: skill.key, revision: skill.revision })) }; } private async authorize(scope: Scope): Promise { - if (!normalizeScopes(this.auth.scopes).includes(scope)) throw new ServiceError(403, "insufficient_scope", `The ${scope} scope is required.`); + if (!(this.auth.oauthGrantId ? this.auth.scopes : normalizeScopes(this.auth.scopes)).includes(scope)) throw new ServiceError(403, "insufficient_scope", `The ${scope} scope is required.`); await this.authorizeIdentity(); } private async authorizeIdentity(): Promise { @@ -440,7 +440,7 @@ export class ApiService { async getRuntimeContext() { await this.authorizeIdentity(); - return publicValue(runtimeContextResponse, { kind: "factorize-runtime-context-v1", authMethod: this.auth.authMethod ?? "oauth", runId: this.auth.runId ?? null, jobId: this.auth.runJobId ?? null, scopes: normalizeScopes(this.auth.scopes) }); + return publicValue(runtimeContextResponse, { kind: "factorize-runtime-context-v1", authMethod: this.auth.authMethod ?? "oauth", runId: this.auth.runId ?? null, jobId: this.auth.runJobId ?? null, scopes: this.auth.oauthGrantId ? this.auth.scopes : normalizeScopes(this.auth.scopes) }); } async getRuntimeLaunchPayload() { @@ -1432,6 +1432,36 @@ export class ApiService { async githubIssueOptions(installationId: number, repositoryId: number) { await this.authorize("integrations:read"); return publicValue(providerOptions, await this.providers().githubIssueOptions(installationId, repositoryId)); } async removeGitHubInstallation(id: number) { await this.authorize("integrations:write"); if (!await new GitHubRepository(databaseFor(this.env), this.auth.tenantId).delete(id)) throw new ServiceError(404, "not_found", "Installation not found"); return { id, deleted: true }; } + async renameMcpClient(input: unknown) { + const { name } = clientNameInput.parse(input); + if (this.auth.authMethod !== "oauth") throw new ServiceError(403, "forbidden", "An OAuth connection is required."); + const identity = await this.agentApi().identity(); + await databaseFor(this.env).pool.query("UPDATE app.agent_identities SET display_name=$3 WHERE tenant_id=$1 AND id=$2", [this.auth.tenantId, identity.id, name]); + return { name }; + } + async updateClientPermissions(grantId: string, input: unknown) { + await this.authorizeOwnerSession("jobs:write"); + const edit = clientPermissionsInput.parse(input); + const client = (await this.listAuthorizedClients()).find(client => client.grantId === grantId); + if (!client) throw new ServiceError(404, "not_found", "Authorization not found."); + if (edit.disabledScopes.some(scope => !client.availableScopes.includes(scope))) throw new ServiceError(400, "invalid_request", "Scope is outside this authorization."); + const { integrations } = await listAgentPolicies(this.env, this.auth.tenantId); + const current = new Map(integrations.map(row => [row.id, row])); + if (Object.entries(edit.integrationOverrides).some(([id, approval]) => { + const row = current.get(id); + return !row || (approval !== false && (!row.available || row.policy === "disabled" || approval !== row.requiredScope)); + })) throw new ServiceError(409, "conflict", "Integration availability changed. Reload permissions."); + const result = await databaseFor(this.env).pool.query(` + INSERT INTO app.agent_identities AS i(tenant_id,kind,subject,user_id,session_version,disabled_scopes,integration_overrides,permissions_revision) + SELECT $1,'oauth',$2,$3,$4,$5,$6,1 WHERE coalesce($7::integer,0)=0 OR EXISTS + (SELECT 1 FROM app.agent_identities WHERE tenant_id=$1 AND kind='oauth' AND subject=$2) + ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET disabled_scopes=excluded.disabled_scopes, + integration_overrides=excluded.integration_overrides, permissions_revision=i.permissions_revision+1 + WHERE i.revoked_at IS NULL AND i.user_id=excluded.user_id AND ($7 IS NULL OR i.permissions_revision=$7) + RETURNING permissions_revision`, [this.auth.tenantId, grantId, this.auth.userId, this.auth.sessionVersion, edit.disabledScopes, JSON.stringify(edit.integrationOverrides), edit.expectedRevision]); + if (!result.rowCount) throw new ServiceError(409, "conflict", "Connection permissions changed. Reload permissions."); + return { ok: true }; + } async listAuthorizedClients() { await this.authorizeOwnerSession("jobs:read"); if (!this.env.OAUTH_PROVIDER) throw new ServiceError(503, "operation_failed", "OAuth management unavailable"); @@ -1439,7 +1469,15 @@ export class ApiService { do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId, { limit: 100, cursor }); grants.push(...page.items.filter(grant => (grant.metadata as any)?.tenantId === this.auth.tenantId && (!grant.expiresAt || grant.expiresAt > Math.floor(Date.now() / 1000)))); cursor = page.cursor; } while (cursor); const clients = await Promise.all([...new Set(grants.map(grant => grant.clientId))].map(async clientId => [clientId, await this.env.OAUTH_PROVIDER!.lookupClient(clientId)] as const)); const byId = new Map(clients); - return publicValue(z.array(authorizedClient), grants.map(grant => ({ grantId: grant.id, clientId: grant.clientId, clientName: byId.get(grant.clientId)?.clientName ?? grant.clientId, scopes: normalizeScopes(grant.scope), authorizationDate: new Date(grant.createdAt * 1000).toISOString(), expiresAt: grant.expiresAt ? new Date(grant.expiresAt * 1000).toISOString() : null, lastUsedAt: null }))); + const settings = await databaseFor(this.env).pool.query("SELECT subject,display_name,disabled_scopes,integration_overrides,permissions_revision FROM app.agent_identities WHERE tenant_id=$1 AND user_id=$2 AND kind='oauth' AND subject=ANY($3)", [this.auth.tenantId, this.auth.userId, grants.map(g => g.id)]); + const byGrant = new Map(settings.rows.map(row => [row.subject, row])); + return publicValue(z.array(authorizedClient), grants.map(grant => { + const row = byGrant.get(grant.id), availableScopes = normalizeScopes(grant.scope); + return { grantId: grant.id, clientId: grant.clientId, clientName: row?.display_name ?? byId.get(grant.clientId)?.clientName ?? grant.clientId, + availableScopes: availableScopes.filter(scope => !scope.startsWith("integration:")), scopes: availableScopes.filter(scope => !row?.disabled_scopes.includes(scope)), revision: row?.permissions_revision ?? 0, + integrationOverrides: row?.integration_overrides ?? {}, authorizationDate: new Date(grant.createdAt * 1000).toISOString(), + expiresAt: grant.expiresAt ? new Date(grant.expiresAt * 1000).toISOString() : null, lastUsedAt: null }; + })); } async revokeOAuthAuthorization(grantId: string) { await this.authorizeOwnerSession("jobs:write"); diff --git a/packages/api/src/oauth-connection-settings.ts b/packages/api/src/oauth-connection-settings.ts new file mode 100644 index 00000000..34c7cf63 --- /dev/null +++ b/packages/api/src/oauth-connection-settings.ts @@ -0,0 +1,11 @@ +import { databaseFor } from "./postgres/database"; +import type { Env, OAuthProps } from "./types"; + +export async function disabledConnectionScopes(env: Env, auth: OAuthProps): Promise { + if (auth.authMethod !== "oauth" || !auth.oauthGrantId) return []; + const { rows } = await databaseFor(env).pool.query<{ disabled_scopes: string[] }>( + "SELECT disabled_scopes FROM app.agent_identities WHERE tenant_id=$1 AND kind='oauth' AND subject=$2 AND user_id=$3", + [auth.tenantId, auth.oauthGrantId, auth.userId], + ); + return rows[0]?.disabled_scopes ?? []; +} diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index c10c01b3..ee90679a 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -74,6 +74,8 @@ export const agentIntegrations = app.table("agent_integrations", { policy:text("policy").$type<"baseline"|"requestable"|"disabled">().notNull().default("requestable"),epoch:integer("epoch").notNull().default(1),revision:integer("revision").notNull().default(1), },t=>[primaryKey({columns:[t.tenantId,t.id]}),unique().on(t.tenantId,t.kind,t.credentialId)]); export const agentIdentities = app.table("agent_identities", { + displayName: text("display_name"), disabledScopes: text("disabled_scopes").array().notNull().default([]), + integrationOverrides: jsonb("integration_overrides").notNull().default({}), permissionsRevision: integer("permissions_revision").notNull().default(0), tenantId:uuid("tenant_id").notNull().references(()=>tenants.id,{onDelete:"cascade"}),id:uuid("id").notNull().defaultRandom(),kind:text("kind").$type<"oauth"|"run"|"vm">().notNull(),subject:text("subject").notNull(),userId:uuid("user_id").notNull(),sessionVersion:integer("session_version").notNull(),revokedAt:timestamp("revoked_at",{withTimezone:true}),createdAt:createdAt(), },t=>[primaryKey({columns:[t.tenantId,t.id]}),unique().on(t.tenantId,t.kind,t.subject)]); export const vmGrants = app.table("vm_grants", { diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index bf41b336..1655126a 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -1,3 +1,5 @@ +import { disabledConnectionScopes } from "./oauth-connection-settings"; +import { clientNameInput } from "./settings-contracts"; import { SkillContentError } from "./skill-files"; import { listenForOutcomes, outcomeRunId } from "./run-outcome-subscription"; import { authenticateVendorRunRequest } from "./vendor-run-auth"; @@ -65,6 +67,11 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP }; try { const url = new URL(request.url), path = url.pathname; + if (auth?.oauthGrantId) { + const disabled = await disabledConnectionScopes(env, auth); + auth = { ...auth, scopes: auth.scopes.filter(scope => !disabled.includes(scope)) }; + if (path.startsWith("/api/v1/agent/") && !auth.scopes.includes("proxy:use")) throw new ServiceError(403, "insufficient_scope", "The proxy:use scope is required."); + } if (path === "/mcp") { if (!auth) throw new ServiceError(401, "invalid_token", "Unauthorized"); const mcpService = new ApiService(env, auth); @@ -77,11 +84,12 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP try { body = await new Response(limited).json(); } catch(error) { if(error instanceof ServiceError) throw error; throw new ServiceError(400,"invalid_request","Request body must be valid JSON."); } mcpBodies.set(request,body); if (body?.method === "subscriptions/listen" && body.params?.notifications?.resourceSubscriptions) { + const listenerAuth = auth; const credentialActive = async () => { - if (auth.authMethod === "vendor_identity") return !!await authenticateVendorRunRequest(request,env); - if (auth.oauthGrantId) { + if (listenerAuth.authMethod === "vendor_identity") return !!await authenticateVendorRunRequest(request,env); + if (listenerAuth.oauthGrantId) { const token = await env.OAUTH_PROVIDER?.unwrapToken(request.headers.get("Authorization")?.slice(7) ?? ""); - return token?.grantId === auth.oauthGrantId && token.expiresAt > Date.now()/1000 && normalizeScopes(token.scope).includes("runs:read"); + return token?.grantId === listenerAuth.oauthGrantId && token.expiresAt > Date.now()/1000 && normalizeScopes(token.scope).includes("runs:read") && !(await disabledConnectionScopes(env, listenerAuth)).includes("runs:read"); } return true; // outcomeStates rechecks API key and owner membership. }; @@ -143,6 +151,7 @@ function createMcpServer(service: ApiService, subscriptions = true): McpServer { try { return structured(await action(input)); } catch (error) { const response = errorResponse(error), detail = await response.json() as any; throw new Error(`${detail.error?.code ?? "operation_failed"}: ${detail.error?.message ?? "Operation failed"}`); } }); + tool("rename_mcp_client", "Set the display name of this OAuth connection in Authorized clients.", clientNameInput, input => service.renameMcpClient(input)); tool("get_api_reflection", "Discover this agent identity, effective Factorize scopes, and granted/requestable integration APIs. Availability describes connection state, not verified credential health.", z.object({}), () => service.getApiReflection()); tool("grant_vm", "Delegate selected proxy integrations to a VM on a supported provider connection.", grantVmInput, (input) => service.grantVm(input)); tool("revoke_vm_grant", "Revoke proxy access for an externally managed VM.", revokeVmInput, ({grantId}: any) => service.revokeVmGrant(grantId)); diff --git a/packages/api/src/settings-contracts.ts b/packages/api/src/settings-contracts.ts index 5afb73fc..4557fedb 100644 --- a/packages/api/src/settings-contracts.ts +++ b/packages/api/src/settings-contracts.ts @@ -1,11 +1,17 @@ import { z } from "zod"; -import { ACCESS_SCOPES } from "./access-tokens"; +import { AGENT_SCOPES, ACCESS_SCOPES } from "./access-tokens"; import { tailIntegration } from "./editor-contracts"; const timestamp = z.string(); export const exeConnection = z.object({ connectionId: z.string(), credentialStatus: z.literal("connected"), accountTags: z.array(z.string()).default([]), tags: z.array(z.string()).optional(), agentKind: z.enum(["codex", "claude", "pi"]).optional(), models: z.array(z.string()).default([]), efforts: z.array(z.string()).default([]) }); export const ampConnection = z.object({ connectionId: z.string(), project: z.string(), apiBaseUrl: z.string().optional() }); export const integrationStatus = z.object({ linear: z.object({ organizationName: z.string().nullable(), viewerEmail: z.string().nullable() }).nullable(), clickup: z.object({ teamName: z.string().nullable() }).nullable(), exe: exeConnection.nullable(), exeConnections: z.array(exeConnection), ampConnections: z.array(ampConnection), cloudflareTail: z.object({ count: z.number().int(), installations: z.array(tailIntegration) }) }); -export const authorizedClient = z.object({ grantId: z.string(), clientId: z.string(), clientName: z.string(), scopes: z.array(z.string()), authorizationDate: timestamp, expiresAt: timestamp.nullable(), lastUsedAt: timestamp.nullable() }); +export const clientNameInput = z.object({ name: z.string().trim().min(1).max(120) }).strict(); +export const clientPermissionsInput = z.object({ + disabledScopes: z.array(z.enum(AGENT_SCOPES)).max(AGENT_SCOPES.length), + integrationOverrides: z.record(z.uuid(), z.union([z.string(), z.literal(false)])).describe("Integration ID to approved epoch-bound scope, or false to block."), + expectedRevision: z.number().int().nonnegative().optional(), +}).strict(); +export const authorizedClient = z.object({ availableScopes: z.array(z.enum(AGENT_SCOPES)), integrationOverrides: clientPermissionsInput.shape.integrationOverrides, revision: z.number().int(), grantId: z.string(), clientId: z.string(), clientName: z.string(), scopes: z.array(z.string()), authorizationDate: timestamp, expiresAt: timestamp.nullable(), lastUsedAt: timestamp.nullable() }); export const accessToken = z.object({ id: z.string(), name: z.string(), scopes: z.array(z.enum(ACCESS_SCOPES)), created_at: timestamp, expires_at: timestamp, last_used_at: timestamp.nullable().optional(), revoked_at: timestamp.nullable().optional() }); export const createdAccessToken = accessToken.extend({ token: z.string() }); export const okResult = z.object({ ok: z.boolean() }); diff --git a/packages/api/test/api-boundary.test.ts b/packages/api/test/api-boundary.test.ts index 01beb9a4..54c8251e 100644 --- a/packages/api/test/api-boundary.test.ts +++ b/packages/api/test/api-boundary.test.ts @@ -8,6 +8,7 @@ import { ApiService, ServiceError } from "../src/flow-service"; import { InvocationError } from "../src/job-domain"; import type { Env, OAuthProps } from "../src/types"; +vi.mock("../src/oauth-connection-settings", () => ({ disabledConnectionScopes: async () => [] })); vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class { constructor( diff --git a/packages/api/test/report-run-error-boundary.test.ts b/packages/api/test/report-run-error-boundary.test.ts index 6bf78f55..c191fcb6 100644 --- a/packages/api/test/report-run-error-boundary.test.ts +++ b/packages/api/test/report-run-error-boundary.test.ts @@ -4,6 +4,7 @@ import { ProtectedApiHandler, protectedApiFetch } from "../src/protected-api"; import { RunRepository } from "../src/postgres/run-repository"; vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class { constructor(public ctx: any, public env: any) {} } })); +vi.mock("../src/oauth-connection-settings", () => ({disabledConnectionScopes: async () => []})); afterEach(() => vi.restoreAllMocks()); const runId = "00000000-0000-4000-8000-000000000001"; diff --git a/packages/app/src/features/settings/authorized-clients.tsx b/packages/app/src/features/settings/authorized-clients.tsx index 8cb9ff9b..034bdee6 100644 --- a/packages/app/src/features/settings/authorized-clients.tsx +++ b/packages/app/src/features/settings/authorized-clients.tsx @@ -1,3 +1,5 @@ +import { useState } from "react"; +import { ClientPermissions, type AuthorizedClient } from "./client-permissions"; import { Button, Page } from "../../shared/ui"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; @@ -6,8 +8,10 @@ import { SettingsLayout } from "./navigation"; import { messageOf } from "../auth/session"; export function AuthorizedClients() { const cache = useQueryClient(), clients = useQuery(clientsQuery); + const [editing, setEditing] = useState(null); const revoke = useMutation({ retry: false, mutationFn: async (grantId: string) => { const { error } = await api.DELETE("/api/v1/access/authorizations/{grantId}", { params: { path: { grantId } } }); if (error) throw new Error(messageOf(error)); }, onSuccess: () => cache.invalidateQueries({ queryKey: clientsQuery.queryKey }) }); return {clients.isPending &&

Loading clients…

}{clients.error &&

{clients.error.message}

}{revoke.error &&

{revoke.error.message}

}{clients.data?.length === 0 &&

No authorized clients.

} -
    {clients.data?.map(client =>
  • {client.clientName}

    {client.scopes.join(", ")} · Authorized {client.authorizationDate} · Expires {client.expiresAt ?? "No expiry"}

  • )}
+
    {clients.data?.map(client =>
  • {client.clientName}

    {client.scopes.join(", ")} · Authorized {client.authorizationDate} · Expires {client.expiresAt ?? "No expiry"}

    {client.availableScopes && }
  • )}
+ {editing && setEditing(null)} />}
; } diff --git a/packages/app/src/features/settings/client-permissions.tsx b/packages/app/src/features/settings/client-permissions.tsx new file mode 100644 index 00000000..404bd7c0 --- /dev/null +++ b/packages/app/src/features/settings/client-permissions.tsx @@ -0,0 +1,50 @@ +import { useState } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { api, type paths } from "factorize-api-client"; +import { Dialog } from "../../shared/dialog"; +import { Button, Input, Label, Select } from "../../shared/ui"; +import { messageOf } from "../auth/session"; +import { clientsQuery } from "./queries"; + +export type AuthorizedClient = paths["/api/v1/access/authorized-clients"]["get"]["responses"][200]["content"]["application/json"][number]; + +export function ClientPermissions({client, close}: {client: AuthorizedClient; close: () => void}) { + const cache = useQueryClient(); + const [disabled, setDisabled] = useState(() => client.availableScopes.filter(scope => !client.scopes.includes(scope))); + const [overrides, setOverrides] = useState(client.integrationOverrides); + const policies = useQuery({queryKey: ["settings", "api-policies"], queryFn: async ({signal}) => { + const {data, error} = await api.GET("/api/v1/integration-api-policies", {signal}); + if (!data || error) throw new Error(messageOf(error)); + return data; + }}); + const integrations = policies.data?.integrations.filter(row => row.available && row.policy !== "disabled"); + const save = useMutation({retry: false, mutationFn: async () => { + const integrationOverrides = Object.fromEntries((policies.data?.integrations ?? []).flatMap(row => { + const approval = overrides[row.id]; + return (row.available && row.policy !== "disabled" && approval === row.requiredScope) || approval === false ? [[row.id, approval] as const] : []; + })); + const {error} = await api.PUT("/api/v1/access/authorizations/{grantId}/permissions", { + params: {path: {grantId: client.grantId}}, body: {disabledScopes: disabled, integrationOverrides, expectedRevision: client.revision}, + }); + if (error) throw new Error(messageOf(error)); + }, onSuccess: close, onSettled: () => cache.invalidateQueries({queryKey: clientsQuery.queryKey})}); + return +
OAuth scopes + {client.availableScopes.map(scope => )} + {client.availableScopes.length === 0 &&

No Factorize scopes authorized.

} +
+
Integration access + {policies.isPending &&

Loading integrations…

} + {policies.error &&

{policies.error.message}

} + {integrations?.length === 0 &&

No integrations available.

} + {integrations?.map(row => )} +
+ {save.error &&

{save.error.message}

} + +
; +} diff --git a/packages/app/test/settings.browser.test.mjs b/packages/app/test/settings.browser.test.mjs index 649b1162..c5453780 100644 --- a/packages/app/test/settings.browser.test.mjs +++ b/packages/app/test/settings.browser.test.mjs @@ -265,3 +265,34 @@ test("dashboard VM presets use dialogs for creation, editing, and deletion", asy await page.getByText("No VM presets yet.").waitFor(); } finally { await context.close(); } }); + +test("owner edits one MCP connection’s scopes and integration access", async () => { + const {context, page} = await setup(); + const id = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", requiredScope = `integration:${id}:3`; + const client = {grantId:"first", clientId:"shared", clientName:"Release assistant", availableScopes:["jobs:read", "jobs:write"], scopes:["jobs:read", "jobs:write"], integrationOverrides:{}, revision:0, authorizationDate:"2026-11-19", expiresAt:null, lastUsedAt:null}; + await page.route("**/api/v1/access/authorized-clients", route => route.fulfill({json:[client]})); + await page.route("**/api/v1/integration-api-policies", route => route.fulfill({json:{integrations:[{id, requiredScope, available:true, policy:"requestable", name:"Linear"}]}})); + let saved; + await page.route("**/api/v1/access/authorizations/first/permissions", route => { + saved = route.request().postDataJSON(); + client.scopes = ["jobs:read"]; + client.integrationOverrides = saved.integrationOverrides; + client.revision++; + return route.fulfill({json:{ok:true}}); + }); + try { + await page.goto(origin + "/settings/authorized-clients"); + const edit = page.getByRole("button", {name:"Edit permissions"}); + await edit.click(); + const dialog = page.getByRole("dialog", {name:"Permissions for Release assistant"}); + await dialog.getByLabel("jobs:write").uncheck(); + await dialog.getByLabel("Linear").selectOption("allow"); + await dialog.getByRole("button", {name:"Save permissions"}).click(); + await dialog.waitFor({state:"hidden"}); + assert.deepEqual(saved, {disabledScopes:["jobs:write"], integrationOverrides:{[id]:requiredScope}, expectedRevision:0}); + await page.reload(); + await edit.click(); + assert.equal(await dialog.getByLabel("jobs:write").isChecked(), false); + assert.equal(await dialog.getByLabel("Linear").inputValue(), "allow"); + } finally { await context.close(); } +}); diff --git a/packages/docs/integrations/oauth.mdx b/packages/docs/integrations/oauth.mdx index ff49d26b..9b1f375d 100644 --- a/packages/docs/integrations/oauth.mdx +++ b/packages/docs/integrations/oauth.mdx @@ -96,9 +96,7 @@ every read. Revocation blocks subsequent calls and reads but cannot undo an upstream action already accepted. Existing VM proxy URLs retain true streaming. The same operations are documented under `/api/v1/agent/reflection`, -`/api/v1/agent/requests`, and `/api/v1/agent/responses/read`. Authorize `proxy:use` to use the HTTP proxy with the agent credential. Existing MCP authorizations without this scope require renewed consent. Other REST operations retain their own authentication requirements. Clients migrating from `request_api` and `read_api_response` send the same JSON arguments to the reflected HTTP endpoints with the Factorize bearer token. Owner policy endpoints require an interactive browser session. Authorized -clients settings revoke individual connections; the existing client-wide revoke -endpoint remains available for compatibility. +`/api/v1/agent/requests`, and `/api/v1/agent/responses/read`. Authorize `proxy:use` to use the HTTP proxy with the agent credential. Existing MCP authorizations without this scope require renewed consent. Other REST operations retain their own authentication requirements. Clients migrating from `request_api` and `read_api_response` send the same JSON arguments to the reflected HTTP endpoints with the Factorize bearer token. Owner policy endpoints require an interactive browser session. In **Settings → Authorized clients**, choose **Edit permissions** to disable or restore originally authorized Factorize scopes. For each integration, choose **Default** to follow workspace policy and OAuth consent, **Allow** to approve the current integration, or **Block** to deny this connection access. Disabling or disconnecting a workspace integration invalidates per-connection approvals. Edits apply to subsequent requests from this connection and its delegated VMs. Owners can also revoke a connection. MCP clients can set their own connection label with `rename_mcp_client`. The scheduler maintenance heartbeat removes expired response objects and their PostgreSQL receipts. A receipt exists before any R2 block is written, including diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index c5bad6df..c8fc8868 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -448,9 +448,7 @@ every read. Revocation blocks subsequent calls and reads but cannot undo an upstream action already accepted. Existing VM proxy URLs retain true streaming. The same operations are documented under `/api/v1/agent/reflection`, -`/api/v1/agent/requests`, and `/api/v1/agent/responses/read`. Authorize `proxy:use` to use the HTTP proxy with the agent credential. Existing MCP authorizations without this scope require renewed consent. Other REST operations retain their own authentication requirements. Clients migrating from `request_api` and `read_api_response` send the same JSON arguments to the reflected HTTP endpoints with the Factorize bearer token. Owner policy endpoints require an interactive browser session. Authorized -clients settings revoke individual connections; the existing client-wide revoke -endpoint remains available for compatibility. +`/api/v1/agent/requests`, and `/api/v1/agent/responses/read`. Authorize `proxy:use` to use the HTTP proxy with the agent credential. Existing MCP authorizations without this scope require renewed consent. Other REST operations retain their own authentication requirements. Clients migrating from `request_api` and `read_api_response` send the same JSON arguments to the reflected HTTP endpoints with the Factorize bearer token. Owner policy endpoints require an interactive browser session. In **Settings → Authorized clients**, choose **Edit permissions** to disable or restore originally authorized Factorize scopes. For each integration, choose **Default** to follow workspace policy and OAuth consent, **Allow** to approve the current integration, or **Block** to deny this connection access. Disabling or disconnecting a workspace integration invalidates per-connection approvals. Edits apply to subsequent requests from this connection and its delegated VMs. Owners can also revoke a connection. MCP clients can set their own connection label with `rename_mcp_client`. The scheduler maintenance heartbeat removes expired response objects and their PostgreSQL receipts. A receipt exists before any R2 block is written, including @@ -621,6 +619,7 @@ The required scope inventory below is authoritative. Legacy `flows:*` and `runs: | `report_run_error` | runs:write | Required `runId` and `reason`; records an error without stopping execution | | `start_run` | runs:start | Literal `prompt`, optional `skill`, `inputs`, `projectId`, `name` and `idempotencyKey`. Returns `runId`, the browser `url`, `outcomeUri`, and `duplicate`. | | `invoke_job` | runs:invoke | Required string `jobId`; optional `name`, `prompt`, `data`, `idempotencyKey` | +| `rename_mcp_client` | Authenticated OAuth connection | `{ "name": "Release assistant" }`. Sets this connection’s display name in Settings → Authorized clients. Names are trimmed and accept 1–120 characters. | | `get_api_reflection` | Authenticated OAuth/run identity | `{}`. Discover the authorization identity, effective scopes, and granted/requestable integration APIs, including instructions, required OAuth scope, and connection availability. | | `grant_vm` | vm:grant and proxy:use | OAuth agent delegates explicit integration IDs to a VM on an eligible exe.dev connection. Requires providerIntegrationId, vm, integrationIds and idempotencyKey. | | `revoke_vm_grant` | vm:grant | Requires grantId. Invalidates guest access and schedules identity integration cleanup. | diff --git a/packages/docs/mcp/tools.mdx b/packages/docs/mcp/tools.mdx index 2334d75d..47545027 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -35,6 +35,7 @@ The required scope inventory below is authoritative. Legacy `flows:*` and `runs: | `report_run_error` | runs:write | Required `runId` and `reason`; records an error without stopping execution | | `start_run` | runs:start | Literal `prompt`, optional `skill`, `inputs`, `projectId`, `name` and `idempotencyKey`. Returns `runId`, the browser `url`, `outcomeUri`, and `duplicate`. | | `invoke_job` | runs:invoke | Required string `jobId`; optional `name`, `prompt`, `data`, `idempotencyKey` | +| `rename_mcp_client` | Authenticated OAuth connection | `{ "name": "Release assistant" }`. Sets this connection’s display name in Settings → Authorized clients. Names are trimmed and accept 1–120 characters. | | `get_api_reflection` | Authenticated OAuth/run identity | `{}`. Discover the authorization identity, effective scopes, and granted/requestable integration APIs, including instructions, required OAuth scope, and connection availability. | | `grant_vm` | vm:grant and proxy:use | OAuth agent delegates explicit integration IDs to a VM on an eligible exe.dev connection. Requires providerIntegrationId, vm, integrationIds and idempotencyKey. | | `revoke_vm_grant` | vm:grant | Requires grantId. Invalidates guest access and schedules identity integration cleanup. | diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 24cd9c89..30d714fc 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -7213,6 +7213,42 @@ paths: items: type: object properties: + availableScopes: + type: array + items: + type: string + enum: + - projects:read + - projects:write + - jobs:read + - jobs:write + - runs:read + - runs:invoke + - runs:start + - runs:cancel + - runs:write + - integrations:read + - integrations:write + - skills:read + - skills:write + - proxy:use + - vm:grant + integrationOverrides: + type: object + propertyNames: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + additionalProperties: + anyOf: + - type: string + - type: boolean + const: false + description: Integration ID to approved epoch-bound scope, or false to block. + revision: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 grantId: type: string clientId: @@ -7234,6 +7270,9 @@ paths: - string - "null" required: + - availableScopes + - integrationOverrides + - revision - grantId - clientId - clientName @@ -7524,6 +7563,106 @@ paths: schema: type: string minLength: 1 + /api/v1/access/authorizations/{grantId}/permissions: + put: + summary: Edit an OAuth connection’s scopes and integration access + responses: + "200": + description: Permissions saved + content: + application/json: + schema: + type: object + properties: + ok: + type: boolean + required: + - ok + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the jobs:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: put_api_v1_access_authorizations_grantId_permissions + tags: + - access + security: + - cookieAuth: [] + x-required-scope: jobs:write + x-owner-session-required: true + parameters: + - name: grantId + in: path + required: true + schema: + type: string + minLength: 1 + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + disabledScopes: + maxItems: 15 + type: array + items: + type: string + enum: + - projects:read + - projects:write + - jobs:read + - jobs:write + - runs:read + - runs:invoke + - runs:start + - runs:cancel + - runs:write + - integrations:read + - integrations:write + - skills:read + - skills:write + - proxy:use + - vm:grant + integrationOverrides: + type: object + propertyNames: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + additionalProperties: + anyOf: + - type: string + - type: boolean + const: false + description: Integration ID to approved epoch-bound scope, or false to block. + expectedRevision: + type: integer + minimum: 0 + maximum: 9007199254740991 + required: + - disabledScopes + - integrationOverrides + additionalProperties: false /api/v1/access/authorizations/{grantId}: delete: summary: Revoke one isolated OAuth connection diff --git a/scripts/agent-api-runtime.test.mjs b/scripts/agent-api-runtime.test.mjs index 815dc69e..68b237b9 100644 --- a/scripts/agent-api-runtime.test.mjs +++ b/scripts/agent-api-runtime.test.mjs @@ -173,6 +173,16 @@ test('agent API OAuth, policy, connection isolation, run identity and response l const request=(token,integration,path='/',extra={})=>proxy(token,'/api/v1/agent/requests',{integration:integration.id,method:'GET',path,...extra}); const scopes=row=>'integration:'+row.id+':'+row.epoch; const first=await authorize(['jobs:read']),second=await authorize(['jobs:read']); + await rpc(first, 'rename_mcp_client', {name:'Release assistant'}); + const clients = await json('/api/v1/access/authorized-clients','GET',undefined,owner); + const siblingConnections = clients.body.filter(client => client.clientId === clientId); + assert.deepEqual(siblingConnections.map(client => client.clientName).sort(), ['Agent fixture','Release assistant']); + const renamed = siblingConnections.find(client => client.clientName === 'Release assistant'); + const permissionPath = '/api/v1/access/authorizations/' + renamed.grantId + '/permissions'; + assert.equal((await json(permissionPath, 'PUT', {disabledScopes:[], integrationOverrides:{[baseline.id]:false}}, owner)).status, 200); + assert.equal((await request(first, baseline)).status, 403); + assert.equal((await request(second, baseline)).status, 200); + assert.equal((await json(permissionPath, 'PUT', {disabledScopes:[], integrationOverrides:{}}, owner)).status, 200); const reflect=await rpc(first,'get_api_reflection');assert.equal(reflect.status,200,reflect.text);assert.equal(reflect.result.integrations.find(row=>row.id===baseline.id).access,'granted');assert.equal(reflect.result.integrations.find(row=>row.id===requestable.id).access,'requestable'); // A new local agent obtains a single device authorization. Its HTTP client // reads the private header file; MCP and shell credentials are never copied. diff --git a/scripts/oauth-runtime.test.mjs b/scripts/oauth-runtime.test.mjs index 093d8201..816713ca 100644 --- a/scripts/oauth-runtime.test.mjs +++ b/scripts/oauth-runtime.test.mjs @@ -83,6 +83,31 @@ test('local OAuth consent and device grants authorize REST/MCP and respect revoc assert.ok((await rpc('tools/list', {}, 2)).result.tools.some(tool => tool.name === 'list_jobs')); assert.deepEqual((await rpc('tools/call', { name: 'list_jobs', arguments: {} }, 3)).result.structuredContent.items, []); assert.deepEqual((await rpc('tools/call', { name: 'list_jobs', arguments: {} }, 5, restBearer)).result.structuredContent.items, []); + const rename = name => rpc('tools/call', {name: 'rename_mcp_client', arguments: {name}}, 8); + const invalidName = await rename(' '); + assert.ok(invalidName.result?.isError || invalidName.error); + assert.equal((await rename(' Release assistant ')).result.structuredContent.name, 'Release assistant'); + const clients = await send('/api/v1/access/authorized-clients', 'GET', undefined, owner); + const connection = clients.json.find(client => client.clientId === clientId); + assert.equal(connection.clientName, 'Release assistant'); + const integrationId = randomUUID(); + await db.query("INSERT INTO app.agent_integrations(tenant_id,id,kind,credential_id,name,available) VALUES ($1,$2,'linear','linear','Linear',true)", [tenantId,integrationId]); + const permissionsPath = '/api/v1/access/authorizations/' + connection.grantId + '/permissions'; + const change = (edit, headers = owner) => send(permissionsPath, 'PUT', JSON.stringify(edit), {...headers, 'Content-Type':'application/json'}); + const integrationKey = 'integration:' + integrationId + ':1'; + const edit = {disabledScopes:['jobs:read'], integrationOverrides:{[integrationId]:integrationKey}, expectedRevision:0}; + assert.equal((await change(edit, restBearer)).status, 403); + assert.equal((await change({...edit,disabledScopes:['jobs:write']})).status, 400); + const saved = await change(edit); + assert.equal(saved.status, 200, saved.text); + assert.equal((await change(edit)).status, 409); + const blocked = await rpc('tools/call', {name:'list_jobs',arguments:{}}, 9); + assert.ok(blocked.error || blocked.result?.isError); + const reflect = async () => (await rpc('tools/call', {name:'get_api_reflection',arguments:{}}, 10)).result.structuredContent; + assert.equal((await reflect()).integrations.find(row => row.id === integrationId).access, 'granted'); + assert.equal((await change({disabledScopes:[],integrationOverrides:{[integrationId]:false},expectedRevision:1})).status, 200); + assert.equal((await reflect()).integrations.find(row => row.id === integrationId).access, 'unavailable'); + assert.deepEqual((await rpc('tools/call', {name:'list_jobs',arguments:{}}, 11)).result.structuredContent.items, []); const deviceClient = await json('/oauth/register', { client_name: 'Device fixture', token_endpoint_auth_method: 'none', grant_types: ['urn:ietf:params:oauth:grant-type:device_code','refresh_token'] }); assert.equal(deviceClient.status, 201, deviceClient.text); const device = await form('/oauth/device_authorization', { client_id: deviceClient.json.client_id, scope: 'flows:read', resource: origin+'/mcp' }); assert.equal(device.status, 200, device.text); const poll = { grant_type: 'urn:ietf:params:oauth:grant-type:device_code', client_id: deviceClient.json.client_id, device_code: device.json.device_code };