Cotton code
222 lines · 13.7 KB · TypeScriptRaw
/** * The IP allowlist (src/allowlist.ts, sealing plan §6): empty it locks nothing; * set, it refuses admin, import and owner-minted MCP tokens from any other * address by name, never a phone's sync or an OAuth connector; it changes only * by a statement the person key signed, fresh and used once, on a route no * list locks. Every address is from the documentation ranges and every key is * made here. */import { describe, expect, it } from "vitest";import { allows, canonicalCidr, canonicalList, statement, type Entry } from "../src/allowlist.ts";import { toBase64Url } from "../src/vault.ts";import { ADMIN, DATABASE_ID, http, mint, OWNER_PHONE, PERSONAL_TABLES, PERSONAL_TOOLS, publishPersonKey, put } from "./personal.ts";const HOME = "203.0.113.7";const ELSEWHERE = "198.51.100.9";const LIST: Entry[] = [  { cidr: "203.0.113.0/24", label: "Home" },  { cidr: "2001:db8::/32", label: "Box" },];interface Keys {  pair: CryptoKeyPair;  fingerprint: string;}async function personKey(): Promise<Keys & { publicKey: string }> {  const pair = (await crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"])) as CryptoKeyPair;  const publicKey = toBase64Url(new Uint8Array((await crypto.subtle.exportKey("raw", pair.publicKey)) as ArrayBuffer));  return { pair, fingerprint: publicKey.slice(0, 8), publicKey };}/** A personal object holding the person key `keys`, its owner phone credential and an owner token. */async function object(slug: string, keys?: Keys & { publicKey: string }): Promise<{ credential: string; owner: string }> {  expect((await http(slug, "PUT", "/v1/admin/business", { name: "Personal", kind: "personal", owner_phone: OWNER_PHONE, database_id: DATABASE_ID, timezone: "Asia/Kolkata" }, ADMIN)).status).toBe(200);  expect((await http(slug, "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables: PERSONAL_TABLES, flavour: { flavour: "personal" } }, ADMIN)).status).toBe(200);  const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: "phone" });  const signed = await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "phone" });  expect(signed.status, JSON.stringify(signed.body)).toBe(200);  if (keys) await publishPersonKey(slug, signed.body.credential, keys.publicKey);  return { credential: signed.body.credential, owner: await mint(slug, signed.body.credential, "coordinator owner", ["owner"]) };}async function signed(keys: Keys, list: Entry[], over: { nonce?: string; issued_at?: string; databaseId?: string } = {}): Promise<Record<string, unknown>> {  const nonce = over.nonce ?? toBase64Url(crypto.getRandomValues(new Uint8Array(16)));  const issuedAt = over.issued_at ?? new Date().toISOString();  const text = await statement(over.databaseId ?? DATABASE_ID, list, nonce, issuedAt);  const sig = new Uint8Array((await crypto.subtle.sign({ name: "Ed25519" }, keys.pair.privateKey, new TextEncoder().encode(text))) as ArrayBuffer);  return { list, nonce, issued_at: issuedAt, signer: keys.fingerprint, sig: toBase64Url(sig) };}function from(ip: string, headers: Record<string, string> = {}): Record<string, string> {  return { "cf-connecting-ip": ip, ...headers };}async function mcpList(slug: string, token: string, ip: string): Promise<{ status: number; body: Record<string, unknown> }> {  return http(slug, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/list" }, from(ip, { authorization: `Bearer ${token}` }));}describe("the allowlist's spelling and matching", () => {  it("names each cidr one way, refusing host bits and non-addresses", () => {    expect(canonicalCidr("203.0.113.0/24")).toBe("203.0.113.0/24");    expect(canonicalCidr("203.0.113.7")).toBe("203.0.113.7/32");    expect(canonicalCidr("203.0.113.7/24")).toBeNull();    expect(canonicalCidr("203.0.113.07/32")).toBeNull();    expect(canonicalCidr("256.0.0.0/8")).toBeNull();    expect(canonicalCidr("2001:DB8:0:0::/32")).toBe("2001:db8::/32");    expect(canonicalCidr("2001:db8:0:0:1:0:0:1")).toBe("2001:db8::1:0:0:1/128");    expect(canonicalCidr("2001:db8::1/129")).toBeNull();    expect(canonicalCidr("::")).toBe("::/128");    expect(canonicalCidr("example.test")).toBeNull();  });  it("lets every address pass an empty list, and only a listed one pass a set list", () => {    expect(allows([], ELSEWHERE)).toBe(true);    expect(allows([], null)).toBe(true);    expect(allows(LIST, HOME)).toBe(true);    expect(allows(LIST, "2001:db8:1::5")).toBe(true);    expect(allows(LIST, ELSEWHERE)).toBe(false);    expect(allows(LIST, "2001:db9::1")).toBe(false);    expect(allows(LIST, null)).toBe(false);    expect(allows(LIST, "not an address")).toBe(false);  });  it("signs the plan's statement over the sorted list's hash", async () => {    expect(canonicalList(LIST)).toBe('[{"cidr":"2001:db8::/32","label":"Box"},{"cidr":"203.0.113.0/24","label":"Home"}]');    const text = await statement(DATABASE_ID, LIST, "nonce-0123456789ab", "2026-11-11T09:00:00.000Z");    const lines = text.split("\n");    expect(lines).toHaveLength(5);    expect(lines[0]).toBe("cotton-allowlist-v1");    expect(lines[1]).toBe(DATABASE_ID);    expect(lines[2]).toMatch(/^[0-9a-f]{64}$/);    expect(lines.slice(3)).toEqual(["nonce-0123456789ab", "2026-11-11T09:00:00.000Z"]);    // The order the list arrives in is not signed.    expect(await statement(DATABASE_ID, [...LIST].reverse(), "nonce-0123456789ab", "2026-11-11T09:00:00.000Z")).toBe(text);  });});describe("the allowlist on the personal object", { timeout: 60_000 }, () => {  it("locks nothing while empty: admin, MCP and import answer from any address", async () => {    const slug = "allow-empty";    const { owner, credential } = await object(slug);    expect((await http(slug, "GET", "/v1/admin/export?limit=1", undefined, from(ELSEWHERE, ADMIN))).status).toBe(200);    expect((await mcpList(slug, owner, ELSEWHERE)).status).toBe(200);    const list = await http<{ list: unknown[] }>(slug, "GET", "/v1/allowlist", undefined, from(ELSEWHERE, { authorization: `Bearer ${credential}` }));    expect(list.body).toEqual({ list: [] });  });  it("once set by a signed change, refuses admin, import and minted tokens from elsewhere by the address seen, and lets the listed address and the phone through", async () => {    const slug = "allow-set";    const keys = await personKey();    const { owner, credential } = await object(slug, keys);    const lane = await mint(slug, credential, "a lane", ["lane:test"], 7);    const changed = await http<{ list: { cidr: string; label: string; added_by_fp: string }[] }>(slug, "POST", "/v1/allowlist", await signed(keys, LIST), from(ELSEWHERE));    expect(changed.status, JSON.stringify(changed.body)).toBe(200);    expect(changed.body.list.map((e) => [e.cidr, e.label, e.added_by_fp])).toEqual([      ["2001:db8::/32", "Box", keys.fingerprint],      ["203.0.113.0/24", "Home", keys.fingerprint],    ]);    const refused = await http<{ code: string; message: string }>(slug, "GET", "/v1/admin/export?limit=1", undefined, from(ELSEWHERE, ADMIN));    expect(refused.status).toBe(403);    expect(refused.body.code).toBe("address_not_allowed");    expect(refused.body.message).toContain(ELSEWHERE);    expect((await http(slug, "GET", "/v1/admin/export?limit=1", undefined, from(HOME, ADMIN))).status).toBe(200);    expect((await http(slug, "GET", "/v1/admin/export?limit=1", undefined, from("2001:db8:5::1", ADMIN))).status).toBe(200);    // No address at all passes no set list.    expect((await http(slug, "GET", "/v1/admin/export?limit=1", undefined, ADMIN)).status).toBe(403);    for (const token of [owner, lane]) {      const mcp = await mcpList(slug, token, ELSEWHERE);      expect(mcp.status).toBe(403);      expect(mcp.body.code).toBe("address_not_allowed");      expect((await mcpList(slug, token, HOME)).status).toBe(200);    }    const imported = await http<{ code: string }>(slug, "POST", "/v1/import/messages", { messages: [] }, from(ELSEWHERE, { authorization: `Bearer ${owner}` }));    expect(imported.status).toBe(403);    expect(imported.body.code).toBe("address_not_allowed");    const media = await http<{ code: string }>(slug, "HEAD", "/v1/media/song/x.mp3", undefined, from(ELSEWHERE, { authorization: `Bearer ${owner}` }));    expect(media.status).toBe(403);    // The phone's own routes are never locked: its address changes.    const phone = { authorization: `Bearer ${credential}` };    expect((await http(slug, "GET", "/v1/sync?since=0", undefined, from(ELSEWHERE, phone))).status).toBe(200);    expect((await http(slug, "GET", "/v1/me", undefined, from(ELSEWHERE, phone))).status).toBe(200);    expect((await http(slug, "HEAD", "/v1/media/song/x.mp3", undefined, from(ELSEWHERE, phone))).status).not.toBe(403);  });  it("leaves an OAuth connector's token unlocked: its addresses are not known", async () => {    const slug = "allow-connector";    const keys = await personKey();    const { owner, credential } = await object(slug, keys);    const minted = await http<{ token: string; made: { id: string } }>(slug, "POST", "/v1/act", { act: "mint_token", args: { name: "connector stand-in", scopes: ["owner"] } }, { authorization: `Bearer ${credential}` });    expect(minted.status, JSON.stringify(minted.body)).toBe(200);    const [connector, id] = [minted.body.token, minted.body.made.id];    // The connector's token is told by its refresh row, as src/oauth.ts writes it.    await put(slug, [{ table: "oauth_refresh", data: { client_id: "client-x", token: id, scope: "owner", expires_at: "2099-01-01T00:00:00.000Z" } }]);    expect((await http(slug, "POST", "/v1/allowlist", await signed(keys, LIST), from(ELSEWHERE))).status).toBe(200);    expect((await mcpList(slug, connector, ELSEWHERE)).status).toBe(200);    expect((await mcpList(slug, owner, ELSEWHERE)).status).toBe(403);  });  it("changes only by a fresh, unused statement the person key signed, on a route reachable from any address", async () => {    const slug = "allow-change";    const keys = await personKey();    const other = await personKey();    await object(slug, keys);    const code = async (body: Record<string, unknown>, ip = ELSEWHERE): Promise<[number, string]> => {      const res = await http<{ code: string }>(slug, "POST", "/v1/allowlist", body, from(ip));      return [res.status, res.body.code];    };    // Stale or from the future.    expect(await code(await signed(keys, LIST, { issued_at: new Date(Date.now() - 6 * 60_000).toISOString() }))).toEqual([403, "stale_statement"]);    expect(await code(await signed(keys, LIST, { issued_at: new Date(Date.now() + 6 * 60_000).toISOString() }))).toEqual([403, "stale_statement"]);    // Forged: another key signing under this key's fingerprint, a list changed after signing, another database's statement.    expect(await code({ ...(await signed(other, LIST)), signer: keys.fingerprint })).toEqual([403, "bad_signature"]);    expect(await code({ ...(await signed(keys, LIST)), list: [LIST[1]] })).toEqual([403, "bad_signature"]);    expect(await code(await signed(keys, LIST, { databaseId: "22222222-2222-4222-8222-222222222222" }))).toEqual([403, "bad_signature"]);    // A key the object does not hold is refused by name, never let through.    expect(await code(await signed(other, LIST))).toEqual([409, "no_person_key"]);    // A cidr not in its one spelling.    expect(await code(await signed(keys, [{ cidr: "203.0.113.7/24", label: "Home" }]))).toEqual([400, "bad_cidr"]);    // A good change, then the same statement again.    const good = await signed(keys, [{ cidr: "203.0.113.0/24", label: "Home" }]);    expect(await code(good)).toEqual([200, undefined]);    expect(await code(good)).toEqual([403, "nonce_used"]);    // Locked out at ELSEWHERE, the change route still answers there, and an empty list unlocks.    expect((await http(slug, "GET", "/v1/admin/export?limit=1", undefined, from(ELSEWHERE, ADMIN))).status).toBe(403);    expect(await code(await signed(keys, []))).toEqual([200, undefined]);    expect((await http(slug, "GET", "/v1/admin/export?limit=1", undefined, from(ELSEWHERE, ADMIN))).status).toBe(200);  });  it("refuses every change on an object holding no person key", async () => {    const slug = "allow-no-key";    const keys = await personKey();    await object(slug);    const res = await http<{ code: string }>(slug, "POST", "/v1/allowlist", await signed(keys, LIST), from(HOME));    expect([res.status, res.body.code]).toEqual([409, "no_person_key"]);  });  it("keeps the list out of rows, the change journal and the acts", async () => {    const slug = "allow-guard";    const keys = await personKey();    const { credential, owner } = await object(slug, keys);    expect((await http(slug, "POST", "/v1/allowlist", await signed(keys, LIST), from(HOME))).status).toBe(200);    const exported = await http(slug, "GET", "/v1/admin/export?limit=10000", undefined, from(HOME, ADMIN));    expect(exported.status).toBe(200);    const synced = await http(slug, "GET", "/v1/sync?since=0", undefined, { authorization: `Bearer ${credential}` });    const changes = await http<{ result: { content: { text: string }[] } }>(slug, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "list_changes", arguments: {} } }, from(HOME, { authorization: `Bearer ${owner}` }));    const acts = await http<{ result: { content: { text: string }[] } }>(slug, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "list_acts", arguments: {} } }, from(HOME, { authorization: `Bearer ${owner}` }));    for (const text of [JSON.stringify(exported.body), JSON.stringify(synced.body), JSON.stringify(changes.body), JSON.stringify(acts.body)]) {      expect(text).not.toContain("203.0.113.0");      expect(text).not.toContain("2001:db8::");      expect(text).not.toContain("cotton-allowlist-v1");    }  });});