Cotton code
102 lines · 5.7 KB · TypeScriptRaw
/** * A narrowing of a sealed table's clear list, end to end (LOCK TABLES 2: H1 and M1): * *   cd apps/business && pnpm -s exec tsx scripts/__tests__/e2e-narrow.ts * * Starts the Worker under `wrangler dev` with the personal object onboarded (`dev-worker.ts`). Then: * * 1. The phone core's walk `an_old_phone_writes_across_a_narrowing_and_is_never_refused` *    (crates/cotton-ffi/src/phone/personal_object_e2e.rs): a copy holding the wider list writes offline while the *    object narrows it, with real values and with nulls; nothing is refused, the same pass brings the narrow list. *    It also leaves a row holding a key that is no column, and makes the Mac a vault device under a key file. * 2. The REAL `seal-migrate` binary (crates/cotton-mac) reseals the table against this Worker, `--from-start`. * 3. seal-check before and after: clear_left, stray and wide go to 0, and no value is said. * 4. A fresh phone copy opens every row (`a_fresh_phone_opens_every_row_the_mac_resealed`). * * Synthetic rows only; wrangler dev is stopped and the temp dir removed however it ends. Cargo runs one at a time with * CARGO_BUILD_JOBS=3 (the box's load rule). */import { spawnSync, type ChildProcess } from "node:child_process";import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { APP, check, startDevWorker, stop } from "./dev-worker.ts";import { WS } from "./fixture.ts";const CRATES = resolve(APP, "../../crates");const WORDS = ["Heron over the weir", "four-stars", "Crane in the rain", "tired", "calm", "Egret at dawn"];const tmp = mkdtempSync(join(tmpdir(), "e2e-narrow-"));let wrangler: ChildProcess | null = null;const cleanup = (): void => {  stop(wrangler);  wrangler = null;  rmSync(tmp, { recursive: true, force: true });};process.on("SIGINT", () => {  cleanup();  process.exit(130);});const cargo = (args: string[], env: Record<string, string>) => spawnSync("cargo", args, { cwd: CRATES, encoding: "utf8", env: { ...process.env, CARGO_BUILD_JOBS: "3", ...env } });const said = (r: ReturnType<typeof cargo>) => (r.error ? String(r.error) : `${r.stdout?.slice(-4000) ?? ""}${r.stderr?.slice(-4000) ?? ""}`);type Standing = { table: string; clear_left: number; stray: number; wide: number; sealed: number; rows: number };try {  const { base, api, admin, credential } = await startDevWorker(tmp, WS, (child) => {    wrangler = child;  });  const minted = await api<{ token?: string }>("POST", "/v1/act", { act: "mint_token", args: { name: "e2e narrow", scopes: ["owner"] } }, credential);  const token = minted.token!;  const macKey = join(tmp, "mac.key");  const env = { COTTON_E2E_BASE: base, COTTON_E2E_CREDENTIAL: credential, COTTON_E2E_DATABASE: WS, COTTON_E2E_TOKEN: token, COTTON_E2E_MAC_KEY: macKey };  const walk = cargo(["test", "-q", "-p", "cotton-ffi", "--lib", "phone::personal_object::e2e::an_old_phone_writes_across_a_narrowing", "--", "--ignored", "--nocapture", "--test-threads=1"], env);  const rows = /E2E-NARROW (\{.*\})/.exec(walk.stdout ?? "");  check(walk.status === 0 && rows, `the old phone's walk passes${walk.status === 0 && rows ? "" : `\n${said(walk)}`}`);  const standing = async (): Promise<Standing> => {    const check_ = await api<{ tables: Standing[] }>("GET", "/v1/admin/seal-check", undefined, admin);    for (const w of WORDS) check(!JSON.stringify(check_).includes(w), `seal-check says no value (${w})`);    return check_.tables.find((t) => t.table === "e2e_narrow")!;  };  const before = await standing();  console.log(`before the reseal: ${JSON.stringify(before)}`);  // The phone's own sweep may already have resealed what it holds under the narrow list; the stray row it never edits.  check(before.clear_left >= 1 && before.stray === 1, "before: rows hold a sealed key in the clear, one a key that is no column");  const dataDir = join(tmp, "mac");  mkdirSync(dataDir);  const tokenFile = join(tmp, "credential");  writeFileSync(tokenFile, `${credential}\n`);  chmodSync(tokenFile, 0o600);  const reseal = cargo(["run", "-q", "-p", "cotton-mac", "--bin", "seal-migrate", "--", "--base", base, "--data-dir", dataDir, "--device-id", "e2e", "--token-file", tokenFile, "--key-file", macKey, "--tables", "e2e_narrow", "--from-start"], {});  console.log(`seal-migrate: exit ${reseal.status}\n${reseal.stdout}`);  check(reseal.status === 0, `the real seal-migrate binary reseals the table\n${said(reseal)}`);  const after = await standing();  console.log(`after the reseal: ${JSON.stringify(after)}`);  check(after.clear_left === 0 && after.stray === 0 && after.wide === 0, "after: nothing left in the clear, no stray key, no row marked");  // The object keeps none of the words anywhere it serves rows.  type Row = { table: string; data: Record<string, unknown> };  const served: Row[] = [];  for (let query = "since=0&tables=e2e_narrow"; ; ) {    const page = await api<{ rows: Row[]; next?: string }>("GET", `/v1/sync?${query}`, undefined, credential);    served.push(...page.rows);    if (!page.next) break;    query = `cursor=${page.next}`;  }  for (const w of WORDS) check(!JSON.stringify(served).includes(w), `no row is served with ${w} in the clear`);  const open = cargo(["test", "-q", "-p", "cotton-ffi", "--lib", "phone::personal_object::e2e::a_fresh_phone_opens_every_row_the_mac_resealed", "--", "--ignored", "--nocapture", "--test-threads=1"], { ...env, COTTON_E2E_ROWS: rows![1]! });  check(open.status === 0 && /E2E-NARROW-OPEN/.test(open.stdout ?? ""), `a fresh phone opens every resealed row${open.status === 0 ? "" : `\n${said(open)}`}`);  console.log("e2e narrow: passed");} catch (error) {  console.error((error as Error).message);  process.exitCode = 1;} finally {  cleanup();}