276 lines · 16.5 KB · TypeScriptRaw
/** * SHARED SPACE: the one membership gate, as a matrix generated from the route list (src/space/routes.ts `ROUTES`). * For every route and every principal who must not get in (a plain member on the owner's routes, someone who is not a * member, a removed member, the owner writing at an old epoch, a member whose sign-in was ended, a link holder on a * member's route, an expired link, a stopped link, a link whose maker was removed), and in the deleted and ending * states, the answer is a refusal that carries nothing of the space: no record, wrap, number, key, member id, file id * or link hash. Then every route is used by the one it is for, on a fresh space. A route added to ROUTES with no * sample below fails to compile and fails here. */import { env, runInDurableObject } from "cloudflare:test";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Business } from "../src/business.ts";import { forgetVouches } from "../src/space/door.ts";import { ROUTES, type Route, type RouteName } from "../src/space/routes.ts";import { fakes, open } from "./calling.ts";import { accept, found, inSpace, kept, linkParts, opaque, person, record, signed, hashOf, upload, wrap, type Person } from "./shared_space_people.ts";vi.setConfig({ testTimeout: 900_000 });beforeEach(() => { fakes();});afterEach(() => { vi.restoreAllMocks();});type Body = Record<string, unknown>;interface People { a: Person; // owner b: Person; // plain member r: Person; // removed n: Person; // signed in, one of a's people, never a member v: Person; // a member whose sign-in is ended}interface Link { id: string; auth: string;}interface World { space: string; epoch: number; id: Record<string, string>; file: string; live: Link; expired: Link; stopped: Link; orphaned: Link; /** Every string a leak would show. */ secrets: string[]; /** The owner's signed handover, first in the chain (AUDIT FIX B1: the space verifies statements). */ handover: string; /** The newest statement, for the owner to take off. */ drop?: { seq: number; hash: string };}type Principal = "owner" | "member" | "non_member" | "removed" | "old_epoch" | "revoked" | "link" | "expired_link" | "stopped_link" | "orphaned_link";const REFUSED: Principal[] = ["member", "non_member", "removed", "old_epoch", "revoked", "link", "expired_link", "stopped_link", "orphaned_link"];const LINKS: Principal[] = ["link", "expired_link", "stopped_link", "orphaned_link"];/** One request per route; `epoch` is the epoch a write names (the old-epoch principal names the previous one). */const SAMPLES: Record<RouteName, (w: World, p: People, epoch: number) => { query?: string; body?: Body }> = { "spaces.list": () => ({}), "spaces.found": () => ({ body: { members: [] } }), "space.read": () => ({}), "roster.list": () => ({ query: "?after=-1" }), "roster.add": (w) => ({ body: { statement: w.handover } }), "roster.drop": (w) => ({ body: w.drop ?? { seq: 1, hash: "0".repeat(64) } }), "records.list": () => ({ query: "?after=0" }), "records.put": (_w, _p, epoch) => ({ body: { epoch, records: [record(`new-${opaque(6)}`, "item", "alb-x", [], epoch)] } }), "records.rewrap": (_w, _p, epoch) => ({ body: { epoch, records: [{ id: "it-old", key: `g1:${epoch}:${opaque(60)}` }] } }), "records.delete": () => ({ body: { ids: ["it-a"] } }), "records.stale": () => ({}), upload: (_w, _p, epoch) => ({ body: { epoch, size: 128 } }), media: (w) => ({ body: { files: [w.file] } }), "members.add": (_w, p) => ({ body: { numbers: [p.n.number] } }), // Sets b to what b is already (add), so the matrix's later cases see the same space. "roles.set": (w, p) => ({ body: { member: w.id[p.b.number], role: "add" } }), "wraps.add": (w, p, epoch) => ({ body: { epoch, wraps: { [w.id[p.n.number] ?? "m0000000000000000"]: wrap() } } }), epoch: (w, p, epoch) => ({ body: { epoch: epoch + 1, remove: [], wraps: { [w.id[p.a.number]!]: wrap(), [w.id[p.b.number]!]: wrap(), [w.id[p.v.number]!]: wrap() }, link_wraps: { [w.live.id]: wrap() } } }), keep: (w, p) => ({ body: { member: w.id[p.r.number] } }), leave: () => ({ body: {} }), "space.delete": () => ({ body: {} }), "links.make": (_w, _p, epoch) => ({ body: { epoch, link: opaque(12), album: "alb-x", public: opaque(32), auth_hash: "0".repeat(64), wrap: wrap(), days: 7 } }), "links.stop": (w) => ({ body: { link: w.live.id } }), "link.read": () => ({ body: {} }), "link.media": (w) => ({ body: { files: [w.file] } }),};/** A space as the matrix needs it: an owner, two members, a removed member, epoch 3, records (one still at epoch 2), a file, four links. */async function world(p: People): Promise<World> { const { space, id } = await found(p.a, [p.b, p.r, p.v]); const { file } = await upload(p.b, space, 256); const records = [record("alb-x", "album", "alb-x", [], 1), record("it-a", "item", "alb-x", [file], 1), record("it-other", "item", "alb-y", [], 1)]; expect((await p.b.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records })).status).toBe(200); const hashes: string[] = []; const makeLink = async (who: Person, epoch: number): Promise<Link> => { const l = await linkParts(); const made = await who.ask("POST", `/v1/spaces/${space}/links`, { epoch, link: l.id, album: "alb-x", public: l.public, auth_hash: l.hash, wrap: wrap(), days: 30 }); expect(made.status, JSON.stringify(made.body)).toBe(200); hashes.push(l.hash, l.public); return { id: l.id, auth: l.auth }; }; // r makes a link while holding ownership (set by hand: only an owner makes links), then is removed: it stops with them. await inSpace(space, (sql) => sql.exec("UPDATE member SET role = 'owner' WHERE id = ?", id[p.r.number])); const orphaned = await makeLink(p.r, 1); await inSpace(space, (sql) => sql.exec("UPDATE member SET role = 'member' WHERE id = ?", id[p.r.number])); const allWraps = (epoch: number, who: Person[]) => ({ epoch, wraps: Object.fromEntries(who.map((x) => [id[x.number]!, wrap()])) }); const second = await p.a.ask("POST", `/v1/spaces/${space}/epoch`, { ...allWraps(2, [p.a, p.b, p.v]), remove: [id[p.r.number]] }); expect(second.status, JSON.stringify(second.body)).toBe(200); expect((await p.b.ask("POST", `/v1/spaces/${space}/records`, { epoch: 2, records: [record("it-old", "item", "alb-x", [], 2)] })).status).toBe(200); const live = await makeLink(p.a, 2); const expired = await makeLink(p.a, 2); const stopped = await makeLink(p.a, 2); await inSpace(space, (sql) => sql.exec("UPDATE link SET expires = ? WHERE id = ?", Date.now() - 1000, expired.id)); expect((await p.a.ask("POST", `/v1/spaces/${space}/links/stop`, { link: stopped.id })).status).toBe(200); const third = await p.a.ask("POST", `/v1/spaces/${space}/epoch`, { ...allWraps(3, [p.a, p.b, p.v]), link_wraps: { [live.id]: wrap() } }); expect(third.status, JSON.stringify(third.body)).toBe(200); // v's sign-in is ended on v's own object. await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(p.v.slug)), (_i: Business, s) => s.storage.sql.exec("UPDATE sessions SET revoked = 1")); forgetVouches(); const held = JSON.parse(await kept(space)) as Record<string, Record<string, unknown>[]>; const secrets = new Set<string>([file, ...Object.values(id), ...[p.a, p.b, p.r, p.v].flatMap((x) => [x.number, x.key, x.sign]), ...hashes]); for (const rows of Object.values(held)) for (const row of rows) for (const v of Object.values(row)) if (typeof v === "string" && /^(w1|g1|r1|s1):/.test(v)) secrets.add(v); const handover = await signed(p.a, id[p.a.number]!, space, 0, "", { kind: "handover" }); return { space, epoch: 3, id, file, live, expired, stopped, orphaned, secrets: [...secrets], handover };}function asker(p: People, who: Principal): Person { if (who === "owner" || who === "old_epoch") return p.a; if (who === "member") return p.b; if (who === "non_member") return p.n; if (who === "removed") return p.r; return p.v;}/** The request one principal makes of one route. */async function asked(route: Route, w: World, p: People, who: Principal): Promise<{ status: number; body: Body }> { const epoch = who === "old_epoch" ? w.epoch - 1 : w.epoch; const sample = SAMPLES[route.name as RouteName](w, p, epoch); const link = who === "expired_link" ? w.expired : who === "stopped_link" ? w.stopped : who === "orphaned_link" ? w.orphaned : w.live; const path = `${route.path.replace(":id", w.space).replace(":link", link.id)}${sample.query ?? ""}`; const body = route.method === "POST" ? (sample.body ?? {}) : undefined; if (LINKS.includes(who)) return open<Body>(route.method, path, body, { authorization: `Bearer ${link.auth}` }); return asker(p, who).ask<Body>(route.method, path, body);}/** What each refused principal must be answered on a route: a status and code; null when the route is theirs to use. */function expected(route: Route, who: Principal): { status: number; code: string } | null { const linkHolder = LINKS.includes(who); if (route.need === "signed_in") return linkHolder || who === "revoked" ? { status: 401, code: "sign_in" } : null; if (route.need === "link") return who === "link" ? null : { status: 404, code: "no_space" }; if (linkHolder || who === "revoked") return { status: 401, code: "sign_in" }; if (who === "non_member" || who === "removed") return { status: 404, code: "no_space" }; if (who === "old_epoch") return route.epoch ? { status: 409, code: "stale_epoch" } : null; if (who === "member") return route.need === "owner" ? { status: 403, code: "owner_only" } : null; return null;}function noLeak(route: Route, who: string, got: { body: Body }, w: World): void { const text = JSON.stringify(got.body); for (const secret of w.secrets) expect(text.includes(secret), `${route.name} as ${who} leaked ${secret.slice(0, 12)}…`).toBe(false); expect(Object.keys(got.body).sort(), `${route.name} as ${who}`).toEqual(["code", "message"]);}async function everyone(): Promise<People> { const [a, b, r, n, v] = [await person(), await person(), await person(), await person(), await person()]; for (const x of [b, r, n, v]) await accept(a, x); for (const x of [r, n, v]) await accept(b, x); return { a, b, r, n, v };}describe("a shared space's one gate, for every route", () => { it("has a sample for every route in ROUTES", () => { for (const route of ROUTES) expect(SAMPLES[route.name], `${route.name} has no sample in the matrix`).toBeTypeOf("function"); }); it("refuses everyone who must not get in, and the refusal carries nothing of the space", async () => { const p = await everyone(); const w = await world(p); const cases: string[] = []; for (const route of ROUTES) { for (const who of REFUSED) { const want = expected(route, who); // A member's route theirs to use would change the space under the rest of the matrix (the last test uses // each); a signed-in route and the live link's own read, or found a space of their own, so they run here. if (!want && route.need !== "signed_in" && route.need !== "link") continue; const got = await asked(route, w, p, who); if (want) { expect({ route: route.name, who, status: got.status, code: got.body?.code }).toEqual({ route: route.name, who, status: want.status, code: want.code }); noLeak(route, who, got, w); cases.push(`${route.name}/${who}`); } else if (route.need === "signed_in") { expect(got.status, `${route.name} as ${who}`).toBe(200); if (route.name === "spaces.list") expect(JSON.stringify(got.body).includes(w.space), `${who}'s list names the space`).toBe(who === "old_epoch" || who === "member"); } else { expect(got.status, `${route.name} as ${who}`).toBe(200); const text = JSON.stringify(got.body); expect(text.includes("it-other")).toBe(false); for (const secret of [...Object.values(w.id), p.a.number, p.b.number]) expect(text.includes(secret), `the link view carries ${secret}`).toBe(false); } } } const memberRoutes = ROUTES.filter((x) => x.need === "member" || x.need === "owner"); for (const route of memberRoutes) for (const who of ["non_member", "removed", "revoked", ...LINKS]) expect(cases).toContain(`${route.name}/${who}`); for (const route of ROUTES.filter((x) => x.need === "owner")) expect(cases).toContain(`${route.name}/member`); for (const route of ROUTES.filter((x) => x.need === "link")) for (const who of ["non_member", "removed", "old_epoch", "revoked", "expired_link", "stopped_link", "orphaned_link"]) expect(cases).toContain(`${route.name}/${who}`); for (const route of ROUTES.filter((x) => "epoch" in x)) expect(cases).toContain(`${route.name}/old_epoch`); const after = await p.a.ask<{ epoch: number; members: { member: string }[] }>("GET", `/v1/spaces/${w.space}`); expect(after.body.epoch).toBe(3); expect(after.body.members.map((m) => m.member).sort()).toEqual([w.id[p.a.number], w.id[p.b.number], w.id[p.v.number]].sort()); }); it("in a deleted space a member only reads and saves, and no link opens; in an ending space nobody gets in", async () => { const p = await everyone(); const w = await world(p); expect((await p.a.ask("POST", `/v1/spaces/${w.space}/delete`, {})).status).toBe(200); for (const route of ROUTES) { if (route.need === "signed_in" || route.name === "leave") continue; const who: Principal = route.need === "link" ? "link" : "member"; const got = await asked(route, w, p, who); if ("whileDeleted" in route) { expect(got.status, `${route.name} while deleted`).toBe(200); continue; } const want = who === "link" ? { status: 404, code: "no_space" } : route.need === "owner" ? { status: 403, code: "owner_only" } : { status: 409, code: "space_deleted" }; expect({ route: route.name, status: got.status, code: got.body?.code }).toEqual({ route: route.name, ...want }); noLeak(route, `${who} (deleted)`, got, w); } // Everyone leaves: the space is ending, and every route answers each of them as if it were not there. for (const x of [p.a, p.b]) expect((await x.ask("POST", `/v1/spaces/${w.space}/leave`, {})).status).toBe(200); await inSpace(w.space, (sql) => { sql.exec("UPDATE member SET left_at = ? WHERE left_at IS NULL", Date.now()); sql.exec("UPDATE meta SET v = 'ending' WHERE k = 'state'"); }); for (const route of ROUTES.filter((x) => x.need === "member" || x.need === "owner")) { for (const who of ["owner", "member"] as Principal[]) { const got = await asked(route, w, p, who); expect({ route: route.name, who, status: got.status }).toEqual({ route: route.name, who, status: 404 }); noLeak(route, `${who} (ending)`, got, w); } } }); it("lets the one it is for use every route, on a fresh space each", async () => { const p = await everyone(); for (const route of ROUTES) { const w = await world(p); // What a route needs to act on, made first: a record at an old epoch, a member with no wrap yet. let epoch = w.epoch; if (route.name === "records.rewrap") { const moved = await p.a.ask("POST", `/v1/spaces/${w.space}/epoch`, { epoch: 4, wraps: { [w.id[p.a.number]!]: wrap(), [w.id[p.b.number]!]: wrap(), [w.id[p.v.number]!]: wrap() }, link_wraps: { [w.live.id]: wrap() } }); expect(moved.status, JSON.stringify(moved.body)).toBe(200); epoch = 4; } if (route.name === "wraps.add") { const added = await p.a.ask<{ members: { member: string; number?: string }[] }>("POST", `/v1/spaces/${w.space}/members`, { numbers: [p.n.number] }); w.id[p.n.number] = added.body.members.find((m) => m.number === p.n.number)!.member; } if (route.name === "roster.drop") { expect((await p.a.ask("POST", `/v1/spaces/${w.space}/roster`, { statement: w.handover })).status).toBe(200); const next = await signed(p.a, w.id[p.a.number]!, w.space, 1, await hashOf(w.handover), { kind: "handover" }); expect((await p.a.ask("POST", `/v1/spaces/${w.space}/roster`, { statement: next })).status).toBe(200); w.drop = { seq: 1, hash: await hashOf(next) }; } const sample = SAMPLES[route.name as RouteName](w, p, epoch); const path = `${route.path.replace(":id", w.space).replace(":link", w.live.id)}${sample.query ?? ""}`; const body = route.method === "POST" ? (sample.body ?? {}) : undefined; const got = route.need === "link" ? await open<Body>(route.method, path, body, { authorization: `Bearer ${w.live.auth}` }) : await p.a.ask<Body>(route.method, path, body); expect(got.status, `${route.name}: ${JSON.stringify(got.body)}`).toBe(200); } });});