diff --git a/packages/api/src/api-service.ts b/packages/api/src/api-service.ts index 0168da24..634282e1 100644 --- a/packages/api/src/api-service.ts +++ b/packages/api/src/api-service.ts @@ -1,6 +1,6 @@ import { cloudflareState, disconnectCloudflare, selectCloudflare, startCloudflare } from "./cloudflare-oauth"; import { initialIntegrationOverrides, lockOAuthPolicy } from "./oauth-reconnect"; -import { lockMcpEventGrant } from "./postgres/mcp-event-outbox"; +import { deleteMcpGrantSubscriptions, lockMcpEventGrant } from "./postgres/mcp-event-outbox"; import { eventPayloadSchema, occurrenceEventName, occurrenceInputSchema, type ReadEventOccurrencesInput, type subscribeEventInput, type unsubscribeEventInput, type setProcessingAcknowledgmentsInput, type acknowledgeEventsInput } from "./mcp-event-contracts"; import { subscribeMcpEvent, unsubscribeMcpEvent, getProcessingAcknowledgments, setProcessingAcknowledgments, acknowledgeEvents, replayUnacknowledgedEvents } from "./mcp-event-subscriptions"; import { vmGrantInput, vmGrantList, vmGrantResult, vmRevokeResult } from "./vm-grant-contracts"; @@ -752,8 +752,7 @@ export class ApiService { await databaseFor(this.env).transaction(async sql => { await lockOAuthPolicy(sql, this.auth); await lockMcpEventGrant(sql, this.auth.tenantId, grantId); - await sql.query(`UPDATE app.mcp_event_subscriptions SET status='stopped',previous_encrypted_secret=NULL,rotated_at=NULL - WHERE tenant_id=$1 AND user_id=$2 AND grant_id=$3 AND status='active'`, [this.auth.tenantId, this.auth.userId, grantId]); + await deleteMcpGrantSubscriptions(sql, { tenant_id: this.auth.tenantId, user_id: this.auth.userId, grant_id: grantId }); await sql.query("INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version,revoked_at) VALUES($1,'oauth',$2,$3,$4,now()) ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET revoked_at=now()",[this.auth.tenantId,grantId,this.auth.userId,this.auth.sessionVersion]); }); await this.env.OAUTH_PROVIDER.revokeGrant(grantId,this.auth.userId); diff --git a/packages/api/src/postgres/mcp-event-outbox.ts b/packages/api/src/postgres/mcp-event-outbox.ts index 148fcddc..36d20d6c 100644 --- a/packages/api/src/postgres/mcp-event-outbox.ts +++ b/packages/api/src/postgres/mcp-event-outbox.ts @@ -1,4 +1,4 @@ -import type { DatabaseClient } from "./database"; +import type { Database, DatabaseClient } from "./database"; // The definition row is already locked FOR SHARE by both writers. This lock // orders subscription activation against occurrence insertion through commit. @@ -18,3 +18,36 @@ export async function enqueueMcpDeliveries(sql: DatabaseClient, tenantId: string export async function lockMcpEventGrant(sql: DatabaseClient, tenantId: string, grantId: string) { await sql.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [`mcp-event-grant:${tenantId}:${grantId}`]); } + +type Grant = { tenant_id: string; user_id: string; grant_id: string }; +const pruneBatchSize = 250; + +// The caller holds the exact grant's advisory lock. Lock subscription rows +// before changing the policy row, matching dispatch's subscription -> policy +// order. Child delivery rows cascade without touching the source Event. +export async function deleteMcpGrantSubscriptions(sql: DatabaseClient, grant: Grant) { + await sql.query(`WITH doomed AS ( + SELECT id FROM app.mcp_event_subscriptions + WHERE tenant_id=$1 AND user_id=$2 AND grant_id=$3 ORDER BY id LIMIT $4 + ) DELETE FROM app.mcp_event_subscriptions s USING doomed + WHERE s.tenant_id=$1 AND s.user_id=$2 AND s.grant_id=$3 AND s.id=doomed.id`, + [grant.tenant_id, grant.user_id, grant.grant_id, pruneBatchSize]); +} + +export async function pruneRevokedMcpSubscriptions(db: Database) { + // Only a durable, exact authorization tombstone is deletion proof. An + // absent provider listing (eventually consistent), expiry, logout, or a + // delivery diagnostic is not sufficient. Never delete the tombstone. + const { rows } = await db.pool.query(`SELECT tenant_id,user_id,subject AS grant_id + FROM app.agent_identities i WHERE kind='oauth' AND revoked_at IS NOT NULL AND EXISTS ( + SELECT 1 FROM app.mcp_event_subscriptions s + WHERE s.tenant_id=i.tenant_id AND s.user_id=i.user_id AND s.grant_id=i.subject + ) ORDER BY revoked_at,tenant_id,subject LIMIT 20`); + for (const grant of rows) await db.transaction(async sql => { + await lockMcpEventGrant(sql, grant.tenant_id, grant.grant_id); + const proof = await sql.query(`SELECT 1 FROM app.agent_identities + WHERE tenant_id=$1 AND user_id=$2 AND kind='oauth' AND subject=$3 AND revoked_at IS NOT NULL`, + [grant.tenant_id, grant.user_id, grant.grant_id]); + if (proof.rowCount) await deleteMcpGrantSubscriptions(sql, grant); + }); +} diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index ae1b98c4..c1ac8ee7 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -4,6 +4,7 @@ import { pruneTotp } from "./totp"; import { googleSignInCallback } from "./auth-api"; import { clearExpiredGoogleSignIns, googleCallbackPath } from "./google-sign-in"; import { AlarmCoordinator as BaseAlarmCoordinator } from "./alarm-coordinator"; +import { pruneRevokedMcpSubscriptions } from "./postgres/mcp-event-outbox"; import { wakeMcpDeliveries } from "./postgres/event-match-repository"; import { staticApp, securityHeaders } from "./static-app"; import { OAuthProvider, AuthorizationError, getOAuthApi, type AuthRequest, type OAuthProviderOptions } from "@cloudflare/workers-oauth-provider"; @@ -175,8 +176,9 @@ export default { async scheduled(_event: ScheduledController, env: Env) { // Ensure the alarm sweep starts even if a producer's immediate wake was missed. await wakeMcpDeliveries(env).catch(() => {}); - // Retire expired VM proofs and incomplete enrollments. const db = databaseFor(env); + await pruneRevokedMcpSubscriptions(db); + // Retire expired VM proofs and incomplete enrollments. await clearExpiredGoogleSignIns(db.pool); await pruneCloudflareOAuth(db.pool); await pruneTotp(db.pool); diff --git a/packages/api/test/mcp-events.postgres.test.ts b/packages/api/test/mcp-events.postgres.test.ts index 18bcd98b..b6ade758 100644 --- a/packages/api/test/mcp-events.postgres.test.ts +++ b/packages/api/test/mcp-events.postgres.test.ts @@ -199,7 +199,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP event webhook lifecycl expect(revocation.status).toBe(200); expect(await revocation.json()).toEqual({ revoked: 1 }); expect(grantActive).toBe(false); - expect((await f.db.pool.query("SELECT status FROM app.mcp_event_subscriptions WHERE id=$1", [subscriptionId])).rows).toEqual([{ status: "stopped" }]); + expect((await f.db.pool.query("SELECT status FROM app.mcp_event_subscriptions WHERE id=$1", [subscriptionId])).rows).toEqual([]); const afterRevoke = await tool("fire_trigger", { triggerId: source.triggerId, idempotencyKey: "after-explicit-revoke", data: {} }, f.auth); expect(afterRevoke.isError).not.toBe(true); await dispatchMcpEvents(f.env); @@ -711,6 +711,82 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP event webhook lifecycl expect((await request("tools/call", { name: "read_event_occurrences", arguments: { occurrenceId: rotated.occurrenceId } }, { ...auth, scopes: [] })).status).toBe(403); }); + + it("deletes only subscriptions on the exact grant revoked through owner settings", async () => { + const otherGrant = { ...auth, oauthGrantId: "grant-same-client" }; + const grants = [auth, otherGrant]; + f.env.OAUTH_PROVIDER!.listUserGrants = async () => ({ items: grants.map(g => ({ + id: g.oauthGrantId!, clientId: g.oauthClientId!, metadata: { tenantId: f.tenantId }, scope: g.scopes, + })) }) as any; + f.env.OAUTH_PROVIDER!.revokeGrant = async (id, userId) => { + expect([id,userId]).toEqual([auth.oauthGrantId,f.userId]); + // A stale provider listing must not allow the explicit revoke to be undone. + }; + const active = (await subscribe()).message.result.id; + const stopped = (await subscribe(otherReceiver)).message.result.id; + const occurrence = await fire("before-revocation"); + await request("events/unsubscribe", { name, arguments: {}, delivery: { url: otherReceiver } }); + const other = (await request("events/subscribe", { name, arguments: {}, delivery: { + mode: "webhook", url: receiver, secret: secret(key), + } }, otherGrant)).message.result.id; + const unaffected = await fire("before-revocation-same-client"); + const foreign = await f.seedEventTrigger(f.otherTenant); + await f.db.pool.query(`INSERT INTO app.mcp_event_subscriptions + (tenant_id,id,user_id,session_version,grant_id,client_id,definition_id,arguments,callback_url, + encrypted_secret,secret_fingerprint,verified_at,generation,status,expires_at) + SELECT $1,id,user_id,session_version,grant_id,client_id,$2,arguments,callback_url, + encrypted_secret,secret_fingerprint,verified_at,generation,status,expires_at + FROM app.mcp_event_subscriptions WHERE tenant_id=$3 AND id=$4`, + [f.otherTenant, foreign.definitionId, f.tenantId, active]); + const revoke = await worker.fetch(new Request( + `${f.env.APP_ORIGIN}/api/v1/access/authorizations/${auth.oauthGrantId}`, + { method: "DELETE", headers: { Cookie: f.cookie, Origin: f.env.APP_ORIGIN } }, + ), f.env, {} as ExecutionContext); + expect(revoke.status).toBe(200); + expect(await revoke.json()).toEqual({ revoked: 1 }); + expect((await f.db.pool.query("SELECT id FROM app.mcp_event_subscriptions WHERE tenant_id=$1", [f.tenantId])).rows).toEqual([{ id: other }]); + expect((await f.db.pool.query("SELECT id FROM app.mcp_event_subscriptions WHERE tenant_id=$1", [f.otherTenant])).rows).toEqual([{ id: active }]); + expect((await f.db.pool.query("SELECT subscription_id,occurrence_id FROM app.mcp_event_deliveries")).rows) + .toEqual([{ subscription_id: other, occurrence_id: unaffected.occurrenceId }]); + expect((await subscribe()).message.result?.id).toBeUndefined(); + await dispatchMcpEvents(f.env); + expect(deliveries.map(event => event.subscriptionId)).toEqual([other]); + expect([active, stopped]).not.toContain(other); + expect((await f.request(`/api/v1/events/${source.definitionId}`)).status).toBe(200); + const history = await (await f.request(`/api/v1/events/${source.definitionId}/occurrences`)).json() as { items: Array<{ id: string }> }; + expect(history.items.map(item => item.id)).toEqual(expect.arrayContaining([occurrence.occurrenceId,unaffected.occurrenceId])); + }); + + it("reconciles historical tombstones but preserves unconfirmed subscriptions during provider failures", async () => { + const retired = { ...auth, oauthGrantId: "grant-tombstoned" }; + const list = vi.fn(async () => ({ items: [auth, retired].map(g => ({ + id: g.oauthGrantId!, clientId: g.oauthClientId!, metadata: { tenantId: f.tenantId }, scope: g.scopes, + })) })); + f.env.OAUTH_PROVIDER!.listUserGrants = list as any; + const stopped = (await subscribe()).message.result.id; + await unsubscribe(); + const stillActive = (await subscribe(otherReceiver)).message.result.id; + const legacy = (await request("events/subscribe", { name, arguments: {}, delivery: { + mode: "webhook", url: receiver, secret: secret(key), + } }, retired)).message.result.id; + await fire("before-reconciliation"); + await f.db.pool.query(`INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version,revoked_at) + VALUES($1,'oauth',$2,$3,$4,now())`, [f.tenantId,retired.oauthGrantId,f.userId,auth.sessionVersion]); + await f.db.pool.query("UPDATE app.mcp_event_subscriptions SET status='stopped' WHERE tenant_id=$1 AND id=$2", [f.tenantId,legacy]); + // A completed-but-empty provider listing and a delivery diagnostic are not deletion proof. + list.mockResolvedValue({items: []}); + await dispatchMcpEvents(f.env); + list.mockRejectedValue(new Error("transient provider timeout")); + const calls = list.mock.calls.length; + for (let i = 0; i < 2; i++) await worker.scheduled({} as ScheduledController, f.env); + expect(list).toHaveBeenCalledTimes(calls); + expect((await f.db.pool.query("SELECT id,status FROM app.mcp_event_subscriptions ORDER BY status")).rows) + .toEqual([{id:stillActive,status:"active"},{id:stopped,status:"stopped"}]); + expect((await f.db.pool.query("SELECT 1 FROM app.mcp_event_deliveries WHERE subscription_id=$1", [legacy])).rowCount).toBe(0); + expect((await f.db.pool.query("SELECT 1 FROM app.event_occurrences WHERE tenant_id=$1", [f.tenantId])).rowCount).toBe(1); + expect((await f.db.pool.query("SELECT 1 FROM app.agent_identities WHERE tenant_id=$1 AND subject=$2 AND revoked_at IS NOT NULL", [f.tenantId,retired.oauthGrantId])).rowCount).toBe(1); + }); + it("rejects failed verification, forbidden destinations, unauthorized calls and cross-tenant names", async () => { const input = { name, delivery: { mode: "webhook", url: receiver, secret: secret(key) } }; for (const [method, params] of [["events/list", {}], ["events/subscribe", input]] as const) {