vault.rotate-sync-identity.test.ts

11.1 KB · raw

1// T-016: rotateSyncIdentity — new root key, cleared peers, recovery pending2//3// Why this test exists: rotateSyncIdentity (MV-8) is the "nuclear option" for4// a lost/stolen device — it swaps in a new root key so the compromised device's5// retained key material becomes useless. It also:6//   - Clears all paired devices (they must re-pair)7//   - Sets session-owned recovery-pending state (new recovery words must be acknowledged)8//   - Rewraps the new root key under the SAME password-derived key (so the9//     vault stays unlockable with the current password)10//   - Does NOT re-encrypt existing entries (they are password-sealed, not11//     root-key-sealed)12//13// This function was added in MV-8 and has ZERO test coverage in the existing14// suite. A regression here would silently fail to rotate the root key or15// silently fail to clear paired devices — leaving the user's vault unprotected16// while the UI presents the rotation as successful.1718import { beforeEach, describe, expect, it, vi } from "vitest";1920type StorageShape = Record<string, unknown>;2122// ---------------------------------------------------------------------------23// Chrome storage mock (same pattern as messages.batch-sanitize.test.ts)24// ---------------------------------------------------------------------------2526function makeChromeStorageMock(): {27  storage: StorageShape;28  chrome: typeof globalThis.chrome;29} {30  const storage: StorageShape = {};31  const sessionStorage: StorageShape = {};32  const chrome = {33    storage: {34      sync: { get: vi.fn(async () => ({})) },35      local: {36        get: vi.fn(async (key?: string | string[]) => {37          if (!key) return { ...storage };38          if (typeof key === "string") return { [key]: storage[key] };39          return (Array.isArray(key) ? key : [key]).reduce<StorageShape>(40            (acc, k) => { acc[k] = storage[k]; return acc; },41            {},42          );43        }),44        set: vi.fn(async (next: StorageShape) => { Object.assign(storage, next); }),45        remove: vi.fn(async (keys: string | string[]) => {46          const ks = Array.isArray(keys) ? keys : [keys];47          for (const k of ks) delete storage[k];48        }),49        clear: vi.fn(async () => {50          for (const k of Object.keys(storage)) delete storage[k];51        }),52      },53      session: {54        get: vi.fn(async (key?: string | string[]) => {55          if (!key) return { ...sessionStorage };56          if (typeof key === "string") return { [key]: sessionStorage[key] };57          return key.reduce<StorageShape>((acc, k) => { acc[k] = sessionStorage[k]; return acc; }, {});58        }),59        set: vi.fn(async (next: StorageShape) => { Object.assign(sessionStorage, next); }),60        remove: vi.fn(async (keys: string | string[]) => {61          for (const key of (Array.isArray(keys) ? keys : [keys])) delete sessionStorage[key];62        }),63      },64    },65    alarms: {66      clear: vi.fn(),67      create: vi.fn(),68      onAlarm: { addListener: vi.fn() },69    },70    idle: {71      setDetectionInterval: vi.fn(),72      onStateChanged: { addListener: vi.fn() },73    },74  } as unknown as typeof globalThis.chrome;75  return { storage, chrome };76}7778// ---------------------------------------------------------------------------79// Tests80// ---------------------------------------------------------------------------8182describe("T-016: rotateSyncIdentity — MV-8 rotation invariants", () => {83  let storage: StorageShape;84  let vault: typeof import("./vault");85  const VAULT_PASSWORD = "rotate-test-pass-007";8687  beforeEach(async () => {88    vi.resetModules();89    const mock = makeChromeStorageMock();90    storage = mock.storage;91    (globalThis as Record<string, unknown>).chrome = mock.chrome;92    vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("no network"); }));9394    vault = await import("./vault");95    await vault.createVault(VAULT_PASSWORD);96  });9798  // T-016a: rotateSyncIdentity returns { ok: true } while vault is unlocked.99  // Bug this catches: the function returns early with { ok: false, error: "vault_locked" }100  // if the vault is not in the "real" mode — testing confirms the vault is101  // actually unlocked when we call the function.102  it("T-016a: rotateSyncIdentity returns { ok: true } while vault is unlocked", async () => {103    const result = await vault.rotateSyncIdentity();104    expect(result.ok).toBe(true);105    expect(result.error).toBeUndefined();106  });107108  // T-016b: root key changes after rotation.109  // getRootKeyHex() exposes the in-memory root key. Before and after rotation110  // the hex strings must differ — confirming a genuinely new key was generated111  // (not a no-op that re-uses the same key material).112  //113  // Bug this catches: a rotation that calls generateAndWrapRootKey() but114  // forgets to swap rootKey in memory (step 4 in rotateSyncIdentity: "Swap115  // in memory only after disk committed") would leave getRootKeyHex() unchanged.116  it("T-016b: getRootKeyHex differs before and after rotation (new key generated)", async () => {117    const rootKeyBefore = vault.getRootKeyHex();118    expect(rootKeyBefore).not.toBeNull();119120    await vault.rotateSyncIdentity();121122    const rootKeyAfter = vault.getRootKeyHex();123    expect(rootKeyAfter).not.toBeNull();124    expect(rootKeyAfter).not.toBe(rootKeyBefore);125  });126127  // T-016c: paired devices are cleared after rotation.128  // After rotation, the old paired devices must no longer appear in storage —129  // their Noise static keys are derived from the old root key and cannot130  // be used to authenticate against the new sync identity.131  //132  // Bug this catches: forgetting to call clearPairedDevices() after rotation133  // would leave stale device entries; the sync layer would attempt to use them134  // and fail in a confusing way (wrong MAC on decrypted handshake).135  it("T-016c: paired devices cleared from storage after rotation", async () => {136    // Pre-populate a fake paired device entry137    const PAIRED_KEY = "peach_paired_devices_v3";138    storage[PAIRED_KEY] = [139      {140        deviceId: "test-device-1",141        publicKey: "deadbeef".repeat(8),142        label: "My Laptop",143        pairedAt: 0,144      },145    ];146147    await vault.rotateSyncIdentity();148149    // The paired devices key must be absent (or empty) in storage150    const devicesAfter = storage[PAIRED_KEY];151    const isEmpty =152      devicesAfter === undefined ||153      devicesAfter === null ||154      (Array.isArray(devicesAfter) && (devicesAfter as unknown[]).length === 0);155    expect(isEmpty).toBe(true);156  });157158  // T-016d: the session-owned recovery-pending state is set after rotation.159  // Rotation generates new 12 recovery words (derived from the new root key).160  // The user MUST re-confirm these words before the old ones become the only161  // backup. The recovery_pending flag routes the popup back to the word display.162  //163  // Bug this catches: forgetting setRecoveryConfirmPending() after rotation164  // means the user is never prompted to re-confirm new recovery words — they165  // continue thinking their old words are valid when they are not.166  it("T-016d: session recovery-pending state is set after rotation", async () => {167    await vault.rotateSyncIdentity();168169    const { isRecoveryConfirmPending } = await import("./recovery-pending");170    await expect(isRecoveryConfirmPending()).resolves.toBe(true);171    expect(storage["peach_recovery_pending"]).toBeUndefined();172  });173174  // T-016e: vault is still unlockable with the same password after rotation.175  // The new root key is re-wrapped under the password-derived key — the user's176  // passphrase still works. This is the most critical invariant: a rotation177  // that breaks the password unlock would lock the user out of their vault.178  //179  // Bug this catches: a rotation that fails to persist the new root key wrapped180  // under the current password (step 2 in rotateSyncIdentity: "Re-wrap the new181  // root key under the current password-derived key") would make the vault182  // inaccessible after the next browser restart.183  it("T-016e: vault still unlocks with the same password after rotation", async () => {184    await vault.rotateSyncIdentity();185186    // Lock the vault (clears in-memory derived key and root key)187    vault.lock();188    expect(vault.isUnlocked()).toBe(false);189190    // Unlock with the same password — must succeed191    const unlocked = await vault.unlock(VAULT_PASSWORD);192    expect(unlocked).toBe(true);193    expect(vault.isUnlocked()).toBe(true);194  });195196  // T-016f: entries are preserved after rotation.197  // Entries are encrypted under the password-derived key, NOT the root key.198  // Rotation changes the root key but leaves entry ciphertext untouched.199  // After rotation and re-lock, existing entries must still be readable.200  it("T-016f: entries encrypted before rotation are still accessible after", async () => {201    // Add an entry before rotation202    const added = await vault.addEntry({203      type: "login",204      title: "Pre-Rotation Entry",205      username: "alice",206      password: "s3cret",207      url: "https://example.com",208      tags: [],209    });210    expect(added.id).toBeTruthy();211212    await vault.rotateSyncIdentity();213214    // Lock and re-unlock215    vault.lock();216    await vault.unlock(VAULT_PASSWORD);217218    // Entry must still be present219    const entries = vault.getEntries();220    const found = entries.find((e) => e.id === added.id);221    expect(found).toBeDefined();222    expect(found?.title).toBe("Pre-Rotation Entry");223  });224225  // T-016g: rotateSyncIdentity returns { ok: false, error: "vault_locked" }226  // when called while the vault is locked. No partial state change must occur.227  it("T-016g: rotateSyncIdentity fails gracefully when vault is locked", async () => {228    vault.lock();229    const result = await vault.rotateSyncIdentity();230    expect(result.ok).toBe(false);231    expect(result.error).toBe("vault_locked");232  });233  it.each([false, true])("does not publish rotation authority into an ended session (reopen=%s)", async (reopen) => {234    const identity = reopen ? await import("./device-identity") : null;235    const before = await identity?.buildLocalIdentity();236    let release!: () => void;237    let committed!: () => void;238    const blocked = new Promise<void>((resolve) => { release = resolve; });239    const issued = new Promise<void>((resolve) => { committed = resolve; });240    vi.spyOn(chrome.storage.local, "set").mockImplementation(async (values) => {241      Object.assign(storage, values);242      if (Object.hasOwn(values, "peach_vault_a")) {243        committed();244        await blocked;245      }246    });247    const rotation = vault.rotateSyncIdentity();248    await issued;249    await vault.lock();250    if (reopen) expect(await vault.unlock(VAULT_PASSWORD)).toBe(true);251    const root = vault.getRootKeyHex();252    release();253    expect(await rotation).toMatchObject({ ok: true });254    expect(vault.getRootKeyHex()).toBe(root);255    expect(vault.isUnlocked()).toBe(reopen);256    const pending = await import("./recovery-pending");257    expect(await pending.isRecoveryConfirmPending()).toBe(true);258    expect(await pending.consumeRecoveryReveal()).toBe(false);259    if (identity) {260      expect(await vault.changePassword(VAULT_PASSWORD, "changed-password-12345")).toBe(true);261      await vault.lock();262      expect(await vault.unlock("changed-password-12345")).toBe(true);263      expect(await identity.buildLocalIdentity()).toEqual(before);264    }265  });266267});