Cotton code
170 lines · 11.5 KB · TypeScriptRaw
import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { OWNER_PHONE, http, mint, personalObject } from "./personal.ts";import { FAILS_PER_HOUR } from "../src/recovery.ts";/** * RULE (R7a and R7c): a way back in (a recovery code, a platform key) is held by the object as a * salt, an auth hash and a wrap it cannot open; the wrap is answered only for the right auth key, inside the try * limit, and the device that opened it may then put its own wrap on its own row. Synthetic keys throughout. */const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");const hex = (bytes: Uint8Array) => [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");const bytes = (fill: number) => new Uint8Array(32).fill(fill);/** The device's half, done here with WebCrypto: two keys from one secret (stand-ins for HKDF's), a wrap under one. */async function wayIn(wrapFill: number, authFill: number) {  const wrapKey = bytes(wrapFill);  const auth = bytes(authFill);  const vmk = bytes(0x42);  const nonce = new Uint8Array(12).fill(9);  const key = await crypto.subtle.importKey("raw", wrapKey, "AES-GCM", false, ["encrypt", "decrypt"]);  const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: new TextEncoder().encode("cotton-recovery:v1:code:1") }, key, vmk));  const wrapped = "r1:" + b64url(new Uint8Array([...nonce, ...ct]));  const authHash = hex(new Uint8Array(await crypto.subtle.digest("SHA-256", auth)));  return { wrapKey, auth: b64url(auth), authHash, wrapped, vmk };}async function device(slug: string, deviceId: string): Promise<Record<string, string>> {  const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: deviceId });  const signed = await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: deviceId });  expect(signed.status, JSON.stringify(signed.body)).toBe(200);  return { authorization: `Bearer ${signed.body.credential}` };}const keyRow = (deviceId: string, key: string, wrapped: string | null) => ({ table: "vault_key", id: `vault-key-${deviceId}`, data: { device_id: deviceId, public_key: key, wrapped_vmk: wrapped, vmk_version: wrapped ? 1 : 0 } });const SALT = b64url(new Uint8Array(16).fill(5));async function founded(slug: string) {  await personalObject(slug);  const holder = await device(slug, "phone-holder");  const made = await http(slug, "POST", "/v1/act", { act: "create", args: keyRow("phone-holder", "A".repeat(43), "w1:SYNTHETIC-holder") }, holder);  expect(made.status, JSON.stringify(made.body)).toBe(200);  return holder;}describe("a way back in", { timeout: 180_000 }, () => {  it("is set only by a device that holds the vault, and is read back without its hash or its wrap", async () => {    const SLUG = "recovery-set";    const holder = await founded(SLUG);    const way = await wayIn(1, 2);    const body = { kind: "code", salt: SALT, kdf: "scrypt:15:8:1", auth_hash: way.authHash, wrapped: way.wrapped, vmk_version: 1, code_enc: "v2:SYNTHETIC-sealed-code" };    const newcomer = await device(SLUG, "phone-new");    const refused = await http<{ code: string }>(SLUG, "POST", "/v1/recovery/set", body, newcomer);    expect([refused.status, refused.body.code]).toEqual([403, "vault_not_held"]);    const weak = await http<{ code: string }>(SLUG, "POST", "/v1/recovery/set", { ...body, kdf: "none" }, holder);    expect([weak.status, weak.body.code]).toEqual([400, "bad_kdf"]);    const set = await http(SLUG, "POST", "/v1/recovery/set", body, holder);    expect(set.status, JSON.stringify(set.body)).toBe(200);    const read = await http<{ code: Record<string, unknown>; google: unknown }>(SLUG, "GET", "/v1/recovery", undefined, newcomer);    expect(read.status).toBe(200);    expect(read.body.code).toMatchObject({ salt: SALT, kdf: "scrypt:15:8:1", vmk_version: 1, code_enc: "v2:SYNTHETIC-sealed-code" });    expect(read.body.code).not.toHaveProperty("wrapped");    expect(read.body.code).not.toHaveProperty("auth_hash");    expect(read.body.google).toBeNull();  });  it("answers the wrap for the right auth key only, and a new code retires the old", async () => {    const SLUG = "recovery-open";    const holder = await founded(SLUG);    const first = await wayIn(1, 2);    await http(SLUG, "POST", "/v1/recovery/set", { kind: "code", salt: SALT, kdf: "scrypt:15:8:1", auth_hash: first.authHash, wrapped: first.wrapped, vmk_version: 1 }, holder);    const fresh = await device(SLUG, "phone-new");    const opened = await http<{ wrapped: string; vmk_version: number }>(SLUG, "POST", "/v1/recovery/open", { kind: "code", auth: first.auth }, fresh);    expect(opened.status, JSON.stringify(opened.body)).toBe(200);    expect(opened.body).toEqual({ wrapped: first.wrapped, vmk_version: 1 });    // Make a new code: the old one opens nothing from then on.    const second = await wayIn(3, 4);    await http(SLUG, "POST", "/v1/recovery/set", { kind: "code", salt: SALT, kdf: "scrypt:15:8:1", auth_hash: second.authHash, wrapped: second.wrapped, vmk_version: 1 }, holder);    const old = await http<{ code: string }>(SLUG, "POST", "/v1/recovery/open", { kind: "code", auth: first.auth }, fresh);    expect([old.status, old.body.code]).toEqual([403, "recovery_wrong"]);    const now = await http<{ wrapped: string }>(SLUG, "POST", "/v1/recovery/open", { kind: "code", auth: second.auth }, fresh);    expect(now.body.wrapped).toBe(second.wrapped);    // A device in by SMS alone (no vault) cannot take a way back in away (ROUTES-AUDIT 12).    const stripped = await http<{ code: string }>(SLUG, "POST", "/v1/recovery/retire", { kind: "code" }, fresh);    expect([stripped.status, stripped.body.code]).toEqual([403, "vault_not_held"]);    const retired = await http<{ retired: boolean }>(SLUG, "POST", "/v1/recovery/retire", { kind: "code" }, holder);    expect(retired.body.retired).toBe(true);    const none = await http<{ code: string }>(SLUG, "POST", "/v1/recovery/open", { kind: "code", auth: second.auth }, fresh);    expect([none.status, none.body.code]).toEqual([404, "recovery_none"]);  });  it("counts wrong tries and makes the next wait, even for the right key", async () => {    const SLUG = "recovery-limit";    const holder = await founded(SLUG);    const way = await wayIn(1, 2);    await http(SLUG, "POST", "/v1/recovery/set", { kind: "code", salt: SALT, kdf: "scrypt:15:8:1", auth_hash: way.authHash, wrapped: way.wrapped, vmk_version: 1 }, holder);    const guesser = await device(SLUG, "phone-guess");    const lefts: number[] = [];    for (let i = 0; i < FAILS_PER_HOUR; i++) {      const wrong = await http<{ code: string; tries_left: number }>(SLUG, "POST", "/v1/recovery/open", { kind: "code", auth: b64url(bytes(100 + i)) }, guesser);      expect([wrong.status, wrong.body.code]).toEqual([403, "recovery_wrong"]);      lefts.push(wrong.body.tries_left);    }    expect(lefts).toEqual([4, 3, 2, 1, 0]);    const waited = await http<{ code: string; retry_after: number }>(SLUG, "POST", "/v1/recovery/open", { kind: "code", auth: way.auth }, guesser);    expect([waited.status, waited.body.code]).toEqual([429, "recovery_wait"]);    expect(waited.body.retry_after).toBeGreaterThan(3000);    // The platform key's tries are its own.    const platform = await http<{ code: string }>(SLUG, "POST", "/v1/recovery/open", { kind: "google", auth: way.auth }, guesser);    expect([platform.status, platform.body.code]).toEqual([404, "recovery_none"]);  });  it("holds nothing that opens the wrap: not the wrap key, and the auth key it is handed opens nothing", async () => {    const SLUG = "recovery-blind";    const holder = await founded(SLUG);    const way = await wayIn(1, 2);    await http(SLUG, "POST", "/v1/recovery/set", { kind: "code", salt: SALT, kdf: "scrypt:15:8:1", auth_hash: way.authHash, wrapped: way.wrapped, vmk_version: 1 }, holder);    const fresh = await device(SLUG, "phone-new");    await http(SLUG, "POST", "/v1/recovery/open", { kind: "code", auth: way.auth }, fresh);    const stub = env.BUSINESS.get(env.BUSINESS.idFromName(SLUG));    const stored = await runInDurableObject(stub, (_instance, state) => {      const sql = state.storage.sql;      return ["recovery", "recovery_try", "recovery_grant"].map((t) => JSON.stringify(sql.exec(`SELECT * FROM ${t}`).toArray())).join("\n");    });    expect(stored).toContain(way.authHash);    expect(stored).not.toContain(b64url(way.wrapKey));    expect(stored).not.toContain(way.auth);    expect(stored).not.toContain(b64url(way.vmk));    // The auth key (all the object ever sees) does not open the wrap; the wrap key the device keeps does.    const text = way.wrapped.slice(3).replace(/-/g, "+").replace(/_/g, "/");    const body = Uint8Array.from(atob(text + "=".repeat((4 - (text.length % 4)) % 4)), (c) => c.charCodeAt(0));    const tryWith = async (raw: Uint8Array) => {      const key = await crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["decrypt"]);      return crypto.subtle.decrypt({ name: "AES-GCM", iv: body.slice(0, 12), additionalData: new TextEncoder().encode("cotton-recovery:v1:code:1") }, key, body.slice(12)).then(() => true, () => false);    };    expect(await tryWith(bytes(2))).toBe(false);    expect(await tryWith(way.wrapKey)).toBe(true);  });  it("lets the device that opened it put its own wrap on its own row, and no other", async () => {    const SLUG = "recovery-founding";    const holder = await founded(SLUG);    const way = await wayIn(1, 2);    await http(SLUG, "POST", "/v1/recovery/set", { kind: "code", salt: SALT, kdf: "scrypt:15:8:1", auth_hash: way.authHash, wrapped: way.wrapped, vmk_version: 1 }, holder);    const fresh = await device(SLUG, "phone-new");    const other = await device(SLUG, "phone-other");    for (const [auth, id, key] of [[fresh, "phone-new", "B"], [other, "phone-other", "C"]] as const) {      const made = await http(SLUG, "POST", "/v1/act", { act: "create", args: keyRow(id, key.repeat(43), null) }, auth);      expect(made.status, JSON.stringify(made.body)).toBe(200);    }    const before = await http<{ code: string }>(SLUG, "POST", "/v1/act", { act: "update", args: { table: "vault_key", id: "vault-key-phone-new", data: { wrapped_vmk: "w1:SYNTHETIC-self", vmk_version: 1 } } }, fresh);    expect([before.status, before.body.code]).toEqual([409, "vault_founded"]);    await http(SLUG, "POST", "/v1/recovery/open", { kind: "code", auth: way.auth }, fresh);    const after = await http(SLUG, "POST", "/v1/act", { act: "update", args: { table: "vault_key", id: "vault-key-phone-new", data: { wrapped_vmk: "w1:SYNTHETIC-self", vmk_version: 1 } } }, fresh);    expect(after.status, JSON.stringify(after.body)).toBe(200);    const stranger = await http<{ code: string }>(SLUG, "POST", "/v1/act", { act: "update", args: { table: "vault_key", id: "vault-key-phone-other", data: { wrapped_vmk: "w1:SYNTHETIC-other", vmk_version: 1 } } }, other);    expect([stranger.status, stranger.body.code]).toEqual([409, "vault_founded"]);  });  it("is the person's devices' alone: never a token's", async () => {    const SLUG = "recovery-token";    const { credential } = await personalObject(SLUG);    const token = await mint(SLUG, credential, "walk", ["read", "write"]);    const read = await http<{ code: string }>(SLUG, "GET", "/v1/recovery", undefined, { authorization: `Bearer ${token}` });    expect(read.status).toBeGreaterThanOrEqual(401);    expect(read.status).toBeLessThan(404);  });});