/** * Shared API suite for RFC-0048 §2 and §5.2 (the PUT of agents' upload links), run on every * SiteGraphStore backend (better-sqlite3 and Miniflare D1 in `test/agent-uploads-api.test.ts`): * the signature, the header checks before any byte, the store's verification, single use, the * other methods, credentials on the PUT, and secret rotation. The rows are opened through the store * here; `create_upload` (rollout step 4) mints them over MCP. */ import { AuditLog } from "@cloudhal/agent-runtime"; import type { Actor } from "@cloudhal/core-contracts"; import { type AgentUpload, type AgentUploadLimits, type SiteGraphStore, seedStarterSite, } from "@cloudhal/core-ts"; import { makePng, text } from "@cloudhal/core-ts/media/fixtures"; import { type SqlDriver, sha256OfBytes } from "@cloudhal/storage"; import { afterAll, beforeEach, describe, expect, it } from "vitest"; import { createApi } from "./app.ts"; import { agentUploadPath, signAgentUpload, signUploadTicket } from "./uploads.ts"; export interface AgentUploadsApiBackend { create(): Promise<{ store: SiteGraphStore; sql: SqlDriver }>; dispose?(): Promise; } const SECRET = "agent-uploads-api-secret-0123456789abcdef"; const robot: Actor = { kind: "agent", id: "agent_apiupload01", name: "Bot" }; const callers: Record = { robot, other: { kind: "agent", id: "agent_apiupload02", name: "Other bot" }, person: { kind: "human", id: "user_apiupload001", name: "Person" }, }; const LIMITS: AgentUploadLimits = { ttlMs: 10 * 60_000, completeMs: 60 * 60_000, maxOpenPerActor: 10, maxOpenPerSite: 50, maxBytes: 25 * 1024 * 1024, }; const CSV = text("station,riders\nKadıköy,412\nBeşiktaş,388\n"); type Json = Record; export function describeAgentUploadsApi(label: string, backend: AgentUploadsApiBackend): void { describe(`API agent upload links: ${label}`, () => { let store: SiteGraphStore; let sql: SqlDriver; let siteId: string; let app: ReturnType; const nowMs = Date.parse("2026-11-29T10:00:00.000Z"); const build = (secret = SECRET) => createApi({ store, audit: new AuditLog(sql), now: () => new Date(nowMs), uploadSecret: secret, resolveActor: async (c) => callers[c.req.header("x-test-caller") ?? ""], }); const open = async (bytes: Uint8Array, mediaType = "text/csv"): Promise => store.uploads.open( siteId, robot, { bytes: bytes.byteLength, mediaType, sha256: await sha256OfBytes(bytes), filename: "f" }, { ...LIMITS, now: new Date(nowMs) }, ); const link = async (u: AgentUpload, secret = SECRET) => agentUploadPath(u, await signAgentUpload(secret, u)); const put = async ( url: string, bytes: Uint8Array, o: { type?: string; length?: string; headers?: Record; method?: string } = {}, ) => { const res = await app.request(url, { method: o.method ?? "PUT", headers: { "content-type": o.type ?? "text/csv", "content-length": o.length ?? String(bytes.byteLength), ...o.headers, }, ...(o.method === "GET" || o.method === "HEAD" ? {} : { body: bytes as Uint8Array }), }); const raw = await res.text(); return { status: res.status, body: (raw ? JSON.parse(raw) : {}) as Json, res }; }; beforeEach(async () => { ({ store, sql } = await backend.create()); siteId = (await seedStarterSite(store, { name: "Agent Uploads", slug: "agent-uploads" })).id; app = build(); }); afterAll(async () => { await backend.dispose?.(); }); it("takes the declared bytes once, audits the receipt without the link, and creates no asset", async () => { const u = await open(CSV); const url = await link(u); const ok = await put(url, CSV); expect(ok.status, JSON.stringify(ok.body)).toBe(200); expect(ok.body).toEqual({ uploadId: u.id, state: "received", sha256: u.sha256, bytes: CSV.byteLength, mediaType: "text/csv", warnings: [], }); expect(await store.getAssetBySha256(siteId, u.sha256)).toBeUndefined(); const again = await put(url, CSV); expect([again.status, again.body.error]).toEqual([410, "upload_used"]); const rows = await new AuditLog(sql).list({ siteId, tool: "asset.upload-received" }); expect(rows).toHaveLength(1); expect(JSON.stringify(rows)).not.toContain("sig="); expect(JSON.stringify(rows)).toContain(robot.id); // complete_upload's store side finishes it. expect((await store.uploads.complete(u.id, robot, new Date(nowMs))).existing).toBe(false); }); it("refuses a missing, wrong or Studio signature, an unknown upload and another site alike", async () => { const u = await open(CSV); const base = `/api/sites/${siteId}/assets/agent-uploads/${u.id}`; for (const sig of ["", "?sig=", `?sig=${"A".repeat(43)}`]) { const r = await put(`${base}${sig}`, CSV); expect([r.status, r.body.error]).toEqual([403, "bad_signature"]); } const studio = await signUploadTicket(SECRET, { id: u.id, siteId, actor: robot, bytes: u.bytes, mediaType: u.mediaType, sha256: u.sha256, options: {}, state: "open", expiresAt: u.expiresAt, createdAt: u.createdAt, }); expect((await put(`${base}?sig=${studio}`, CSV)).body.error).toBe("bad_signature"); const url = await link(u); const otherSite = url.replace(siteId, "site_doesnotexist"); expect((await put(otherSite, CSV)).status).toBe(404); const unknown = url.replace(u.id, "upl_doesnotexist01"); expect([(await put(unknown, CSV)).status, (await put(unknown, CSV)).body.error]).toEqual([ 404, "upload_not_found", ]); // Nothing was claimed. expect((await store.uploads.get(u.id))?.state).toBe("open"); }); it("answers 405 to every other method, revealing nothing", async () => { const u = await open(CSV); const url = await link(u); for (const method of ["GET", "POST", "DELETE", "PATCH"]) { const r = await put(url, CSV, { method }); expect([r.status, r.body.error, r.res.headers.get("allow")]).toEqual([ 405, "method_not_allowed", "PUT", ]); } const unknown = await put(url.replace(u.id, "upl_doesnotexist01"), CSV, { method: "GET" }); expect(unknown.status).toBe(405); }); it("checks the headers before any byte: encoding, type, length and the cap", async () => { const u = await open(CSV); const url = await link(u); const cases: [Parameters[2], number, string][] = [ [{ headers: { "content-encoding": "gzip" } }, 415, "encoding_refused"], [{ type: "image/png" }, 415, "type_mismatch"], [{ type: "" }, 415, "type_mismatch"], [{ length: String(CSV.byteLength + 1) }, 400, "size_mismatch"], [{ length: "" }, 400, "size_mismatch"], [{ length: String(200 * 1024 * 1024) }, 413, "too_large"], ]; for (const [o, status, error] of cases) { const r = await put(url, CSV, o); expect([r.status, r.body.error], JSON.stringify(o)).toEqual([status, error]); } // A charset parameter is fine; none of the above used an attempt. expect((await store.uploads.get(u.id))?.attempts).toBe(0); const ok = await put(url, CSV, { type: "text/csv; charset=utf-8" }); expect(ok.status, JSON.stringify(ok.body)).toBe(200); }); it("the store's verification: a wrong hash, then a declared PNG whose bytes are not one", async () => { const u = await open(CSV); const url = await link(u); const wrong = CSV.slice(); wrong[0] = (wrong[0] ?? 0) ^ 1; const r = await put(url, wrong); expect([r.status, r.body.error]).toEqual([400, "checksum_mismatch"]); expect((await store.uploads.get(u.id))?.attempts).toBe(1); expect((await put(url, CSV)).status).toBe(200); const v = await open(CSV, "image/png"); const png = await put(await link(v), CSV, { type: "image/png" }); expect(png.status).toBe(415); // A real PNG goes through the buffered path. const image = makePng({ width: 2, height: 2 }); const w = await open(image, "image/png"); const done = await put(await link(w), image, { type: "image/png" }); expect(done.status, JSON.stringify(done.body)).toBe(200); }); it("ignores cookies and people; another agent's credential is refused", async () => { const u = await open(CSV); const url = await link(u); const other = await put(url, CSV, { headers: { "x-test-caller": "other" } }); expect([other.status, other.body.error]).toEqual([403, "not_your_upload"]); const person = await put(url, CSV, { headers: { "x-test-caller": "person", cookie: "better-auth.session_token=x" }, }); expect(person.status, JSON.stringify(person.body)).toBe(200); const v = await open(CSV); const own = await put(await link(v), CSV, { headers: { "x-test-caller": "robot" } }); expect(own.status).toBe(200); }); it("a browser on another origin is refused", async () => { const u = await open(CSV); const r = await put(await link(u), CSV, { headers: { origin: "https://evil.example" } }); expect(r.status).toBe(403); expect((await store.uploads.get(u.id))?.state).toBe("open"); }); it("rotating the secret voids unused links and leaves received bytes completable", async () => { const used = await open(CSV); expect((await put(await link(used), CSV)).status).toBe(200); const unused = await open(CSV); const oldUrl = await link(unused); app = build("agent-uploads-api-rotated-0123456789abcdef"); expect((await put(oldUrl, CSV)).body.error).toBe("bad_signature"); expect((await store.uploads.complete(used.id, robot, new Date(nowMs))).existing).toBe(false); }); it("refuses taken-down content at the PUT (410)", async () => { const u = await open(CSV); const person = callers.person as Actor; await store.ingestAsset({ siteId, bytes: CSV, declaredType: "text/csv", uploadedBy: person, source: { kind: "upload" }, }); await store.purgeBlob(siteId, u.sha256, person, { text: "test", legal: false }); const r = await put(await link(u), CSV); expect([r.status, r.body.error]).toEqual([410, "purged"]); }); }); }