/** * RFC-0048 §2.3 item 7 through the deployment's real resolver (Better Auth): the `upload-link` * route authorizes nothing by credential, but every request's credential is still resolved first, * so an agent key or bearer of another agent is refused (`not_your_upload`), while a person's * session, the upload's own key and an unknown key are ignored. §3.2: what the API logs for a * failed PUT never carries the link. */ import { SiteGraphStore, seedStarterSite } from "@cloudhal/core-ts"; import { text } from "@cloudhal/core-ts/media/fixtures"; import { MemoryBlobStore, sha256OfBytes } from "@cloudhal/storage"; import { BetterSqlite3Driver } from "@cloudhal/storage/sqlite"; import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; import Database from "better-sqlite3"; import { afterEach, describe, expect, it, vi } from "vitest"; import { createApi } from "../src/app.ts"; import { agentIdForKey, createAuth } from "../src/auth.ts"; import { agentUploadPath, signAgentUpload } from "../src/uploads.ts"; const ORIGIN = "http://studio.test"; const SECRET = "agent-uploads-auth-secret-0123456789abcdef"; const CSV = text("route,stops\nF1,4\n"); type Json = Record; async function world() { const database = new Database(":memory:"); const sql = new BetterSqlite3Driver(database); const store = new SiteGraphStore({ sql, blobs: new MemoryBlobStore() }); await store.init(); const auth = createAuth({ database, sql, baseURL: ORIGIN, secret: "agent-uploads-auth-test-secret-0123456789", signUp: "first-user", }); const app = createApi({ store, resolvePrincipal: auth.resolvePrincipal, authHandler: auth.handler, agentKeys: auth.agentKeys, staff: auth.staff, signUp: auth.signUp, uploadSecret: SECRET, mcp: { stateKey: "agent-uploads-auth-state-key-0123456789ab" }, }); const siteId = (await seedStarterSite(store, { name: "Auth Uploads", slug: "auth-uploads" })).id; let ip = 1; const call = async ( method: string, path: string, o: { headers?: Record; body?: BodyInit; json?: unknown } = {}, ) => { const res = await app.request(`${ORIGIN}${path}`, { method, headers: { "cf-connecting-ip": `10.9.0.${ip++}`, ...(o.json !== undefined ? { "content-type": "application/json" } : {}), ...o.headers, }, ...(o.json !== undefined ? { body: JSON.stringify(o.json) } : o.body ? { body: o.body } : {}), }); const raw = await res.text(); return { status: res.status, body: (raw ? JSON.parse(raw) : {}) as Json }; }; const signUp = await call("POST", "/api/auth/sign-up/email", { json: { name: "Olive Owner", email: "owner@example.com", password: "correct horse battery" }, }); expect(signUp.status, JSON.stringify(signUp.body)).toBe(200); // The session cookie, as the auth handler set it. const res = await app.request(`${ORIGIN}/api/auth/sign-in/email`, { method: "POST", headers: { "content-type": "application/json", "cf-connecting-ip": "10.9.1.1" }, body: JSON.stringify({ email: "owner@example.com", password: "correct horse battery" }), }); const cookie = (res.headers.getSetCookie?.() ?? []) .map((c) => c.split(";")[0] as string) .find((c) => c.startsWith("better-auth.session_token=")) ?? ""; expect(cookie).not.toBe(""); const newKey = async (name: string) => { const r = await call("POST", "/api/agent-keys", { headers: { cookie }, json: { name } }); expect(r.status, JSON.stringify(r.body)).toBe(201); return r.body as { id: string; key: string }; }; const connect = async (key: string) => { const client = new Client( { name: "upload-agent", version: "1.0.0" }, { capabilities: {}, versionNegotiation: { mode: "auto" } }, ); await client.connect( new StreamableHTTPClientTransport(new URL(`${ORIGIN}/mcp`), { requestInit: { headers: { "x-api-key": key } }, fetch: async (input, init) => app.fetch(new Request(input, init as RequestInit)), }), ); return client; }; const mine = await newKey("mine"); const theirs = await newKey("theirs"); return { store, siteId, call, cookie, mine, theirs, connect }; } describe("agent upload links with the real resolver", () => { afterEach(() => vi.restoreAllMocks()); it("refuses another agent's key or bearer, and ignores a session, its own key and unknown keys", async () => { const w = await world(); const actor = { kind: "agent" as const, id: agentIdForKey(w.mine.id) }; const open = async () => { const u = await w.store.uploads.open( w.siteId, actor, { bytes: CSV.byteLength, mediaType: "text/csv", sha256: await sha256OfBytes(CSV) }, { ttlMs: 600_000, completeMs: 3_600_000, maxOpenPerActor: 10, maxOpenPerSite: 50, maxBytes: 25 * 1024 * 1024, }, ); return agentUploadPath(u, await signAgentUpload(SECRET, u)); }; const put = (url: string, headers: Record) => w.call("PUT", url, { headers: { "content-type": "text/csv", "content-length": String(CSV.byteLength), ...headers, }, body: CSV as Uint8Array, }); const url = await open(); for (const headers of [ { "x-api-key": w.theirs.key }, { authorization: `Bearer ${w.theirs.key}` }, ]) { const r = await put(url, headers); expect([r.status, r.body.error], JSON.stringify(headers)).toEqual([403, "not_your_upload"]); } const unknown = await put(url, { "x-api-key": "not-a-key-at-all" }); expect(unknown.status, JSON.stringify(unknown.body)).toBe(200); const own = await put(await open(), { "x-api-key": w.mine.key }); expect(own.status, JSON.stringify(own.body)).toBe(200); const session = await put(await open(), { cookie: w.cookie }); expect(session.status, JSON.stringify(session.body)).toBe(200); }); it("over /mcp: get_mode says links are on, create_upload links here, the PUT, complete_upload", async () => { const w = await world(); const client = await w.connect(w.mine.key); const mode = (await client.callTool({ name: "get_mode", arguments: {} })).structuredContent as { uploads: { signedUrl: boolean }; }; expect(mode.uploads.signedUrl).toBe(true); expect(client.getInstructions()).toContain("create_upload"); const created = await client.callTool({ name: "create_upload", arguments: { siteId: w.siteId, filename: "routes.csv", bytes: CSV.byteLength, mediaType: "text/csv", sha256: await sha256OfBytes(CSV), alt: null, title: "Ferry routes", }, }); expect(created.isError, JSON.stringify(created.content)).toBeFalsy(); const out = created.structuredContent as { uploadId: string; url: string; status: string }; expect(out.status).toBe("upload"); expect(out.url.startsWith(`${ORIGIN}/api/sites/${w.siteId}/assets/agent-uploads/`)).toBe(true); const put = await w.call("PUT", out.url.slice(ORIGIN.length), { headers: { "content-type": "text/csv", "content-length": String(CSV.byteLength) }, body: CSV as Uint8Array, }); expect(put.status, JSON.stringify(put.body)).toBe(200); const done = await client.callTool({ name: "complete_upload", arguments: { siteId: w.siteId, uploadId: out.uploadId }, }); expect(done.isError, JSON.stringify(done.content)).toBeFalsy(); const asset = (done.structuredContent as { asset: { title: Record } }).asset; expect(asset.title).toEqual({ en: "Ferry routes" }); await client.close(); }); it("an unexpected failure is logged without the link", async () => { const w = await world(); const actor = { kind: "agent" as const, id: agentIdForKey(w.mine.id) }; const u = await w.store.uploads.open( w.siteId, actor, { bytes: CSV.byteLength, mediaType: "text/csv", sha256: await sha256OfBytes(CSV) }, { ttlMs: 600_000, completeMs: 3_600_000, maxOpenPerActor: 10, maxOpenPerSite: 50, maxBytes: 25 * 1024 * 1024, }, ); const sig = await signAgentUpload(SECRET, u); vi.spyOn(w.store.uploads, "receive").mockRejectedValue(new Error("the disk is on fire")); const logged: unknown[] = []; vi.spyOn(console, "error").mockImplementation((...args) => void logged.push(...args)); const r = await w.call("PUT", agentUploadPath(u, sig), { headers: { "content-type": "text/csv", "content-length": String(CSV.byteLength) }, body: CSV as Uint8Array, }); expect([r.status, r.body.error]).toEqual([500, "internal"]); expect(logged.length).toBeGreaterThan(0); const text = logged.map((a) => (a instanceof Error ? `${a.message}\n${a.stack}` : String(a))); expect(text.join("\n")).not.toContain(sig); expect(JSON.stringify(r.body)).not.toContain(sig); }); });