/** * RFC-0048 step 4: `create_upload` and `complete_upload` through `runTool`, with the PUT run on the * store as the API's route runs it: modes and approvals, the capability flag, dedupe, limits, the * §5.3 refusals with their reasons, the strict output, and audit rows without the link. */ import { createHash } from "node:crypto"; import { type AgentMode, AuditLog, defaultScopes, PolicyEngine } from "@cloudhal/agent-runtime"; import type { Asset, Site } from "@cloudhal/core-contracts"; import { type AgentUpload, SiteGraphStore, seedStarterSite } from "@cloudhal/core-ts"; import { makePng } from "@cloudhal/core-ts/media/fixtures"; import { MemoryBlobStore, migrate, migrations } from "@cloudhal/storage"; import { BetterSqlite3Driver } from "@cloudhal/storage/sqlite"; import { beforeEach, describe, expect, it } from "vitest"; import { serverInstructions } from "../src/server-instructions.ts"; import { defineTools, runTool, type ToolContext, ToolError, toolPolicies } from "../src/tools.ts"; const tools = defineTools(); const byName = Object.fromEntries(tools.map((t) => [t.name, t])); const policy = new PolicyEngine(toolPolicies(tools)); const agent = { kind: "agent" as const, id: "agent_uploader01", name: "Uploader" }; const other = { kind: "agent" as const, id: "agent_uploader02", name: "Other" }; const CSV = new TextEncoder().encode("line,stops\nM2,16\nM4,19\n"); const sha = (b: Uint8Array) => createHash("sha256").update(b).digest("hex"); const ORIGIN = "https://admin.example.com"; const links = { link: async (u: AgentUpload) => `/api/sites/${u.siteId}/assets/agent-uploads/${u.id}?sig=SIGNED`, origin: ORIGIN, verifiable: true, }; const streamOf = (b: Uint8Array) => new ReadableStream({ start(c) { c.enqueue(b); c.close(); }, }); type CreateOut = { status: string; uploadId: string | null; url: string | null; method: string | null; headers: { "content-type": string } | null; expiresAt: string | null; completeBy: string | null; curl: string | null; asset: Asset | null; }; describe("agent upload links (create_upload, complete_upload)", () => { let store: SiteGraphStore; let audit: AuditLog; let site: Site; let ctx: ToolContext; beforeEach(async () => { const sql = await BetterSqlite3Driver.open(":memory:"); await migrate(sql, migrations); store = new SiteGraphStore({ sql, blobs: new MemoryBlobStore() }); audit = new AuditLog(sql); site = await seedStarterSite(store, { name: "Upload Site", slug: "upload" }); ctx = { store, principal: { actor: agent, scopes: defaultScopes(agent) }, uploads: links }; }); const as = (actor: typeof agent, mode?: AgentMode, extra: Partial = {}) => ({ ...ctx, principal: { actor, scopes: defaultScopes(actor), ...(mode ? { mode } : {}) }, ...extra, }); const call = ( name: string, args: Record, o: { as?: ToolContext; confirmed?: boolean } = {}, ) => runTool(byName[name] as (typeof tools)[number], args, o.as ?? ctx, { policy, audit, confirmed: o.confirmed ?? false, }); const failure = async (p: Promise) => { try { await p; } catch (e) { if (e instanceof ToolError) return e; throw e; } throw new Error("expected a ToolError"); }; const csvArgs = (extra: Record = {}) => ({ siteId: site.id, filename: "lines.csv", bytes: CSV.byteLength, mediaType: "text/csv", sha256: sha(CSV), ...extra, }); const create = async (extra: Record = {}, o: { as?: ToolContext } = {}) => (await call("create_upload", csvArgs(extra), o)).result as CreateOut; it("hands out a link, takes the bytes, completes once, and keeps the link out of the audit", async () => { const out = await create({ title: "Metro lines", alt: null, slug: null, license: null }); expect(Object.keys(out).sort()).toEqual( [ "asset", "completeBy", "curl", "expiresAt", "headers", "method", "status", "uploadId", "url", ].sort(), ); expect(out).toMatchObject({ status: "upload", method: "PUT", headers: { "content-type": "text/csv" }, asset: null, }); expect(out.url).toBe( `${ORIGIN}/api/sites/${site.id}/assets/agent-uploads/${out.uploadId}?sig=SIGNED`, ); expect(out.curl).toBe( `curl --fail-with-body -X PUT -H 'content-type: text/csv' --upload-file 'lines.csv' '${out.url}'`, ); expect(Date.parse(out.expiresAt ?? "") - Date.parse(out.completeBy ?? "")).toBe(-50 * 60_000); const id = out.uploadId as string; const early = await failure(call("complete_upload", { siteId: site.id, uploadId: id })); expect([early.code, early.details.reason]).toEqual(["conflict", "upload_pending"]); await store.uploads.receive(id, streamOf(CSV)); const done = (await call("complete_upload", { siteId: site.id, uploadId: id })).result as { asset: Asset; existing: boolean; snapshot?: { id: string }; url: string; }; expect(done.existing).toBe(false); expect(done.asset).toMatchObject({ mediaType: "text/csv", title: { en: "Metro lines" }, uploadedBy: agent, source: { kind: "upload", filename: "lines.csv" }, }); expect(done.snapshot?.id).toMatch(/^snap_/); const again = (await call("complete_upload", { siteId: site.id, uploadId: id })).result as { asset: Asset; existing: boolean; snapshot?: unknown; }; expect([again.asset.id, again.existing, again.snapshot]).toEqual([ done.asset.id, true, undefined, ]); const rows = await audit.list({ siteId: site.id }); const tools = rows.map((r) => r.tool); expect(tools).toContain("create_upload"); expect(tools).toContain("complete_upload"); expect(JSON.stringify(rows)).not.toContain("sig="); const created = rows.find((r) => r.tool === "create_upload"); const effect = (created?.input ?? {}) as { effect?: { upload?: { id: string } } }; expect(effect.effect?.upload?.id).toBe(id); }); it("answers existing for bytes already in the library, with no link", async () => { await call("upload_asset", { siteId: site.id, filename: "lines.csv", data: Buffer.from(CSV).toString("base64"), }); const out = await create(); expect(out).toMatchObject({ status: "existing", uploadId: null, url: null, curl: null }); expect(out.asset?.sha256).toBe(sha(CSV)); }); it("plan refuses both; manual asks once, at create, with the size and hash prefix", async () => { const plan = as(agent, "plan"); expect((await call("create_upload", csvArgs(), { as: plan })).decision.kind).toBe("deny"); expect( (await call("complete_upload", { siteId: site.id, uploadId: "upl_whatever01" }, { as: plan })) .decision.kind, ).toBe("deny"); const manual = as(agent, "manual"); const asked = await call("create_upload", csvArgs({ alt: "Metro" }), { as: manual }); expect(asked.decision.kind).toBe("approval-required"); expect(asked.approvalPrompt).toBe( `Add media "Metro" (lines.csv, ${CSV.byteLength} B, CSV, sha256 ${sha(CSV).slice(0, 12)}…) to "Upload Site"? It becomes public only when the site is published.`, ); const approved = (await call("create_upload", csvArgs(), { as: manual, confirmed: true })) .result as CreateOut; await store.uploads.receive(approved.uploadId as string, streamOf(CSV)); const done = await call( "complete_upload", { siteId: site.id, uploadId: approved.uploadId }, { as: manual }, ); expect(done.decision.kind).toBe("allow"); expect((done.result as { existing: boolean }).existing).toBe(false); }); it("is off without links, when the operator turns it off, or without a shared secret", async () => { for (const off of [ { uploads: undefined }, { media: { agentUploads: false } }, { uploads: { ...links, verifiable: false } }, ] as Partial[]) { const e = await failure(call("create_upload", csvArgs(), { as: { ...ctx, ...off } })); expect([e.code, e.details.reason]).toEqual(["invalid", "signed_upload_unsupported"]); const mode = (await call("get_mode", {}, { as: { ...ctx, ...off } })).result as { uploads: { signedUrl: boolean }; }; expect(mode.uploads.signedUrl).toBe(false); } const on = (await call("get_mode", {})).result as { uploads: unknown }; expect(on.uploads).toEqual({ signedUrl: true, maxBytes: 25 * 1024 * 1024, linkSeconds: 600 }); expect(serverInstructions(ctx.principal, { uploads: true })).toContain("create_upload"); expect(serverInstructions(ctx.principal)).not.toContain("create_upload"); }); it("refuses with §5.3's reasons: cap, type, alt, open uploads, daily limit", async () => { const small = { ...ctx, media: { agentUploadBytes: 10 } }; const big = await failure(call("create_upload", csvArgs(), { as: small })); expect([big.code, big.details.reason]).toEqual(["too_large", "upload_cap"]); const svg = await failure(call("create_upload", csvArgs({ mediaType: "image/svg+xml" }))); expect([svg.code, svg.details.reason]).toEqual(["invalid", "unsupported_type"]); expect(svg.message).toContain("SVG and HTML are refused"); const png = makePng({ width: 2, height: 2 }); const noAlt = await failure( call( "create_upload", csvArgs({ filename: "dot.png", mediaType: "image/png", bytes: png.byteLength, sha256: sha(png), }), ), ); expect(noAlt.code).toBe("invalid"); for (let i = 0; i < 10; i++) await create(); const many = await failure(call("create_upload", csvArgs())); expect([many.code, many.details.reason]).toEqual(["denied", "too_many_uploads"]); const daily = as(other, undefined, { media: { agentDailyAssets: 2 } }); await create({}, { as: daily }); await create({}, { as: daily }); const limited = await failure(call("create_upload", csvArgs(), { as: daily })); expect(limited.code).toBe("denied"); expect(limited.message).toContain("in the last 24 hours"); }); it("complete_upload: another key's upload is unknown; a refused PUT and an expiry say what to do", async () => { const out = await create(); const id = out.uploadId as string; const theirs = await failure( call("complete_upload", { siteId: site.id, uploadId: id }, { as: as(other) }), ); expect([theirs.code, theirs.details.reason]).toEqual(["not_found", "upload_not_found"]); const unknown = await failure( call("complete_upload", { siteId: site.id, uploadId: "upl_doesnotexist1" }), ); expect(unknown.details.reason).toBe("upload_not_found"); await store.uploads .receive(id, streamOf(new TextEncoder().encode("line,stops\nM2,17\nM4,19\n"))) .catch(() => {}); const failed = await failure(call("complete_upload", { siteId: site.id, uploadId: id })); expect([failed.code, failed.details.reason]).toEqual(["conflict", "upload_failed"]); expect(failed.message).toContain("1 of 3"); const later = { ...ctx, now: () => new Date(Date.now() + 2 * 3_600_000) }; const expired = await failure( call("complete_upload", { siteId: site.id, uploadId: id }, { as: later }), ); expect([expired.code, expired.details.reason]).toEqual(["invalid", "upload_expired"]); }); });