From 0529b04db4a0e7c810e21f0898a3ce3172c02e6f Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:57:24 -0400 Subject: [PATCH 1/5] Expose scoped retained evidence discovery through HTTP and MCP --- lib/context/README.md | 17 +++ .../evidenceManifestOperation.test.ts | 97 +++++++++++++++ .../evidenceManifestTransports.test.ts | 117 ++++++++++++++++++ lib/context/evidenceManifestSchemas.ts | 38 ++++++ lib/context/processContextOperation.ts | 5 + .../processEvidenceManifestOperation.ts | 37 ++++++ .../oauth/__tests__/fullOAuthCatalog.test.ts | 9 +- lib/mcp/oauth/contextToolOperations.ts | 12 +- lib/mcp/oauth/registerFullOAuthTools.ts | 10 +- .../context/registerEvidenceManifestTool.ts | 52 ++++++++ lib/mcp/tools/index.ts | 2 + scripts/mcp-oauth/tool-policy.json | 9 ++ 12 files changed, 402 insertions(+), 3 deletions(-) create mode 100644 lib/context/__tests__/evidenceManifestOperation.test.ts create mode 100644 lib/context/__tests__/evidenceManifestTransports.test.ts create mode 100644 lib/context/evidenceManifestSchemas.ts create mode 100644 lib/context/processEvidenceManifestOperation.ts create mode 100644 lib/mcp/tools/context/registerEvidenceManifestTool.ts diff --git a/lib/context/README.md b/lib/context/README.md index 77cf5e417..42af3e2e6 100644 --- a/lib/context/README.md +++ b/lib/context/README.md @@ -248,3 +248,20 @@ Both enrichment coordinators propagate this signal. The in-process plan drains already-running work before rejecting and starts no further modules once the uncertainty is known. RPC errors remain attached as internal causes; the public error message does not include private database diagnostics. + +### Retained evidence discovery + +`POST /api/context` with `action: "list_evidence_versions"`, `request_id`, +optional `organization_id` and `after_id` reads an authorized saved request's +retained source-version metadata. Standard MCP exposes the same operation as +`list_context_evidence_versions` with a concrete schema and no `action` parameter. +Pass returned `next_id` as `after_id` while `has_more` is true (up to 50 versions +per page). Each page rechecks access and withdrawal; pages are not a frozen export. + +The typed response distinguishes customer assertions from observations and +current document inputs from retained history. It exposes no source contents, +storage paths, signed URLs or rights decisions. It invokes no collection, paid +provider or roster operation. Both the dedicated tool and delegated expansion of +the combined action are excluded from OAuth pending the organization-grant audit. +Requires Database PR92's `list_context_request_evidence_versions`; it is not yet +a production capability, original-file registration, parsing or an assessment. diff --git a/lib/context/__tests__/evidenceManifestOperation.test.ts b/lib/context/__tests__/evidenceManifestOperation.test.ts new file mode 100644 index 000000000..5ecea73b4 --- /dev/null +++ b/lib/context/__tests__/evidenceManifestOperation.test.ts @@ -0,0 +1,97 @@ +import { expect, it, vi } from "vitest"; +import { processContextOperation } from "../processContextOperation"; +vi.mock("../authorizeContextOwner", () => ({ authorizeContextOwner: vi.fn() })); +const actor = "11111111-1111-4111-8111-111111111111"; +const owner = "22222222-2222-4222-8222-222222222222"; +const request = "33333333-3333-4333-8333-333333333333"; +const version = "44444444-4444-4444-8444-444444444444"; +const input = { action: "list_evidence_versions", request_id: request, organization_id: owner }; +const item = { + source_version_id: version, + source_id: actor, + source_kind: "customer", + fingerprint: "a".repeat(64), + retrieved_at: "2026-10-09T18:00:00+00:00", + evidence_kinds: ["customer_assertion"], + is_current: true, +}; +const page = { + owner_id: owner, + request_id: request, + versions: [item], + has_more: false, + next_id: null, +}; +function setup(value: unknown = page) { + return { + rpc: vi.fn(async (_name: string, _params: Record) => value), + dispatch: vi.fn(), + authorize: vi.fn(async () => ({ accountId: actor, ownerId: owner, organizationId: owner })), + }; +} +it("reads retained evidence using the authenticated actor without dispatch", async () => { + const deps = setup(); + expect(await processContextOperation(actor, input, deps)).toEqual(page); + expect(deps.authorize).toHaveBeenCalledExactlyOnceWith(actor, owner); + expect(deps.rpc).toHaveBeenCalledExactlyOnceWith("list_context_request_evidence_versions", { + p_actor: actor, + p_owner: owner, + p_request: request, + p_after: null, + }); + expect(deps.dispatch).not.toHaveBeenCalled(); +}); +it("returns an empty final page", async () => { + const value = { ...page, versions: [] }; + expect(await processContextOperation(actor, input, setup(value))).toEqual(value); +}); +it("denies revoked access before reading", async () => { + const deps = setup(); + deps.authorize.mockRejectedValueOnce(new Error("Access denied")); + await expect(processContextOperation(actor, input, deps)).rejects.toThrow("Access denied"); + expect(deps.rpc).not.toHaveBeenCalled(); +}); +it.each(["account_id", "actor_id", "owner_id", "rights_verified"])( + "rejects injected %s before authorization", + async key => { + const deps = setup(); + await expect( + processContextOperation(actor, { ...input, [key]: owner }, deps), + ).rejects.toThrow(); + expect(deps.authorize).not.toHaveBeenCalled(); + }, +); +it.each([ + { ...page, owner_id: actor }, + { ...page, request_id: actor }, + { ...page, versions: [item, item] }, + { ...page, versions: Array(51).fill(item) }, + { ...page, versions: [{ ...item, evidence_kinds: ["creative_proposal"] }] }, + { ...page, versions: [{ ...item, evidence_kinds: [] }] }, + { ...page, versions: [{ ...item, evidence_kinds: ["observation", "observation"] }] }, + { ...page, versions: [{ ...item, retrieved_at: "yesterday" }] }, + { ...page, versions: [{ ...item, content: "private payload" }] }, + { ...page, versions: [{ ...item, rights_verified: true }] }, + { ...page, next_id: version }, + { ...page, has_more: true, next_id: version }, + { ...page, has_more: true, next_id: null }, +])("rejects unsafe or inconsistent output %#", async value => { + await expect(processContextOperation(actor, input, setup(value))).rejects.toThrow(); +}); +it("passes a valid cursor and checks the full page's last version", async () => { + const versions = Array.from({ length: 50 }, (_, i) => ({ + ...item, + source_version_id: `44444444-4444-4444-8444-${String(i).padStart(12, "0")}`, + })); + const value = { ...page, versions, has_more: true, next_id: versions[49].source_version_id }; + const deps = setup(value); + expect(await processContextOperation(actor, { ...input, after_id: version }, deps)).toEqual( + value, + ); + expect(deps.rpc.mock.calls[0][1].p_after).toBe(version); +}); +it("rejects a returned version equal to the incoming cursor", async () => { + await expect( + processContextOperation(actor, { ...input, after_id: version }, setup()), + ).rejects.toThrow(); +}); diff --git a/lib/context/__tests__/evidenceManifestTransports.test.ts b/lib/context/__tests__/evidenceManifestTransports.test.ts new file mode 100644 index 000000000..a712bfa65 --- /dev/null +++ b/lib/context/__tests__/evidenceManifestTransports.test.ts @@ -0,0 +1,117 @@ +import { expect, it, vi } from "vitest"; +import { NextRequest, NextResponse } from "next/server"; +import { contextOperationHandler } from "../contextOperationHandler"; +import { registerEvidenceManifestTool } from "@/lib/mcp/tools/context/registerEvidenceManifestTool"; +import { callContextRpc } from "@/lib/supabase/context_requests/callContextRpc"; +import { authorizeContextOwner } from "../authorizeContextOwner"; +import { validateAuthContext } from "@/lib/auth/validateAuthContext"; +import { resolveAccountId } from "@/lib/mcp/resolveAccountId"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +vi.mock("../authorizeContextOwner", () => ({ authorizeContextOwner: vi.fn() })); +vi.mock("@/lib/auth/validateAuthContext", () => ({ validateAuthContext: vi.fn() })); +vi.mock("@/lib/mcp/resolveAccountId", () => ({ resolveAccountId: vi.fn() })); +vi.mock("@/lib/supabase/context_requests/callContextRpc", () => ({ callContextRpc: vi.fn() })); +vi.mock("../dispatchContextRequest", () => ({ dispatchContextRequest: vi.fn() })); +vi.mock("../dispatchContextReleaseVerification", () => ({ + dispatchContextReleaseVerification: vi.fn(), +})); +vi.mock("../dispatchContextReleaseTrackIsrcs", () => ({ + dispatchContextReleaseTrackIsrcs: vi.fn(), +})); +const actor = "11111111-1111-4111-8111-111111111111"; +const request = "22222222-2222-4222-8222-222222222222"; +const page = { owner_id: actor, request_id: request, versions: [], has_more: false, next_id: null }; +function setup() { + vi.mocked(validateAuthContext).mockResolvedValue({ accountId: actor } as never); + vi.mocked(resolveAccountId).mockResolvedValue({ accountId: actor, error: null }); + vi.mocked(authorizeContextOwner).mockResolvedValue({ + accountId: actor, + ownerId: actor, + organizationId: null, + }); + vi.mocked(callContextRpc).mockResolvedValue(page); + const registerTool = vi.fn(); + registerEvidenceManifestTool({ registerTool } as never); + return registerTool.mock.calls[0][2]; +} +function http(input: unknown = { action: "list_evidence_versions", request_id: request }) { + return contextOperationHandler( + new NextRequest("http://localhost/api/context", { + method: "POST", + body: JSON.stringify(input), + }), + ); +} +it("HTTP and standard MCP return identical saved metadata through the real domain handler", async () => { + const tool = setup(); + expect(await (await http()).json()).toEqual(page); + const result = await tool({ request_id: request }, {}); + expect(JSON.parse(result.content[0].text)).toEqual(page); + expect(callContextRpc).toHaveBeenLastCalledWith("list_context_request_evidence_versions", { + p_actor: actor, + p_owner: actor, + p_request: request, + p_after: null, + }); +}); +it("both transports withhold malformed backend data", async () => { + const tool = setup(); + vi.mocked(callContextRpc).mockResolvedValue({ ...page, private_content: "secret" }); + expect((await http()).status).toBe(409); + const result = await tool({ request_id: request }, {}); + expect(result.isError).toBe(true); + expect(result.content[0].text).not.toContain("secret"); +}); +it("both transports deny revoked owner authorization", async () => { + const tool = setup(); + vi.mocked(authorizeContextOwner).mockRejectedValue(new Error("secret revoked member")); + expect((await http()).status).toBe(409); + const result = await tool({ request_id: request }, {}); + expect(result.isError).toBe(true); + expect(result.content[0].text).not.toContain("secret"); +}); +it("both transports require authentication", async () => { + const tool = setup(); + vi.mocked(validateAuthContext).mockResolvedValue(NextResponse.json({}, { status: 401 })); + vi.mocked(resolveAccountId).mockResolvedValue({ + accountId: null, + error: "Authentication required", + }); + expect((await http()).status).toBe(401); + expect((await tool({ request_id: request }, {})).isError).toBe(true); +}); +it("both transports reject actor overrides", async () => { + const tool = setup(); + expect( + (await http({ action: "list_evidence_versions", request_id: request, account_id: actor })) + .status, + ).toBe(400); + expect((await tool({ request_id: request, account_id: actor }, {})).isError).toBe(true); +}); +it("discovers and executes the concrete tool using the real MCP SDK", async () => { + setup(); + const server = new McpServer({ name: "evidence-test", version: "1" }); + registerEvidenceManifestTool(server); + const client = new Client({ name: "fixture", version: "1" }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + try { + const { tools } = await client.listTools(); + expect(tools[0].inputSchema.required).toEqual(["request_id"]); + expect(tools[0].inputSchema.properties).toHaveProperty("after_id"); + expect(tools[0].inputSchema.properties).not.toHaveProperty("account_id"); + expect(tools[0].annotations?.readOnlyHint).toBe(true); + const result = await client.callTool({ + name: "list_context_evidence_versions", + arguments: { request_id: request }, + }); + expect(result.isError).not.toBe(true); + expect(JSON.parse((result.content as { text: string }[])[0].text)).toEqual(page); + } finally { + await client.close(); + await server.close(); + } +}); diff --git a/lib/context/evidenceManifestSchemas.ts b/lib/context/evidenceManifestSchemas.ts new file mode 100644 index 000000000..418f45208 --- /dev/null +++ b/lib/context/evidenceManifestSchemas.ts @@ -0,0 +1,38 @@ +import { z } from "zod"; + +export const evidenceManifestOperationSchema = z.strictObject({ + action: z.literal("list_evidence_versions"), + request_id: z.uuid(), + organization_id: z.uuid().optional(), + after_id: z.uuid().optional(), +}); +export const evidenceManifestPageSchema = z.strictObject({ + request_id: z.uuid(), + owner_id: z.uuid(), + versions: z + .array( + z.strictObject({ + source_version_id: z.uuid(), + source_id: z.uuid(), + source_kind: z.enum([ + "provider_metadata", + "audio", + "lyrics", + "artwork", + "web", + "social", + "customer", + ]), + fingerprint: z.string().length(64), + retrieved_at: z.iso.datetime({ offset: true }), + evidence_kinds: z + .array(z.enum(["observation", "estimate", "interpretation", "customer_assertion"])) + .min(1) + .max(4), + is_current: z.boolean(), + }), + ) + .max(50), + has_more: z.boolean(), + next_id: z.uuid().nullable(), +}); diff --git a/lib/context/processContextOperation.ts b/lib/context/processContextOperation.ts index 1a6587d44..bb1cf30f8 100644 --- a/lib/context/processContextOperation.ts +++ b/lib/context/processContextOperation.ts @@ -1,5 +1,7 @@ import { releaseCaseOperationSchemas } from "./releaseCaseOperationSchemas"; import { processReleaseCaseOperation } from "./processReleaseCaseOperation"; +import { evidenceManifestOperationSchema } from "./evidenceManifestSchemas"; +import { processEvidenceManifestOperation } from "./processEvidenceManifestOperation"; import { createHash } from "node:crypto"; import { z } from "zod"; import { authorizeContextOwner } from "./authorizeContextOwner"; @@ -19,6 +21,7 @@ const briefFields = { }; export const contextOperationSchema = z.discriminatedUnion("action", [ + evidenceManifestOperationSchema, ...releaseCaseOperationSchemas, z.strictObject({ action: z.literal("save_brief"), @@ -192,6 +195,8 @@ export async function processContextOperation( accountId, args.organization_id, ); + if (args.action === "list_evidence_versions") + return processEvidenceManifestOperation(accountId, ownerId, args, deps.rpc); if ( args.action === "list_release_cases" || args.action === "read_release_case" || diff --git a/lib/context/processEvidenceManifestOperation.ts b/lib/context/processEvidenceManifestOperation.ts new file mode 100644 index 000000000..35a2629e5 --- /dev/null +++ b/lib/context/processEvidenceManifestOperation.ts @@ -0,0 +1,37 @@ +import { + evidenceManifestPageSchema, + evidenceManifestOperationSchema, +} from "./evidenceManifestSchemas"; +import type { z } from "zod"; + +/** Metadata discovery only; the database independently checks current actor and request access. */ +export async function processEvidenceManifestOperation( + actor: string, + owner: string, + args: z.infer, + rpc: (name: string, params: Record) => Promise, +) { + const page = evidenceManifestPageSchema.parse( + await rpc("list_context_request_evidence_versions", { + p_actor: actor, + p_owner: owner, + p_request: args.request_id, + p_after: args.after_id ?? null, + }), + ); + const ids = page.versions.map(version => version.source_version_id); + if ( + page.owner_id !== owner || + page.request_id !== args.request_id || + new Set(ids).size !== ids.length || + ids.includes(args.after_id ?? "") || + page.versions.some( + version => new Set(version.evidence_kinds).size !== version.evidence_kinds.length, + ) || + (page.has_more + ? page.versions.length !== 50 || page.next_id !== ids.at(-1) + : page.next_id !== null) + ) + throw new Error("Evidence manifest unavailable"); + return page; +} diff --git a/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts b/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts index 867b4cd23..4819c46f7 100644 --- a/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts +++ b/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts @@ -33,12 +33,18 @@ it("discovers the entire delegated catalog over the real MCP SDK", async () => { ), "get_daily_email_status", "set_daily_email_status", - ...Object.values(contextToolOperations).map(operation => operation.name), + ...Object.values(contextToolOperations) + .filter(operation => !("delegated" in operation && operation.delegated === false)) + .map(operation => operation.name), ].sort(), ); for (const tool of tools) expect(tool.inputSchema.properties).not.toHaveProperty("account_id"); expect(tools).toHaveLength(77); for (const operation of Object.values(contextToolOperations)) { + if ("delegated" in operation && operation.delegated === false) { + expect(tools.map(tool => tool.name)).not.toContain(operation.name); + continue; + } const tool = tools.find(tool => tool.name === operation.name)!; expect(Object.keys(tool.inputSchema.properties ?? {}).length).toBeGreaterThan(0); expect(tool.inputSchema.properties).not.toHaveProperty("action"); @@ -49,6 +55,7 @@ it("discovers the entire delegated catalog over the real MCP SDK", async () => { expect(JSON.stringify(artist)).not.toMatch(/system prompt|copy.*conversation/i); expect(tools.map(tool => tool.name)).not.toContain("list_professional_roster"); expect(tools.map(tool => tool.name)).not.toContain("confirm_professional_roster"); + expect(tools.map(tool => tool.name)).not.toContain("list_context_evidence_versions"); expect( tools.find(tool => tool.name === "send_email")!.inputSchema.required ?? [], ).not.toContain("room_id"); diff --git a/lib/mcp/oauth/contextToolOperations.ts b/lib/mcp/oauth/contextToolOperations.ts index d729c64ca..a68ec4c7c 100644 --- a/lib/mcp/oauth/contextToolOperations.ts +++ b/lib/mcp/oauth/contextToolOperations.ts @@ -4,6 +4,13 @@ import type { contextOperationSchema } from "@/lib/context/processContextOperati type Action = z.infer["action"]; /** Each public operation has its own schema and permission classification. */ export const contextToolOperations = { + list_evidence_versions: { + name: "list_music_evidence_versions", + description: + "List retained source versions for a saved request. Excluded pending organization-grant audit.", + readOnly: true, + delegated: false, + }, list_release_cases: { name: "list_music_release_cases", description: "List saved release cases and their review status.", @@ -148,4 +155,7 @@ export const contextToolOperations = { "Compile a creative direction or playlist pitch brief from saved music context without saving a snapshot.", readOnly: true, }, -} satisfies Record; +} satisfies Record< + Action, + { name: string; description: string; readOnly: boolean; delegated?: boolean } +>; diff --git a/lib/mcp/oauth/registerFullOAuthTools.ts b/lib/mcp/oauth/registerFullOAuthTools.ts index 69a26a8b0..289739b45 100644 --- a/lib/mcp/oauth/registerFullOAuthTools.ts +++ b/lib/mcp/oauth/registerFullOAuthTools.ts @@ -37,7 +37,14 @@ export function registerFullOAuthTools( ) => { // Credentials never belong in model-visible output. Professional roster tools // remain excluded until their delegated organization-grant audit is complete. - if (["get_api_key", "list_professional_roster", "confirm_professional_roster"].includes(name)) + if ( + [ + "get_api_key", + "list_professional_roster", + "confirm_professional_roster", + "list_context_evidence_versions", + ].includes(name) + ) return; if (name === "context" && !operation) { if (!(config.inputSchema instanceof z.ZodDiscriminatedUnion)) @@ -47,6 +54,7 @@ export function registerFullOAuthTools( const action = option.shape.action.value as keyof typeof contextToolOperations; const metadata = contextToolOperations[action]; if (!metadata) throw new Error(`Missing delegated context policy for ${action}`); + if ("delegated" in metadata && metadata.delegated === false) continue; register( name, { ...config, description: metadata.description, inputSchema: option }, diff --git a/lib/mcp/tools/context/registerEvidenceManifestTool.ts b/lib/mcp/tools/context/registerEvidenceManifestTool.ts new file mode 100644 index 000000000..b61a86a7f --- /dev/null +++ b/lib/mcp/tools/context/registerEvidenceManifestTool.ts @@ -0,0 +1,52 @@ +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { McpAuthInfo } from "@/lib/mcp/verifyApiKey"; +import { resolveAccountId } from "@/lib/mcp/resolveAccountId"; +import { getToolResultSuccess } from "@/lib/mcp/getToolResultSuccess"; +import { getToolResultError } from "@/lib/mcp/getToolResultError"; +import { evidenceManifestOperationSchema } from "@/lib/context/evidenceManifestSchemas"; +import { processContextOperation } from "@/lib/context/processContextOperation"; +import { callContextRpc } from "@/lib/supabase/context_requests/callContextRpc"; + +/** Concrete discoverable schema; shares HTTP authorization and typed metadata validation. */ +export function registerEvidenceManifestTool(server: McpServer) { + const schema = evidenceManifestOperationSchema.omit({ action: true }); + server.registerTool( + "list_context_evidence_versions", + { + description: + "List up to 50 retained evidence versions for a saved request without collection. Pass returned next_id as after_id when has_more is true. Versions distinguish submitted assertions from observations and current from historical evidence; presence never proves rights. Each page rechecks access and withdrawals, and is not a frozen export or action authorization.", + inputSchema: schema, + annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, + }, + async (input, extra) => { + try { + const args = schema.parse(input); + const { accountId, error } = await resolveAccountId({ + authInfo: extra.authInfo as McpAuthInfo | undefined, + accountIdOverride: undefined, + }); + if (error || !accountId) + return { ...getToolResultError("Authentication required"), isError: true }; + return getToolResultSuccess( + await processContextOperation( + accountId, + { ...args, action: "list_evidence_versions" }, + { + rpc: callContextRpc, + dispatch: async () => { + throw new Error("Evidence discovery cannot dispatch collection"); + }, + }, + ), + ); + } catch { + return { + ...getToolResultError( + "Evidence manifest unavailable. Check workspace, request and cursor access.", + ), + isError: true, + }; + } + }, + ); +} diff --git a/lib/mcp/tools/index.ts b/lib/mcp/tools/index.ts index 5b628153c..a153cba5f 100644 --- a/lib/mcp/tools/index.ts +++ b/lib/mcp/tools/index.ts @@ -18,6 +18,7 @@ import { registerAllFileTools } from "./files"; import { registerAllFlamingoTools } from "./flamingo"; import { registerAllYouTubeTools } from "./youtube"; import { registerTranscribeTools } from "./transcribe"; +import { registerEvidenceManifestTool } from "./context/registerEvidenceManifestTool"; import { registerSendEmailTool } from "./registerSendEmailTool"; import { registerAllArtistTools } from "./artists"; import { registerAllChatsTools } from "./chats"; @@ -35,6 +36,7 @@ import { registerAllPulseTools } from "./pulse"; export const registerAllTools = (server: McpServer): void => { registerAllSitesTools(server); registerContextTool(server); + registerEvidenceManifestTool(server); registerAllArtistTools(server); registerAllArtistSocialsTools(server); registerAllCatalogTools(server); diff --git a/scripts/mcp-oauth/tool-policy.json b/scripts/mcp-oauth/tool-policy.json index a48a29e3b..8ee93b932 100644 --- a/scripts/mcp-oauth/tool-policy.json +++ b/scripts/mcp-oauth/tool-policy.json @@ -493,5 +493,14 @@ ], "status": "requires OAuth execution audit before enablement", "authorizationWork": "Bind account and requested resources to the selected grant context; enforce scopes, current access, and redacted errors at execution. Verify billing owner, entitlement, credit checks, and bounded retry behavior before starting provider work." + }, + { + "name": "list_context_evidence_versions", + "file": "lib/mcp/tools/context/registerEvidenceManifestTool.ts", + "scopes": [ + "mcp:read" + ], + "status": "excluded pending organization-grant execution audit", + "authorizationWork": "Retained private evidence: bind actor and workspace and recheck request/version withdrawals. Exclude dedicated tool and combined Context action from delegated OAuth until audited." } ] From 72d7e678ef54bb02961898214645ac6dcdeab56c Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:04:53 -0400 Subject: [PATCH 2/5] Connect evidence RPC and tighten provenance validation --- lib/context/EVIDENCE-MANIFEST.md | 17 +++++++ lib/context/README.md | 18 +------- .../evidenceManifestOperation.test.ts | 2 + .../evidenceManifestTransports.test.ts | 4 +- lib/context/evidenceManifestSchemas.ts | 2 +- .../context/registerEvidenceManifestTool.ts | 5 ++- .../__tests__/evidenceManifestRpc.test.ts | 44 +++++++++++++++++++ .../context_requests/callContextRpc.ts | 1 + scripts/mcp-oauth/tool-policy.json | 2 +- 9 files changed, 75 insertions(+), 20 deletions(-) create mode 100644 lib/context/EVIDENCE-MANIFEST.md create mode 100644 lib/supabase/context_requests/__tests__/evidenceManifestRpc.test.ts diff --git a/lib/context/EVIDENCE-MANIFEST.md b/lib/context/EVIDENCE-MANIFEST.md new file mode 100644 index 000000000..023380a86 --- /dev/null +++ b/lib/context/EVIDENCE-MANIFEST.md @@ -0,0 +1,17 @@ +# Retained evidence discovery + +`POST /api/context` with `action: "list_evidence_versions"`, `request_id`, +optional `organization_id` and `after_id` reads an authorized saved request's +retained source-version metadata. Standard MCP exposes the same operation as +`list_context_evidence_versions` with a concrete schema and no `action` parameter. +Pass returned `next_id` as `after_id` while `has_more` is true (up to 50 versions +per page). Each page rechecks access and withdrawal; pages are not a frozen export. + +The typed response distinguishes customer assertions from observations and +current document inputs from retained history. It exposes no source contents, +storage paths, signed URLs or rights decisions. It invokes no collection, paid +provider or roster operation. Both the dedicated tool and delegated expansion of +the combined action are excluded from OAuth pending the organization-grant audit. +Requires Database PR92's `list_context_request_evidence_versions`. This feature +has not been released. It performs no original-file registration, parsing or +assessment. diff --git a/lib/context/README.md b/lib/context/README.md index 42af3e2e6..af4822034 100644 --- a/lib/context/README.md +++ b/lib/context/README.md @@ -249,19 +249,5 @@ already-running work before rejecting and starts no further modules once the uncertainty is known. RPC errors remain attached as internal causes; the public error message does not include private database diagnostics. -### Retained evidence discovery - -`POST /api/context` with `action: "list_evidence_versions"`, `request_id`, -optional `organization_id` and `after_id` reads an authorized saved request's -retained source-version metadata. Standard MCP exposes the same operation as -`list_context_evidence_versions` with a concrete schema and no `action` parameter. -Pass returned `next_id` as `after_id` while `has_more` is true (up to 50 versions -per page). Each page rechecks access and withdrawal; pages are not a frozen export. - -The typed response distinguishes customer assertions from observations and -current document inputs from retained history. It exposes no source contents, -storage paths, signed URLs or rights decisions. It invokes no collection, paid -provider or roster operation. Both the dedicated tool and delegated expansion of -the combined action are excluded from OAuth pending the organization-grant audit. -Requires Database PR92's `list_context_request_evidence_versions`; it is not yet -a production capability, original-file registration, parsing or an assessment. + +See [retained evidence discovery](./EVIDENCE-MANIFEST.md) for scoped source-version listing. diff --git a/lib/context/__tests__/evidenceManifestOperation.test.ts b/lib/context/__tests__/evidenceManifestOperation.test.ts index 5ecea73b4..59bb8a829 100644 --- a/lib/context/__tests__/evidenceManifestOperation.test.ts +++ b/lib/context/__tests__/evidenceManifestOperation.test.ts @@ -70,6 +70,8 @@ it.each([ { ...page, versions: [{ ...item, evidence_kinds: [] }] }, { ...page, versions: [{ ...item, evidence_kinds: ["observation", "observation"] }] }, { ...page, versions: [{ ...item, retrieved_at: "yesterday" }] }, + { ...page, versions: [{ ...item, fingerprint: "z".repeat(64) }] }, + { ...page, versions: [{ ...item, fingerprint: "A".repeat(64) }] }, { ...page, versions: [{ ...item, content: "private payload" }] }, { ...page, versions: [{ ...item, rights_verified: true }] }, { ...page, next_id: version }, diff --git a/lib/context/__tests__/evidenceManifestTransports.test.ts b/lib/context/__tests__/evidenceManifestTransports.test.ts index a712bfa65..42840e601 100644 --- a/lib/context/__tests__/evidenceManifestTransports.test.ts +++ b/lib/context/__tests__/evidenceManifestTransports.test.ts @@ -80,7 +80,9 @@ it("both transports require authentication", async () => { error: "Authentication required", }); expect((await http()).status).toBe(401); - expect((await tool({ request_id: request }, {})).isError).toBe(true); + const result = await tool({ request_id: request }, {}); + expect(result.isError).toBe(true); + expect(result.content[0].text).toContain("Recoup API key"); }); it("both transports reject actor overrides", async () => { const tool = setup(); diff --git a/lib/context/evidenceManifestSchemas.ts b/lib/context/evidenceManifestSchemas.ts index 418f45208..d9877af0c 100644 --- a/lib/context/evidenceManifestSchemas.ts +++ b/lib/context/evidenceManifestSchemas.ts @@ -23,7 +23,7 @@ export const evidenceManifestPageSchema = z.strictObject({ "social", "customer", ]), - fingerprint: z.string().length(64), + fingerprint: z.string().regex(/^[a-f0-9]{64}$/), retrieved_at: z.iso.datetime({ offset: true }), evidence_kinds: z .array(z.enum(["observation", "estimate", "interpretation", "customer_assertion"])) diff --git a/lib/mcp/tools/context/registerEvidenceManifestTool.ts b/lib/mcp/tools/context/registerEvidenceManifestTool.ts index b61a86a7f..6d66186df 100644 --- a/lib/mcp/tools/context/registerEvidenceManifestTool.ts +++ b/lib/mcp/tools/context/registerEvidenceManifestTool.ts @@ -26,7 +26,10 @@ export function registerEvidenceManifestTool(server: McpServer) { accountIdOverride: undefined, }); if (error || !accountId) - return { ...getToolResultError("Authentication required"), isError: true }; + return { + ...getToolResultError("Authentication required. Connect using a Recoup API key."), + isError: true, + }; return getToolResultSuccess( await processContextOperation( accountId, diff --git a/lib/supabase/context_requests/__tests__/evidenceManifestRpc.test.ts b/lib/supabase/context_requests/__tests__/evidenceManifestRpc.test.ts new file mode 100644 index 000000000..2c0e50960 --- /dev/null +++ b/lib/supabase/context_requests/__tests__/evidenceManifestRpc.test.ts @@ -0,0 +1,44 @@ +import { expect, it, vi } from "vitest"; +import { callContextRpc } from "../callContextRpc"; +import { processContextOperation } from "@/lib/context/processContextOperation"; +const rpc = vi.hoisted(() => vi.fn()); +vi.mock("../../serverClient", () => ({ default: { rpc } })); +vi.mock("@/lib/context/authorizeContextOwner", () => ({ authorizeContextOwner: vi.fn() })); +const actor = "11111111-1111-4111-8111-111111111111"; +const request = "22222222-2222-4222-8222-222222222222"; +it("connects evidence discovery through the real RPC adapter", async () => { + const page = { + request_id: request, + owner_id: actor, + versions: [], + has_more: false, + next_id: null, + }; + rpc.mockResolvedValue({ data: page, error: null }); + const dispatch = vi.fn(); + expect( + await processContextOperation( + actor, + { action: "list_evidence_versions", request_id: request }, + { + rpc: callContextRpc, + dispatch, + authorize: async () => ({ accountId: actor, ownerId: actor, organizationId: null }), + }, + ), + ).toEqual(page); + expect(rpc).toHaveBeenLastCalledWith("list_context_request_evidence_versions", { + p_actor: actor, + p_owner: actor, + p_request: request, + p_after: null, + }); + expect(dispatch).not.toHaveBeenCalled(); +}); +it("does not expose the unbounded helper through the adapter", async () => { + rpc.mockClear(); + await expect(callContextRpc("context_request_evidence_versions", {})).rejects.toThrow( + "Unknown context operation", + ); + expect(rpc).not.toHaveBeenCalled(); +}); diff --git a/lib/supabase/context_requests/callContextRpc.ts b/lib/supabase/context_requests/callContextRpc.ts index dab3f941d..284bc521f 100644 --- a/lib/supabase/context_requests/callContextRpc.ts +++ b/lib/supabase/context_requests/callContextRpc.ts @@ -7,6 +7,7 @@ export async function callContextRpc( params: Record, ): Promise { const allowed = [ + "list_context_request_evidence_versions", "list_context_release_cases", "read_context_release_case", "review_context_release_case", diff --git a/scripts/mcp-oauth/tool-policy.json b/scripts/mcp-oauth/tool-policy.json index 8ee93b932..d4548caab 100644 --- a/scripts/mcp-oauth/tool-policy.json +++ b/scripts/mcp-oauth/tool-policy.json @@ -501,6 +501,6 @@ "mcp:read" ], "status": "excluded pending organization-grant execution audit", - "authorizationWork": "Retained private evidence: bind actor and workspace and recheck request/version withdrawals. Exclude dedicated tool and combined Context action from delegated OAuth until audited." + "authorizationWork": "Retained private evidence: bind actor and workspace, scope after_id to a visible source version in the authorized request, and recheck request/version withdrawals. Exclude dedicated tool and combined Context action from delegated OAuth until audited." } ] From e95a80009b258b5195028a149f08b2c3e4aa9678 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:19:10 -0400 Subject: [PATCH 3/5] Add authenticated GET evidence metadata endpoint --- app/api/context/evidence/route.ts | 15 ++++ lib/context/EVIDENCE-MANIFEST.md | 9 +- .../__tests__/evidenceManifestGet.test.ts | 90 +++++++++++++++++++ lib/context/getEvidenceManifestHandler.ts | 36 ++++++++ lib/context/validateEvidenceManifestQuery.ts | 20 +++++ 5 files changed, 167 insertions(+), 3 deletions(-) create mode 100644 app/api/context/evidence/route.ts create mode 100644 lib/context/__tests__/evidenceManifestGet.test.ts create mode 100644 lib/context/getEvidenceManifestHandler.ts create mode 100644 lib/context/validateEvidenceManifestQuery.ts diff --git a/app/api/context/evidence/route.ts b/app/api/context/evidence/route.ts new file mode 100644 index 000000000..2261aa8b2 --- /dev/null +++ b/app/api/context/evidence/route.ts @@ -0,0 +1,15 @@ +import { getEvidenceManifestHandler } from "@/lib/context/getEvidenceManifestHandler"; +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; + +/** Read retained evidence metadata without collection or mutation. */ +export const GET = getEvidenceManifestHandler; + +/** + * Permit authenticated browser clients to preflight the read endpoint. + * + * @returns Empty CORS preflight response. + */ +export function OPTIONS() { + return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); +} diff --git a/lib/context/EVIDENCE-MANIFEST.md b/lib/context/EVIDENCE-MANIFEST.md index 023380a86..0b9ca871d 100644 --- a/lib/context/EVIDENCE-MANIFEST.md +++ b/lib/context/EVIDENCE-MANIFEST.md @@ -1,8 +1,11 @@ # Retained evidence discovery -`POST /api/context` with `action: "list_evidence_versions"`, `request_id`, -optional `organization_id` and `after_id` reads an authorized saved request's -retained source-version metadata. Standard MCP exposes the same operation as +`GET /api/context/evidence?request_id=` reads retained source-version +metadata for an authorized saved request. Optional query parameters are +`organization_id` and `after_id`. Unknown or repeated fields are rejected; +responses use `Cache-Control: private, no-store`. The existing Context command +surface also accepts `POST /api/context` with `action: "list_evidence_versions"` +and the same fields. Standard MCP exposes the same operation as `list_context_evidence_versions` with a concrete schema and no `action` parameter. Pass returned `next_id` as `after_id` while `has_more` is true (up to 50 versions per page). Each page rechecks access and withdrawal; pages are not a frozen export. diff --git a/lib/context/__tests__/evidenceManifestGet.test.ts b/lib/context/__tests__/evidenceManifestGet.test.ts new file mode 100644 index 000000000..579099fcb --- /dev/null +++ b/lib/context/__tests__/evidenceManifestGet.test.ts @@ -0,0 +1,90 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import { NextRequest, NextResponse } from "next/server"; +import { GET, OPTIONS } from "@/app/api/context/evidence/route"; +import { authorizeContextOwner } from "../authorizeContextOwner"; +import { validateAuthContext } from "@/lib/auth/validateAuthContext"; +const rpc = vi.hoisted(() => vi.fn()); +vi.mock("@/lib/supabase/serverClient", () => ({ default: { rpc } })); +vi.mock("../authorizeContextOwner", () => ({ authorizeContextOwner: vi.fn() })); +vi.mock("@/lib/auth/validateAuthContext", () => ({ validateAuthContext: vi.fn() })); +const actor = "11111111-1111-4111-8111-111111111111"; +const request = "22222222-2222-4222-8222-222222222222"; +const cursor = "33333333-3333-4333-8333-333333333333"; +const page = { owner_id: actor, request_id: request, versions: [], has_more: false, next_id: null }; +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(validateAuthContext).mockResolvedValue({ accountId: actor } as never); + vi.mocked(authorizeContextOwner).mockResolvedValue({ + accountId: actor, + ownerId: actor, + organizationId: null, + }); + rpc.mockResolvedValue({ data: page, error: null }); +}); +function get(query = `request_id=${request}`) { + return GET(new NextRequest(`http://localhost/api/context/evidence?${query}`)); +} +it("GET reaches the real bounded RPC adapter and prevents response caching", async () => { + const response = await get(); + expect(response.status).toBe(200); + expect(await response.json()).toEqual(page); + expect(response.headers.get("cache-control")).toBe("private, no-store"); + expect(rpc).toHaveBeenCalledExactlyOnceWith("list_context_request_evidence_versions", { + p_actor: actor, + p_owner: actor, + p_request: request, + p_after: null, + }); +}); +it.each([ + "", + "request_id=bad", + `request_id=${request}&request_id=${request}`, + `request_id=${request}&account_id=${actor}`, + `request_id=${request}&action=ingest`, + `request_id=${request}&after_id=bad`, +])("rejects invalid or ambiguous query %s before authorization", async query => { + expect((await get(query)).status).toBe(400); + expect(validateAuthContext).not.toHaveBeenCalled(); + expect(rpc).not.toHaveBeenCalled(); +}); +it("uses the exact cursor without triggering collection", async () => { + expect((await get(`request_id=${request}&after_id=${cursor}`)).status).toBe(200); + expect(rpc.mock.calls[0][1].p_after).toBe(cursor); +}); +it("passes the selected organization to both authorization layers", async () => { + vi.mocked(authorizeContextOwner).mockResolvedValue({ + accountId: actor, + ownerId: cursor, + organizationId: cursor, + }); + rpc.mockResolvedValue({ data: { ...page, owner_id: cursor }, error: null }); + expect((await get(`request_id=${request}&organization_id=${cursor}`)).status).toBe(200); + expect(validateAuthContext).toHaveBeenCalledWith(expect.any(NextRequest), { + organizationId: cursor, + }); + expect(authorizeContextOwner).toHaveBeenCalledWith(actor, cursor); + expect(rpc.mock.calls[0][1].p_owner).toBe(cursor); +}); +it("supports browser authorization preflight without reading evidence", async () => { + const response = await OPTIONS(); + expect(response.headers.get("access-control-allow-methods")).toContain("GET"); + expect(response.headers.get("access-control-allow-headers")).toContain("Authorization"); + expect(rpc).not.toHaveBeenCalled(); +}); +it("requires authenticated access", async () => { + vi.mocked(validateAuthContext).mockResolvedValue(NextResponse.json({}, { status: 401 })); + expect((await get()).status).toBe(401); + expect(rpc).not.toHaveBeenCalled(); +}); +it("withholds revoked scope and malformed private response data", async () => { + vi.mocked(authorizeContextOwner).mockRejectedValueOnce(new Error("private revoked member")); + const denied = await get(); + expect(denied.status).toBe(409); + expect(await denied.text()).not.toContain("private revoked member"); + expect(rpc).not.toHaveBeenCalled(); + rpc.mockResolvedValue({ data: { ...page, secret_content: "private secret" }, error: null }); + const malformed = await get(); + expect(malformed.status).toBe(409); + expect(await malformed.text()).not.toContain("private secret"); +}); diff --git a/lib/context/getEvidenceManifestHandler.ts b/lib/context/getEvidenceManifestHandler.ts new file mode 100644 index 000000000..9448663f7 --- /dev/null +++ b/lib/context/getEvidenceManifestHandler.ts @@ -0,0 +1,36 @@ +import { NextRequest, NextResponse } from "next/server"; +import { validateEvidenceManifestQuery } from "./validateEvidenceManifestQuery"; +import { validateAuthContext } from "@/lib/auth/validateAuthContext"; +import { processContextOperation } from "./processContextOperation"; +import { callContextRpc } from "@/lib/supabase/context_requests/callContextRpc"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; + +/** Conventional HTTP retrieval with the same scoped domain operation as standard MCP. */ +export async function getEvidenceManifestHandler(request: NextRequest) { + const parsed = validateEvidenceManifestQuery(request.nextUrl.searchParams); + if (parsed instanceof NextResponse) return parsed; + const auth = await validateAuthContext(request, { organizationId: parsed.organization_id }); + if (auth instanceof NextResponse) { + auth.headers.set("Cache-Control", "private, no-store"); + return auth; + } + const headers = { ...getCorsHeaders(), "Cache-Control": "private, no-store" }; + try { + const result = await processContextOperation( + auth.accountId, + { ...parsed, action: "list_evidence_versions" }, + { + rpc: callContextRpc, + dispatch: async () => { + throw new Error("Evidence discovery cannot dispatch collection"); + }, + }, + ); + return NextResponse.json(result, { headers }); + } catch { + return NextResponse.json( + { error: "Evidence manifest unavailable. Check workspace, request and cursor access." }, + { status: 409, headers }, + ); + } +} diff --git a/lib/context/validateEvidenceManifestQuery.ts b/lib/context/validateEvidenceManifestQuery.ts new file mode 100644 index 000000000..9dfe063ff --- /dev/null +++ b/lib/context/validateEvidenceManifestQuery.ts @@ -0,0 +1,20 @@ +import { NextResponse } from "next/server"; +import { evidenceManifestOperationSchema } from "./evidenceManifestSchemas"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; + +/** Strict retrieval parameters; repeated fields cannot choose a different scope or cursor. */ +export function validateEvidenceManifestQuery(query: URLSearchParams) { + const keys = [...query.keys()]; + const parsed = evidenceManifestOperationSchema + .omit({ action: true }) + .safeParse(Object.fromEntries(query)); + return parsed.success && new Set(keys).size === keys.length + ? parsed.data + : NextResponse.json( + { error: "Invalid evidence query" }, + { + status: 400, + headers: { ...getCorsHeaders(), "Cache-Control": "private, no-store" }, + }, + ); +} From 05b7e91111ad736632c6e4ebeb86fb0806a91d21 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:24:10 -0400 Subject: [PATCH 4/5] Throttle authenticated evidence GET requests with shared limiter --- lib/context/EVIDENCE-MANIFEST.md | 2 +- .../__tests__/evidenceManifestGet.test.ts | 5 +++ .../evidenceManifestThrottle.test.ts | 44 +++++++++++++++++++ lib/context/checkEvidenceReadRateLimit.ts | 32 ++++++++++++++ lib/context/getEvidenceManifestHandler.ts | 3 ++ 5 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 lib/context/__tests__/evidenceManifestThrottle.test.ts create mode 100644 lib/context/checkEvidenceReadRateLimit.ts diff --git a/lib/context/EVIDENCE-MANIFEST.md b/lib/context/EVIDENCE-MANIFEST.md index 0b9ca871d..94a91dbec 100644 --- a/lib/context/EVIDENCE-MANIFEST.md +++ b/lib/context/EVIDENCE-MANIFEST.md @@ -3,7 +3,7 @@ `GET /api/context/evidence?request_id=` reads retained source-version metadata for an authorized saved request. Optional query parameters are `organization_id` and `after_id`. Unknown or repeated fields are rejected; -responses use `Cache-Control: private, no-store`. The existing Context command +responses use `Cache-Control: private, no-store`. GET allows 120 requests per authenticated account per 60-second window across cursors/workspaces using the existing shared database limiter. Exhaustion returns 429 with `Retry-After`; limiter failure returns 503 before evidence access. This does not establish a cross-transport quota for POST or MCP. The existing Context command surface also accepts `POST /api/context` with `action: "list_evidence_versions"` and the same fields. Standard MCP exposes the same operation as `list_context_evidence_versions` with a concrete schema and no `action` parameter. diff --git a/lib/context/__tests__/evidenceManifestGet.test.ts b/lib/context/__tests__/evidenceManifestGet.test.ts index 579099fcb..c93c6949f 100644 --- a/lib/context/__tests__/evidenceManifestGet.test.ts +++ b/lib/context/__tests__/evidenceManifestGet.test.ts @@ -3,6 +3,10 @@ import { NextRequest, NextResponse } from "next/server"; import { GET, OPTIONS } from "@/app/api/context/evidence/route"; import { authorizeContextOwner } from "../authorizeContextOwner"; import { validateAuthContext } from "@/lib/auth/validateAuthContext"; +import { consumeOAuthRateLimit } from "@/lib/supabase/oauth_rate_limits/consumeOAuthRateLimit"; +vi.mock("@/lib/supabase/oauth_rate_limits/consumeOAuthRateLimit", () => ({ + consumeOAuthRateLimit: vi.fn(), +})); const rpc = vi.hoisted(() => vi.fn()); vi.mock("@/lib/supabase/serverClient", () => ({ default: { rpc } })); vi.mock("../authorizeContextOwner", () => ({ authorizeContextOwner: vi.fn() })); @@ -13,6 +17,7 @@ const cursor = "33333333-3333-4333-8333-333333333333"; const page = { owner_id: actor, request_id: request, versions: [], has_more: false, next_id: null }; beforeEach(() => { vi.clearAllMocks(); + vi.mocked(consumeOAuthRateLimit).mockResolvedValue(0); vi.mocked(validateAuthContext).mockResolvedValue({ accountId: actor } as never); vi.mocked(authorizeContextOwner).mockResolvedValue({ accountId: actor, diff --git a/lib/context/__tests__/evidenceManifestThrottle.test.ts b/lib/context/__tests__/evidenceManifestThrottle.test.ts new file mode 100644 index 000000000..1be4f833e --- /dev/null +++ b/lib/context/__tests__/evidenceManifestThrottle.test.ts @@ -0,0 +1,44 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import { NextRequest } from "next/server"; +import { GET } from "@/app/api/context/evidence/route"; +import { consumeOAuthRateLimit } from "@/lib/supabase/oauth_rate_limits/consumeOAuthRateLimit"; +const { rpc } = vi.hoisted(() => ({ rpc: vi.fn() })); +vi.mock("@/lib/supabase/serverClient", () => ({ default: { rpc } })); +vi.mock("@/lib/supabase/oauth_rate_limits/consumeOAuthRateLimit", () => ({ + consumeOAuthRateLimit: vi.fn(), +})); +vi.mock("@/lib/auth/validateAuthContext", () => ({ + validateAuthContext: vi.fn(async () => ({ accountId: actor })), +})); +const actor = "11111111-1111-4111-8111-111111111111"; +const request = "22222222-2222-4222-8222-222222222222"; +const cursor = "33333333-3333-4333-8333-333333333333"; +beforeEach(() => vi.clearAllMocks()); +it("shares authenticated actor throttling across cursor and workspace choices", async () => { + vi.mocked(consumeOAuthRateLimit).mockResolvedValue(23); + for (const query of ["", `&after_id=${cursor}&organization_id=${cursor}`]) { + const response = await GET( + new NextRequest(`http://localhost/api/context/evidence?request_id=${request}${query}`), + ); + expect(response.status).toBe(429); + expect(response.headers.get("retry-after")).toBe("23"); + expect(response.headers.get("cache-control")).toBe("private, no-store"); + } + expect(rpc).not.toHaveBeenCalled(); + const calls = vi.mocked(consumeOAuthRateLimit).mock.calls; + expect(calls[0]).toEqual(calls[1]); + expect(calls[0]).toEqual([ + expect.stringMatching(/^[a-f0-9]{64}$/), + [{ key: expect.stringMatching(/^[a-f0-9]{64}$/), limit: 120 }], + ]); + expect(JSON.stringify(calls)).not.toContain(actor); +}); +it("fails closed when shared throttling is unavailable", async () => { + vi.mocked(consumeOAuthRateLimit).mockRejectedValue(new Error("private limiter error")); + const response = await GET( + new NextRequest(`http://localhost/api/context/evidence?request_id=${request}`), + ); + expect(response.status).toBe(503); + expect(await response.text()).not.toContain("private limiter error"); + expect(rpc).not.toHaveBeenCalled(); +}); diff --git a/lib/context/checkEvidenceReadRateLimit.ts b/lib/context/checkEvidenceReadRateLimit.ts new file mode 100644 index 000000000..0f3c29149 --- /dev/null +++ b/lib/context/checkEvidenceReadRateLimit.ts @@ -0,0 +1,32 @@ +import { createHash } from "node:crypto"; +import { NextResponse } from "next/server"; +import { consumeOAuthRateLimit } from "@/lib/supabase/oauth_rate_limits/consumeOAuthRateLimit"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; + +/** Shared GET budget per authenticated account, independent of cursor or workspace. */ +export async function checkEvidenceReadRateLimit(accountId: string) { + const hash = (value: string) => createHash("sha256").update(value).digest("hex"); + const headers = { ...getCorsHeaders(), "Cache-Control": "private, no-store" }; + try { + const retry = await consumeOAuthRateLimit(hash("context-evidence-read:v1"), [ + { key: hash(`context-evidence-read:${accountId}`), limit: 120 }, + ]); + return retry > 0 + ? NextResponse.json( + { error: "Too many evidence requests. Try again later." }, + { + status: 429, + headers: { ...headers, "Retry-After": String(retry) }, + }, + ) + : null; + } catch { + return NextResponse.json( + { error: "Evidence request throttling unavailable. Try again later." }, + { + status: 503, + headers, + }, + ); + } +} diff --git a/lib/context/getEvidenceManifestHandler.ts b/lib/context/getEvidenceManifestHandler.ts index 9448663f7..11ced70bb 100644 --- a/lib/context/getEvidenceManifestHandler.ts +++ b/lib/context/getEvidenceManifestHandler.ts @@ -3,6 +3,7 @@ import { validateEvidenceManifestQuery } from "./validateEvidenceManifestQuery"; import { validateAuthContext } from "@/lib/auth/validateAuthContext"; import { processContextOperation } from "./processContextOperation"; import { callContextRpc } from "@/lib/supabase/context_requests/callContextRpc"; +import { checkEvidenceReadRateLimit } from "./checkEvidenceReadRateLimit"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; /** Conventional HTTP retrieval with the same scoped domain operation as standard MCP. */ @@ -14,6 +15,8 @@ export async function getEvidenceManifestHandler(request: NextRequest) { auth.headers.set("Cache-Control", "private, no-store"); return auth; } + const limited = await checkEvidenceReadRateLimit(auth.accountId); + if (limited) return limited; const headers = { ...getCorsHeaders(), "Cache-Control": "private, no-store" }; try { const result = await processContextOperation( From a8c7fe94776fb7c4fca9a03a6cf5023ff7bc6a74 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:32:27 -0400 Subject: [PATCH 5/5] Assert exact actor key in evidence throttle regression --- lib/context/__tests__/evidenceManifestThrottle.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/context/__tests__/evidenceManifestThrottle.test.ts b/lib/context/__tests__/evidenceManifestThrottle.test.ts index 1be4f833e..d6361bd43 100644 --- a/lib/context/__tests__/evidenceManifestThrottle.test.ts +++ b/lib/context/__tests__/evidenceManifestThrottle.test.ts @@ -29,7 +29,7 @@ it("shares authenticated actor throttling across cursor and workspace choices", expect(calls[0]).toEqual(calls[1]); expect(calls[0]).toEqual([ expect.stringMatching(/^[a-f0-9]{64}$/), - [{ key: expect.stringMatching(/^[a-f0-9]{64}$/), limit: 120 }], + [{ key: "111ac3322f9d42a8895a2198dff3a4c27270e564e79e52d05bb52e05fa958728", limit: 120 }], ]); expect(JSON.stringify(calls)).not.toContain(actor); });