Cotton code
198 lines · 12.4 KB · TypeScriptRaw
/** * THE CIRCLE, SEALED (PEOPLE-DESIGN b.4, step A; src/chat/chat.ts `reseal`): once a phone has handed the object its * arrival key, every Circle row (one of his people, someone asking, someone blocked) also keeps its number and name * sealed to that key (`sealed`, "a2:"), which the object itself cannot open. The clear fields stay as they were: old * rows keep working beside sealed ones. And GET /v1/chat/people reads the Circle's own rows, never the database's * rows table, on an object of 200k rows. Every number is invented. */import { env, runInDurableObject } from "cloudflare:test";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { DEK_ENC, SEALED_ENC, bodyAad } from "../src/seal.ts";import { CIRCLE_BOX, tellGone, type ChatHost } from "../src/chat/chat.ts";import { VALUE_TABLE } from "../src/arrival.ts";import { arrivalPub, openArrivalRow } from "./arrival_keys.ts";import { bearer, fakes, open } from "./calling.ts";import { ADMIN, http } from "./personal.ts";import { chatPhone, type ChatPhone } from "./chat.ts";vi.setConfig({ testTimeout: 240_000 });let n = 0;const fresh = (): string => `+91900005${String(1000 + ++n).padStart(4, "0")}`;const ROWS = 200_000;beforeEach(() => {  fakes();});afterEach(() => {  vi.restoreAllMocks();});const dir = () => env.DIRECTORY.get(env.DIRECTORY.idFromName("directory"));type Entry = { number: string; name: string | null; sealed?: string };type People = { people: Entry[]; asking: Entry[]; blocked: Entry[] };async function opened(sealed: string, db: string): Promise<{ number: string; name: string | null }> {  expect(sealed).toMatch(/^a2:/);  const [body, dek] = sealed.slice(3).split("|");  const row = await openArrivalRow({ [SEALED_ENC]: body, [DEK_ENC]: dek }, bodyAad(db, VALUE_TABLE, CIRCLE_BOX), VALUE_TABLE, CIRCLE_BOX);  return JSON.parse(String(row.payload)) as { number: string; name: string | null };}describe("the Circle, sealed (b.4 step A)", () => {  it("keeps each row's number and name sealed to the arrival key beside the clear ones, and reads no rows table", async () => {    const a: ChatPhone = await chatPhone(fresh(), `dev-sealed-${++n}`);    const b: ChatPhone = await chatPhone(fresh(), `dev-sealed-${++n}`);    const c: ChatPhone = await chatPhone(fresh(), `dev-sealed-${++n}`);    const d: ChatPhone = await chatPhone(fresh(), `dev-sealed-${++n}`);    const ask = <T>(method: string, path: string, body?: unknown) => open<T>(method, path, body, bearer(a.credential));    const db = (await ask<{ business: { database_id: string } }>("GET", "/v1/me")).body.business.database_id;    // Before any key is handed: rows as they always were, nothing sealed.    await a.say("accept", b.number);    expect((await ask<People>("GET", "/v1/chat/people")).body.people.find((p) => p.number === b.number)).toEqual({ number: b.number, name: null, waiting: true });    // The phone hands its arrival key; from then on each row written is sealed too.    const handed = await ask("POST", "/v1/act", { act: "create", args: { table: "seal_key", id: "arrival", data: { pub: await arrivalPub() } } });    expect(handed.status, JSON.stringify(handed.body)).toBe(200);    await b.say("accept", a.number);    await a.say("accept", b.number);    await c.say("accept", a.number); // c asks a    await a.say("block", d.number);    const people = (await ask<People>("GET", "/v1/chat/people")).body;    const mine = people.people.find((p) => p.number === b.number)!;    expect(mine).toMatchObject({ number: b.number, waiting: false });    expect(await opened(mine.sealed!, db)).toEqual({ number: b.number, name: mine.name });    const asking = people.asking.find((p) => p.number === c.number)!;    expect(await opened(asking.sealed!, db)).toMatchObject({ number: c.number });    const blocked = people.blocked.find((p) => p.number === d.number)!;    expect(await opened(blocked.sealed!, db)).toMatchObject({ number: d.number });    // The sealed copy holds no number the object could read.    for (const e of [mine, asking, blocked]) expect(e.sealed).not.toContain(e.number.slice(1));    // Rule 2: 200k rows in the database; GET /v1/chat/people reads the Circle's rows, not the rows table.    const slug = (await dir().lookup(a.number))!;    const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));    const now = new Date().toISOString();    await runInDurableObject(stub, (_i, state) => {      state.storage.sql.exec(        `WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?)         INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at)         SELECT 'session', 'session-' || i, '{"sealed_enc":"s1:AAAA","dek_enc":"d1:AAAA","seal_v":1}', NULL, 1, 0, ?, ? FROM n`,        ROWS,        now,        now,      );    });    await ask("GET", "/v1/chat/people"); // warm: the object's once-per-instance work is not the read's    type Counted = { cursors: SqlStorageCursor<Record<string, SqlStorageValue>>[]; said: string[] };    await runInDurableObject(stub, (_i, state) => {      const sql = state.storage.sql as unknown as { exec: (...x: unknown[]) => SqlStorageCursor<Record<string, SqlStorageValue>>; __counted?: Counted; __exec?: (...x: unknown[]) => SqlStorageCursor<Record<string, SqlStorageValue>> };      const exec = (sql.__exec ??= sql.exec.bind(sql));      const counted: Counted = { cursors: [], said: [] };      sql.__counted = counted;      sql.exec = (...x: unknown[]) => {        const cursor = exec(...x);        counted.cursors.push(cursor);        counted.said.push(String(x[0]).replace(/\s+/g, " ").slice(0, 200));        return cursor;      };    });    expect((await ask("GET", "/v1/chat/people")).status).toBe(200);    const { rowsRead, heavy } = await runInDurableObject(stub, (_i, state) => {      const sql = state.storage.sql as unknown as { __counted: Counted; __exec: unknown; exec: unknown };      const counted = sql.__counted;      sql.exec = sql.__exec;      return { rowsRead: counted.cursors.reduce((s, c) => s + c.rowsRead, 0), heavy: counted.cursors.map((c, i) => ({ n: c.rowsRead, sql: counted.said[i] })).filter((x) => x.n > 1000) };    });    expect(heavy, JSON.stringify(heavy)).toEqual([]);    expect(rowsRead).toBeLessThan(2000);  });  it("with the switch on, keeps no clear number in a new row, and still routes, accepts, blocks and tells by its digest (step B)", async () => {    const a: ChatPhone = await chatPhone(fresh(), `dev-sealed-${++n}`);    const b: ChatPhone = await chatPhone(fresh(), `dev-sealed-${++n}`);    const c: ChatPhone = await chatPhone(fresh(), `dev-sealed-${++n}`);    const d: ChatPhone = await chatPhone(fresh(), `dev-sealed-${++n}`);    const ask = <T>(method: string, path: string, body?: unknown) => open<T>(method, path, body, bearer(a.credential));    const db = (await ask<{ business: { database_id: string } }>("GET", "/v1/me")).body.business.database_id;    const slug = (await dir().lookup(a.number))!;    const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));    expect((await ask("POST", "/v1/act", { act: "create", args: { table: "seal_key", id: "arrival", data: { pub: await arrivalPub() } } })).status).toBe(200);    await runInDurableObject(stub, (instance) => (instance as unknown as { store: { setMeta(k: string, v: string): void } }).store.setMeta("circle_sealed_only", "on"));    // b and a add each other: a's row for b keeps no clear number, yet b is found (by digest) as having added a back.    await a.say("accept", b.number);    await b.say("accept", a.number);    let people = (await ask<People>("GET", "/v1/chat/people")).body;    const mine = people.people.find((p) => p.sealed && p.number === null)!;    expect(mine, JSON.stringify(people)).toMatchObject({ number: null, name: null, waiting: false });    expect(await opened(mine.sealed!, db)).toEqual({ number: b.number, name: null });    // c asks with a name; accepting carries the sealed copy, name and all, though the object no longer reads it.    await stub.chatAskIn({ from: c.number, name: "Chitra Invented" });    people = (await ask<People>("GET", "/v1/chat/people")).body;    expect(people.asking).toHaveLength(1);    expect(people.asking[0]).toMatchObject({ number: null, name: null });    expect(await opened(people.asking[0]!.sealed!, db)).toEqual({ number: c.number, name: "Chitra Invented" });    await a.say("accept", c.number);    people = (await ask<People>("GET", "/v1/chat/people")).body;    const fromAsk = await Promise.all(people.people.map((p) => opened(p.sealed!, db)));    expect(fromAsk).toContainEqual({ number: c.number, name: "Chitra Invented" });    // Blocked, then unblocked: the sealed copy goes to Blocked and back.    await a.say("block", c.number);    people = (await ask<People>("GET", "/v1/chat/people")).body;    expect(await opened(people.blocked[0]!.sealed!, db)).toEqual({ number: c.number, name: "Chitra Invented" });    await a.say("unblock", c.number);    people = (await ask<People>("GET", "/v1/chat/people")).body;    expect(await Promise.all(people.people.map((p) => opened(p.sealed!, db)))).toContainEqual({ number: c.number, name: "Chitra Invented" });    await a.say("block", d.number);    // Nothing in a's Circle tables holds a number in the clear.    const stored = await runInDurableObject(stub, (_i, state) => JSON.stringify(["chat_peer", "chat_ask", "chat_blocked"].map((t) => state.storage.sql.exec(`SELECT number, name FROM ${t}`).toArray())));    for (const x of [b, c, d]) expect(stored).not.toContain(x.number.slice(1));    expect(stored).not.toContain("Chitra");    // a's account goes: b's object is told, found by the bound slug or the digest, not a number.    const told = await runInDurableObject(stub, (instance) => tellGone((instance as unknown as { chatHost(): ChatHost }).chatHost()));    expect(told).toBe(2); // b and c    const bStub = env.BUSINESS.get(env.BUSINESS.idFromName((await dir().lookup(b.number))!));    const left = await runInDurableObject(bStub, (_i, state) => state.storage.sql.exec<{ left_at: string | null }>("SELECT left_at FROM chat_peer WHERE left_at IS NOT NULL").toArray());    expect(left).toHaveLength(1);  });  it("seals the rows written before, only when the coordinator runs it, a few a call, and drops their clear numbers only when asked (step C)", async () => {    const a: ChatPhone = await chatPhone(fresh(), `dev-sealed-${++n}`);    const b: ChatPhone = await chatPhone(fresh(), `dev-sealed-${++n}`);    const ask = <T>(method: string, path: string, body?: unknown) => open<T>(method, path, body, bearer(a.credential));    const db = (await ask<{ business: { database_id: string } }>("GET", "/v1/me")).body.business.database_id;    const slug = (await dir().lookup(a.number))!;    await a.say("accept", b.number);    await b.say("accept", a.number);    expect((await ask("POST", "/v1/act", { act: "create", args: { table: "seal_key", id: "arrival", data: { pub: await arrivalPub() } } })).status).toBe(200);    type Converted = { arrival: boolean; tables: Record<string, { toSeal: number; clear: number; done: number }> };    const run = (body: unknown, headers: Record<string, string> = ADMIN) => http<Converted>(slug, "POST", "/v1/admin/circle/seal", body, headers);    // The owner's own credential cannot run it.    expect((await run({ confirm: "seal" }, bearer(a.credential))).status).toBe(403);    // Counting changes nothing.    const counted = await run({});    expect(counted.body.tables.chat_peer).toEqual({ toSeal: 1, clear: 1, done: 0 });    expect((await ask<People>("GET", "/v1/chat/people")).body.people[0]!.sealed).toBeUndefined();    // Sealed, clear number kept.    expect((await run({ confirm: "seal", most: 1 })).body.tables.chat_peer).toMatchObject({ toSeal: 1, done: 1 });    let people = (await ask<People>("GET", "/v1/chat/people")).body.people;    expect(people[0]).toMatchObject({ number: b.number, waiting: false });    expect(await opened(people[0]!.sealed!, db)).toEqual({ number: b.number, name: null });    // Dropped: still one of a's people, found by digest, read from the sealed copy alone.    expect((await run({ confirm: "seal", drop: true })).body.tables.chat_peer).toMatchObject({ clear: 1, done: 1 });    expect((await run({})).body.tables.chat_peer).toEqual({ toSeal: 0, clear: 0, done: 0 });    people = (await ask<People>("GET", "/v1/chat/people")).body.people;    expect(people[0]).toMatchObject({ number: null, waiting: false });    expect(await opened(people[0]!.sealed!, db)).toEqual({ number: b.number, name: null });  });});