Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", {
Expand Down
13 changes: 8 additions & 5 deletions packages/api/src/oauth-connection-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string[]> {
if (auth.authMethod !== "oauth" || !auth.oauthGrantId) return grantScopes;
export async function effectiveConnectionScopes(env: Env, auth: OAuthProps, credentialScopes: string[]): Promise<string[]> {
if (auth.authMethod !== "oauth" || !auth.oauthGrantId) return credentialScopes;
const { rows } = await databaseFor(env).pool.query<ConnectionScopePolicy>(
"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]);
}
4 changes: 2 additions & 2 deletions packages/api/src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,8 +275,8 @@ export class ProtectedApiHandler extends WorkerEntrypoint<Env, OAuthProps> {
const token = credential && this.env.OAUTH_PROVIDER ? await this.env.OAUTH_PROVIDER.unwrapToken<OAuthProps>(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);
}
Expand Down
16 changes: 10 additions & 6 deletions packages/api/test/event-match-repository.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
33 changes: 33 additions & 0 deletions packages/api/test/oauth-connection-settings.test.ts
Original file line number Diff line number Diff line change
@@ -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([]);
});
});
2 changes: 1 addition & 1 deletion packages/app/src/features/settings/client-permissions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <Dialog title={`Permissions for ${client.clientName}`} close={close}><p className="mb-3 text-sm">Changes take effect as soon as you save.</p><fieldset className="grid gap-2"><legend>Agent API scopes</legend>{client.availableScopes.map(scope => <Label key={scope}><Input type="checkbox" checked={allowed.includes(scope)} onChange={event => setAllowed(event.target.checked ? [...allowed, scope] : allowed.filter(value => value !== scope))} />{client.scopeLabels[scope] ?? scope}</Label>)}</fieldset>{save.error && <p role="alert">{save.error.message}</p>}<Button variant="primary" disabled={save.isPending} onClick={() => save.mutate()}>Save permissions</Button></Dialog>;
return <Dialog title={`Permissions for ${client.clientName}`} close={close}><p className="mb-3 text-sm">Removing permissions takes effect immediately. To use permissions its token does not already carry, the client must reconnect and authorize again.</p><fieldset className="grid gap-2"><legend>Agent API scopes</legend>{client.availableScopes.map(scope => <Label key={scope}><Input type="checkbox" checked={allowed.includes(scope)} onChange={event => setAllowed(event.target.checked ? [...allowed, scope] : allowed.filter(value => value !== scope))} />{client.scopeLabels[scope] ?? scope}</Label>)}</fieldset>{save.error && <p role="alert">{save.error.message}</p>}<Button variant="primary" disabled={save.isPending} onClick={() => save.mutate()}>Save permissions</Button></Dialog>;
}
2 changes: 1 addition & 1 deletion packages/docs/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
26 changes: 24 additions & 2 deletions scripts/oauth-runtime.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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, []);
Expand Down
Loading