vault.session-escrow.test.ts

17.7 KB · raw

1import { beforeEach, describe, expect, it, vi } from "vitest";23// PCH-01-008: a password change must refresh the MV3 session-key escrow so the4// next service-worker restore decrypts the new-key Slot A. The backing stores5// are closed over by the chrome mock on globalThis, so they survive the6// vi.resetModules() we use to simulate a service-worker restart mid-test.789type StorageShape = Record<string, unknown>;1011function deferred(): { promise: Promise<void>; resolve: () => void } {12  let resolve!: () => void;13  const promise = new Promise<void>((done) => {14    resolve = done;15  });16  return { promise, resolve };17}1819function pauseSessionKeyWrite(session: StorageShape): {20  started: Promise<void>;21  release: () => void;22} {23  const started = deferred();24  const release = deferred();25  const sessionSet = chrome.storage.session.set as unknown as ReturnType<typeof vi.fn>;26  sessionSet.mockImplementation(async (next: Record<string, unknown>) => {27    if ("peach_session_dk" in next) {28      started.resolve();29      await release.promise;30    }31    Object.assign(session, next);32  });33  return { started: started.promise, release: release.resolve };34}3536describe("vault session escrow refresh (PCH-01-008)", () => {37  let local: StorageShape;38  let session: StorageShape;3940  beforeEach(() => {41    vi.resetModules();42    local = {};43    session = {};44    const area = (store: StorageShape) => ({45      get: vi.fn(async (key?: string | string[]) => {46        if (!key) return store;47        if (typeof key === "string") return { [key]: store[key] };48        return key.reduce<Record<string, unknown>>((r, k) => { r[k] = store[k]; return r; }, {});49      }),50      set: vi.fn(async (next: Record<string, unknown>) => { Object.assign(store, next); }),51      remove: vi.fn(async (keys: string | string[]) => {52        for (const k of Array.isArray(keys) ? keys : [keys]) delete store[k];53      }),54    });55    (globalThis as { chrome?: typeof chrome }).chrome = {56      storage: { local: area(local), session: area(session) },57      alarms: { clear: vi.fn(), create: vi.fn(), onAlarm: { addListener: vi.fn() } },58      idle: { setDetectionInterval: vi.fn(), onStateChanged: { addListener: vi.fn() } },59    } as unknown as typeof chrome;60    vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("network disabled"); }));61  });6263  it("change_password_updates_session_escrow", async () => {64    const v1 = await import("./vault");65    await v1.createVault("old-pass-abc123");66    await v1.addEntry({ type: "login", title: "Acct", password: "pw" });67    expect(await v1.changePassword("old-pass-abc123", "new-pass-xyz789")).toBe(true);6869    // Simulate a SW restart after the awaited escrow refresh: a fresh module70    // has derivedKey=null but session/local persist.71    vi.resetModules();72    const v2 = await import("./vault");73    expect(await v2.restoreFromSession()).toBe(true);74    expect(v2.getEntries().some((e) => e.title === "Acct")).toBe(true);75  });7677  it("recovery_updates_session_escrow", async () => {78    const v1 = await import("./vault");79    await v1.createVault("orig-pass-abc123");80    await v1.addEntry({ type: "login", title: "Recovered", password: "pw" });8182    const words = await v1.getRecoveryWords();83    await v1.lock();84    await v1.recoverWithWords(words, "reset-pass-xyz789");8586    vi.resetModules();87    const v2 = await import("./vault");88    expect(await v2.restoreFromSession()).toBe(true);89    expect(v2.getEntries().some((e) => e.title === "Recovered")).toBe(true);90  });9192  it("unlockWithKey runs the post-unlock hook like the password path", async () => {93    const v1 = await import("./vault");94    await v1.createVault("pin-hook-pass-abc123");95    // The PIN path unwraps the pre-derived vault key; pin the hook wiring only.96    const derivedHex = v1.getDerivedKeyHex();97    await v1.lock();9899    const afterUnlock = vi.fn(async () => undefined);100    v1.setLockedSyncHooks({ refresh: async () => undefined, afterUnlock });101    // The PIN path unwraps the vault key from the PIN wrap; this test pins the102    // hook wiring, so it drives the key directly.103    const result = await v1.unlockWithKey(derivedHex);104    expect(result.ok).toBe(true);105    expect(afterUnlock).toHaveBeenCalledTimes(1);106  });107108  it("restoreFromSession rehydrates rootKey so background sync survives a SW restart", async () => {109    // Background sync bug: entry.ts calls restoreFromSession() on every SW wake-up,110    // then triggerSyncIfReachable. The runner needs getRootKeyHex() to be non-null111    // — sync identity derives from rootKey, not derivedKey. The previous112    // restoreFromSession only set rootKey when the slot had recovery_salt +113    // recovery_wrapped_root_key; for any vault that hadn't been through114    // the recovery bootstrap, rootKey was silently null and the runner returned115    // VAULT_LOCKED. The fix is to always derive rootKey from pw_root_* (which116    // are present on every vault since createVault).117    const v1 = await import("./vault");118    await v1.createVault("strong-pass-abc123");119    // unlock() is the real-world path that saves the MV3 session key — the120    // user's popup opens, types the password, and the session key is parked121    // in chrome.storage.session for the next SW wake.122    await v1.unlock("strong-pass-abc123");123    const rootBeforeDead = v1.getRootKeyHex();124    expect(rootBeforeDead).not.toBeNull();125126    // Simulate a SW kill: flush the fire-and-forget saveSessionKey promise,127    // then reset modules so a fresh vault.ts reads the persisted session key.128    await Promise.resolve();129    vi.resetModules();130    const v2 = await import("./vault");131    expect(await v2.restoreFromSession()).toBe(true);132    // The bug shape: rootKey was null after restore, so the runner short-circuited133    // to VAULT_LOCKED even though entries were present.134    expect(v2.getRootKeyHex()).not.toBeNull();135    expect(v2.getRootKeyHex()).toBe(rootBeforeDead);136  });137138  it("lock() clears the MV3 session key so a manual lock survives a SW restart", async () => {139    // Bug shape: lock() used to keep the session key in chrome.storage.session140    // so background sync could re-wake a restored vault. MV3 idle-kills the SW141    // after ~30s, so a popup reopened a minute after locking woke a cold SW,142    // restoreFromSession() found the surviving key, and the vault silently143    // re-unlocked without the password. Every lock path (manual lock icon,144    // popup close with lockOnClose=true, auto-lock alarm, idle) flows through145    // lock(), and all of them are deliberate locks — none should be undone by146    // the next SW restart. clearSessionKey() mirrors the fire-and-forget147    // saveSessionKey() pattern used by unlock().148    const v1 = await import("./vault");149    await v1.createVault("strong-pass-abc123");150    await v1.unlock("strong-pass-abc123");151    const sessionKeyBeforeLock = await chrome.storage.session.get("peach_session_dk");152    expect(sessionKeyBeforeLock.peach_session_dk).toBeDefined();153154    // The lock-on-close path: popup port disconnect, alarm tick, etc.155    v1.lock();156    expect(v1.isUnlocked()).toBe(false);157    // Flush the fire-and-forget clearSessionKey microtask, then confirm the158    // key was actually removed from chrome.storage.session.159    await Promise.resolve();160    const sessionKeyAfterLock = await chrome.storage.session.get("peach_session_dk");161    expect(sessionKeyAfterLock.peach_session_dk).toBeUndefined();162163    // The next SW wake must NOT restore the vault — restoreFromSession() finds164    // no session key and the vault stays locked until the password is typed.165    vi.resetModules();166    const v2 = await import("./vault");167    expect(await v2.restoreFromSession()).toBe(false);168    expect(v2.isUnlocked()).toBe(false);169    expect(v2.getRootKeyHex()).toBeNull();170  });171172  it("a lock invalidates a real unlock paused while writing session escrow", async () => {173    const vault = await import("./vault");174    await vault.createVault("strong-pass-abc123");175    await vault.lock();176177    const write = pauseSessionKeyWrite(session);178    const unlocking = vault.unlock("strong-pass-abc123");179    await write.started;180181    let lockSettled = false;182    const locking = vault.lock().then(() => {183      lockSettled = true;184    });185    await new Promise((resolve) => setTimeout(resolve, 0));186    const lockSettledBeforeWrite = lockSettled;187    write.release();188189    expect(lockSettledBeforeWrite).toBe(false);190    await expect(unlocking).resolves.toBe(false);191    await locking;192    expect(vault.isUnlocked()).toBe(false);193    expect(session.peach_session_dk).toBeUndefined();194195    vi.resetModules();196    const restarted = await import("./vault");197    expect(await restarted.restoreFromSession()).toBe(false);198  });199200  it("a lock invalidates a duress unlock paused while writing session escrow", async () => {201    const vault = await import("./vault");202    await vault.createVault("real-pass-abc123");203    await vault.setupDuress("duress-pass-xyz789");204    await vault.lock();205206    const write = pauseSessionKeyWrite(session);207    const unlocking = vault.unlock("duress-pass-xyz789");208    await write.started;209210    const locking = vault.lock();211    await Promise.resolve();212    write.release();213214    await expect(unlocking).resolves.toBe(false);215    await locking;216    expect(vault.isUnlocked()).toBe(false);217    expect(session.peach_session_dk).toBeUndefined();218  });219220  it("a lock invalidates a key unlock paused while writing session escrow", async () => {221    const vault = await import("./vault");222    await vault.createVault("strong-pass-abc123");223    const keyHex = vault.getDerivedKeyHex();224    await vault.lock();225226    const write = pauseSessionKeyWrite(session);227    const unlocking = vault.unlockWithKey(keyHex);228    await write.started;229230    const locking = vault.lock();231    await Promise.resolve();232    write.release();233234    await expect(unlocking).resolves.toEqual({ ok: false, error: "invalid_key" });235    await locking;236    expect(vault.isUnlocked()).toBe(false);237    expect(session.peach_session_dk).toBeUndefined();238  });239240  it("a lock invalidates a password change paused while writing session escrow", async () => {241    const vault = await import("./vault");242    await vault.createVault("old-pass-abc123");243244    const write = pauseSessionKeyWrite(session);245    const changing = vault.changePassword("old-pass-abc123", "new-pass-xyz789");246    await write.started;247248    const locking = vault.lock();249    await Promise.resolve();250    write.release();251252    await expect(changing).resolves.toBe(false);253    await locking;254    expect(vault.isUnlocked()).toBe(false);255    expect(session.peach_session_dk).toBeUndefined();256257    vi.resetModules();258    const restarted = await import("./vault");259    expect(await restarted.restoreFromSession()).toBe(false);260  });261262  it("a lock clears a recovery re-key paused while writing session escrow", async () => {263    const vault = await import("./vault");264    await vault.createVault("old-pass-abc123");265    const words = await vault.getRecoveryWords();266    await vault.lock();267268    const write = pauseSessionKeyWrite(session);269    const changing = vault.recoverWithWords(words, "new-pass-xyz789");270    await write.started;271272    let lockSettled = false;273    const locking = vault.lock().then(() => {274      lockSettled = true;275    });276    await new Promise((resolve) => setTimeout(resolve, 0));277    const lockSettledBeforeWrite = lockSettled;278    write.release();279280    expect(lockSettledBeforeWrite).toBe(false);281    await expect(changing).resolves.toEqual({ committed: true, unlocked: false });282    await locking;283    expect(vault.isUnlocked()).toBe(false);284    expect(session.peach_session_dk).toBeUndefined();285286    vi.resetModules();287    const restarted = await import("./vault");288    expect(await restarted.restoreFromSession()).toBe(false);289  });290291  it("a lock invalidates a restore paused while reading the session key", async () => {292    const v1 = await import("./vault");293    await v1.createVault("strong-pass-abc123");294    await v1.unlock("strong-pass-abc123");295    await vi.waitFor(() => expect(session.peach_session_dk).toBeDefined());296297    const staleSessionKey = session.peach_session_dk;298    const readStarted = deferred();299    const releaseRead = deferred();300    const sessionGet = chrome.storage.session.get as unknown as ReturnType<typeof vi.fn>;301    sessionGet.mockImplementation(async (key?: string | string[]) => {302      if (key === "peach_session_dk") {303        readStarted.resolve();304        await releaseRead.promise;305        return { peach_session_dk: staleSessionKey };306      }307      if (!key) return session;308      const keys = Array.isArray(key) ? key : [key];309      return keys.reduce<StorageShape>((result, entry) => {310        result[entry] = session[entry];311        return result;312      }, {});313    });314315    vi.resetModules();316    const v2 = await import("./vault");317    const restoring = v2.restoreFromSession();318    await readStarted.promise;319320    await v2.lock();321    releaseRead.resolve();322323    await expect(restoring).resolves.toBe(false);324    expect(v2.isUnlocked()).toBe(false);325    expect(v2.getRootKeyHex()).toBeNull();326  });327328  it("keeps decrypted restore state private until the final epoch-checked commit", async () => {329    const v1 = await import("./vault");330    await v1.createVault("strong-pass-abc123");331    await v1.unlock("strong-pass-abc123");332    await vi.waitFor(() => expect(session.peach_session_dk).toBeDefined());333334    const settingsReadStarted = deferred();335    const releaseSettingsRead = deferred();336    const localGet = chrome.storage.local.get as unknown as ReturnType<typeof vi.fn>;337    localGet.mockImplementation(async (key?: string | string[]) => {338      if (key === "peach_settings") {339        settingsReadStarted.resolve();340        await releaseSettingsRead.promise;341      }342      if (!key) return local;343      const keys = Array.isArray(key) ? key : [key];344      return keys.reduce<StorageShape>((result, entry) => {345        result[entry] = local[entry];346        return result;347      }, {});348    });349350    vi.resetModules();351    const v2 = await import("./vault");352    const restoring = v2.restoreFromSession();353    await settingsReadStarted.promise;354355    try {356      expect(v2.isUnlocked()).toBe(false);357      const locking = Promise.resolve(v2.lock());358      expect(v2.isUnlocked()).toBe(false);359      releaseSettingsRead.resolve();360      await locking;361362      await expect(restoring).resolves.toBe(false);363      expect(v2.isUnlocked()).toBe(false);364      expect(v2.getRootKeyHex()).toBeNull();365    } finally {366      releaseSettingsRead.resolve();367      await Promise.allSettled([restoring]);368    }369  });370371  it("does not resolve lock until session escrow is absent", async () => {372    const vault = await import("./vault");373    const pending = await import("./recovery-pending");374    await vault.createVault("strong-pass-abc123");375    await vault.unlock("strong-pass-abc123");376    await pending.setRecoveryConfirmPending();377    await vi.waitFor(() => {378      expect(session.peach_session_dk).toBeDefined();379      expect(session.peach_recovery_pending).toBeDefined();380    });381382    const removalStarted = deferred();383    const releaseRemoval = deferred();384    const sessionRemove = chrome.storage.session.remove as unknown as ReturnType<typeof vi.fn>;385    sessionRemove.mockImplementation(async (keys: string | string[]) => {386      removalStarted.resolve();387      await releaseRemoval.promise;388      for (const key of Array.isArray(keys) ? keys : [keys]) delete session[key];389    });390391    let settled = false;392    const locking = Promise.resolve(vault.lock()).then(() => {393      settled = true;394    });395    expect(vault.isUnlocked()).toBe(false);396    await removalStarted.promise;397398    try {399      await Promise.resolve();400      expect(settled).toBe(false);401    } finally {402      releaseRemoval.resolve();403      await locking;404    }405406    expect(session.peach_session_dk).toBeUndefined();407    expect(session.peach_recovery_pending).toBeDefined();408  });409410  it("disabled escrow clears the stored key and blocks save and restore", async () => {411    const v1 = await import("./vault");412    await v1.createVault("strong-pass-abc123");413    await v1.unlock("strong-pass-abc123");414    await vi.waitFor(() => expect(session.peach_session_dk).toBeDefined());415    const parked = session.peach_session_dk;416417    await v1.applyStorageHardening(false);418    expect(session.peach_session_dk).toBeUndefined();419420    // A later unlock must not re-park the key while escrow is off.421    await v1.unlock("strong-pass-abc123");422    await Promise.resolve();423    expect(session.peach_session_dk).toBeUndefined();424425    // A restarted worker with the same stored key restores only when the426    // hardening result allows escrow; a disabled escrow fails closed.427    session.peach_session_dk = parked;428    vi.resetModules();429    const v2 = await import("./vault");430    expect(await v2.restoreFromSession()).toBe(true);431432    vi.resetModules();433    const v3 = await import("./vault");434    await v3.applyStorageHardening(false);435    expect(session.peach_session_dk).toBeUndefined();436    expect(await v3.restoreFromSession()).toBe(false);437    expect(v3.isUnlocked()).toBe(false);438  });439440  it("deduplicates simultaneous restores and runs the unlock hook once", async () => {441    const v1 = await import("./vault");442    await v1.createVault("strong-pass-abc123");443    await v1.unlock("strong-pass-abc123");444    await vi.waitFor(() => expect(session.peach_session_dk).toBeDefined());445446    vi.resetModules();447    const v2 = await import("./vault");448    const afterUnlock = vi.fn(async () => undefined);449    v2.setLockedSyncHooks({450      refresh: vi.fn(async () => undefined),451      afterUnlock,452    });453    const sessionGet = chrome.storage.session.get as unknown as ReturnType<typeof vi.fn>;454    sessionGet.mockClear();455456    await expect(Promise.all([457      v2.restoreFromSession(),458      v2.restoreFromSession(),459    ])).resolves.toEqual([true, true]);460461    expect(sessionGet.mock.calls.filter(([key]) => key === "peach_session_dk")).toHaveLength(1);462    expect(afterUnlock).toHaveBeenCalledTimes(1);463  });464});