vault.session-escrow.test.ts

17.0 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("restoreFromSession rehydrates rootKey so background sync survives a SW restart", async () => {93    // Background sync bug: entry.ts calls restoreFromSession() on every SW wake-up,94    // then triggerSyncIfReachable. The runner needs getRootKeyHex() to be non-null95    // — sync identity derives from rootKey, not derivedKey. The previous96    // restoreFromSession only set rootKey when the slot had recovery_salt +97    // recovery_wrapped_root_key; for any vault that hadn't been through98    // the recovery bootstrap, rootKey was silently null and the runner returned99    // VAULT_LOCKED. The fix is to always derive rootKey from pw_root_* (which100    // are present on every vault since createVault).101    const v1 = await import("./vault");102    await v1.createVault("strong-pass-abc123");103    // unlock() is the real-world path that saves the MV3 session key — the104    // user's popup opens, types the password, and the session key is parked105    // in chrome.storage.session for the next SW wake.106    await v1.unlock("strong-pass-abc123");107    const rootBeforeDead = v1.getRootKeyHex();108    expect(rootBeforeDead).not.toBeNull();109110    // Simulate a SW kill: flush the fire-and-forget saveSessionKey promise,111    // then reset modules so a fresh vault.ts reads the persisted session key.112    await Promise.resolve();113    vi.resetModules();114    const v2 = await import("./vault");115    expect(await v2.restoreFromSession()).toBe(true);116    // The bug shape: rootKey was null after restore, so the runner short-circuited117    // to VAULT_LOCKED even though entries were present.118    expect(v2.getRootKeyHex()).not.toBeNull();119    expect(v2.getRootKeyHex()).toBe(rootBeforeDead);120  });121122  it("lock() clears the MV3 session key so a manual lock survives a SW restart", async () => {123    // Bug shape: lock() used to keep the session key in chrome.storage.session124    // so background sync could re-wake a restored vault. MV3 idle-kills the SW125    // after ~30s, so a popup reopened a minute after locking woke a cold SW,126    // restoreFromSession() found the surviving key, and the vault silently127    // re-unlocked without the password. Every lock path (manual lock icon,128    // popup close with lockOnClose=true, auto-lock alarm, idle) flows through129    // lock(), and all of them are deliberate locks — none should be undone by130    // the next SW restart. clearSessionKey() mirrors the fire-and-forget131    // saveSessionKey() pattern used by unlock().132    const v1 = await import("./vault");133    await v1.createVault("strong-pass-abc123");134    await v1.unlock("strong-pass-abc123");135    const sessionKeyBeforeLock = await chrome.storage.session.get("peach_session_dk");136    expect(sessionKeyBeforeLock.peach_session_dk).toBeDefined();137138    // The lock-on-close path: popup port disconnect, alarm tick, etc.139    v1.lock();140    expect(v1.isUnlocked()).toBe(false);141    // Flush the fire-and-forget clearSessionKey microtask, then confirm the142    // key was actually removed from chrome.storage.session.143    await Promise.resolve();144    const sessionKeyAfterLock = await chrome.storage.session.get("peach_session_dk");145    expect(sessionKeyAfterLock.peach_session_dk).toBeUndefined();146147    // The next SW wake must NOT restore the vault — restoreFromSession() finds148    // no session key and the vault stays locked until the password is typed.149    vi.resetModules();150    const v2 = await import("./vault");151    expect(await v2.restoreFromSession()).toBe(false);152    expect(v2.isUnlocked()).toBe(false);153    expect(v2.getRootKeyHex()).toBeNull();154  });155156  it("a lock invalidates a real unlock paused while writing session escrow", async () => {157    const vault = await import("./vault");158    await vault.createVault("strong-pass-abc123");159    await vault.lock();160161    const write = pauseSessionKeyWrite(session);162    const unlocking = vault.unlock("strong-pass-abc123");163    await write.started;164165    let lockSettled = false;166    const locking = vault.lock().then(() => {167      lockSettled = true;168    });169    await new Promise((resolve) => setTimeout(resolve, 0));170    const lockSettledBeforeWrite = lockSettled;171    write.release();172173    expect(lockSettledBeforeWrite).toBe(false);174    await expect(unlocking).resolves.toBe(false);175    await locking;176    expect(vault.isUnlocked()).toBe(false);177    expect(session.peach_session_dk).toBeUndefined();178179    vi.resetModules();180    const restarted = await import("./vault");181    expect(await restarted.restoreFromSession()).toBe(false);182  });183184  it("a lock invalidates a duress unlock paused while writing session escrow", async () => {185    const vault = await import("./vault");186    await vault.createVault("real-pass-abc123");187    await vault.setupDuress("duress-pass-xyz789");188    await vault.lock();189190    const write = pauseSessionKeyWrite(session);191    const unlocking = vault.unlock("duress-pass-xyz789");192    await write.started;193194    const locking = vault.lock();195    await Promise.resolve();196    write.release();197198    await expect(unlocking).resolves.toBe(false);199    await locking;200    expect(vault.isUnlocked()).toBe(false);201    expect(session.peach_session_dk).toBeUndefined();202  });203204  it("a lock invalidates a key unlock paused while writing session escrow", async () => {205    const vault = await import("./vault");206    await vault.createVault("strong-pass-abc123");207    const keyHex = vault.getDerivedKeyHex();208    await vault.lock();209210    const write = pauseSessionKeyWrite(session);211    const unlocking = vault.unlockWithKey(keyHex);212    await write.started;213214    const locking = vault.lock();215    await Promise.resolve();216    write.release();217218    await expect(unlocking).resolves.toEqual({ ok: false, error: "invalid_key" });219    await locking;220    expect(vault.isUnlocked()).toBe(false);221    expect(session.peach_session_dk).toBeUndefined();222  });223224  it("a lock invalidates a password change paused while writing session escrow", async () => {225    const vault = await import("./vault");226    await vault.createVault("old-pass-abc123");227228    const write = pauseSessionKeyWrite(session);229    const changing = vault.changePassword("old-pass-abc123", "new-pass-xyz789");230    await write.started;231232    const locking = vault.lock();233    await Promise.resolve();234    write.release();235236    await expect(changing).resolves.toBe(false);237    await locking;238    expect(vault.isUnlocked()).toBe(false);239    expect(session.peach_session_dk).toBeUndefined();240241    vi.resetModules();242    const restarted = await import("./vault");243    expect(await restarted.restoreFromSession()).toBe(false);244  });245246  it("a lock clears a recovery re-key paused while writing session escrow", async () => {247    const vault = await import("./vault");248    await vault.createVault("old-pass-abc123");249    const words = await vault.getRecoveryWords();250    await vault.lock();251252    const write = pauseSessionKeyWrite(session);253    const changing = vault.recoverWithWords(words, "new-pass-xyz789");254    await write.started;255256    let lockSettled = false;257    const locking = vault.lock().then(() => {258      lockSettled = true;259    });260    await new Promise((resolve) => setTimeout(resolve, 0));261    const lockSettledBeforeWrite = lockSettled;262    write.release();263264    expect(lockSettledBeforeWrite).toBe(false);265    await expect(changing).resolves.toEqual({ committed: true, unlocked: false });266    await locking;267    expect(vault.isUnlocked()).toBe(false);268    expect(session.peach_session_dk).toBeUndefined();269270    vi.resetModules();271    const restarted = await import("./vault");272    expect(await restarted.restoreFromSession()).toBe(false);273  });274275  it("a lock invalidates a restore paused while reading the session key", async () => {276    const v1 = await import("./vault");277    await v1.createVault("strong-pass-abc123");278    await v1.unlock("strong-pass-abc123");279    await vi.waitFor(() => expect(session.peach_session_dk).toBeDefined());280281    const staleSessionKey = session.peach_session_dk;282    const readStarted = deferred();283    const releaseRead = deferred();284    const sessionGet = chrome.storage.session.get as unknown as ReturnType<typeof vi.fn>;285    sessionGet.mockImplementation(async (key?: string | string[]) => {286      if (key === "peach_session_dk") {287        readStarted.resolve();288        await releaseRead.promise;289        return { peach_session_dk: staleSessionKey };290      }291      if (!key) return session;292      const keys = Array.isArray(key) ? key : [key];293      return keys.reduce<StorageShape>((result, entry) => {294        result[entry] = session[entry];295        return result;296      }, {});297    });298299    vi.resetModules();300    const v2 = await import("./vault");301    const restoring = v2.restoreFromSession();302    await readStarted.promise;303304    await v2.lock();305    releaseRead.resolve();306307    await expect(restoring).resolves.toBe(false);308    expect(v2.isUnlocked()).toBe(false);309    expect(v2.getRootKeyHex()).toBeNull();310  });311312  it("keeps decrypted restore state private until the final epoch-checked commit", async () => {313    const v1 = await import("./vault");314    await v1.createVault("strong-pass-abc123");315    await v1.unlock("strong-pass-abc123");316    await vi.waitFor(() => expect(session.peach_session_dk).toBeDefined());317318    const settingsReadStarted = deferred();319    const releaseSettingsRead = deferred();320    const localGet = chrome.storage.local.get as unknown as ReturnType<typeof vi.fn>;321    localGet.mockImplementation(async (key?: string | string[]) => {322      if (key === "peach_settings") {323        settingsReadStarted.resolve();324        await releaseSettingsRead.promise;325      }326      if (!key) return local;327      const keys = Array.isArray(key) ? key : [key];328      return keys.reduce<StorageShape>((result, entry) => {329        result[entry] = local[entry];330        return result;331      }, {});332    });333334    vi.resetModules();335    const v2 = await import("./vault");336    const restoring = v2.restoreFromSession();337    await settingsReadStarted.promise;338339    try {340      expect(v2.isUnlocked()).toBe(false);341      const locking = Promise.resolve(v2.lock());342      expect(v2.isUnlocked()).toBe(false);343      releaseSettingsRead.resolve();344      await locking;345346      await expect(restoring).resolves.toBe(false);347      expect(v2.isUnlocked()).toBe(false);348      expect(v2.getRootKeyHex()).toBeNull();349    } finally {350      releaseSettingsRead.resolve();351      await Promise.allSettled([restoring]);352    }353  });354355  it("does not resolve lock until session escrow is absent", async () => {356    const vault = await import("./vault");357    const pending = await import("./recovery-pending");358    await vault.createVault("strong-pass-abc123");359    await vault.unlock("strong-pass-abc123");360    await pending.setRecoveryConfirmPending();361    await vi.waitFor(() => {362      expect(session.peach_session_dk).toBeDefined();363      expect(session.peach_recovery_pending).toBeDefined();364    });365366    const removalStarted = deferred();367    const releaseRemoval = deferred();368    const sessionRemove = chrome.storage.session.remove as unknown as ReturnType<typeof vi.fn>;369    sessionRemove.mockImplementation(async (keys: string | string[]) => {370      removalStarted.resolve();371      await releaseRemoval.promise;372      for (const key of Array.isArray(keys) ? keys : [keys]) delete session[key];373    });374375    let settled = false;376    const locking = Promise.resolve(vault.lock()).then(() => {377      settled = true;378    });379    expect(vault.isUnlocked()).toBe(false);380    await removalStarted.promise;381382    try {383      await Promise.resolve();384      expect(settled).toBe(false);385    } finally {386      releaseRemoval.resolve();387      await locking;388    }389390    expect(session.peach_session_dk).toBeUndefined();391    expect(session.peach_recovery_pending).toBeDefined();392  });393394  it("disabled escrow clears the stored key and blocks save and restore", async () => {395    const v1 = await import("./vault");396    await v1.createVault("strong-pass-abc123");397    await v1.unlock("strong-pass-abc123");398    await vi.waitFor(() => expect(session.peach_session_dk).toBeDefined());399    const parked = session.peach_session_dk;400401    await v1.applyStorageHardening(false);402    expect(session.peach_session_dk).toBeUndefined();403404    // A later unlock must not re-park the key while escrow is off.405    await v1.unlock("strong-pass-abc123");406    await Promise.resolve();407    expect(session.peach_session_dk).toBeUndefined();408409    // A restarted worker with the same stored key restores only when the410    // hardening result allows escrow; a disabled escrow fails closed.411    session.peach_session_dk = parked;412    vi.resetModules();413    const v2 = await import("./vault");414    expect(await v2.restoreFromSession()).toBe(true);415416    vi.resetModules();417    const v3 = await import("./vault");418    await v3.applyStorageHardening(false);419    expect(session.peach_session_dk).toBeUndefined();420    expect(await v3.restoreFromSession()).toBe(false);421    expect(v3.isUnlocked()).toBe(false);422  });423424  it("deduplicates simultaneous restores and runs the unlock hook once", async () => {425    const v1 = await import("./vault");426    await v1.createVault("strong-pass-abc123");427    await v1.unlock("strong-pass-abc123");428    await vi.waitFor(() => expect(session.peach_session_dk).toBeDefined());429430    vi.resetModules();431    const v2 = await import("./vault");432    const afterUnlock = vi.fn(async () => undefined);433    v2.setLockedSyncHooks({434      refresh: vi.fn(async () => undefined),435      afterUnlock,436    });437    const sessionGet = chrome.storage.session.get as unknown as ReturnType<typeof vi.fn>;438    sessionGet.mockClear();439440    await expect(Promise.all([441      v2.restoreFromSession(),442      v2.restoreFromSession(),443    ])).resolves.toEqual([true, true]);444445    expect(sessionGet.mock.calls.filter(([key]) => key === "peach_session_dk")).toHaveLength(1);446    expect(afterUnlock).toHaveBeenCalledTimes(1);447  });448});