/** * RFC-0048 §2 and §5.2: the PUT of an agent's upload link, * `PUT /api/sites/:siteId/assets/agent-uploads/:uploadId?sig=…`, the only `upload-link` route. * The link is the credential: the route guard reads no session for it, and this handler checks the * signature against the `media_uploads` row a governed `create_upload` minted, then lets the store * claim the row and stage exactly the declared bytes. It never creates an asset; `complete_upload` * does. Cookies are ignored; an agent credential, when one is sent, must be the upload's own. * Refused PUTs are not audited (a flood cannot fill the log); the row counts them. * * The link's `sig` is never logged: Workers Logs and traces drop query strings * (`redact_query_string`, `observabilitySettings` in the CLI, ADR-0027), the API itself logs no * request URLs (`test/agent-uploads-auth.test.ts` checks an unexpected failure's log line), and * neither audit rows nor answers carry it. Worker-safe. */ import type { Actor } from "@cloudhal/core-contracts"; import { type AgentUpload, InvariantError, NotFoundError } from "@cloudhal/core-ts"; import { MEDIA_TYPES } from "@cloudhal/core-ts/media"; import { Hono } from "hono"; import type { Env } from "../context.ts"; import { apiError } from "../errors.ts"; import { param } from "../params.ts"; import { verifyAgentUpload } from "../uploads.ts"; const notFoundUpload = () => apiError(404, "upload_not_found", "no such upload on this site"); /** The media type of a `Content-Type` header, without parameters such as `charset`. */ function headerType(value: string | undefined): string { const end = value?.indexOf(";") ?? -1; return (end >= 0 ? value?.slice(0, end) : value)?.trim().toLowerCase() ?? ""; } /** The header checks of §2.3, before any byte is read. */ function checkHeaders( u: AgentUpload, h: { type: string | undefined; length: string | undefined; encoding: string | undefined; cap: number; }, ): void { const encoding = h.encoding?.trim().toLowerCase(); if (encoding && encoding !== "identity") throw apiError(415, "encoding_refused", "send the file's bytes as they are, not encoded", { contentEncoding: encoding, }); if (headerType(h.type) !== u.mediaType) throw apiError( 415, "type_mismatch", `the Content-Type must be ${u.mediaType}, as declared to create_upload`, { expected: u.mediaType }, ); const length = h.length === undefined || h.length.trim() === "" ? Number.NaN : Number(h.length); if (Number.isFinite(length) && length > h.cap) throw apiError(413, "too_large", `files of this type may be at most ${h.cap} bytes`, { bytes: length, limit: h.cap, }); if (length !== u.bytes) throw apiError( 400, "size_mismatch", `send Content-Length: ${u.bytes}, the size declared to create_upload`, { expected: u.bytes }, ); } /** The store's refusals as §5.2's answers; everything else goes to the API's error handler. */ function receiveError(e: unknown): never { if (e instanceof NotFoundError) throw notFoundUpload(); if (e instanceof InvariantError) { if (e.code === "too_large") throw apiError(413, "too_large", e.message, e.details); // RFC-0048 §5.2: the blob is being collected; a new PUT within the link's attempts may pass. if (e.code === "retry") throw apiError(409, "retry", e.message, e.details); } throw e; } export const agentUploads: Hono = new Hono().put("/:uploadId", async (c) => { const store = c.get("store"); const body = c.req.raw.body; const drop = () => body?.cancel().catch(() => {}); const upload = await store.uploads.get(param(c, "uploadId")); // A wrong site answers like an unknown upload, so the route cannot probe for uploads. if (!upload || upload.siteId !== param(c, "siteId")) { await drop(); throw notFoundUpload(); } if (!(await verifyAgentUpload(c.get("uploadSecret"), upload, c.req.query("sig")))) { await drop(); throw apiError(403, "bad_signature", "this upload link is not valid; call create_upload again"); } // Credentials are ignored, except that an agent's must be the upload's own (§2.3 item 7). The // principal was resolved for every request before `routeGuard` (keys, bearers, sessions); the // guard only skips authorizing it on this route. const caller = c.get("principal")?.actor; if (caller?.kind === "agent" && caller.id !== upload.actor.id) { await drop(); throw apiError(403, "not_your_upload", "this upload was created by another agent key"); } try { checkHeaders(upload, { type: c.req.header("content-type"), length: c.req.header("content-length"), encoding: c.req.header("content-encoding"), cap: MEDIA_TYPES[upload.mediaType]?.cap ?? upload.bytes, }); if (!body) throw apiError(400, "size_mismatch", "the request has no body"); } catch (e) { await drop(); throw e; } let received: AgentUpload; try { received = await store.uploads.receive(upload.id, body, c.get("now")()); } catch (e) { receiveError(e); } const staged = received.received; const actor = { kind: upload.actor.kind, id: upload.actor.id } as Actor; await c.get("audit")?.record({ at: c.get("now")().toISOString(), actor, siteId: upload.siteId, tool: "asset.upload-received", decision: "allow", outcome: "ok", input: { uploadId: upload.id, bytes: upload.bytes, sha256: upload.sha256, mediaType: upload.mediaType, attempts: received.attempts, ...(staged?.originalSha256 ? { metadataStripped: true } : {}), }, }); return c.json({ uploadId: upload.id, state: received.state, sha256: upload.sha256, bytes: upload.bytes, mediaType: upload.mediaType, warnings: staged?.warnings ?? [], }); });