From 38581b7d6533862fbe7814770917bc4a60e2484d Mon Sep 17 00:00:00 2001 From: Brendan Asselstine Date: Tue, 24 Nov 2026 06:34:18 -0700 Subject: [PATCH 1/2] Keep OAuth authorization within token scopes --- packages/api-client/src/schema.d.ts | 2 +- packages/api/src/api-contract.ts | 2 +- packages/api/src/oauth-connection-settings.ts | 13 +++++--- packages/api/src/protected-api.ts | 4 +-- .../event-match-repository.postgres.test.ts | 16 +++++---- .../test/oauth-connection-settings.test.ts | 33 +++++++++++++++++++ .../features/settings/client-permissions.tsx | 2 +- packages/docs/openapi.yaml | 2 +- 8 files changed, 57 insertions(+), 17 deletions(-) create mode 100644 packages/api/test/oauth-connection-settings.test.ts diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 3cefe494..61dbceb9 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -964,7 +964,7 @@ export interface paths { get?: never; /** * Set an OAuth connection’s effective scopes and integration access - * @description Interactive owner session required. Saving updates the connection immediately and can add scopes beyond the original OAuth request. + * @description Interactive owner session required. Removing permissions takes effect immediately. A scope not carried by the current token requires a fresh OAuth authorization and token. * * Requires the triggers:write scope. * diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 56162355..2d7314e2 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -549,7 +549,7 @@ export const API_ROUTES: RouteContract[] = [ ), route("PUT", "/api/v1/access/authorizations/{grantId}/permissions", "triggers:write", { summary: "Set an OAuth connection’s effective scopes and integration access", - description: "Interactive owner session required. Saving updates the connection immediately and can add scopes beyond the original OAuth request.", + description: "Interactive owner session required. Removing permissions takes effect immediately. A scope not carried by the current token requires a fresh OAuth authorization and token.", responses: {"200": {description: "Permissions saved", content: {"application/json": {schema: jsonSchema(okResult, "output")}}}}, }, (service, {params, body}) => service.updateClientPermissions(params.grantId, body), {ownerSession: true, body: clientPermissionsUpdate}), route("GET", "/api/v1/vms", "vms:read", { diff --git a/packages/api/src/oauth-connection-settings.ts b/packages/api/src/oauth-connection-settings.ts index dc4e7af2..85abbef9 100644 --- a/packages/api/src/oauth-connection-settings.ts +++ b/packages/api/src/oauth-connection-settings.ts @@ -3,15 +3,18 @@ import type { Env, OAuthProps } from "./types"; export type ConnectionScopePolicy = { disabled_scopes: string[]; scope_overrides: string[] | null }; -export function applyConnectionScopes(grantScopes: string[], policy?: ConnectionScopePolicy) { - return (policy?.scope_overrides ?? grantScopes).filter(scope => !policy?.disabled_scopes.includes(scope)); +export function applyConnectionScopes(credentialScopes: string[], policy?: ConnectionScopePolicy): string[] { + // Connection policy can narrow a credential but cannot confer scopes on it. + const allowed = policy?.scope_overrides == null ? null : new Set(policy.scope_overrides); + const disabled = new Set(policy?.disabled_scopes); + return credentialScopes.filter(scope => (allowed === null || allowed.has(scope)) && !disabled.has(scope)); } -export async function effectiveConnectionScopes(env: Env, auth: OAuthProps, grantScopes: string[] = auth.scopes): Promise { - if (auth.authMethod !== "oauth" || !auth.oauthGrantId) return grantScopes; +export async function effectiveConnectionScopes(env: Env, auth: OAuthProps, credentialScopes: string[]): Promise { + if (auth.authMethod !== "oauth" || !auth.oauthGrantId) return credentialScopes; const { rows } = await databaseFor(env).pool.query( "SELECT disabled_scopes,scope_overrides 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 applyConnectionScopes(grantScopes, rows[0]); + return applyConnectionScopes(credentialScopes, rows[0]); } diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 5ed3898c..e8601dd2 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -275,8 +275,8 @@ export class ProtectedApiHandler extends WorkerEntrypoint { const token = credential && this.env.OAUTH_PROVIDER ? await this.env.OAUTH_PROVIDER.unwrapToken(credential) : null; if (!token || token.userId !== auth.userId || !token.grant?.clientId) return Response.json({error:{code:"invalid_token",message:"Invalid OAuth authorization"}}, {status:401}); // Props describe original consent. The presented token may be narrowed. - const grantScopes = normalizeScopes(token.scope).filter(scope => normalizeScopes(auth.scopes).includes(scope)); - auth = {...auth, authMethod: "oauth", scopes: grantScopes, oauthGrantId: token.grantId, oauthClientId: token.grant.clientId, oauthExpiresAt: token.expiresAt}; + const tokenScopes = normalizeScopes(token.scope).filter(scope => normalizeScopes(auth.scopes).includes(scope)); + auth = {...auth, authMethod: "oauth", scopes: tokenScopes, oauthGrantId: token.grantId, oauthClientId: token.grant.clientId, oauthExpiresAt: token.expiresAt}; } return protectedApiFetch(request, this.env, auth, this.ctx); } diff --git a/packages/api/test/event-match-repository.postgres.test.ts b/packages/api/test/event-match-repository.postgres.test.ts index 1bdbadcf..294ba3a8 100644 --- a/packages/api/test/event-match-repository.postgres.test.ts +++ b/packages/api/test/event-match-repository.postgres.test.ts @@ -9,21 +9,25 @@ vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, const url = process.env.AUTH_TEST_DATABASE_URL; describe.skipIf(!url)("durable Event occurrences", () => { - it("lets owners add and remove standard and integration scopes for a connected client immediately", async () => { + it("applies connection permission edits within each OAuth credential’s scope limit", async () => { const f = await loadingFixture(url!); try { const grantId = "scope-grant"; const now = Math.floor(Date.now()/1000); - f.env.OAUTH_PROVIDER = { listUserGrants: async () => ({items:[{id:grantId,clientId:"test-client",metadata:{tenantId:f.tenantId},scope:["triggers:read"],createdAt:now,expiresAt:null}]}), lookupClient: async () => ({clientId:"test-client",clientName:"Test client"}) } as any; const integrationId = crypto.randomUUID(); await f.db.pool.query("INSERT INTO app.agent_integrations(tenant_id,id,kind,credential_id,name,available,policy,epoch) VALUES($1,$2,'bearer','test-secret','Test integration',true,'requestable',1)",[f.tenantId,integrationId]); const integrationScope = `integration:${integrationId}:1`; + const readOnly = ["triggers:read"]; + const readWrite = [...readOnly,"triggers:write","proxy:use",integrationScope]; + f.env.OAUTH_PROVIDER = { listUserGrants: async () => ({items:[{id:grantId,clientId:"test-client",metadata:{tenantId:f.tenantId},scope:readWrite,createdAt:now,expiresAt:null}]}), lookupClient: async () => ({clientId:"test-client",clientName:"Test client"}) } as any; const service = new ApiService(f.env,f.auth); - await service.updateClientPermissions(grantId,{scopes:["triggers:read","triggers:write","proxy:use",integrationScope],expectedRevision:0}); const auth = {...f.auth,authMethod:"oauth" as const,oauthGrantId:grantId}; - expect(await effectiveConnectionScopes(f.env,auth,["triggers:read"])).toEqual(["triggers:read","triggers:write","proxy:use",integrationScope]); - await service.updateClientPermissions(grantId,{scopes:["triggers:read"],expectedRevision:1}); - expect(await effectiveConnectionScopes(f.env,auth,["triggers:read","triggers:write","proxy:use",integrationScope])).toEqual(["triggers:read"]); + await service.updateClientPermissions(grantId,{scopes:readWrite,expectedRevision:0}); + expect(await effectiveConnectionScopes(f.env,auth,readOnly)).toEqual(readOnly); + expect(await effectiveConnectionScopes(f.env,auth,readWrite)).toEqual(readWrite); + await service.updateClientPermissions(grantId,{scopes:readOnly,expectedRevision:1}); + expect(await effectiveConnectionScopes(f.env,auth,readOnly)).toEqual(readOnly); + expect(await effectiveConnectionScopes(f.env,auth,readWrite)).toEqual(readOnly); } finally { await f.cleanup(); } }); it("deletes an Event with its Triggers, input sources, match state, and occurrence history", async () => { diff --git a/packages/api/test/oauth-connection-settings.test.ts b/packages/api/test/oauth-connection-settings.test.ts new file mode 100644 index 00000000..17e1804c --- /dev/null +++ b/packages/api/test/oauth-connection-settings.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; +import { applyConnectionScopes } from "../src/oauth-connection-settings"; + +describe("OAuth connection scope policy", () => { + it("retains separate scope limits for credentials under the same policy", () => { + const basic = ["fixture:read"]; + const extended = [...basic, "fixture:edit"]; + const expanded = { scope_overrides: extended, disabled_scopes: [] }; + expect(applyConnectionScopes(basic, expanded)).toEqual(basic); + expect(applyConnectionScopes(extended, expanded)).toEqual(extended); + + const restricted = { scope_overrides: basic, disabled_scopes: [] }; + expect(applyConnectionScopes(basic, restricted)).toEqual(basic); + expect(applyConnectionScopes(extended, restricted)).toEqual(basic); + }); + + it("honors explicit denials even when the override includes a scope", () => { + const scopes = ["fixture:read", "fixture:edit"]; + expect(applyConnectionScopes(scopes, { + scope_overrides: scopes, disabled_scopes: ["fixture:edit"], + })).toEqual(["fixture:read"]); + expect(applyConnectionScopes(scopes, { + scope_overrides: null, disabled_scopes: ["fixture:edit"], + })).toEqual(["fixture:read"]); + }); + + it("distinguishes an empty allowlist from no override", () => { + const scopes = ["fixture:read"]; + expect(applyConnectionScopes(scopes)).toEqual(scopes); + expect(applyConnectionScopes(scopes, { scope_overrides: [], disabled_scopes: [] })).toEqual([]); + expect(applyConnectionScopes([], { scope_overrides: scopes, disabled_scopes: [] })).toEqual([]); + }); +}); diff --git a/packages/app/src/features/settings/client-permissions.tsx b/packages/app/src/features/settings/client-permissions.tsx index 3200a761..c58b11e2 100644 --- a/packages/app/src/features/settings/client-permissions.tsx +++ b/packages/app/src/features/settings/client-permissions.tsx @@ -13,5 +13,5 @@ export function ClientPermissions({ client, close }: { client: AuthorizedClient; const { error } = await api.PUT("/api/v1/access/authorizations/{grantId}/permissions", { params: { path: { grantId: client.grantId } }, body: { scopes: allowed, expectedRevision: client.revision } }); if (error) throw new Error(messageOf(error)); }, onSuccess: close, onSettled: () => cache.invalidateQueries({ queryKey: clientsQuery.queryKey }) }); - return

Changes take effect as soon as you save.

Agent API scopes{client.availableScopes.map(scope => )}
{save.error &&

{save.error.message}

}
; + return

Removing permissions takes effect immediately. To use permissions its token does not already carry, the client must reconnect and authorize again.

Agent API scopes{client.availableScopes.map(scope => )}
{save.error &&

{save.error.message}

}
; } diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 5f7c916b..633e45cb 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -4304,7 +4304,7 @@ paths: put: summary: Set an OAuth connection’s effective scopes and integration access description: |- - Interactive owner session required. Saving updates the connection immediately and can add scopes beyond the original OAuth request. + Interactive owner session required. Removing permissions takes effect immediately. A scope not carried by the current token requires a fresh OAuth authorization and token. Requires the triggers:write scope. From c910dc44c6f53b0d2bf0c30744e7abfb3d76bf09 Mon Sep 17 00:00:00 2001 From: Brendan Asselstine Date: Tue, 24 Nov 2026 06:38:11 -0700 Subject: [PATCH 2/2] Cover reauthorization in the OAuth Worker fixture --- scripts/oauth-runtime.mjs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/scripts/oauth-runtime.mjs b/scripts/oauth-runtime.mjs index 7a3606b1..a229833d 100644 --- a/scripts/oauth-runtime.mjs +++ b/scripts/oauth-runtime.mjs @@ -189,8 +189,30 @@ export async function checkOAuth({ read: send, stream, db, tenantId, userId, coo assert.equal((await change(edit)).status, 409); const blocked = await rpc('tools/call', {name:'list_triggers',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'); + const reflect = async (credentials = bearer) => (await rpc('tools/call', {name:'get_api_reflection',arguments:{}}, 10, credentials)).result.structuredContent; + assert.equal((await reflect()).integrations.find(row => row.id === integrationId).access, 'requestable'); + + // Newly selected scopes are carried by a freshly authorized credential. + const freshVerifier = randomBytes(32).toString('base64url'); + const freshQuery = new URLSearchParams(authorizationQuery); + freshQuery.set('scope', [...edit.scopes, 'proxy:use'].join(' ')); + freshQuery.set('state', 'fixture-reauthorize'); + freshQuery.set('code_challenge', createHash('sha256').update(freshVerifier).digest('base64url')); + const freshPreview = await json('/api/v1/oauth/consent/preview', {authorizationQuery: freshQuery.toString()}, owner); + assert.equal(freshPreview.status, 200, freshPreview.text); + const freshConsent = await json('/api/v1/oauth/consent/decision', { + request: freshPreview.json.request, signature: freshPreview.json.signature, decision: 'allow', scopes: [...edit.scopes, 'proxy:use'], + }, owner); + assert.equal(freshConsent.status, 200, freshConsent.text); + const freshDestination = new URL(freshConsent.json.redirectTo); + assert.equal(freshDestination.searchParams.get('state'), 'fixture-reauthorize'); + const freshExchange = await form('/oauth/token', { + grant_type: 'authorization_code', client_id: clientId, code: freshDestination.searchParams.get('code'), + redirect_uri: redirectUri, code_verifier: freshVerifier, resource: origin+'/mcp', + }); + assert.equal(freshExchange.status, 200, freshExchange.text); + const freshBearer = { Authorization: 'Bearer '+freshExchange.json.access_token }; + assert.equal((await reflect(freshBearer)).integrations.find(row => row.id === integrationId).access, 'granted'); assert.equal((await change({scopes: originalScopes, expectedRevision: 1})).status, 200); assert.equal((await reflect()).integrations.find(row => row.id === integrationId).access, 'unavailable'); assert.deepEqual((await rpc('tools/call', {name:'list_triggers',arguments:{}}, 11)).result.structuredContent.items, []);