diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 61dbceb9..9465e47f 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -4484,7 +4484,7 @@ export interface operations { /** @description Complete owner-selected effective scope set for this connection. */ scopes?: string[]; disabledScopes?: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "integrations:read" | "integrations:write" | "vms:read" | "vms:edit" | "proxy:use" | "apps:manage")[]; - /** @description Integration ID to approved epoch-bound scope, or false to block. */ + /** @description Integration ID to approved epoch-bound scope, or false to block. Explicit approval is required to re-enable a blocked integration, including when scopes are supplied. */ integrationOverrides?: { [key: string]: string | false; }; diff --git a/packages/api/src/api-service.ts b/packages/api/src/api-service.ts index d34b8fde..f3f19523 100644 --- a/packages/api/src/api-service.ts +++ b/packages/api/src/api-service.ts @@ -20,7 +20,7 @@ import { AgentApiService, listAgentPolicies } from "./agent-api"; import {ProxyPayloads,createPayloadInput,appendPayloadInput,finalizePayloadInput,attachmentInput} from "./proxy-payloads"; import {ProxyOperations,operationRef,operationRead} from "./proxy-operations"; import {queryApiResponseInput} from "./agent-api-contracts"; -import { apiPolicyInput, integrationRef, requestApiInput, readApiResponseInput } from "./agent-api-contracts"; +import { apiPolicyInput, integrationRef, integrationScopePattern, requestApiInput, readApiResponseInput } from "./agent-api-contracts"; import { integrationStatus, exeConnection, accessToken, createdAccessToken, clientPermissionsUpdate, clientNameInput, authorizedClient } from "./settings-contracts"; import { namedOption, providerOptions, githubRepository, githubInstallation, tailIntegration } from "./editor-contracts"; import { z } from "zod"; @@ -600,22 +600,25 @@ export class ApiService { const client = (await this.listAuthorizedClients()).find(client => client.grantId === grantId); if (!client) throw new ServiceError(404, "not_found", "Authorization not found."); const { integrations } = await listAgentPolicies(this.env, this.auth.tenantId); - let scopes = edit.scopes; - if (!scopes) { - scopes = client.scopes.filter(scope => !edit.disabledScopes?.includes(scope as any)); - for (const [id, approval] of Object.entries(edit.integrationOverrides ?? {})) { - const integration = integrations.find(row => row.id === id); - if (!integration || (approval !== false && approval !== integration.requiredScope)) throw new ServiceError(409,"conflict","Integration availability changed. Reload permissions."); - scopes = approval === false ? scopes.filter(scope => scope !== integration.requiredScope) : [...scopes,integration.requiredScope]; - } + let scopes = edit.scopes ?? client.scopes.filter(scope => !edit.disabledScopes?.includes(scope as any)); + for (const [id, approval] of Object.entries(edit.integrationOverrides ?? {})) { + const integration = integrations.find(row => row.id === id); + if (!integration || (approval !== false && approval !== integration.requiredScope)) throw new ServiceError(409,"conflict","Integration availability changed. Reload permissions."); + scopes = approval === false ? scopes.filter(scope => scope.match(integrationScopePattern)?.[1] !== id) : [...scopes, approval]; } + // A previously denied integration needs an explicit approval for its current epoch. + // A full scope snapshot alone might come from an older or stale permissions editor. + scopes = scopes.filter(scope => { + const id = scope.match(integrationScopePattern)?.[1]; + return !id || client.integrationOverrides[id] !== false || edit.integrationOverrides?.[id] === scope; + }); if (scopes.some(scope => !client.availableScopes.includes(scope) && !client.scopes.includes(scope))) throw new ServiceError(400, "invalid_request", "Scope is outside this authorization."); const currentScopes = new Set(integrations.filter(row => row.available && row.policy !== "disabled").map(row => row.requiredScope)); if (scopes.some(scope => scope.startsWith("integration:") && !currentScopes.has(scope) && !client.scopes.includes(scope))) throw new ServiceError(409, "conflict", "Integration availability changed. Reload permissions."); const integrationOverrides = { ...client.integrationOverrides }; for (const integration of integrations) { if (scopes.includes(integration.requiredScope)) delete integrationOverrides[integration.id]; - else if (integration.available && integration.policy !== "disabled") integrationOverrides[integration.id] = false; + else if (edit.integrationOverrides?.[integration.id] === false || (integration.available && integration.policy !== "disabled")) integrationOverrides[integration.id] = false; } 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,scope_overrides,integration_overrides,permissions_revision) @@ -643,8 +646,11 @@ export class ApiService { return publicValue(z.array(authorizedClient), grants.map(grant => { const row = byGrant.get(grant.id), grantedScopes = normalizeScopes(grant.scope); const baseScopes = row?.scope_overrides ?? grantedScopes.filter(scope => !row?.disabled_scopes.includes(scope)); - const baselineScopes = integrations.filter(integration => integration.policy === "baseline" && integration.available && row?.integration_overrides?.[integration.id] !== false).map(integration => integration.requiredScope); - const scopes = [...new Set([...baseScopes,...baselineScopes])].filter(scope => !row?.disabled_scopes.includes(scope)); + const baselineScopes = integrations.filter(integration => integration.policy === "baseline" && integration.available).map(integration => integration.requiredScope); + const scopes = [...new Set([...baseScopes,...baselineScopes])].filter(scope => { + const id = scope.match(integrationScopePattern)?.[1]; + return !row?.disabled_scopes.includes(scope) && (!id || row?.integration_overrides?.[id] !== false); + }); const availableScopes = [...new Set([...globallyAvailable, ...scopes])]; return { grantId: grant.id, clientId: grant.clientId, clientName: row?.display_name ?? byId.get(grant.clientId)?.clientName ?? grant.clientId, appName: byId.get(grant.clientId)?.clientName ?? grant.clientId, availableScopes, scopeLabels, scopes, revision: row?.permissions_revision ?? 0, diff --git a/packages/api/src/settings-contracts.ts b/packages/api/src/settings-contracts.ts index 95f202b1..d3b2ad1b 100644 --- a/packages/api/src/settings-contracts.ts +++ b/packages/api/src/settings-contracts.ts @@ -10,7 +10,7 @@ export const clientPermissionsInput = z.object({ scopes: z.array(z.string()).max(100).optional().describe("Complete owner-selected effective scope set for this connection."), // Accept the previous restriction-only payload during client upgrades. disabledScopes: z.array(z.enum(AGENT_SCOPES)).max(AGENT_SCOPES.length).optional(), - integrationOverrides: z.record(z.uuid(), z.union([z.string(), z.literal(false)])).optional().describe("Integration ID to approved epoch-bound scope, or false to block."), + integrationOverrides: z.record(z.uuid(), z.union([z.string(), z.literal(false)])).optional().describe("Integration ID to approved epoch-bound scope, or false to block. Explicit approval is required to re-enable a blocked integration, including when scopes are supplied."), expectedRevision: z.number().int().nonnegative().optional(), }).strict().refine(value => value.scopes !== undefined || value.disabledScopes !== undefined || value.integrationOverrides !== undefined, "Supply a scope selection."); export const clientPermissionsUpdate = clientPermissionsInput; diff --git a/packages/api/test/connection-permissions.postgres.test.ts b/packages/api/test/connection-permissions.postgres.test.ts new file mode 100644 index 00000000..ea652d3b --- /dev/null +++ b/packages/api/test/connection-permissions.postgres.test.ts @@ -0,0 +1,67 @@ +import { expect, it, vi } from "vitest"; +import { protectedApiFetch } from "../src/protected-api"; +import { loadingFixture } from "./helpers/loading-fixture"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); + +const url = process.env.AUTH_TEST_DATABASE_URL; + +it.skipIf(!url)("preserves blocked integrations through a connection permission edit until explicitly re-enabled", async () => { + const f = await loadingFixture(url!); + try { + const [linear, github] = [crypto.randomUUID(), crypto.randomUUID()]; + const [linearScope, githubScope] = [`integration:${linear}:1`, `integration:${github}:1`]; + const blocked = { [linear]: false, [github]: false }; + const grantId = "fixture-grant"; + const readScopes = ["team:read", "proxy:use"]; + Object.assign(f.env, { OAUTH_PROVIDER: { + listUserGrants: async () => ({ items: [{ + id: grantId, clientId: "fixture-client", metadata: { tenantId: f.tenantId }, + scope: [...readScopes, linearScope, githubScope], createdAt: Math.floor(Date.now() / 1000), + }] }), + lookupClient: async () => ({ clientName: "Fixture client" }), + } }); + await f.db.pool.query(`INSERT INTO app.agent_integrations(tenant_id,id,kind,credential_id,name,available,policy) + VALUES ($1,$2,'linear','linear','Linear',true,'baseline'), ($1,$3,'github','123','GitHub',true,'requestable')`, [f.tenantId, linear, github]); + await f.db.pool.query(`INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version,integration_overrides,permissions_revision) + VALUES ($1,'oauth',$2,$3,$4,$5,1)`, [f.tenantId, grantId, f.userId, f.auth.sessionVersion, JSON.stringify(blocked)]); + + const fetch = (path: string, method: string, body?: object) => protectedApiFetch(new Request(f.env.APP_ORIGIN + path, { + method, headers: { Cookie: f.cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, + body: body === undefined ? undefined : JSON.stringify(body), + }), f.env, f.auth, {} as ExecutionContext); + const read = async () => { + const response = await fetch("/api/v1/access/authorized-clients", "GET"); + expect(response.status, await response.clone().text()).toBe(200); + const [client] = await response.json() as { scopes: string[]; availableScopes: string[]; revision: number; integrationOverrides: Record }[]; + return client; + }; + const save = async (body: object) => { + const response = await fetch(`/api/v1/access/authorizations/${grantId}/permissions`, "PUT", body); + expect(response.status, await response.text()).toBe(200); + }; + + const initial = await read(); + expect(initial).toMatchObject({ scopes: readScopes, revision: 1, integrationOverrides: blocked }); + expect(initial.availableScopes).toEqual(expect.arrayContaining([linearScope, githubScope])); + await save({ scopes: initial.scopes, expectedRevision: initial.revision }); + const saved = await read(); + expect(saved).toMatchObject({ scopes: readScopes, revision: 2, integrationOverrides: blocked }); + + const updatedScopes = [...saved.scopes, "team:write"]; + await save({ scopes: updatedScopes, expectedRevision: saved.revision }); + const edited = await read(); + expect(edited).toMatchObject({ scopes: updatedScopes, revision: 3, integrationOverrides: blocked }); + + await save({ + scopes: [...edited.scopes, linearScope], expectedRevision: edited.revision, + integrationOverrides: { [linear]: linearScope }, + }); + const reenabled = await read(); + expect(reenabled).toMatchObject({ scopes: [...updatedScopes, linearScope], revision: 4 }); + expect(reenabled.integrationOverrides).toEqual({ [github]: false }); + } finally { + await f.cleanup(); + } +}); diff --git a/packages/app/src/features/settings/client-permissions.tsx b/packages/app/src/features/settings/client-permissions.tsx index c58b11e2..673dc9c6 100644 --- a/packages/app/src/features/settings/client-permissions.tsx +++ b/packages/app/src/features/settings/client-permissions.tsx @@ -6,11 +6,22 @@ import { Button, Input, Label } 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 }) { +export function ClientPermissions({ client: initialClient, close }: { client: AuthorizedClient; close: () => void }) { const cache = useQueryClient(); - const [allowed, setAllowed] = useState(() => client.availableScopes.filter(scope => client.scopes.includes(scope))); + // Keep the edited scope selection and its revision tied to the same snapshot. + const [client] = useState(() => initialClient); + const deniedIntegrationId = (scope: string) => { + const [kind, id] = scope.split(":"); + return kind === "integration" && client.integrationOverrides[id] === false ? id : undefined; + }; + const [allowed, setAllowed] = useState(() => client.availableScopes.filter(scope => client.scopes.includes(scope) && !deniedIntegrationId(scope))); const save = useMutation({ retry: false, mutationFn: async () => { - const { error } = await api.PUT("/api/v1/access/authorizations/{grantId}/permissions", { params: { path: { grantId: client.grantId } }, body: { scopes: allowed, expectedRevision: client.revision } }); + const integrationOverrides: Record = {}; + for (const scope of allowed) { + const id = deniedIntegrationId(scope); + if (id) integrationOverrides[id] = scope; + } + const { error } = await api.PUT("/api/v1/access/authorizations/{grantId}/permissions", { params: { path: { grantId: client.grantId } }, body: { scopes: allowed, expectedRevision: client.revision, ...(Object.keys(integrationOverrides).length && { integrationOverrides }) } }); if (error) throw new Error(messageOf(error)); }, onSuccess: close, onSettled: () => cache.invalidateQueries({ queryKey: clientsQuery.queryKey }) }); 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/app/test/functional/client-permissions.spec.mjs b/packages/app/test/functional/client-permissions.spec.mjs new file mode 100644 index 00000000..b328a1a0 --- /dev/null +++ b/packages/app/test/functional/client-permissions.spec.mjs @@ -0,0 +1,60 @@ +import { expect } from "@playwright/test"; +import { test } from "./fixtures.mjs"; + +test("saving client permissions keeps a blocked integration unchecked until explicitly selected", async ({ page, origin }) => { + const integrationId = "18a2410e-ea09-4fe0-af8a-719c0c91e6e2"; + const integrationScope = `integration:${integrationId}:1`; + const initialScopes = ["team:read", "proxy:use"]; + const editedScopes = ["team:read", "team:write", "proxy:use"]; + let revision = 1; + let scopes = initialScopes; + let denied = true; + const edits = []; + await page.route("**/api/v1/session", route => route.fulfill({ json: { + authenticated: true, user: { id: "owner", email: "owner@example.test" }, + team: { id: "workspace", name: "Workspace", role: "owner" }, capabilities: [], + } })); + await page.route("**/api/v1/access/authorized-clients", route => route.fulfill({ json: [{ + grantId: "fixture-grant", clientId: "fixture-client", clientName: "Fixture client", + availableScopes: [...editedScopes, integrationScope], scopes, revision, + scopeLabels: { [integrationScope]: "Linear integration access" }, + integrationOverrides: denied ? { [integrationId]: false } : {}, + authorizationDate: "2026-10-09T12:00:00Z", expiresAt: null, lastUsedAt: null, + }] })); + await page.route("**/api/v1/access/authorizations/fixture-grant/permissions", route => { + const edit = route.request().postDataJSON(); + edits.push(edit); + revision++; + scopes = edit.scopes; + if (edit.integrationOverrides?.[integrationId] === integrationScope) denied = false; + return route.fulfill({ json: { ok: true } }); + }); + await page.goto(origin + "/clients/fixture-grant"); + const editButton = page.getByRole("button", { name: "Edit permissions" }); + const integration = page.getByRole("checkbox", { name: "Linear integration access" }); + const save = async () => { + await page.getByRole("button", { name: "Save permissions" }).click(); + await expect(page.getByRole("dialog")).toHaveCount(0); + }; + await editButton.click(); + await expect(integration).not.toBeChecked(); + await save(); + expect(edits.at(-1)).toEqual({ scopes: initialScopes, expectedRevision: 1 }); + + await page.reload(); + await editButton.click(); + await expect(integration).not.toBeChecked(); + await page.getByRole("checkbox", { name: "team:write", exact: true }).check(); + await save(); + expect(edits.at(-1)).toEqual({ scopes: [...initialScopes, "team:write"], expectedRevision: 2 }); + + await page.reload(); + await editButton.click(); + await expect(integration).not.toBeChecked(); + await integration.check(); + await save(); + expect(edits.at(-1)).toEqual({ + scopes: [...editedScopes, integrationScope], expectedRevision: 3, + integrationOverrides: { [integrationId]: integrationScope }, + }); +}); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 633e45cb..bc2ad30e 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -4384,7 +4384,7 @@ paths: - proxy:use - apps:manage integrationOverrides: - description: Integration ID to approved epoch-bound scope, or false to block. + description: Integration ID to approved epoch-bound scope, or false to block. Explicit approval is required to re-enable a blocked integration, including when scopes are supplied. type: object propertyNames: type: string