vault.rotate-sync-identity.test.ts

12.7 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  it("preserves historical issuer verification through root rotation and re-pair", async () => {159    const paired = await import("./paired-devices");160    const identity = await import("./device-identity");161    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");162    const { pubkeyToHex } = await import("../shared/sync-identity");163    const { signDeviceRevocation } = await import("../shared/device-manifest");164    await identity.getOrCreateDeviceId();165    const signing = await deriveSyncSigningKeypair(new Uint8Array(32).fill(7), "old-issuer");166    const peer = { deviceId: "old-issuer", deviceName: "Old", deviceType: "android" as const, longTermPublicKeyHex: "a".repeat(64), signingPublicKeyHex: pubkeyToHex(signing.publicKeyRaw), pairedAt: 1, trustSource: "direct" as const };167    await paired.upsertPairedDevice(peer);168    const record = await signDeviceRevocation({ deviceId: "removed", longTermPublicKeyHex: "b".repeat(64), revokedAt: 1, revokedByDeviceId: peer.deviceId }, signing.privateKey);169    await paired.mergeDeviceRevocations([record]);170    expect(await vault.rotateSyncIdentity()).toMatchObject({ ok: true });171    expect(await paired.listPairedDevices()).toEqual([]);172    expect(((await paired.listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual([peer.signingPublicKeyHex]);173    await paired.upsertPairedDevice({ ...peer, deviceId: "repaired-peer" });174    const { createSyncVaultAdapter } = await import("./sync-vault-adapter");175    expect((await createSyncVaultAdapter().buildOutgoingDeviceManifest?.())?.body.revoked).toEqual([record]);176  });177178  // T-016d: the session-owned recovery-pending state is set after rotation.179  // Rotation generates new 12 recovery words (derived from the new root key).180  // The user MUST re-confirm these words before the old ones become the only181  // backup. The recovery_pending flag routes the popup back to the word display.182  //183  // Bug this catches: forgetting setRecoveryConfirmPending() after rotation184  // means the user is never prompted to re-confirm new recovery words — they185  // continue thinking their old words are valid when they are not.186  it("T-016d: session recovery-pending state is set after rotation", async () => {187    await vault.rotateSyncIdentity();188189    const { isRecoveryConfirmPending } = await import("./recovery-pending");190    await expect(isRecoveryConfirmPending()).resolves.toBe(true);191    expect(storage["peach_recovery_pending"]).toBeUndefined();192  });193194  // T-016e: vault is still unlockable with the same password after rotation.195  // The new root key is re-wrapped under the password-derived key — the user's196  // passphrase still works. This is the most critical invariant: a rotation197  // that breaks the password unlock would lock the user out of their vault.198  //199  // Bug this catches: a rotation that fails to persist the new root key wrapped200  // under the current password (step 2 in rotateSyncIdentity: "Re-wrap the new201  // root key under the current password-derived key") would make the vault202  // inaccessible after the next browser restart.203  it("T-016e: vault still unlocks with the same password after rotation", async () => {204    await vault.rotateSyncIdentity();205206    // Lock the vault (clears in-memory derived key and root key)207    vault.lock();208    expect(vault.isUnlocked()).toBe(false);209210    // Unlock with the same password — must succeed211    const unlocked = await vault.unlock(VAULT_PASSWORD);212    expect(unlocked).toBe(true);213    expect(vault.isUnlocked()).toBe(true);214  });215216  // T-016f: entries are preserved after rotation.217  // Entries are encrypted under the password-derived key, NOT the root key.218  // Rotation changes the root key but leaves entry ciphertext untouched.219  // After rotation and re-lock, existing entries must still be readable.220  it("T-016f: entries encrypted before rotation are still accessible after", async () => {221    // Add an entry before rotation222    const added = await vault.addEntry({223      type: "login",224      title: "Pre-Rotation Entry",225      username: "alice",226      password: "s3cret",227      url: "https://example.com",228      tags: [],229    });230    expect(added.id).toBeTruthy();231232    await vault.rotateSyncIdentity();233234    // Lock and re-unlock235    vault.lock();236    await vault.unlock(VAULT_PASSWORD);237238    // Entry must still be present239    const entries = vault.getEntries();240    const found = entries.find((e) => e.id === added.id);241    expect(found).toBeDefined();242    expect(found?.title).toBe("Pre-Rotation Entry");243  });244245  // T-016g: rotateSyncIdentity returns { ok: false, error: "vault_locked" }246  // when called while the vault is locked. No partial state change must occur.247  it("T-016g: rotateSyncIdentity fails gracefully when vault is locked", async () => {248    vault.lock();249    const result = await vault.rotateSyncIdentity();250    expect(result.ok).toBe(false);251    expect(result.error).toBe("vault_locked");252  });253  it.each([false, true])("does not publish rotation authority into an ended session (reopen=%s)", async (reopen) => {254    const identity = reopen ? await import("./device-identity") : null;255    const before = await identity?.buildLocalIdentity();256    let release!: () => void;257    let committed!: () => void;258    const blocked = new Promise<void>((resolve) => { release = resolve; });259    const issued = new Promise<void>((resolve) => { committed = resolve; });260    vi.spyOn(chrome.storage.local, "set").mockImplementation(async (values) => {261      Object.assign(storage, values);262      if (Object.hasOwn(values, "peach_vault_a")) {263        committed();264        await blocked;265      }266    });267    const rotation = vault.rotateSyncIdentity();268    await issued;269    await vault.lock();270    if (reopen) expect(await vault.unlock(VAULT_PASSWORD)).toBe(true);271    const root = vault.getRootKeyHex();272    release();273    expect(await rotation).toMatchObject({ ok: true });274    expect(vault.getRootKeyHex()).toBe(root);275    expect(vault.isUnlocked()).toBe(reopen);276    const pending = await import("./recovery-pending");277    expect(await pending.isRecoveryConfirmPending()).toBe(true);278    expect(await pending.consumeRecoveryReveal()).toBe(false);279    if (identity) {280      expect(await vault.changePassword(VAULT_PASSWORD, "changed-password-12345")).toBe(true);281      await vault.lock();282      expect(await vault.unlock("changed-password-12345")).toBe(true);283      expect(await identity.buildLocalIdentity()).toEqual(before);284    }285  });286287});