Cotton code
233 lines · 18.3 KB · TypeScriptRaw
/** * ADMIN KEYS 4 (NEXT-ADMIN-KEYS-4, the branch review of 27 Nov): the machines producer mint, a definition's access * fields, undo and restore_version through the one write guard, outward decided in one place, and the lows. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import CATALOGUE from "../src/mcp/catalogue.json";import { ACTS } from "../src/acts.ts";import { ACT_REACH, outwardAct, outwardTool, TOOL_REACH } from "../src/key_allow.ts";import { PRODUCER_ALLOW } from "../src/token_scopes.ts";import { ADMIN, http, mint, NOTES_OPEN, personalObject, TODOS_OPEN, tool } from "./personal.ts";type Row = { id: string; table?: string; data: Record<string, unknown> };const object = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const tokens = (slug: string) => runInDurableObject(object(slug), (i) => [...(i as unknown as { store: { scan(t: string): Iterable<Row> } }).store.scan("mcp_token")]);const tableDef = (slug: string, id: string) => runInDurableObject(object(slug), (i) => (i as unknown as { store: { definitions(k: string): Record<string, unknown>[] } }).store.definitions("table").find((d) => d.id === id) ?? null);const act = (slug: string, token: string, name: string, args: Record<string, unknown>) => http<{ code?: string; message?: string; token?: string; made?: { id: string } }>(slug, "POST", "/v1/act", { act: name, args }, { authorization: `Bearer ${token}` });/** The Disk tool's table (claims-sweep.sh), made as the owner makes it: `machine` is retired (TABLE DROP 1), disk_claim stays. */async function diskClaims(slug: string): Promise<void> {  const made = await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [{ format_version: 1, id: "disk_claim", name: "Disk claim", plural: "Disk claims", visibility: "owner", columns: [{ key: "name", type: "text" }, { key: "claim_id", type: "text", readonly: true }] }] }, ADMIN);  expect(made.status, JSON.stringify(made.body)).toBe(200);}const PRODUCER = { name: "machines producer", scopes: ["read", "write"], expires_in_days: 90, allow: { read: ["disk_claim", "machine", "project", "session"], write: ["disk_claim", "machine"] }, producer_of: ["machine", "disk_claim"] };describe("ADMIN KEYS 4 (1): the machines producer, the second mint a key may make", () => {  it("an owner-scope key mints exactly the producer shape, named producer in the same write; it writes its table, reads devices and sessions, and mints nothing", async () => {    const slug = "ak4-producer";    const { credential, owner } = await personalObject(slug);    await diskClaims(slug);    const made = await act(slug, owner, "mint_token", PRODUCER);    expect(made.status, JSON.stringify(made.body)).toBe(200);    const producer = made.body.token!;    const row = (await tokens(slug)).find((r) => r.data.name === "machines producer")!;    const ownerRow = (await tokens(slug)).find((r) => r.data.name !== "machines producer" && !r.data.minted_by)!;    expect(JSON.parse(String(row.data.allow))).toEqual(PRODUCER_ALLOW);    expect(row.data.minted_by).toBe(ownerRow.id);    expect(row.data.scopes).toEqual(["read", "write"]);    // Named producer of the table this database holds; `machine`, retired here, is skipped.    expect(((await tableDef(slug, "disk_claim"))?.producer as { token_id: string }).token_id).toBe(row.id);    expect(await tableDef(slug, "machine")).toBeNull();    // It fills the readonly columns of its own table (the producer); the owner's key does not.    const wrote = await tool(slug, producer, "create_record", { table: "disk_claim", data: { name: "invented-mac", claim_id: "c-1" } });    expect(wrote.isError, wrote.content[0]!.text).toBe(false);    expect((await tool(slug, owner, "create_record", { table: "disk_claim", data: { name: "x", claim_id: "c-2" } })).content[0]!.text).toBe('"claim_id" is read only');    for (const [name, args] of [["list_devices", { includeRevoked: false }], ["list_sessions", {}], ["list_records", { table: "disk_claim" }]] as const) {      const r = await tool(slug, producer, name, args);      expect(r.isError, `${name}: ${r.content[0]!.text}`).toBe(false);    }    // Nothing else of the owner's, and it mints nothing (it holds no owner scope).    expect((await tool(slug, producer, "list_records", { table: "todo" })).isError).toBe(true);    expect((await act(slug, producer, "mint_token", { ...PRODUCER, name: "again" })).status).toBe(403);    expect((await act(slug, producer, "mint_token", { name: "lane", scopes: ["read", "lane:x"], expires_in_days: 1 })).status).toBe(403);    // The owner's own device still mints any key; the lane shape still works for a key.    expect((await act(slug, owner, "mint_token", { name: "Lane invented", scopes: ["read", "lane:invented"], expires_in_days: 7 })).status).toBe(200);    expect((await act(slug, credential, "mint_token", { name: "phone key", scopes: ["read"], expires_in_days: 1 })).status).toBe(200);  }, 240_000);  it("refuses every other shape, by an owner key, a lane token, a narrower key and a connection-less wider ask", async () => {    const slug = "ak4-producer-refused";    const { credential, owner } = await personalObject(slug);    await diskClaims(slug);    for (const wider of [      { ...PRODUCER, scopes: ["read", "write", "machines"] },      { ...PRODUCER, scopes: ["owner"] },      { ...PRODUCER, expires_in_days: 91 },      { ...PRODUCER, expires_in_days: undefined },      { ...PRODUCER, allow: { read: "*", write: ["disk_claim", "machine"] } },      { ...PRODUCER, allow: { read: ["disk_claim", "machine", "project", "session", "note"], write: ["disk_claim", "machine"] } },      { ...PRODUCER, allow: { ...PRODUCER.allow, outward: true } },      { ...PRODUCER, allow: { ...PRODUCER.allow, acts: ["update_definition"] } },      { ...PRODUCER, allow: undefined },      { ...PRODUCER, producer_of: ["note"] },      { ...PRODUCER, producer_of: [] },      { ...PRODUCER, visibility: "public" },    ]) {      const r = await act(slug, owner, "mint_token", wider);      expect([r.status, r.body.code], JSON.stringify(wider)).toEqual([403, "access_act"]);    }    const lane = await mint(slug, credential, "Lane invented", ["read", "lane:invented"], 7);    const narrow = await mint(slug, credential, "Invented reader", ["read", "write"], 7);    for (const key of [lane, narrow]) expect((await act(slug, key, "mint_token", PRODUCER)).status).toBe(403);    expect(((await tableDef(slug, "disk_claim"))?.producer ?? null)).toBeNull();  }, 240_000);});describe("ADMIN KEYS 4 (2): what in a definition decides access is never a key's", () => {  it("refuses producer, visibility and a column's readonly to a key, at update_definition and the definition act; the phone still sets them", async () => {    const slug = "ak4-definition";    const { credential, owner } = await personalObject(slug, NOTES_OPEN);    await diskClaims(slug);    const ownRow = (await tokens(slug))[0]!;    for (const args of [      { table: "disk_claim", producer: { token_id: ownRow.id } },      { table: "disk_claim", visibility: "public" },      { table: "disk_claim", columns: (((await tableDef(slug, "disk_claim"))!.columns as Record<string, unknown>[]).map((c) => (c.key === "claim_id" ? { ...c, readonly: false } : c))) },    ]) {      const r = await tool(slug, owner, "update_definition", args);      expect([r.isError, r.content[0]!.text], JSON.stringify(args).slice(0, 80)).toEqual([true, expect.stringMatching(/who may read or write the table/)]);      const definition = { ...(await tableDef(slug, args.table))!, ...args };      delete (definition as Record<string, unknown>).table;      const viaAct = await act(slug, owner, "definition", { kind: "table", definition: { ...definition, id: args.table } });      expect([viaAct.status, viaAct.body.message], JSON.stringify(args).slice(0, 80)).toEqual([400, expect.stringMatching(/who may read or write the table/)]);    }    // A key still changes how a table looks.    const look = await tool(slug, owner, "update_definition", { table: "disk_claim", plural: "Invented claims" });    expect(look.isError, look.content[0]!.text).toBe(false);    // The owner's phone names a producer.    const phone = await act(slug, credential, "definition", { kind: "table", definition: { ...(await tableDef(slug, "disk_claim"))!, producer: { token_id: ownRow.id } } });    expect(phone.status, JSON.stringify(phone.body)).toBe(200);  }, 240_000);});describe("ADMIN KEYS 4 (3): undo and restore_version go through the one write guard", () => {  it("a key cannot undo or restore a change to a table that holds who may do what; it still undoes its own writes", async () => {    const slug = "ak4-undo";    const { credential, owner } = await personalObject(slug, { open: TODOS_OPEN });    // A change on mcp_token: the owner's phone revokes a key.    await mint(slug, credential, "Invented victim", ["read"], 1);    const victim = (await tokens(slug)).find((r) => r.data.name === "Invented victim")!;    expect((await act(slug, credential, "revoke_token", { id: victim.id })).status).toBe(200);    const change = await runInDurableObject(object(slug), (i) => (i as unknown as { ctx: { storage: { sql: { exec(q: string, ...a: unknown[]): { toArray(): { id: number }[] } } } } }).ctx.storage.sql.exec("SELECT id FROM change WHERE table_id = 'mcp_token' AND record_id = ? ORDER BY id DESC LIMIT 1", victim.id).toArray()[0]!.id);    const undone = await tool(slug, owner, "undo", { change_id: change });    expect(undone.isError).toBe(true);    const restored = await tool(slug, owner, "restore_version", { table: "mcp_token", id: victim.id, change_id: change });    expect(restored.isError).toBe(true);    expect((await tokens(slug)).find((r) => r.id === victim.id)!.data.revoked_at).toBeTruthy();    // The reviewer's sequences, on tables a tool draws: a device row and a settled ask, each with a change a key names.    for (const [table, data] of [["device", { name: "Invented Mac", device_id: "invented-device" }], ["assistant_ask", { state: "allowed" }]] as const) {      const planted = await runInDurableObject(object(slug), (i) => {        const sql = (i as unknown as { ctx: { storage: { sql: { exec(q: string, ...a: unknown[]): { toArray(): { id: number }[] } } } } }).ctx.storage.sql;        const now = new Date().toISOString();        sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES (?, ?, ?, NULL, 1, 0, ?, ?)", table, `ak4-${table}`, JSON.stringify(data), now, now);        sql.exec("INSERT INTO change (at, actor, via, table_id, record_id, kind, before, after, version) VALUES (?, NULL, 'phone', ?, ?, 'create', NULL, ?, 1)", now, table, `ak4-${table}`, JSON.stringify(data));        return sql.exec("SELECT id FROM change WHERE table_id = ? ORDER BY id DESC LIMIT 1", table).toArray()[0]!.id;      });      const back = await tool(slug, owner, "undo", { change_id: planted });      expect([back.isError, back.content[0]!.text], table).toEqual([true, expect.stringMatching(/holds who may do what/)]);      const put = await tool(slug, owner, "restore_version", { table, id: `ak4-${table}`, change_id: planted });      expect(put.isError, table).toBe(true);      const still = await runInDurableObject(object(slug), (i) => (i as unknown as { ctx: { storage: { sql: { exec(q: string, ...a: unknown[]): { toArray(): { deleted: number }[] } } } } }).ctx.storage.sql.exec("SELECT deleted FROM rows WHERE table_id = ? AND id = ?", table, `ak4-${table}`).toArray()[0]!.deleted);      expect(still, `${table} stands`).toBe(0);    }    // Its own write it undoes.    const made = JSON.parse((await tool(slug, owner, "create_record", { table: "todo", data: { title: "Invented todo" } })).content[0]!.text) as { change_id: number };    const back = await tool(slug, owner, "undo", { change_id: made.change_id });    expect(back.isError, back.content[0]!.text).toBe(false);  }, 240_000);});describe("ADMIN KEYS 4 (4): outward is decided in one place, by what a thing does", () => {  it("classes every tool in the catalogue and every act, and nothing else", () => {    const tools = (CATALOGUE as { tools: { name: string }[] }).tools.map((t) => t.name).sort();    expect(Object.keys(TOOL_REACH).sort()).toEqual(tools);    expect(Object.keys(ACT_REACH).sort()).toEqual(Object.keys(ACTS).sort());    // What reaches a person or a server outside Cotton.    for (const t of ["agent_chat_post", "agent_chat_react"]) expect(outwardTool(t, {}), t).toBe(true);    expect(outwardTool("put_document", { url: "https://invented.example/x" })).toBe(true);    expect(outwardTool("put_document", { bytes_base64: "aGk=" })).toBe(false);    expect(outwardTool("create_record", { table: "outbox" })).toBe(true);    expect(outwardTool("create_record", { table: "note" })).toBe(false);    expect(outwardTool("run_act", { act: "fetch_add", args: {} })).toBe(true);    expect(outwardTool("run_act", { act: "create", args: { table: "fetch" } })).toBe(true);    for (const a of ["message", "subscribe_podcast", "find_book", "find_film", "find_lyrics", "fetch_cover", "fetch_add", "import_opml", "refresh_podcast", "book", "order"]) expect(outwardAct(a, {}), a).toBe(true);    expect(outwardTool("an_unknown_tool", {})).toBe(true);  });  it("a key without outward cannot post in a chat or fetch a url; a key that may not write documents never fetches", async () => {    const slug = "ak4-outward";    const { credential } = await personalObject(slug, { open: [...NOTES_OPEN.open, "document"] });    const inside = await mint(slug, credential, "Invented inside", ["read", "write"], 1, undefined, { read: ["note", "document"], write: ["note", "document"] });    const post = await tool(slug, inside, "agent_chat_post", { thread: "invented", body: "hello" });    expect([post.isError, post.content[0]!.text]).toEqual([true, expect.stringMatching(/outside Cotton/)]);    const fetched = await tool(slug, inside, "put_document", { name: "x.pdf", url: "https://invented.example/x.pdf" });    expect([fetched.isError, fetched.content[0]!.text]).toEqual([true, expect.stringMatching(/outside Cotton/)]);    // Outward but no write of documents: refused before any request is made.    const away = await mint(slug, credential, "Invented away", ["read", "write"], 1, undefined, { read: ["note", "document"], write: ["note"], outward: true });    const before = await tool(slug, away, "put_document", { name: "x.pdf", url: "https://invented.example/x.pdf" });    expect([before.isError, before.content[0]!.text]).toEqual([true, expect.stringMatching(/does not write document/)]);    // Inside bytes are not outward.    const bytes = await tool(slug, inside, "put_document", { name: "x.txt", bytes_base64: "aGVsbG8=" });    expect(bytes.isError, bytes.content[0]!.text).toBe(false);  }, 240_000);});describe("ADMIN KEYS 4 (lows)", () => {  it("a key ends only itself or a key it minted; narrowing a minter narrows its lane tokens and ends a wider minted key", async () => {    const slug = "ak4-revoke";    const { credential, owner } = await personalObject(slug);    const other = await mint(slug, credential, "Invented other", ["read"], 1);    void other;    const otherRow = (await tokens(slug)).find((r) => r.data.name === "Invented other")!;    expect((await act(slug, owner, "revoke_token", { id: otherRow.id })).body.code).toBe("access_act");    const lane = await act(slug, owner, "mint_token", { name: "Lane invented", scopes: ["read", "lane:invented"], expires_in_days: 7 });    expect(lane.status).toBe(200);    expect((await act(slug, owner, "mint_token", PRODUCER)).status).toBe(200);    const rows = await tokens(slug);    const ownerRow = rows.find((r) => !r.data.minted_by && r.data.name !== "Invented other")!;    const laneRow = rows.find((r) => r.data.name === "Lane invented")!;    const producerRow = rows.find((r) => r.data.name === "machines producer")!;    // The owner's phone narrows the minting key to notes only.    const narrowed = await act(slug, credential, "token_allow", { id: ownerRow.id, allow: { read: ["note"], write: [] } });    expect(narrowed.status, JSON.stringify(narrowed.body)).toBe(200);    const after = await tokens(slug);    expect(JSON.parse(String(after.find((r) => r.id === laneRow.id)!.data.allow))).toMatchObject({ read: ["note"], write: [] });    expect(after.find((r) => r.id === producerRow.id)!.data.revoked_at).toBeTruthy();    // A key it minted it ends (lane-stop).    expect((await act(slug, owner, "revoke_token", { id: laneRow.id })).status).toBe(200);  }, 240_000);  it("a narrowed key's link to a table it does not read is refused alike whether the record is there or not", async () => {    const slug = "ak4-links";    const { credential, owner } = await personalObject(slug, { open: TODOS_OPEN });    const projectMade = await tool(slug, owner, "create_project", { name: "Invented project", slug: "invented-project" });    expect(projectMade.isError, projectMade.content[0]!.text).toBe(false);    const projectId = await runInDurableObject(object(slug), (i) => [...(i as unknown as { store: { scan(t: string): Iterable<Row> } }).store.scan("project")].find((r) => r.data.slug === "invented-project")!.id);    const todos = await mint(slug, credential, "Invented todos", ["read", "write"], 1, undefined, { read: ["todo"], write: ["todo"] });    const there = await tool(slug, todos, "create_record", { table: "todo", data: { title: "Linked", project: projectId } });    const missing = await tool(slug, todos, "create_record", { table: "todo", data: { title: "Linked", project: "00000000-0000-4000-8000-000000000000" } });    expect(there.content[0]!.text, "the same answer either way").toBe(missing.content[0]!.text.replace("00000000-0000-4000-8000-000000000000", projectId));    expect(there.isError).toBe(true);    expect(missing.isError).toBe(true);    expect(there.content[0]!.text.replace(projectId, "")).not.toMatch(/Invented project/);  }, 240_000);  it("a signed-out device is refused at /v1/keys", async () => {    const slug = "ak4-keys-device";    const { credential } = await personalObject(slug);    expect((await http(slug, "GET", "/v1/keys", undefined, { authorization: `Bearer ${credential}` })).status).toBe(200);    expect((await http(slug, "POST", "/v1/sign-out", {}, { authorization: `Bearer ${credential}` })).status).toBeLessThan(300);    expect((await http(slug, "GET", "/v1/keys", undefined, { authorization: `Bearer ${credential}` })).status).toBeGreaterThanOrEqual(401);  }, 240_000);});