Cotton code
150 lines · 11.9 KB · TypeScriptRaw
/** * The owner allows (src/owner_asks.ts; ROUTES-AUDIT finding 8, coordinator 23 Nov 2026): with token scopes on, an * assistant's token that sends mail from the owner's domain, changes where an address forwards, or invites guests to a * Google event is not refused outright and is not let through: the request is kept, a card row goes to the owner's * phones, and only the owner's own device allows it (then it runs, once) or refuses it. Off, nothing changes. Every * account, address and guest is invented. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { bodyAad } from "../src/seal.ts";import { openArrivalRow } from "./arrival_keys.ts";import { ADMIN, DATABASE_ID, http, personalObject } from "./personal.ts";type Doc = Record<string, unknown>;const as = (token: string) => ({ authorization: `Bearer ${token}` });const DOMAIN = "invented-asks.example";async function setUp(slug: string, on: boolean, arrival = true) {  const { credential } = await personalObject(slug, { arrival });  const device = as(credential);  await http(slug, "POST", "/v1/mail/domains", { domain: DOMAIN }, device);  expect((await http(slug, "POST", "/v1/mail/domains/prove-dev", { domain: DOMAIN }, device)).status).toBe(200);  expect((await http(slug, "POST", "/v1/mail/addresses", { address: `me@${DOMAIN}`, forwardTo: null, isDefault: true }, device)).status).toBe(200);  const minted = await http<{ token: string }>(slug, "POST", "/v1/act", { act: "mint_token", args: { name: "Invented Assistant", scopes: ["owner"], allow: "all" } }, device);  expect(minted.status, JSON.stringify(minted.body)).toBe(200);  if (on) {    const gate = await http<{ holders: { token_id: string }[] }>(slug, "GET", "/v1/admin/token-scopes", undefined, ADMIN);    expect((await http(slug, "POST", "/v1/admin/token-scopes", { on: true, excuse: gate.body.holders.map((h) => h.token_id) }, ADMIN)).status).toBe(200);  }  return { device, token: as(minted.body.token) };}/** The rows as the server holds and serves them: what it can read without a key. */async function stored(slug: string, device: Record<string, string>): Promise<{ id: string; data: Doc }[]> {  const sync = await http<{ rows: { table: string; id: string; data: Doc }[] }>(slug, "GET", "/v1/sync?since=0", undefined, device);  return sync.body.rows.filter((r) => r.table === "assistant_ask");}/** The cards as the owner's phone reads them: each row opened with the arrival key (LOCK TABLES 1: sealed at arrival). */async function asks(slug: string, device: Record<string, string>): Promise<Doc[]> {  return Promise.all((await stored(slug, device)).map(async (r) => ({ id: r.id, ...r.data, ...(await openArrivalRow(r.data, bodyAad(DATABASE_ID, "assistant_ask", r.id), "assistant_ask", r.id)) })));}const SEND = { draft: "11111111-2222-4333-8444-555555555555", from: `me@${DOMAIN}`, to: ["asha@invented.example"], cc: [], bcc: ["hidden@invented.example"], subject: "Invented plans", text: "Shall we walk on Saturday?", attachments: [{ name: "plan.txt", mime: "text/plain", content: "aGVsbG8=" }] };const EVENT = { op: "insert", id: "21111111-2222-4333-8444-555555555555", notify: "all", event: { summary: "Invented picnic", start: { date: "2026-12-01" }, end: { date: "2026-12-02" }, attendees: [{ email: "a@invented.example" }, { email: "b@invented.example" }] } };describe("the owner allows", { timeout: 120_000 }, () => {  it("on: the three acts wait for the owner's Allow on the phone; nothing else a token does on a device route gets in", async () => {    const slug = "owner-asks-on";    const { device, token } = await setUp(slug, true);    // Each of the three is kept and asked, answered 202 with the ask.    const send = await http<Doc>(slug, "POST", "/v1/mail/send", SEND, token);    expect(send.status, JSON.stringify(send.body)).toBe(202);    expect(send.body.code).toBe("owner_asked");    const forward = await http<Doc>(slug, "POST", "/v1/mail/addresses", { address: `me@${DOMAIN}`, forwardTo: "elsewhere@invented.example" }, token);    expect(forward.status).toBe(202);    const guests = await http<Doc>(slug, "POST", "/v1/google/events", EVENT, token);    expect(guests.status).toBe(202);    // The rest stays refused: reading mail settings, an address with no forwarding asked, an event with no guests.    expect((await http(slug, "GET", "/v1/mail/settings", undefined, token)).status).toBe(403);    expect((await http(slug, "POST", "/v1/mail/addresses", { address: `you@${DOMAIN}` }, token)).status).toBe(403);    expect((await http(slug, "POST", "/v1/google/events", { ...EVENT, event: { ...EVENT.event, attendees: [] } }, token)).status).toBe(403);    // What the server keeps of each card: its kind, the asking token, times and state; never an address, a subject,    // a title or a guest (LOCK TABLES 1). The phone opens the rest.    const raw = JSON.stringify(await stored(slug, device));    for (const word of ["asha@invented.example", "Invented plans", "elsewhere@invented.example", "Invented picnic", "a@invented.example", `me@${DOMAIN}`]) expect(raw, word).not.toContain(word);    expect((await stored(slug, device)).every((r) => typeof r.data.sealed_enc === "string" && r.data.state === "waiting" && typeof r.data.token_id === "string")).toBe(true);    // The phone's cards (sealed for it): everything Allow would send, bcc, text and attachments too (AUDIT C 5).    const cards = await asks(slug, device);    expect(cards.map((c) => [c.kind, c.state, c.client])).toEqual(expect.arrayContaining([["mail_send", "waiting", "Invented Assistant"], ["mail_forward", "waiting", "Invented Assistant"], ["guests", "waiting", "Invented Assistant"]]));    const sendCard = cards.find((c) => c.kind === "mail_send")!;    expect(sendCard).toMatchObject({ from: `me@${DOMAIN}`, to: ["asha@invented.example"], bcc: ["hidden@invented.example"], subject: "Invented plans", text: SEND.text, text_chars: SEND.text.length, attachments: ["plan.txt (text/plain, 5 bytes)"] });    for (const word of ["hidden@invented.example", "Shall we walk"]) expect(raw, word).not.toContain(word);    expect(cards.find((c) => c.kind === "guests")).toMatchObject({ title: "Invented picnic", count: 2, notify: true });    // Only the owner's own device answers: not the token, not the admin; and a card is not written by hand.    expect((await http(slug, "POST", "/v1/asks/allow", { ask_id: forward.body.ask_id }, token)).status).toBe(403);    expect((await http(slug, "POST", "/v1/asks/allow", { ask_id: forward.body.ask_id }, ADMIN)).status).toBe(403);    expect((await http(slug, "POST", "/v1/act", { act: "update", args: { table: "assistant_ask", id: forward.body.ask_id, data: { state: "allowed" } } }, device)).status).toBe(403);    // Allow runs the kept request once, as the device would: the address now forwards. The token reads the outcome.    const allowed = await http<Doc>(slug, "POST", "/v1/asks/allow", { ask_id: forward.body.ask_id }, device);    expect(allowed.status, JSON.stringify(allowed.body)).toBe(200);    expect(allowed.body).toMatchObject({ state: "done", status: 200 });    const settings = await http<{ addresses: { address: string; forwardTo: string | null }[] }>(slug, "GET", "/v1/mail/settings", undefined, device);    expect(settings.body.addresses.find((a) => a.address === `me@${DOMAIN}`)?.forwardTo).toBe("elsewhere@invented.example");    const read = await http<Doc>(slug, "GET", `/v1/asks/${forward.body.ask_id}`, undefined, token);    expect(read.body).toMatchObject({ kind: "mail_forward", state: "done", status: 200 });    // The answer the token reads is kept on the server alone; the card's copy is sealed for the phone.    expect(JSON.stringify(read.body.answer)).toContain("elsewhere@invented.example");    expect(JSON.stringify(await stored(slug, device))).not.toContain("elsewhere@invented.example");    // Once: a second Allow finds nothing to run.    expect((await http(slug, "POST", "/v1/asks/allow", { ask_id: forward.body.ask_id }, device)).status).toBe(409);    // Refuse drops it; it never runs, and the token reads that.    expect((await http<Doc>(slug, "POST", "/v1/asks/refuse", { ask_id: send.body.ask_id }, device)).body).toMatchObject({ state: "refused" });    expect((await http<Doc>(slug, "GET", `/v1/asks/${send.body.ask_id}`, undefined, token)).body).toMatchObject({ state: "refused", status: null });    expect((await http(slug, "POST", "/v1/asks/allow", { ask_id: send.body.ask_id }, device)).status).toBe(409);  });  it("an ask written open before the table was sealed: its answer never goes into the row, and an older answer still reads", async () => {    const slug = "owner-asks-legacy";    const { device, token } = await setUp(slug, true);    const forward = await http<Doc>(slug, "POST", "/v1/mail/addresses", { address: `me@${DOMAIN}`, forwardTo: "legacy@invented.example" }, token);    expect(forward.status).toBe(202);    const askId = String(forward.body.ask_id);    const onObject = <T>(fn: (sql: SqlStorage) => T) => runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, state) => fn(state.storage.sql));    // As a build before LOCK TABLES 1 wrote it: the card in the clear, waiting across the deploy.    const open = (data: Doc) => onObject((sql) => sql.exec("UPDATE rows SET data = ? WHERE table_id = 'assistant_ask' AND id = ?", JSON.stringify(data), askId));    const clearCard = { kind: "mail_forward", address: `me@${DOMAIN}`, forward_to: "legacy@invented.example", token_id: (await stored(slug, device))[0]!.data.token_id, client: "Invented Assistant", asked_at: new Date().toISOString(), expires_at: new Date(Date.now() + 600_000).toISOString(), state: "waiting" };    await open(clearCard);    const allowed = await http<Doc>(slug, "POST", "/v1/asks/allow", { ask_id: askId }, device);    expect(allowed.status, JSON.stringify(allowed.body)).toBe(200);    const row = (await stored(slug, device)).find((r) => r.id === askId)!;    expect(row.data).toMatchObject({ state: "done", status: 200 });    expect("answer" in row.data).toBe(false);    expect(JSON.stringify((await http<Doc>(slug, "GET", `/v1/asks/${askId}`, undefined, token)).body.answer)).toContain("legacy@invented.example");    // An ask answered before LOCK TABLES 1: its answer on the open row, nothing kept beside it; the asking token still reads it.    await open({ ...clearCard, state: "done", status: 200, answer: JSON.stringify({ forwardTo: "older@invented.example" }) });    await onObject((sql) => sql.exec("DELETE FROM owner_ask_answer WHERE ask_id = ?", askId));    expect((await http<Doc>(slug, "GET", `/v1/asks/${askId}`, undefined, token)).body).toMatchObject({ state: "done", answer: { forwardTo: "older@invented.example" } });  });  it("off: nothing is asked, a token reaches these routes as before", async () => {    const slug = "owner-asks-off";    const { device, token } = await setUp(slug, false);    const forward = await http<Doc>(slug, "POST", "/v1/mail/addresses", { address: `me@${DOMAIN}`, forwardTo: "elsewhere@invented.example" }, token);    expect(forward.status, JSON.stringify(forward.body)).toBe(200);    expect(await asks(slug, device)).toEqual([]);  });  it("with no arrival key handed yet, an ask is refused: nothing is kept, no card is written in the clear", async () => {    const slug = "owner-asks-no-key";    const { device, token } = await setUp(slug, true, false);    const send = await http<Doc>(slug, "POST", "/v1/mail/send", SEND, token);    expect(send.status).toBe(409);    expect(send.body.code).toBe("no_arrival_key");    expect(await stored(slug, device)).toEqual([]);  });  it("an assistant cannot bury the phone: at most five asks wait at once", async () => {    const slug = "owner-asks-most";    const { token } = await setUp(slug, true);    for (let i = 0; i < 5; i++) expect((await http(slug, "POST", "/v1/mail/send", { ...SEND, draft: `31111111-2222-4333-8444-55555555555${i}` }, token)).status).toBe(202);    expect((await http<Doc>(slug, "POST", "/v1/mail/send", SEND, token)).body).toMatchObject({ code: "too_many_asks" });  });});