/** * FOUNDER ROW CHECK (src/vault_key_check.ts). An old phone build that founded a local vault before sign-in, signed in * to an EXISTING account with the vault public key its genuine row already carries (the key survived a reinstall), and * posted its `founder:<device key>` row wrapping its LOCAL vault key: the object took it for the device's own re-wrap * and retired the genuine row, which wrapped the account's key. Built here through the real act path with synthetic * keys and wraps; the check flags it, says nothing it must not, and leaves a clean account unflagged. */import { env, runInDurableObject, SELF } from"cloudflare:test";import { describe, expect, it } from"vitest";import { Asks } from"../src/approval.ts";importtype { VaultKeyPage, VaultKeyReport } from"../src/vault_key_check.ts";import * as vaultIdentity from"../src/vault_identity.ts";import { ADMIN, DATABASE_ID, http, OWNER_PHONE, personalObject } from"./personal.ts";// Synthetic public halves and wraps: nothing holds a private key to any of them.const KEY_A = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";const KEY_B = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";const ACCOUNT_WRAP_A = "w1:SYNTHETIC-account-for-a";const ACCOUNT_WRAP_B = "w1:SYNTHETIC-account-for-b";const LOCAL_WRAP_A = "w1:SYNTHETIC-local-for-a";const FOUNDER_ID = "founder:synthetic-device-key";/** A key check value the old Worker's state is made with (see `account`). */const OLD_WORKER_CHECK = "T0xELVdPUktFUi1TVEFURQ";asyncfunction 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}` };}/** An ask for `deviceId` with `vaultKey` that `approver` approved after the codes were compared, as the object holds one. */asyncfunction admittedBy(slug: string, deviceId: string, vaultKey: string, approver: string): Promise<void> {await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), async (_i, state) => {const t = Math.floor(Date.now() / 1000);const id = `cta_${deviceId}`;newAsks(state.storage.sql).add({ id, phone: OWNER_PHONE, deviceId, deviceName: null, vaultKey, commit: "c", createdAt: t, expiresAt: t + 180 }); state.storage.sql.exec("UPDATE approval_ask SET reveal = 'r', state = 'approved', decided_by = ?, decided_at = ? WHERE id = ?", approver, t, id); });}asyncfunction act(slug: string, auth: Record<string, string>, name: string, args: Record<string, unknown>): Promise<{ status: number; body: Record<string, unknown> }> {returnawait http(slug, "POST", "/v1/act", { act: name, args }, auth);}asyncfunction liveKeyRows(slug: string, auth: Record<string, string>): Promise<Map<string, Record<string, unknown>>> {const res = await http<{ rows: { table: string; id: string; data: Record<string, unknown>; deleted?: boolean }[] }>(slug, "GET", "/v1/sync?since=0&tables=vault_key", undefined, auth); expect(res.status, JSON.stringify(res.body)).toBe(200);returnnewMap(res.body.rows.filter((r) => r.table === "vault_key" && !r.deleted).map((r) => [r.id, r.data]));}/** * An account whose vault phone A founded and which let phone B in. With `founderPost`, phone A then comes back as an * old build after a reinstall (same device id, same vault public key) and posts its local founding. */asyncfunction account(slug: string, founderPost: boolean): Promise<{ a: Record<string, string>; b: Record<string, string> }> {await personalObject(slug);const a = await device(slug, "phone-a");const b = await device(slug, "phone-b"); expect((await act(slug, a, "create", { table: "vault_key", id: "vault-key-phone-a", data: { device_id: "phone-a", public_key: KEY_A, wrapped_vmk: null, vmk_version: 0 } })).status).toBe(200); expect((await act(slug, a, "update", { table: "vault_key", id: "vault-key-phone-a", data: { wrapped_vmk: ACCOUNT_WRAP_A, vmk_version: 1 } })).status).toBe(200); expect((await act(slug, b, "create", { table: "vault_key", id: "vault-key-phone-b", data: { device_id: "phone-b", public_key: KEY_B, wrapped_vmk: null, vmk_version: 0 } })).status).toBe(200);await admittedBy(slug, "phone-b", KEY_B, "phone-a"); expect((await act(slug, a, "update", { table: "vault_key", id: "vault-key-phone-b", data: { wrapped_vmk: ACCOUNT_WRAP_B, vmk_version: 1 } })).status).toBe(200);if (founderPost) {// The Worker before KEPT FOUR 3 A retired the genuine row on this post. The guard retires only between rows declared// the same key identity on the same device, so the old Worker's state is made here the one way the guard still// retires: the genuine row's identity set as the post declares it (src/vault_identity.ts).await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), async (_i, state) => { vaultIdentity.noteWrap(state.storage.sql, "vault-key-phone-a", OLD_WORKER_CHECK, 1, "phone-a"); });const posted = await act(slug, a, "create", { table: "vault_key", id: FOUNDER_ID, data: { device_id: "phone-a", public_key: KEY_A, wrapped_vmk: LOCAL_WRAP_A, vmk_version: 1 }, vmk_check: OLD_WORKER_CHECK }); expect(posted.status, JSON.stringify(posted.body)).toBe(200); }return { a, b };}const check = async (slug: string) => await http<VaultKeyReport & { code?: string }>(slug, "GET", "/v1/admin/vault-key-check", undefined, ADMIN);describe("the founder row check", () => { it("the bug as the review read it (the old Worker's state): an old build's founder row is kept as the device's re-wrap and retires its genuine row", async () => {const slug = "vault-check-bad";const { a } = await account(slug, true);const rows = await liveKeyRows(slug, a);// The genuine row, the only wrap of the ACCOUNT's key for phone A, is gone; the founder row wraps the local key. expect([...rows.keys()].sort()).toEqual([FOUNDER_ID, "vault-key-phone-b"]); expect(rows.get(FOUNDER_ID)?.wrapped_vmk).toBe(LOCAL_WRAP_A); }); it("flags the bad account, with kinds and counts only", async () => {const slug = "vault-check-flagged";await account(slug, true);const r = await check(slug); expect(r.status, JSON.stringify(r.body)).toBe(200); expect(r.body).toMatchObject({ vault_key_rows: 2, wrapped_rows: 2, founder_rows: 1, founder_wrapped_rows: 1, retired_rows: 1, devices: 2, devices_flagged: 1, flagged: true }); expect(r.body.findings).toEqual([ expect.objectContaining({ flagged: true, founder_wrapped: true, founder_retired_wrapped_row: true, retired_rows: 1, retired_row_undoable: 1, founder_after_vault_held: "yes", founder_only_wrap: true,// Both at version 1: the object cannot see the founder row is behind. founder_version_behind: false, heal_may_copy_founder_wrap: false, seal_key_after_founder: "no", person_key_after_founder: "no", }), ]);// Never a key, a wrap, a row id, a device id or the number.const said = JSON.stringify(r.body);for (const secret of [KEY_A, KEY_B, ACCOUNT_WRAP_A, ACCOUNT_WRAP_B, LOCAL_WRAP_A, FOUNDER_ID, "synthetic-device-key", "phone-a", "phone-b", "vault-key-phone", OWNER_PHONE, "SYNTHETIC"]) expect(said).not.toContain(secret); }); it("sees the heal that would copy the founder row's wrap onto the device's next row of the same key", async () => {const slug = "vault-check-heal";const { a } = await account(slug, true);// The phone publishes its key again, unwrapped, under a new id: its next pull would take the founder row's wrap. expect((await act(slug, a, "create", { table: "vault_key", id: "vault-key-phone-a-again", data: { device_id: "phone-a", public_key: KEY_A, wrapped_vmk: null, vmk_version: 0 } })).status).toBe(200);const r = await check(slug); expect(r.body.findings[0]).toMatchObject({ flagged: true, heal_may_copy_founder_wrap: true, same_key_live_rows: 1 }); }); it("leaves a clean account unflagged, and one whose founder row founded the vault (the device's first wrap)", async () => {const clean = "vault-check-clean";await account(clean, false);const r = await check(clean); expect(r.status, JSON.stringify(r.body)).toBe(200); expect(r.body).toMatchObject({ vault_key_rows: 2, wrapped_rows: 2, founder_rows: 0, retired_rows: 0, devices_flagged: 0, same_key_wrapped_groups: 0, flagged: false, findings: [] });// A phone that founded locally and signed in to a NEW account: its founder row is the vault's first wrap, and it lets another in.const fresh = "vault-check-fresh";await personalObject(fresh);const a = await device(fresh, "phone-a");const b = await device(fresh, "phone-b"); expect((await act(fresh, a, "create", { table: "vault_key", id: FOUNDER_ID, data: { device_id: "phone-a", public_key: KEY_A, wrapped_vmk: ACCOUNT_WRAP_A, vmk_version: 1 } })).status).toBe(200); expect((await act(fresh, b, "create", { table: "vault_key", id: "vault-key-phone-b", data: { device_id: "phone-b", public_key: KEY_B, wrapped_vmk: null, vmk_version: 0 } })).status).toBe(200);await admittedBy(fresh, "phone-b", KEY_B, "phone-a"); expect((await act(fresh, a, "update", { table: "vault_key", id: "vault-key-phone-b", data: { wrapped_vmk: ACCOUNT_WRAP_B, vmk_version: 1 } })).status).toBe(200);const f = await check(fresh); expect(f.body).toMatchObject({ founder_rows: 1, flagged: false }); expect(f.body.findings).toEqual([expect.objectContaining({ flagged: false, founder_retired_wrapped_row: false, founder_after_vault_held: "not_seen", founder_only_wrap: true, founder_version_behind: false })]); }); it("takes the admin token alone", async () => {const slug = "vault-check-door";const { credential } = await personalObject(slug);const r = await http<{ code: string }>(slug, "GET", "/v1/admin/vault-key-check", undefined, { authorization: `Bearer ${credential}` }); expect([r.status, r.body.code]).toEqual([403, "admin_only"]); }); it("runs over every database the directory holds, a page at a time, in counts and kinds only; one database's report by its id", async () => {const bad = "vault-check-fan-bad";const clean = "vault-check-fan-clean";const CLEAN_ID = "44444444-4444-4444-8444-444444444444";const CLEAN_PHONE = "+919000000444";await account(bad, true);await account(clean, false);// Each object its own database and number, as the directory requires. expect((await http(clean, "PUT", "/v1/admin/business", { owner_phone: CLEAN_PHONE, database_id: CLEAN_ID }, ADMIN)).status).toBe(200);const enter = async (database_id: string, slug: string, phone: string) => {const res = await SELF.fetch("https://cottondb.com/v1/admin/directory", { method: "POST", headers: { "content-type": "application/json", ...ADMIN }, body: JSON.stringify({ database_id, slug, phone }) }); expect(res.status, await res.clone().text()).toBe(200); };await enter(DATABASE_ID, bad, OWNER_PHONE);await enter(CLEAN_ID, clean, CLEAN_PHONE);const ask = async <T>(path: string, headers: Record<string, string> = ADMIN) => {const res = await SELF.fetch(`https://cottondb.com/v1/admin/vault-keys/check${path}`, { headers });return { status: res.status, body: (await res.json()) as T & { code?: string } }; }; expect((await ask("", { authorization: "Bearer not-the-admin" })).status).toBe(403);const all = await ask<VaultKeyPage>("?limit=200"); expect(all.status, JSON.stringify(all.body)).toBe(200); expect([all.body.objects, all.body.flagged, all.body.failed, all.body.next]).toEqual([2, 1, 0, null]); expect(all.body.kinds.founder_retired_wrapped_row).toBe(1);const said = JSON.stringify(all.body);for (const never of [DATABASE_ID, CLEAN_ID, OWNER_PHONE, CLEAN_PHONE]) expect(said).not.toContain(never);// A page of one goes on from its position.const first = await ask<VaultKeyPage>("?limit=1"); expect([first.body.objects, first.body.next]).toEqual([1, 1]);const second = await ask<VaultKeyPage>("?limit=1&from=1"); expect([second.body.objects, second.body.next]).toEqual([1, 2]); expect((await ask<VaultKeyPage>("?limit=1&from=2")).body).toMatchObject({ objects: 0, next: null }); expect(first.body.flagged + second.body.flagged).toBe(1);// One database, by its id: its whole report.const one = await ask<VaultKeyReport>(`/${DATABASE_ID}`); expect([one.status, one.body.flagged, one.body.identity.pinned]).toEqual([200, true, 0]); expect((await ask<VaultKeyReport>(`/${CLEAN_ID}`)).body).toMatchObject({ flagged: false, vault_key_rows: 2 }); expect((await ask("/55555555-5555-4555-8555-555555555555")).status).toBe(404); expect((await ask(`/${CLEAN_ID}`, { authorization: "Bearer not-the-admin" })).status).toBe(403); });});