diff --git a/lib/context/OWNERSHIP.md b/lib/context/OWNERSHIP.md new file mode 100644 index 000000000..14c84293f --- /dev/null +++ b/lib/context/OWNERSHIP.md @@ -0,0 +1,88 @@ +# Context ownership contract + +Status: implemented and fixture-tested in this repository; not hosted-verified. This document states what the API enforces for every Context operation across HTTP, MCP (API key and OAuth) and background workers, and what it does not claim. Refs recoupable/app#2120 (CE04) in epic recoupable/app#2116. `README.md` describes the operations themselves; this file covers only who may run them and what a denial looks like. + +## 1. Identity comes only from transport authentication + +- HTTP `POST /api/context` (`contextOperationHandler.ts`): the body is parsed with the strict `contextOperationSchema` first, so `account_id` or any other identity field in the body is rejected with 400. `validateAuthContext` then resolves the account from `x-api-key` or a bearer token. +- MCP `context` tool (`lib/mcp/tools/context/registerContextTool.ts`): `resolveAccountId` reads the account from `authInfo`; the tool accepts no override argument. +- MCP OAuth per-action tools (`lib/mcp/oauth/registerFullOAuthTools.ts`): each option of `contextOperationSchema` becomes one public tool named in `contextToolOperations.ts`. The public schema strips `action` and `account_id`. On every call the grant is re-verified, the public input is re-parsed, the action is re-injected and the verified account is bound before the same `context` callback runs. +- Request, release and enrichment workers receive `actor` and `owner` only from the dispatching operation, after it authorized them, and recheck both (section 3). +- The guest worker (`guest/runGuestContext.ts`) is the exception: it starts from a guest ID and lease token, not an actor. After extraction it loads `actor` and `owner` from `context_guest_worker_scope`. They are set only when a signed-in account adopted the guest work through the authorized `claim` action, and the worker then rechecks them before `complete_context_guest`. Unadopted guest work has no actor or owner and is scoped by its private bearer capability. + +## 2. Authorization before any private read, write or dispatch + +- `processContextOperation` (`processContextOperation.ts`) is the single domain surface for HTTP, MCP and OAuth. It parses the input, then calls `authorizeContextOwner(accountId, organization_id)` before any database RPC, Supabase wrapper or workflow dispatch. The owner is the selected organization or, without one, the personal account. +- `authorizeContextOwner` (`authorizeContextOwner.ts`) rechecks organization membership through `validateOrganizationAccess` on every call. It never retains a grant and fails closed when the membership lookup errors. +- HTTP additionally checks organization membership at the transport (`lib/auth/validateAuthContext.ts`): a non-member receives 403 before the domain layer runs. MCP has no transport-level organization check; the domain layer is its enforcement point. Both transports deny the same operations; HTTP only denies earlier. +- Every account-scoped Context RPC takes `p_owner`, and release-case RPCs also take `p_actor`. The database filters by owner on every read and write (`database/supabase/migrations/2026092*_context_*.sql`, `20261008160000_context_release_cases.sql`), and Context tables and functions are revoked from `public`, `anon` and `authenticated`, so only the service role reaches them. Release-case RPCs additionally lock the actor's membership row inside the transaction (`authorize_context_case_actor`, `SELECT … FOR SHARE`). +- Guest RPCs are not owner-scoped. They are scoped by the hashed bearer capability (`p_hash`: `read_context_guest`, `start_context_guest`, `adopt_context_guest`) or by the guest ID and lease token (`p_id`, `p_token`: `claim_context_guest_worker`, `context_guest_worker_scope`, `complete_context_guest`, `fail_context_guest`). `adopt_context_guest` also takes the authorized `p_actor` and `p_owner`. + +## 3. Workers recheck membership before commit + +Queued work does not inherit the permission that queued it. + +- `runContextRequest` (`runContextRequest.ts`) authorizes at start and again after provider extraction, immediately before `commit_spotify_context`. A denial at the recheck records `fail_context_request` with a fixed generic message and never commits. +- `runReleaseVerification` (`planning/runReleaseVerification.ts`) authorizes at planning, at execution authorization, at node authorization and again at provider authorization inside `dispatchPlannedContextModule`. Each check also re-reads the release target and aborts if it changed. +- `runRecordedReleaseTrackIsrcs` and `runReleaseTrackIsrcs` (`planning/`): `loadCurrentReleaseTrackSlots` authorizes before and after pagination on every read. Execution and node authorization reload the slots. `runReleaseTrackIsrcs` rechecks membership once more before `complete_context_release_track_isrcs`. +- Recorded runs (`planning/runRecordedContextModules.ts` with `runPlannedContextModules.ts`) behave differently depending on when access is revoked: + - Revoked before execution authorization: the run rejects before any execution row exists. + - Revoked at node authorization: the scheduler catches the denial and saves one generic node outcome, `{ key, status: "failed", failureStage: "authorize" }`, through `save_context_execution_outcome`. The run then resolves normally. No node is claimed, no provider is dispatched, no credential is fetched and no error text is stored. + - An existing or uncertain node claim stops for reconciliation instead of calling a provider again. +- `runContextEnrichment` (`enrichment/runContextEnrichment.ts`) authorizes before claiming and again after the paid call, immediately before `complete_context_enrichment`. A denial at the recheck marks the attempt with `fail_context_enrichment` (owner and attempt ID only) and never completes it. +- `runGuestContext` rechecks an adopted guest's actor and owner before `complete_context_guest`. A denial records `fail_context_guest` (guest ID and lease token only). +- The `contextWorkflow` review step (`app/workflows/context/recordContextPlanStep.ts` → `planning/recordBlockedContextPlan.ts`) authorizes once through `planStoredContextModules` at the start of the step, before it reads the request or records anything. + +## 4. Derived documents inherit their inputs' restrictions + +- `withdraw_context_source` is owner-scoped and cascades in one function: the source is withdrawn, its results become `withdrawn`, and the owner's documents that pointed at those results are detached (`current_result_id` cleared, revision bumped) in `20260920010000_context_foundation.sql`. +- `compileContextBrief` reads only owner-scoped documents through `read_context_documents` and instructs consumers to treat quoted evidence as source material, not instructions. A saved brief snapshot reads back as `unavailable`, with its content withheld, when any input request is no longer complete or any cited source has been withdrawn; a newer result only marks it `superseded` (`20260926170000_context_brief_snapshots.sql`). Release-case review receipts withhold withdrawn evidence. +- Customer corrections are owner-scoped while canonical Spotify subjects stay global (`20260922161000_context_release_corrections.sql`): a public identity never grants private access. +- Guest work (`/api/context/guest`) is cookie-scoped; claiming it into an account revokes anonymous reads in SQL. + +## 5. Denials are opaque on every transport + +The security property is fixed. Every denial is a non-success result, HTTP denials are 4xx, and no response carries the underlying error message, the selected organization ID or other private detail. A denial is deliberately indistinguishable from a missing request or an unavailable provider. The envelope and exact status code belong to the Context error contract; open api#1005 replaces the domain-layer rows below with typed codes (a denial becomes 403 `permission_denied` with `code`, `retryable` and `guidance`). The fixture tests pin only the property, so either envelope satisfies them. + +Current values on `main`: + +| Transport | Denial point | Response | +| ----------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | +| HTTP | transport organization check | 403 `{ "status": "error", "error": "Access denied to specified organization_id" }` | +| HTTP | domain layer (`authorizeContextOwner` or any domain error) | 409 `{ "error": "Context operation could not complete. …" }` | +| MCP API key | domain layer | `{ "success": false, "message": "Context operation failed. …" }` | +| MCP OAuth | grant, scope or client mismatch | `isError` with "Operation unavailable or permission denied …" | +| MCP OAuth | invalid tool arguments (`ZodError`) | `isError` with "Invalid tool arguments. Check the tool schema and try again." | +| MCP OAuth | tool rate limit | `isError` with the limiter's own fixed message ("Tool rate limit reached; retry in N seconds") | +| MCP OAuth | domain layer | the same opaque `context` tool result as the API-key path | + +## 6. Fixture tests + +- `__tests__/ownershipParity.test.ts` covers every option of `contextOperationSchema`. Options are iterated generically through `buildContextOperationFixture.ts`, so actions that sibling PRs add are covered on merge, provided the candidate pool can satisfy their required fields. Three scenarios run through the real handler, the real MCP callback and the real `processContextOperation`: + - Authorized: the same actor, arguments and dependencies on both transports, with membership rechecked by the domain layer. Every private sink call (RPC, Supabase wrapper or workflow dispatch) receives the authorized organization as owner and the authenticated account as actor. HTTP and MCP make identical sink calls and return the same result. With an empty database answer, 19 of 27 actions succeed on both transports; the other 8 fail identically on both. + - Denied in the domain layer, with a private canary in the error: both transports return an opaque non-success, the canary and organization ID are absent, and no sink runs. + - Denied organization membership: HTTP stops at the transport with 403; MCP is denied by the domain layer; no sink runs. +- `__tests__/oauthContextParity.test.ts` registers the real `context` tool through `registerFullOAuthTools`. It checks one public tool per action, action re-injection, verified-identity forwarding, `readOnlyHint` matching `contextToolOperations`, and an opaque result on domain denial. +- `__tests__/workerRevocationParity.test.ts` revokes membership after work was queued. `runReleaseVerification` and `runRecordedReleaseTrackIsrcs` run through the real recorder, scheduler and execution wrappers against one mocked RPC boundary: + - Revoked before execution authorization: the run rejects and nothing is recorded. + - Revoked before node authorization: the run resolves, exactly one `failed`/`authorize` outcome is saved, and no claim, dispatch or credential fetch occurs. + - The same suite covers `runContextRequest`, `runContextEnrichment` (revoked while queued and during the paid call), an adopted `runGuestContext` job, and the `contextWorkflow` review step. + - In every case, no RPC parameter carries the revocation detail. +- `__tests__/authorizeContextOwner.test.ts`, `__tests__/releaseCaseOperations.test.ts`, `__tests__/spotifyPipeline.test.ts`, `__tests__/guest.test.ts` and the database fixtures in `database/supabase/tests/` cover the underlying checks. + +Ticket acceptance coverage: + +- Item 1 (REST, MCP and worker parity) and item 2 (revocation while queued or running) are fixture-tested here. +- Item 3 (another customer's private canary through briefs, caches, snippets or exports) is covered only indirectly. A denied caller reaches no private sink, and every authorized read is bound to the caller's own owner. The only canary is the authorization error. No cross-customer brief, cache, snippet or export fixture exists yet. +- Item 4 (corrections scoping) is documented from the database migration in section 4 and not exercised by these suites. +- Item 5 (storage, retention and withdrawal) is owned by the open storage PRs listed in section 7. + +## 7. Explicit non-claims + +- Worker commit RPCs (`commit_spotify_context`, `save_context_execution_outcome`, `complete_context_release_track_isrcs`, `complete_context_enrichment`) do not recheck the actor inside the transaction. The application rechecks membership immediately before calling them, but the RPC itself trusts `p_owner`. Shared commit RPCs with an in-transaction lock belong to CE05/CE06 (recoupable/app#2121, #2122). +- The `contextWorkflow` review step authorizes only at its start. If access is revoked between planning and saving, it still records the blocked plan's server-owned reasons. It never claims a node or calls a provider. +- In-transaction actor locks exist today only for release cases. Evidence-attachment RPCs with the same lock are in open database#90 / api#983 and are not covered here. +- Private deletable storage, original-file receipts and the revoked-membership-during-download lifecycle are in open api#986–#991 and database#94/#95. +- Supporting-text extraction is still `not_implemented`, so no privileged-instruction path exists yet. The untrusted-evidence posture is enforced only in brief and enrichment prompts. +- Parity is verified in-process by invoking the registered MCP callbacks, not over a network MCP session. Nothing here is hosted- or live-verified. +- Workflow runtime logs may carry a thrown error's message server-side. A run revoked before execution authorization rejects with that error. Only customer-readable records and transport responses are asserted opaque. diff --git a/lib/context/__tests__/buildContextOperationFixture.ts b/lib/context/__tests__/buildContextOperationFixture.ts new file mode 100644 index 000000000..700711a92 --- /dev/null +++ b/lib/context/__tests__/buildContextOperationFixture.ts @@ -0,0 +1,44 @@ +import { z } from "zod"; + +// Ordered so the first match is the most specific plausible value for a field. +// Spotify and YouTube IDs are syntactic fixtures only; nothing is fetched or resolved. +const candidates: unknown[] = [ + "key-1", + "a".repeat(64), + "11111111-1111-4111-8111-111111111111", + "https://open.spotify.com/album/abcdefghijklmnopqrstuv", + "https://open.spotify.com/track/2ay96C6SLNv9urvXKD3ecB", + "https://www.youtube.com/watch?v=AbCdEfGhI_1", + "2026-01-01", + 1, + 0, + -1, + 1000, + true, + false, +]; + +function buildValue(key: string, field: z.ZodType): unknown { + if (field instanceof z.ZodObject) return buildContextOperationFixture(field); + if (field instanceof z.ZodLiteral) return field.value; + if (field instanceof z.ZodEnum) return field.options[0]; + if (field instanceof z.ZodArray) + return field.safeParse([]).success ? [] : [buildValue(key, field.element as z.ZodType)]; + const value = candidates.find(candidate => field.safeParse(candidate).success); + if (value === undefined) throw new Error(`No fixture candidate satisfies field ${key}`); + return value; +} + +/** + * Build the smallest valid input for one Context operation schema without a per-action map, + * so every current and future action in the discriminated union is covered automatically. + * Optional and defaulted fields are omitted; required fields take the first valid candidate. + */ +export function buildContextOperationFixture(schema: z.ZodObject): Record { + const fixture: Record = {}; + for (const [key, field] of Object.entries(schema.shape)) { + if (field instanceof z.ZodOptional || field instanceof z.ZodDefault) continue; + fixture[key] = buildValue(key, field as z.ZodType); + } + return fixture; +} diff --git a/lib/context/__tests__/oauthContextParity.test.ts b/lib/context/__tests__/oauthContextParity.test.ts new file mode 100644 index 000000000..3b88b62a2 --- /dev/null +++ b/lib/context/__tests__/oauthContextParity.test.ts @@ -0,0 +1,175 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { contextOperationSchema, processContextOperation } from "../processContextOperation"; +import { authorizeContextOwner } from "../authorizeContextOwner"; +import { registerFullOAuthTools } from "@/lib/mcp/oauth/registerFullOAuthTools"; +import { contextToolOperations } from "@/lib/mcp/oauth/contextToolOperations"; +import { callContextRpc } from "@/lib/supabase/context_requests/callContextRpc"; +import { dispatchContextRequest } from "../dispatchContextRequest"; +import { dispatchContextReleaseVerification } from "../dispatchContextReleaseVerification"; +import { dispatchContextReleaseTrackIsrcs } from "../dispatchContextReleaseTrackIsrcs"; +import { buildContextOperationFixture } from "./buildContextOperationFixture"; + +const sinks = vi.hoisted(() => ({ + callContextRpc: vi.fn(), + dispatchContextRequest: vi.fn(), + dispatchContextReleaseVerification: vi.fn(), + dispatchContextReleaseTrackIsrcs: vi.fn(), + planStoredContextModules: vi.fn(), + listContextRequestExecutions: vi.fn(), + listContextCatalogMembers: vi.fn(), + expandContextCatalogMembers: vi.fn(), + listContextCatalogMemberTargets: vi.fn(), +})); +const ids = vi.hoisted(() => ({ + owner: "11111111-1111-4111-8111-111111111111", + organization: "22222222-2222-4222-8222-222222222222", + canary: "CANARY-private-membership-detail-7f3a", +})); +vi.mock("@/lib/supabase/context_requests/callContextRpc", () => ({ + callContextRpc: sinks.callContextRpc, +})); +vi.mock("../dispatchContextRequest", () => ({ + dispatchContextRequest: sinks.dispatchContextRequest, +})); +vi.mock("../dispatchContextReleaseVerification", () => ({ + dispatchContextReleaseVerification: sinks.dispatchContextReleaseVerification, +})); +vi.mock("../dispatchContextReleaseTrackIsrcs", () => ({ + dispatchContextReleaseTrackIsrcs: sinks.dispatchContextReleaseTrackIsrcs, +})); +vi.mock("../planning/planStoredContextModules", () => ({ + planStoredContextModules: sinks.planStoredContextModules, +})); +vi.mock("@/lib/supabase/context_requests/listContextRequestExecutions", () => ({ + listContextRequestExecutions: sinks.listContextRequestExecutions, +})); +vi.mock("@/lib/supabase/context_requests/listContextCatalogMembers", () => ({ + listContextCatalogMembers: sinks.listContextCatalogMembers, +})); +vi.mock("@/lib/supabase/context_requests/expandContextCatalogMembers", () => ({ + expandContextCatalogMembers: sinks.expandContextCatalogMembers, +})); +vi.mock("@/lib/supabase/context_requests/listContextCatalogMemberTargets", () => ({ + listContextCatalogMemberTargets: sinks.listContextCatalogMemberTargets, +})); +vi.mock("@/lib/organizations/canAccessAccount", () => ({ canAccessAccount: vi.fn() })); +vi.mock("@/lib/organizations/validateOrganizationAccess", () => ({ + validateOrganizationAccess: vi.fn(async () => true), +})); +vi.mock("../authorizeContextOwner", async importOriginal => { + const actual = await importOriginal(); + return { authorizeContextOwner: vi.fn(actual.authorizeContextOwner) }; +}); +vi.mock("../processContextOperation", async importOriginal => { + const actual = await importOriginal(); + return { ...actual, processContextOperation: vi.fn(actual.processContextOperation) }; +}); +// The delegated catalog is derived from the real Context tool, not a hand-written copy. +vi.mock("@/lib/mcp/tools", async () => { + const { registerContextTool } = await import("@/lib/mcp/tools/context/registerContextTool"); + return { registerAllTools: (server: McpServer) => registerContextTool(server) }; +}); + +const { owner, organization, canary } = ids; +const access = { + accountId: owner, + clientId: "client", + grantId: "grant", + scopes: ["mcp:tools"], + expiresAt: 9999999999, + resource: "https://api.recoupable.dev/mcp", + context: "personal" as const, +}; +const extra = { + authInfo: { + token: "secret", + clientId: "client", + scopes: access.scopes, + extra: { accountId: owner, oauth: access }, + }, +}; +const operations = contextOperationSchema.options.map(option => { + const action = option.shape.action.value as keyof typeof contextToolOperations; + const input: Record = { + ...buildContextOperationFixture(option), + organization_id: organization, + }; + delete input.action; + return { action, option, input, expected: option.parse({ ...input, action }) }; +}); + +function setup() { + const registered = new Map(); + const server = { + registerTool: vi.fn((name, config, run) => registered.set(name, { config, run })), + }; + const prepare = vi.fn(async (_name: string, args: Record) => args); + registerFullOAuthTools(server as unknown as McpServer, vi.fn().mockResolvedValue(access), { + prepare, + listArtists: vi.fn().mockResolvedValue([]), + }); + return { registered, prepare }; +} + +afterEach(() => vi.resetAllMocks()); + +it("registers exactly one delegated tool per Context action", () => { + const { registered } = setup(); + const expected = Object.values(contextToolOperations).map(operation => operation.name); + expect([...registered.keys()].filter(name => name !== "list_artists").sort()).toEqual( + [...expected].sort(), + ); + expect(registered.size).toBe(contextOperationSchema.options.length + 1); +}); + +describe.each(operations)("OAuth Context parity: $action", ({ action, input, expected }) => { + const metadata = contextToolOperations[action]; + + it("exposes the action-free schema with the catalog's permission classification", () => { + const { registered } = setup(); + const tool = registered.get(metadata.name)!; + // Context writes save idempotent evidence; no action deletes, so none is destructive. + expect(tool.config.annotations).toMatchObject({ + readOnlyHint: metadata.readOnly, + destructiveHint: false, + }); + expect(tool.config.inputSchema.shape.action).toBeUndefined(); + expect(tool.config.inputSchema.safeParse(input).success).toBe(true); + expect(tool.config.inputSchema.safeParse({ ...input, action }).success).toBe(false); + expect(tool.config.inputSchema.safeParse({ ...input, account_id: owner }).success).toBe(false); + }); + + it("re-injects the action and forwards the verified identity to the shared operation", async () => { + const { registered, prepare } = setup(); + await registered.get(metadata.name)!.run(input, extra); + expect(prepare).toHaveBeenCalledExactlyOnceWith("context", expected, owner); + expect(processContextOperation).toHaveBeenCalledExactlyOnceWith( + owner, + expected, + expect.objectContaining({ + rpc: callContextRpc, + dispatch: dispatchContextRequest, + dispatchRelease: dispatchContextReleaseVerification, + dispatchReleaseTracks: dispatchContextReleaseTrackIsrcs, + }), + ); + expect(authorizeContextOwner).toHaveBeenCalledExactlyOnceWith(owner, organization); + }); + + it("returns an opaque result when the domain layer denies the actor", async () => { + vi.mocked(authorizeContextOwner).mockRejectedValue(new Error(`Access denied: ${canary}`)); + const { registered } = setup(); + const result = await registered.get(metadata.name)!.run(input, extra); + // The envelope belongs to the Context error contract; ownership pins only opacity. + expect(JSON.parse(result.content[0].text)).toMatchObject({ + success: false, + message: expect.any(String), + }); + expect(JSON.stringify(result)).not.toContain(canary); + expect(JSON.stringify(result)).not.toContain(organization); + expect(processContextOperation).toHaveBeenCalledTimes(1); + for (const [name, sink] of Object.entries(sinks)) + expect(sink, `${name} ran after a denial`).not.toHaveBeenCalled(); + }); +}); diff --git a/lib/context/__tests__/ownershipParity.test.ts b/lib/context/__tests__/ownershipParity.test.ts new file mode 100644 index 000000000..8332e0c25 --- /dev/null +++ b/lib/context/__tests__/ownershipParity.test.ts @@ -0,0 +1,251 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { NextRequest } from "next/server"; +import { contextOperationHandler } from "../contextOperationHandler"; +import { contextOperationSchema, processContextOperation } from "../processContextOperation"; +import { authorizeContextOwner } from "../authorizeContextOwner"; +import { validateOrganizationAccess } from "@/lib/organizations/validateOrganizationAccess"; +import { registerContextTool } from "@/lib/mcp/tools/context/registerContextTool"; +import { callContextRpc } from "@/lib/supabase/context_requests/callContextRpc"; +import { dispatchContextRequest } from "../dispatchContextRequest"; +import { dispatchContextReleaseVerification } from "../dispatchContextReleaseVerification"; +import { dispatchContextReleaseTrackIsrcs } from "../dispatchContextReleaseTrackIsrcs"; +import { buildContextOperationFixture } from "./buildContextOperationFixture"; + +// Every private sink the domain layer can reach. None may run after a denial. +const sinks = vi.hoisted(() => ({ + callContextRpc: vi.fn(), + dispatchContextRequest: vi.fn(), + dispatchContextReleaseVerification: vi.fn(), + dispatchContextReleaseTrackIsrcs: vi.fn(), + planStoredContextModules: vi.fn(), + listContextRequestExecutions: vi.fn(), + listContextCatalogMembers: vi.fn(), + expandContextCatalogMembers: vi.fn(), + listContextCatalogMemberTargets: vi.fn(), +})); +const ids = vi.hoisted(() => ({ + actor: "11111111-1111-4111-8111-111111111111", + organization: "22222222-2222-4222-8222-222222222222", + canary: "CANARY-private-membership-detail-7f3a", +})); +vi.mock("@/lib/supabase/context_requests/callContextRpc", () => ({ + callContextRpc: sinks.callContextRpc, +})); +vi.mock("../dispatchContextRequest", () => ({ + dispatchContextRequest: sinks.dispatchContextRequest, +})); +vi.mock("../dispatchContextReleaseVerification", () => ({ + dispatchContextReleaseVerification: sinks.dispatchContextReleaseVerification, +})); +vi.mock("../dispatchContextReleaseTrackIsrcs", () => ({ + dispatchContextReleaseTrackIsrcs: sinks.dispatchContextReleaseTrackIsrcs, +})); +vi.mock("../planning/planStoredContextModules", () => ({ + planStoredContextModules: sinks.planStoredContextModules, +})); +vi.mock("@/lib/supabase/context_requests/listContextRequestExecutions", () => ({ + listContextRequestExecutions: sinks.listContextRequestExecutions, +})); +vi.mock("@/lib/supabase/context_requests/listContextCatalogMembers", () => ({ + listContextCatalogMembers: sinks.listContextCatalogMembers, +})); +vi.mock("@/lib/supabase/context_requests/expandContextCatalogMembers", () => ({ + expandContextCatalogMembers: sinks.expandContextCatalogMembers, +})); +vi.mock("@/lib/supabase/context_requests/listContextCatalogMemberTargets", () => ({ + listContextCatalogMemberTargets: sinks.listContextCatalogMemberTargets, +})); +// Real transports and real domain dispatcher; only identity lookups and membership are faked. +vi.mock("@/lib/auth/getApiKeyAccountId", () => ({ + getApiKeyAccountId: vi.fn(async () => ids.actor), +})); +vi.mock("@/lib/auth/getAuthenticatedAccountId", () => ({ getAuthenticatedAccountId: vi.fn() })); +vi.mock("@/lib/organizations/canAccessAccount", () => ({ canAccessAccount: vi.fn() })); +vi.mock("@/lib/organizations/validateOrganizationAccess", () => ({ + validateOrganizationAccess: vi.fn(), +})); +vi.mock("../authorizeContextOwner", async importOriginal => { + const actual = await importOriginal(); + return { authorizeContextOwner: vi.fn(actual.authorizeContextOwner) }; +}); +vi.mock("../processContextOperation", async importOriginal => { + const actual = await importOriginal(); + return { ...actual, processContextOperation: vi.fn(actual.processContextOperation) }; +}); + +const { actor, organization, canary } = ids; +const sharedDependencies = { + rpc: callContextRpc, + dispatch: dispatchContextRequest, + dispatchRelease: dispatchContextReleaseVerification, + dispatchReleaseTracks: dispatchContextReleaseTrackIsrcs, +}; +const operations = contextOperationSchema.options.map(option => ({ + action: option.shape.action.value as string, + option, + // Organization scope is the only scope where membership can be denied or revoked. + operation: option.parse({ + ...buildContextOperationFixture(option), + organization_id: organization, + }), +})); + +function callHttp(operation: Record) { + return contextOperationHandler( + new NextRequest("http://localhost/api/context", { + method: "POST", + headers: { "x-api-key": "fixture-key", "content-type": "application/json" }, + body: JSON.stringify(operation), + }), + ); +} +async function callMcp(operation: Record) { + const registerTool = vi.fn(); + registerContextTool({ registerTool } as never); + const result = await registerTool.mock.calls[0][2](operation, { + authInfo: { extra: { accountId: actor } }, + }); + return { result, text: result.content[0].text as string }; +} +function expectNoPrivateSink() { + for (const [name, sink] of Object.entries(sinks)) + expect(sink, `${name} ran after a denial`).not.toHaveBeenCalled(); +} +type SinkName = keyof typeof sinks; +// Where each private sink receives the workspace owner and, when it takes one, the actor. +const scopeOf: Record { owner: unknown; actor?: unknown }> = { + callContextRpc: ([, params]) => { + const { p_owner, p_actor } = params as Record; + return { owner: p_owner, actor: p_actor }; + }, + dispatchContextRequest: ([account, owner]) => ({ actor: account, owner }), + dispatchContextReleaseVerification: ([account, owner]) => ({ actor: account, owner }), + dispatchContextReleaseTrackIsrcs: ([account, owner]) => ({ actor: account, owner }), + planStoredContextModules: ([account, owner]) => ({ actor: account, owner }), + listContextRequestExecutions: ([owner]) => ({ owner }), + listContextCatalogMembers: ([owner]) => ({ owner }), + expandContextCatalogMembers: ([owner]) => ({ owner }), + listContextCatalogMemberTargets: ([owner]) => ({ owner }), +}; +function recordedSinkCalls() { + return (Object.keys(sinks) as SinkName[]).flatMap(name => + sinks[name].mock.calls.map(args => ({ name, args: args as unknown[] })), + ); +} +/** The authorized owner, never the actor's personal workspace or a caller-supplied ID, reaches every sink. */ +function expectSinksBoundToWorkspace(calls: ReturnType) { + expect(calls.length, "authorized operation reached no private sink").toBeGreaterThan(0); + for (const { name, args } of calls) { + const scope = scopeOf[name](args); + expect(scope.owner, `${name} owner`).toBe(organization); + if (scope.actor !== undefined) expect(scope.actor, `${name} actor`).toBe(actor); + } +} +/** + * The denial envelope and exact status belong to the Context error contract. Ownership pins only + * the security property: a client-error denial on both transports with no private detail. + */ +function expectHttpDenial(status: number) { + expect(status).toBeGreaterThanOrEqual(400); + expect(status).toBeLessThan(500); +} + +afterEach(() => { + vi.unstubAllEnvs(); + vi.resetAllMocks(); +}); + +describe.each(operations)("Context ownership parity: $action", ({ option, operation }) => { + it("authorized: both transports reach the same sinks, bound to the authorized workspace", async () => { + expect(option.safeParse(operation).success).toBe(true); + // Server gates on so gated actions reach their first private read. + vi.stubEnv("CONTEXT_SPOTIFY_RELEASE_VERIFY_ENABLED", "true"); + vi.stubEnv("CONTEXT_SPOTIFY_RELEASE_TRACK_ISRC_ENABLED", "true"); + vi.mocked(validateOrganizationAccess).mockResolvedValue(true); + // An empty database answer, so both transports serialize the same result. + const answerEmpty = () => Object.values(sinks).forEach(sink => sink.mockResolvedValue(null)); + answerEmpty(); + + const response = await callHttp(operation); + expect([400, 401, 403]).not.toContain(response.status); + const httpBody = await response.json(); + const httpSinkCalls = recordedSinkCalls(); + expectSinksBoundToWorkspace(httpSinkCalls); + expect(processContextOperation).toHaveBeenCalledExactlyOnceWith( + actor, + operation, + expect.objectContaining(sharedDependencies), + ); + expect(authorizeContextOwner).toHaveBeenCalledExactlyOnceWith(actor, organization); + // HTTP checks membership at the transport and again inside the domain layer. + expect(validateOrganizationAccess).toHaveBeenCalledTimes(2); + + vi.clearAllMocks(); + vi.mocked(validateOrganizationAccess).mockResolvedValue(true); + answerEmpty(); + const { text } = await callMcp(operation); + // Same private reads, writes and dispatches with the same arguments, and the same outcome. + expect(recordedSinkCalls()).toEqual(httpSinkCalls); + if (response.ok) expect(JSON.parse(text)).toEqual(httpBody); + else expect(JSON.parse(text)).toMatchObject({ success: false }); + expect(processContextOperation).toHaveBeenCalledExactlyOnceWith( + actor, + operation, + expect.objectContaining(sharedDependencies), + ); + expect(authorizeContextOwner).toHaveBeenCalledExactlyOnceWith(actor, organization); + expect(validateOrganizationAccess).toHaveBeenCalledExactlyOnceWith({ + accountId: actor, + organizationId: organization, + }); + }); + + it("denied in the domain layer: opaque failure through both transports, no private sink", async () => { + // Transport membership passes (a stale grant); the domain recheck fails with private detail. + vi.mocked(validateOrganizationAccess).mockResolvedValue(true); + vi.mocked(authorizeContextOwner).mockRejectedValue(new Error(`Access denied: ${canary}`)); + + const response = await callHttp(operation); + expectHttpDenial(response.status); + const body = await response.json(); + expect(body).toMatchObject({ error: expect.any(String) }); + expect(JSON.stringify(body)).not.toContain(canary); + expect(JSON.stringify(body)).not.toContain(organization); + expect(processContextOperation).toHaveBeenCalledTimes(1); + expectNoPrivateSink(); + + const { result, text } = await callMcp(operation); + expect(JSON.parse(text)).toMatchObject({ success: false, message: expect.any(String) }); + expect(JSON.stringify(result)).not.toContain(canary); + expect(JSON.stringify(result)).not.toContain(organization); + expect(processContextOperation).toHaveBeenCalledTimes(2); + expect(authorizeContextOwner).toHaveBeenCalledTimes(2); + expectNoPrivateSink(); + }); + + it("denied organization membership: HTTP stops at the transport, MCP in the domain layer", async () => { + vi.mocked(validateOrganizationAccess).mockResolvedValue(false); + + const response = await callHttp(operation); + expect(response.status).toBe(403); + expect(JSON.stringify(await response.json())).not.toContain(organization); + expect(processContextOperation).not.toHaveBeenCalled(); + expect(authorizeContextOwner).not.toHaveBeenCalled(); + expectNoPrivateSink(); + + const { result, text } = await callMcp(operation); + expect(JSON.parse(text)).toMatchObject({ success: false, message: expect.any(String) }); + expect(JSON.stringify(result)).not.toContain(organization); + expect(processContextOperation).toHaveBeenCalledExactlyOnceWith( + actor, + operation, + expect.objectContaining(sharedDependencies), + ); + expect(authorizeContextOwner).toHaveBeenCalledExactlyOnceWith(actor, organization); + expect(validateOrganizationAccess).toHaveBeenLastCalledWith({ + accountId: actor, + organizationId: organization, + }); + expectNoPrivateSink(); + }); +}); diff --git a/lib/context/__tests__/workerRevocationParity.test.ts b/lib/context/__tests__/workerRevocationParity.test.ts new file mode 100644 index 000000000..47d69cbe8 --- /dev/null +++ b/lib/context/__tests__/workerRevocationParity.test.ts @@ -0,0 +1,307 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { runContextRequest } from "../runContextRequest"; +import { + runContextEnrichment, + type ContextEnrichmentResult, +} from "../enrichment/runContextEnrichment"; +import { runGuestContext } from "../guest/runGuestContext"; +import { authorizeContextOwner } from "../authorizeContextOwner"; +import { runReleaseVerification } from "../planning/runReleaseVerification"; +import { runRecordedReleaseTrackIsrcs } from "../planning/runRecordedReleaseTrackIsrcs"; +import { runRecordedContextModules } from "../planning/runRecordedContextModules"; +import { recordContextPlanStep } from "@/app/workflows/context/recordContextPlanStep"; + +type Rpc = (name: string, params: Record) => Promise; +// One database boundary for every worker: the real recorder, execution wrappers and planners +// reach the same mocked RPC, so each persisted record can be inspected for private detail. +const { rpc } = vi.hoisted(() => ({ rpc: vi.fn() })); +vi.mock("@/lib/supabase/context_requests/callContextRpc", () => ({ callContextRpc: rpc })); +vi.mock("../authorizeContextOwner", () => ({ authorizeContextOwner: vi.fn() })); + +const actor = "11111111-1111-4111-8111-111111111111"; +const owner = "22222222-2222-4222-8222-222222222222"; +const requestId = "33333333-3333-4333-8333-333333333333"; +const subjectId = "44444444-4444-4444-8444-444444444444"; +const sourceResultId = "55555555-5555-4555-8555-555555555555"; +const executionRow = "66666666-6666-4666-8666-666666666666"; +const claimId = "77777777-7777-4777-8777-777777777777"; +const attemptId = "88888888-8888-4888-8888-888888888888"; +const canary = "CANARY-private-membership-detail-7f3a"; +type Recorder = typeof runRecordedContextModules; + +/** Membership that is valid when work is queued and revoked at a chosen later point. */ +function membership() { + let revoked = false; + return { + revoke: () => { + revoked = true; + }, + authorize: vi.fn(async () => { + if (revoked) throw new Error(`Access denied: ${canary}`); + return { ownerId: owner }; + }), + }; +} +/** Pass-through to the real recorder; it only times the revocation before execution authorization. */ +function revokeThenRecord(revoke: () => void): Recorder { + return (input, callbacks) => { + revoke(); + return runRecordedContextModules(input, callbacks); + }; +} +/** Routes the recorder's execution RPCs; `onCreate` runs once the execution row exists. */ +function routeRecorderRpc(reads: Record, onCreate: () => void) { + rpc.mockImplementation(async name => { + if (name in reads) return reads[name]; + if (name === "create_context_execution") { + onCreate(); + return { id: executionRow, created: true }; + } + if (name === "claim_context_execution_node") return { state: "claimed", claimId }; + if (name === "save_context_execution_outcome") return {}; + throw new Error(`Unexpected RPC ${name}`); + }); +} +const rpcNames = () => rpc.mock.calls.map(([name]) => name); +const savedOutcomes = () => + rpc.mock.calls.filter(([name]) => name === "save_context_execution_outcome").map(([, p]) => p); +/** Every record a worker wrote is customer-readable; none may carry the revocation detail. */ +function expectNoPrivateDetailPersisted() { + expect(JSON.stringify(rpc.mock.calls)).not.toContain(canary); +} + +afterEach(() => { + vi.unstubAllEnvs(); + vi.resetAllMocks(); +}); + +describe("runContextRequest", () => { + const request = { + id: requestId, + owner_id: owner, + created_by: actor, + input: { url: "https://open.spotify.com/track/2ay96C6SLNv9urvXKD3ecB" }, + status: "queued", + }; + it("revoked during extraction: no commit, failure recorded without private detail", async () => { + const { authorize, revoke } = membership(); + rpc.mockImplementation(async name => + name === "read_context_request" ? request : name === "claim_context_request" ? true : null, + ); + const extract = vi.fn(async () => { + revoke(); + return { trackId: "2ay96C6SLNv9urvXKD3ecB" }; + }); + await expect( + runContextRequest(actor, owner, requestId, { rpc, authorize, extract } as never), + ).rejects.toThrow(canary); + expect(rpcNames()).not.toContain("commit_spotify_context"); + expect(rpcNames()).toContain("fail_context_request"); + expectNoPrivateDetailPersisted(); + expect(authorize).toHaveBeenCalledTimes(2); + expect(extract).toHaveBeenCalledTimes(1); + }); +}); + +describe("runReleaseVerification (real recorder and execution wrappers)", () => { + const target = { + subjectId, + kind: "release", + identityConfirmed: false, + availableFields: ["spotify_id"], + reusableModules: [], + }; + const reads = { list_context_release_request_target: target }; + const key = `${subjectId}:spotify_release`; + + it("revoked before execution authorization: rejects, nothing recorded or dispatched", async () => { + vi.stubEnv("CONTEXT_SPOTIFY_RELEASE_VERIFY_ENABLED", "true"); + const { authorize, revoke } = membership(); + routeRecorderRpc(reads, () => undefined); + const dispatch = vi.fn(); + const getSpotifyToken = vi.fn(); + await expect( + runReleaseVerification(actor, owner, requestId, { + authorize, + dispatch, + getSpotifyToken, + record: revokeThenRecord(revoke), + }), + ).rejects.toThrow(canary); + expect(rpcNames()).toEqual(["list_context_release_request_target"]); + expect(dispatch).not.toHaveBeenCalled(); + expect(getSpotifyToken).not.toHaveBeenCalled(); + }); + + it("revoked before node authorization: node fails at authorize, generic outcome saved once", async () => { + vi.stubEnv("CONTEXT_SPOTIFY_RELEASE_VERIFY_ENABLED", "true"); + const { authorize, revoke } = membership(); + routeRecorderRpc(reads, revoke); + const dispatch = vi.fn(); + const getSpotifyToken = vi.fn(); + const result = await runReleaseVerification(actor, owner, requestId, { + authorize, + dispatch, + getSpotifyToken, + }); + const failed = { key, status: "failed", failureStage: "authorize" }; + expect(result.outcomes).toEqual([failed]); + expect(dispatch).not.toHaveBeenCalled(); + expect(getSpotifyToken).not.toHaveBeenCalled(); + expect(rpcNames()).not.toContain("claim_context_execution_node"); + expect(savedOutcomes()).toEqual([ + { p_owner: owner, p_execution: result.executionId, p_node_key: key, p_outcome: failed }, + ]); + expectNoPrivateDetailPersisted(); + }); +}); + +describe("runRecordedReleaseTrackIsrcs (real recorder and execution wrappers)", () => { + const page = { + state: "ready", + releaseId: "AAAAAAAAAAAAAAAAAAAAAA", + sourceResultId, + coverage: "full", + collectedSlots: 1, + reportedTotal: 1, + linkedSlots: 1, + unavailableSlots: 0, + hasMore: false, + nextCursor: null, + slots: [ + { + slotIndex: 0, + spotifyTrackId: "BBBBBBBBBBBBBBBBBBBBBB", + discNumber: 1, + trackNumber: 1, + sourceResultId, + }, + ], + }; + const reads = { list_context_release_track_slots: page }; + const key = `${subjectId}:spotify_release_track_isrcs`; + + it("revoked before execution authorization: rejects, nothing recorded or collected", async () => { + vi.stubEnv("CONTEXT_SPOTIFY_RELEASE_TRACK_ISRC_ENABLED", "true"); + const { authorize, revoke } = membership(); + routeRecorderRpc(reads, () => undefined); + const collect = vi.fn(); + const getSpotifyToken = vi.fn(); + await expect( + runRecordedReleaseTrackIsrcs(actor, owner, requestId, subjectId, { + authorize, + collect: collect as never, + getSpotifyToken, + record: revokeThenRecord(revoke), + }), + ).rejects.toThrow(canary); + expect(rpcNames().every(name => name === "list_context_release_track_slots")).toBe(true); + expect(collect).not.toHaveBeenCalled(); + expect(getSpotifyToken).not.toHaveBeenCalled(); + }); + + it("revoked before node authorization: node fails at authorize, generic outcome saved once", async () => { + vi.stubEnv("CONTEXT_SPOTIFY_RELEASE_TRACK_ISRC_ENABLED", "true"); + const { authorize, revoke } = membership(); + routeRecorderRpc(reads, revoke); + const collect = vi.fn(); + const getSpotifyToken = vi.fn(); + const result = await runRecordedReleaseTrackIsrcs(actor, owner, requestId, subjectId, { + authorize, + collect: collect as never, + getSpotifyToken, + }); + const failed = { key, status: "failed", failureStage: "authorize" }; + expect(result.outcomes).toEqual([failed]); + expect(collect).not.toHaveBeenCalled(); + expect(getSpotifyToken).not.toHaveBeenCalled(); + expect(rpcNames()).not.toContain("claim_context_execution_node"); + expect(savedOutcomes()).toEqual([ + { p_owner: owner, p_execution: result.executionId, p_node_key: key, p_outcome: failed }, + ]); + expectNoPrivateDetailPersisted(); + }); +}); + +describe("runContextEnrichment", () => { + const module = { + key: `${subjectId}:song_summary`, + topic: "song_summary", + subjectId, + provider: "fixture", + model: "fixture", + input: {}, + sources: [], + }; + const result: ContextEnrichmentResult = { + content: { summary: "fixture" }, + coverage: "full", + trace: {}, + costUsd: null, + costStatus: "unknown", + }; + + it("revoked while queued: no claim and no paid call", async () => { + const { authorize, revoke } = membership(); + revoke(); + const call = vi.fn(); + await expect( + runContextEnrichment(actor, owner, requestId, module, { authorize, rpc, call }), + ).rejects.toThrow(canary); + expect(rpc).not.toHaveBeenCalled(); + expect(call).not.toHaveBeenCalled(); + }); + + it("revoked during the paid call: no completion, attempt failed without private detail", async () => { + const { authorize, revoke } = membership(); + rpc.mockImplementation(async name => + name === "claim_context_enrichment" ? { state: "claimed", attemptId } : null, + ); + const call = vi.fn(async () => { + revoke(); + return result; + }); + await expect( + runContextEnrichment(actor, owner, requestId, module, { authorize, rpc, call }), + ).rejects.toThrow(canary); + expect(rpcNames()).toEqual(["claim_context_enrichment", "fail_context_enrichment"]); + expect(rpc).toHaveBeenLastCalledWith("fail_context_enrichment", { + p_owner: owner, + p_attempt: attemptId, + }); + expectNoPrivateDetailPersisted(); + }); +}); + +describe("runGuestContext", () => { + it("adopted guest revoked during extraction: no completion, failure without private detail", async () => { + const { authorize, revoke } = membership(); + rpc.mockImplementation(async name => + name === "claim_context_guest_worker" + ? { input: { trackId: "2ay96C6SLNv9urvXKD3ecB" } } + : name === "context_guest_worker_scope" + ? { actor, owner } + : null, + ); + const extract = vi.fn(async () => { + revoke(); + return {} as never; + }); + await expect(runGuestContext(requestId, { rpc, extract, authorize })).rejects.toThrow(canary); + expect(authorize).toHaveBeenCalledExactlyOnceWith(actor, owner); + expect(rpcNames()).not.toContain("complete_context_guest"); + const failure = rpc.mock.calls.find(([name]) => name === "fail_context_guest")![1]; + expect(Object.keys(failure).sort()).toEqual(["p_id", "p_token"]); + expectNoPrivateDetailPersisted(); + }); +}); + +describe("recordContextPlanStep (contextWorkflow review step)", () => { + it("revoked while queued: no request read, execution or outcome is recorded", async () => { + vi.stubEnv("CONTEXT_RECORD_BLOCKED_PLAN_ENABLED", "true"); + vi.mocked(authorizeContextOwner).mockRejectedValue(new Error(`Access denied: ${canary}`)); + await expect(recordContextPlanStep(actor, owner, requestId)).rejects.toThrow(canary); + expect(authorizeContextOwner).toHaveBeenCalledExactlyOnceWith(actor, owner); + expect(rpc).not.toHaveBeenCalled(); + }); +});