Repository navigation
Expose retained Context evidence discovery #985
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sidneyswift
wants to merge
5
commits into
main
Choose a base branch
from
codex/context-evidence-manifest
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
0529b04
Expose scoped retained evidence discovery through HTTP and MCP
sidneyswift 72d7e67
Connect evidence RPC and tighten provenance validation
sidneyswift e95a800
Add authenticated GET evidence metadata endpoint
sidneyswift 05b7e91
Throttle authenticated evidence GET requests with shared limiter
sidneyswift a8c7fe9
Assert exact actor key in evidence throttle regression
sidneyswift File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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() }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| # Retained evidence discovery | ||
|
|
||
| `GET /api/context/evidence?request_id=<uuid>` 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`. 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. | ||
| 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. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| 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"; | ||
| 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() })); | ||
| 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(consumeOAuthRateLimit).mockResolvedValue(0); | ||
| 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"); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| 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<string, unknown>) => 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, 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 }, | ||
| { ...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(); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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: "111ac3322f9d42a8895a2198dff3a4c27270e564e79e52d05bb52e05fa958728", 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(); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.