Cotton code
277 lines · 18.6 KB · TypeScriptRaw
import { env, runInDurableObject } from "cloudflare:test";import { beforeAll, describe, expect, it } from "vitest";import { openRow, tableKey } from "../src/seal.ts";import { SEAL_BATCH, twins } from "../src/seal_migration.ts";import { ADMIN, answer, DATABASE_ID, http, mint, personalObject, tool, TODOS_OPEN } from "./personal.ts";import { rowTokens, sealRow } from "./seal-device.ts";import { holdsWord } from "./clear-word.ts";/** * RULE (sealing plan §7): a table that held open rows is * marked sealed, and a device migrates them in two steps: each sealed twin is * staged beside its clear row, read back as stored, verified by the device, * and only then committed in the row's place, while the row is still at the * version the device read. Nothing the device seals is plaintext the object * keeps: not in rows, the change log, the act log, or the twins. Synthetic * rows only; the table is this test's own (no kit table is sealed). */const OPEN_DIARY = {  format_version: 1,  id: "migrated_diary",  name: "Migrated diary",  plural: "Migrated diaries",  title: "body",  date: "written_at",  columns: [    { key: "written_at", type: "date" },    { key: "body", type: "longtext", required: true },    { key: "keep_open", type: "boolean" },    { key: "trashed_at", type: "date" },  ],};const SPEC = { clear: ["written_at", "trashed_at", "keep_open"], blind: ["body"] };const SEALED_DIARY = { ...OPEN_DIARY, seal: SPEC };const TABLE = OPEN_DIARY.id;/** Words the guard looks for wherever the object keeps text once the rows are sealed. */const SECRET_WORDS = ["xylophone-harbour", "periwinkle", "gondolier"];const DK = Uint8Array.from({ length: 32 }, (_, i) => (i * 7 + 3) & 0xff);async function act(slug: string, credential: string, name: string, args: Record<string, unknown>): Promise<{ status: number; body: Record<string, unknown> }> {  return http(slug, "POST", "/v1/act", { act: name, args }, { authorization: `Bearer ${credential}` });}function onObject<T>(slug: string, fn: (sql: SqlStorage) => T): Promise<T> {  return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_instance, state) => fn(state.storage.sql));}/** Every text the object keeps of the table's rows, its changes, every act, and the twins. */async function kept(slug: string): Promise<{ rows: string; change: string; acts: string; twins: string }> {  return onObject(slug, (sql) => {    const all = (q: string) => JSON.stringify(sql.exec(q).toArray());    return {      rows: all(`SELECT data FROM rows WHERE table_id = '${TABLE}'`),      change: all(`SELECT before, after FROM change WHERE table_id = '${TABLE}'`),      acts: all("SELECT args, outcome FROM acts"),      twins: all("SELECT * FROM seal_twin"),    };  });}async function held(slug: string, id: string): Promise<{ version: number; data: Record<string, unknown> }> {  return onObject(slug, (sql) => {    const r = sql.exec<{ version: number; data: string }>("SELECT version, data FROM rows WHERE table_id = ? AND id = ?", TABLE, id).one();    return { version: Number(r.version), data: JSON.parse(r.data) as Record<string, unknown> };  });}/** The device's half for one open row: its clear columns plus a seal of the rest, and its tokens. */async function twinOf(id: string, row: Record<string, unknown>, version: number): Promise<Record<string, unknown>> {  const clear: Record<string, unknown> = {};  const sealed: Record<string, unknown> = {};  for (const [k, v] of Object.entries(row)) (SPEC.clear.includes(k) ? clear : sealed)[k] = v;  return { id, expect_version: version, data: { ...clear, ...(await sealRow(DK, TABLE, id, 1, sealed)) }, blind: await rowTokens(DK, TABLE, SPEC, row) };}describe("migrating a table's open rows into sealed ones", () => {  const slug = "seal-migration";  let credential = "";  let owner = "";  const ids: string[] = [];  const plain: Record<string, Record<string, unknown>> = {};  beforeAll(async () => {    ({ credential, owner } = await personalObject(slug, { open: TODOS_OPEN, windows: true }));    // The table as it stood before sealing: open, its rows written by a device and by an assistant, and edited.    expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [OPEN_DIARY] }, ADMIN)).status).toBe(200);    const bodies = ["xylophone-harbour at dawn", "periwinkle notes", "gondolier song", "kept for agents"];    for (const [i, body] of bodies.entries()) {      const data: Record<string, unknown> = { written_at: `2026-11-0${i + 1}`, body, ...(i === 3 ? { keep_open: true } : {}) };      const made = await act(slug, credential, "create", { table: TABLE, data });      expect(made.status, JSON.stringify(made.body)).toBe(200);      const id = (made.body.changed as { id: string }[])[0]!.id;      ids.push(id);      plain[id] = data;    }    const edited = await answer<{ record: { id: string } }>(slug, owner, "update_record", { table: TABLE, id: ids[1], patch: { body: "periwinkle notes, again" } });    expect(edited.record.id).toBe(ids[1]);    plain[ids[1]!]!.body = "periwinkle notes, again";    // An earlier Worker's act log cut a long args text at 4000 characters, so it no longer reads as JSON.    await onObject(slug, (sql) =>      sql.exec("INSERT INTO acts (id, at, person_id, act, args, outcome) VALUES ('cut-act', '2026-11-01T00:00:00Z', NULL, 'create', ?, 'done')", `{"table":"${TABLE}","data":{"body":"gondolier ${"x".repeat(60)}`),    );    // Then the table is marked sealed (§7 step 2): its open rows stay readable until swept.    const marked = await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [SEALED_DIARY] }, ADMIN);    expect(marked.status, JSON.stringify(marked.body)).toBe(200);  }, 120_000);  it("reads back a whole batch of twins, more than one statement may name", async () => {    // The live object refused this read (the object's SQL binds a hundred values a statement) and no row of a big table sealed.    const named = Array.from({ length: SEAL_BATCH }, () => crypto.randomUUID());    expect(await onObject(slug, (sql) => twins(sql, TABLE, named))).toEqual([]);  });  it("counts what is open before the sweep, by table, and never says content", async () => {    const check = await http<{ tables: Record<string, unknown>[] }>(slug, "GET", "/v1/admin/seal-check", undefined, ADMIN);    expect(check.status).toBe(200);    const mine = check.body.tables.find((t) => t.table === TABLE);    expect(mine).toMatchObject({ rows: 4, sealed: 0, open: 3, keep_open: 1, twins: 0, change_plain: 0 });    expect(Number(mine!.acts_plain)).toBeGreaterThanOrEqual(4);    for (const w of SECRET_WORDS) expect(JSON.stringify(check.body)).not.toContain(w);    // A device session is not the admin: the check takes the admin token or an owner-scope token.    expect((await http(slug, "GET", "/v1/admin/seal-check", undefined, { authorization: `Bearer ${credential}` })).status).toBe(403);  });  it("stages a twin beside its clear row, leaving the row untouched, and hands the twin back as stored", async () => {    const id = ids[0]!;    const before = await held(slug, id);    const staged = await act(slug, credential, "seal_stage", { table: TABLE, rows: [await twinOf(id, plain[id]!, before.version)] });    expect(staged.status, JSON.stringify(staged.body)).toBe(200);    const { staged: list, left } = staged.body as { staged: { id: string; twin: string }[]; left: unknown[] };    expect(left).toEqual([]);    expect(list.map((s) => s.id)).toEqual([id]);    // The clear row is as it was: the clear copy stays until the twin is verified and committed.    expect(await held(slug, id)).toEqual(before);    const read = await http<{ twins: { twin: string; id: string; expect_version: number; data: Record<string, unknown>; blind: string[] }[] }>(slug, "GET", `/v1/seal/twins?table=${TABLE}&twins=${list[0]!.twin}`, undefined, { authorization: `Bearer ${credential}` });    expect(read.status).toBe(200);    const twin = read.body.twins[0]!;    // The device's check: the twin as stored opens to the clear row it read.    const opened = await openRow(await tableKey(DK, DATABASE_ID, TABLE, 1), DATABASE_ID, TABLE, id, twin.data);    expect(opened).toMatchObject(plain[id]!);    expect(twin.blind.sort()).toEqual((await rowTokens(DK, TABLE, SPEC, plain[id]!)).sort());    // A token never reads the twins: only the owner's own devices.    const token = await mint(slug, credential, "assistant", ["owner"]);    expect((await http(slug, "GET", `/v1/seal/twins?table=${TABLE}&twins=${twin.twin}`, undefined, { authorization: `Bearer ${token}` })).status).toBe(403);    // Commit: the row takes the twin; its plaintext goes from the row and its earlier changes.    const committed = await act(slug, credential, "seal_commit", { table: TABLE, twins: [twin.twin] });    expect(committed.status, JSON.stringify(committed.body)).toBe(200);    expect(committed.body).toMatchObject({ sealed: [id], left: [] });    const after = await held(slug, id);    expect(Object.keys(after.data).sort()).toEqual(["dek_enc", "seal_v", "sealed_enc", "written_at"]);    // Committing the same twin again does nothing: it is gone (idempotent).    const again = await act(slug, credential, "seal_commit", { table: TABLE, twins: [twin.twin] });    expect(again.body).toMatchObject({ sealed: [], left: [{ id: twin.twin, code: "no_such_twin" }] });    expect(await held(slug, id)).toEqual(after);  });  it("drops a twin whose row was edited after the stage, keeps the edit in the clear, and refuses a stage at a stale version", async () => {    const id = ids[1]!;    const before = await held(slug, id);    const staged = await act(slug, credential, "seal_stage", { table: TABLE, rows: [await twinOf(id, plain[id]!, before.version)] });    const twin = (staged.body.staged as { twin: string }[])[0]!.twin;    // An edit lands between the stage and the commit. Outside a window an assistant's is refused (window_needed) and a    // device's clear copy too (sealed_in_clear); inside one the object seals the edit itself, so it lands in the clear only    // as a row from before the table was sealed takes it: here, the table opened again for the one edit, then sealed.    const outside = await tool(slug, owner, "update_record", { table: TABLE, id, patch: { body: "periwinkle notes, third" } });    expect(outside.isError).toBe(true);    expect(JSON.stringify(outside.content)).toContain("window");    // The table was open before: a device's clear copy is a phone still holding that list, taken and told its    // definitions are old, never refused (SEALING-CONTRACT.md). The row stays open, for the sweep to seal.    expect((await act(slug, credential, "update", { table: TABLE, id, data: { body: "periwinkle notes, from the phone" } })).body).toMatchObject({ definitions_stale: true });    expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [OPEN_DIARY] }, ADMIN)).status).toBe(200);    await answer(slug, owner, "update_record", { table: TABLE, id, patch: { body: "periwinkle notes, third" } });    expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [SEALED_DIARY] }, ADMIN)).status).toBe(200);    plain[id]!.body = "periwinkle notes, third";    const committed = await act(slug, credential, "seal_commit", { table: TABLE, twins: [twin] });    expect(committed.body).toMatchObject({ sealed: [], left: [{ id, code: "version_moved" }] });    const now = await held(slug, id);    expect(now.data.body, "the edit is kept, never overwritten by the older twin").toBe("periwinkle notes, third");    expect(await onObject(slug, (sql) => Number(sql.exec<{ n: number }>("SELECT count(*) AS n FROM seal_twin WHERE table_id = ?", TABLE).one().n))).toBe(0);    // A stage at the version read before the edit is left, by name.    const stale = await act(slug, credential, "seal_stage", { table: TABLE, rows: [await twinOf(id, plain[id]!, before.version)] });    expect(stale.body).toMatchObject({ staged: [], left: [{ id, code: "version_moved" }] });    // Read again, at the row's version now: it seals.    const fresh = await act(slug, credential, "seal_stage", { table: TABLE, rows: [await twinOf(id, plain[id]!, now.version)] });    const freshTwin = (fresh.body.staged as { twin: string }[])[0]!.twin;    expect((await act(slug, credential, "seal_commit", { table: TABLE, twins: [freshTwin] })).body).toMatchObject({ sealed: [id] });  });  it("keeps only the latest stage of a row, refuses what is not a device's sealed batch, and never lets a token stage", async () => {    const id = ids[2]!;    const { version } = await held(slug, id);    const first = (await act(slug, credential, "seal_stage", { table: TABLE, rows: [await twinOf(id, plain[id]!, version)] })).body.staged as { twin: string }[];    const second = (await act(slug, credential, "seal_stage", { table: TABLE, rows: [await twinOf(id, plain[id]!, version)] })).body.staged as { twin: string }[];    expect((await act(slug, credential, "seal_commit", { table: TABLE, twins: [first[0]!.twin] })).body).toMatchObject({ sealed: [], left: [{ code: "no_such_twin" }] });    // Plaintext in a twin is refused like any device write, and nothing of it is logged.    const clear = await act(slug, credential, "seal_stage", { table: TABLE, rows: [{ id, expect_version: version, data: { body: "gondolier", ...(await sealRow(DK, TABLE, id, 1, {})) } }] });    expect(clear.body).toMatchObject({ code: "sealed_in_clear" });    expect((await act(slug, credential, "seal_stage", { table: TABLE, rows: [{ id, expect_version: version, data: { written_at: "2026-11-03" } }] })).body).toMatchObject({ code: "seal_column_missing" });    expect((await act(slug, credential, "seal_stage", { table: TABLE, rows: Array.from({ length: 501 }, () => ({})) })).status).toBe(413);    expect((await act(slug, credential, "seal_stage", { table: TABLE, rows: [] })).body).toMatchObject({ code: "bad_args" });    const token = await mint(slug, credential, "assistant-2", ["owner"]);    expect((await tool(slug, token, "run_act", { act: "seal_stage", args: { table: TABLE, rows: [await twinOf(id, plain[id]!, version)] } })).isError).toBe(true);    expect((await tool(slug, token, "run_act", { act: "seal_commit", args: { table: TABLE, twins: [second[0]!.twin] } })).isError).toBe(true);    // A table that is not sealed has nothing to migrate.    expect((await act(slug, credential, "seal_purge", { table: "todo" })).body).toMatchObject({ code: "not_sealed" });    expect((await act(slug, credential, "seal_commit", { table: TABLE, twins: [second[0]!.twin] })).body).toMatchObject({ sealed: [id] });  });  it("purges the act log's earlier plaintext, after which the check counts nothing open but the row kept open, and no secret word is kept anywhere", async () => {    const purged = await act(slug, credential, "seal_purge", { table: TABLE });    expect(purged.status, JSON.stringify(purged.body)).toBe(200);    expect(Number(purged.body.scrubbed)).toBeGreaterThanOrEqual(4);    // Purging again changes nothing.    expect((await act(slug, credential, "seal_purge", { table: TABLE })).body).toMatchObject({ scrubbed: 0 });    const check = await http<{ tables: Record<string, unknown>[] }>(slug, "GET", "/v1/admin/seal-check", undefined, ADMIN);    expect(check.body.tables.find((t) => t.table === TABLE)).toMatchObject({ table: TABLE, rows: 4, sealed: 3, open: 0, keep_open: 1, twins: 0, change_plain: 0, acts_plain: 0, clear_left: 0, stray: 0, wide: 0 });    const logged = await kept(slug);    for (const w of SECRET_WORDS) {      expect(holdsWord(logged.rows, w), `rows.data holds ${w}`).toBe(false);      expect(holdsWord(logged.change, w), `change holds ${w}`).toBe(false);      expect(holdsWord(logged.acts, w), `acts holds ${w}`).toBe(false);      expect(holdsWord(logged.twins, w), `seal_twin holds ${w}`).toBe(false);    }    // The row kept open for agents stays as it was.    expect((await held(slug, ids[3]!)).data).toMatchObject({ body: "kept for agents", keep_open: true });  });});/** * RULE: `seal_purge` finds an earlier act by * the act's own table rule, not only by a `"table"` its args name: the * business `message` act writes business_message and never names it, and its * text is scrubbed from the act log once that table is sealed, as a later * message's is when it is logged. */describe("purging an act that does not name its table", () => {  const slug = "seal-purge-own-table";  const WORD = "quetzal-lantern";  it("scrubs a message act's text once business_message is sealed, and the check counts it before", async () => {    const { credential } = await personalObject(slug, { open: TODOS_OPEN, windows: true });    const me = await http<{ person: { id: string } }>(slug, "GET", "/v1/me", undefined, { authorization: `Bearer ${credential}` });    const sent = await act(slug, credential, "message", { text: `meet by the ${WORD}`, person: me.body.person.id });    expect(sent.status, JSON.stringify(sent.body)).toBe(200);    // The built-in message table (src/business.ts MESSAGE_TABLE), marked sealed: its text and name kept only in the seal.    const sealedMessage = {      format_version: 1,      id: "business_message",      name: "Message",      plural: "Messages",      visibility: "mine(person)",      date: "at",      columns: [        { key: "name", label: "Message", type: "text", required: true },        { key: "person", label: "Person", type: "link", link_to: "person", required: true },        { key: "from", label: "From", type: "choice", choices: ["member", "staff"], required: true },        { key: "text", label: "Text", type: "longtext", required: true },        { key: "about", label: "About", type: "text" },        { key: "at", label: "At", type: "date", required: true },      ],      seal: { clear: ["person", "from", "at"], blind: [] },    };    const marked = await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [sealedMessage] }, ADMIN);    expect(marked.status, JSON.stringify(marked.body)).toBe(200);    const check = await http<{ tables: Record<string, unknown>[] }>(slug, "GET", "/v1/admin/seal-check", undefined, ADMIN);    expect(check.body.tables.find((t) => t.table === "business_message")).toMatchObject({ acts_plain: 1 });    const purged = await act(slug, credential, "seal_purge", { table: "business_message" });    expect(purged.body).toMatchObject({ table: "business_message", scrubbed: 1 });    const acts = await onObject(slug, (sql) => sql.exec<{ act: string; args: string }>("SELECT act, args FROM acts WHERE act = 'message'").toArray());    expect(acts).toHaveLength(1);    expect(acts[0]!.args).not.toContain(WORD);    expect(JSON.parse(acts[0]!.args)).toMatchObject({ text: "‹sealed›", person: me.body.person.id });    expect((await act(slug, credential, "seal_purge", { table: "business_message" })).body).toMatchObject({ scrubbed: 0 });  }, 60_000);});