Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions app/api/context/evidence/route.ts
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() });
}
20 changes: 20 additions & 0 deletions lib/context/EVIDENCE-MANIFEST.md
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
Comment thread
sidneyswift marked this conversation as resolved.
Resolved
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.
3 changes: 3 additions & 0 deletions lib/context/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,3 +248,6 @@ Both enrichment coordinators propagate this signal. The in-process plan drains
already-running work before rejecting and starts no further modules once the
Comment thread
sidneyswift marked this conversation as resolved.
Resolved
uncertainty is known. RPC errors remain attached as internal causes; the public
error message does not include private database diagnostics.


See [retained evidence discovery](./EVIDENCE-MANIFEST.md) for scoped source-version listing.
95 changes: 95 additions & 0 deletions lib/context/__tests__/evidenceManifestGet.test.ts
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");
});
99 changes: 99 additions & 0 deletions lib/context/__tests__/evidenceManifestOperation.test.ts
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();
});
44 changes: 44 additions & 0 deletions lib/context/__tests__/evidenceManifestThrottle.test.ts
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();
});
Loading
Loading