sync-generation.test.ts

15.2 KB · raw

1// The §11 secure-reset contract: the durable generation record, the six states,2// create-on-miss refusal, archival by generation, crash recovery at every step,3// and the sync gate. Runs entirely against an in-memory io — no Chrome, no4// vault, no crypto.56import { afterEach, describe, expect, it, vi } from "vitest";7import {8  GENERATION_UNKNOWN,9  browserGenerationIo,10  hasLegacyTrustState,11  LEGACY_ACTIVE,12  REPAIRING,13  RESET_CONFIRMED,14  RESET_REQUIRED,15  V2_ACTIVE,16  V2_ANCHOR,17  assertSyncAllowed,18  confirmSecureReset,19  decodeGeneration,20  encodeGeneration,21  enterResetRequired,22  isPostReset,23  mintDecision,24  onDirectV2PairingEstablished,25  resolveGeneration,26  type ResetResult,27  type SyncGeneration,28  type SyncGenerationBlob,29  type SyncGenerationIo,30} from "./sync-generation";3132class CrashAt extends Error {}3334class FakeGenerationIo implements SyncGenerationIo {35  blob: unknown = null;36  pairedDevices = false;37  revocations = false;38  archivedIssuers = false;39  pendingHolders = false;40  legacyRouteMaterial = false;4142  /** Storage that refuses the write, to model a generation that cannot land. */43  failWrites = false;44  failArchive = false;45  failClear = false;46  failIdentity = false;4748  /** Simulated process death: the checkpoint with this name throws. */49  crashAt: string | null = null;5051  archiveRef: string | null = null;52  archiveCount = 0;53  cleared = false;54  identityMints = 0;55  deviceId = "anchor-device";5657  /** The order the reset actually touched storage. */58  readonly calls: string[] = [];5960  get record(): SyncGeneration | null {61    return decodeGeneration(this.blob)?.active ?? null;62  }6364  async readBlob(): Promise<unknown> {65    return this.blob;66  }6768  async writeBlob(blob: SyncGenerationBlob): Promise<boolean> {69    if (this.failWrites) return false;70    this.blob = JSON.parse(encodeGeneration(blob)) as unknown;71    return true;72  }7374  async hasPairedDevices(): Promise<boolean> {75    return this.pairedDevices;76  }7778  async hasArchivedIssuers(): Promise<boolean> {79    return this.archivedIssuers;80  }8182  async hasRevocations(): Promise<boolean> {83    return this.revocations;84  }8586  async hasPendingHolders(): Promise<boolean> {87    return this.pendingHolders;88  }8990  async hasLegacyRouteMaterial(): Promise<boolean> {91    return this.legacyRouteMaterial;92  }9394  async archiveLegacyState(generation: number): Promise<string | null> {95    if (this.failArchive) return null;96    this.archiveCount += 1;97    this.archiveRef = `peach_sync_archive_g${generation}_v1`;98    this.calls.push(`archive:${generation}`);99    return this.archiveRef;100  }101102  async clearLegacyTrustState(): Promise<boolean> {103    if (this.failClear) return false;104    this.cleared = true;105    this.pairedDevices = false;106    this.revocations = false;107    this.archivedIssuers = false;108    this.pendingHolders = false;109    this.legacyRouteMaterial = false;110    this.calls.push("clear");111    return true;112  }113114  async ensureV2Identity(): Promise<boolean> {115    if (this.failIdentity) return false;116    this.identityMints += 1;117    this.calls.push("identity");118    return true;119  }120121  async getDeviceId(): Promise<string> {122    return this.deviceId;123  }124125  reset(nowMs = 1_000): Promise<ResetResult> {126    return confirmSecureReset(this, {127      nowMs,128      checkpoint: (name) => {129        if (name === this.crashAt) throw new CrashAt(name);130      },131    });132  }133}134135const CHECKPOINTS = [136  "before-confirmed",137  "before-archive",138  "after-archive",139  "before-clear",140  "after-clear",141  "before-identity",142  "after-identity",143  "before-generation-write",144  "after-generation-write",145];146147describe("sync generation — derived state", () => {148  it("derives V2_ACTIVE at generation 2 for a fresh install, and persists it", async () => {149    const io = new FakeGenerationIo();150    const record = await resolveGeneration(io, 1_000);151    expect(record.state).toBe(V2_ACTIVE);152    expect(record.generation).toBe(2);153    expect(io.record).toEqual(record);154  });155156  it("derives LEGACY_ACTIVE at generation 1 when any trust state is present", async () => {157    const io = new FakeGenerationIo();158    io.pairedDevices = true;159    const record = await resolveGeneration(io, 1_000);160    expect(record.state).toBe(LEGACY_ACTIVE);161    expect(record.generation).toBe(1);162  });163164  it("resolves an unreadable record to UNKNOWN rather than to a generation", async () => {165    const io = new FakeGenerationIo();166    io.blob = "{ not json";167    expect((await resolveGeneration(io, 1_000)).state).toBe(GENERATION_UNKNOWN);168    expect(await assertSyncAllowed(io, 1_000)).toBe("sync_generation_unknown");169  });170171  it("refuses a record of another schema instead of misreading it", async () => {172    // The rollback case: a build that does not know the generation must not173    // treat v2 state as legacy trust.174    const io = new FakeGenerationIo();175    io.blob = {176      schemaVersion: 99,177      active: { schemaVersion: 99, generation: 7, state: V2_ACTIVE, createdAt: 1 },178    };179    expect(await assertSyncAllowed(io, 1_000)).toBe("sync_generation_unknown");180  });181182  it("refuses an unrecognised state instead of guessing", async () => {183    const io = new FakeGenerationIo();184    io.blob = {185      schemaVersion: 1,186      active: { schemaVersion: 1, generation: 1, state: "WOBBLING", createdAt: 1 },187    };188    expect(await assertSyncAllowed(io, 1_000)).toBe("sync_generation_unknown");189  });190191  it("does not trust a derived record that could not be persisted", async () => {192    const io = new FakeGenerationIo();193    io.pairedDevices = true;194    io.failWrites = true;195    expect((await resolveGeneration(io, 1_000)).state).toBe(GENERATION_UNKNOWN);196    expect(await assertSyncAllowed(io, 1_000)).toBe("sync_generation_unknown");197  });198});199200describe("sync generation — create-on-miss refusal (§11.5)", () => {201  it("refuses to mint over every class of trust state", async () => {202    const classes: Array<[string, (io: FakeGenerationIo) => void]> = [203      ["paired device", (io) => (io.pairedDevices = true)],204      ["revocation", (io) => (io.revocations = true)],205      ["archived issuer", (io) => (io.archivedIssuers = true)],206      ["pending holder", (io) => (io.pendingHolders = true)],207      ["legacy route material", (io) => (io.legacyRouteMaterial = true)],208    ];209    for (const [label, configure] of classes) {210      const io = new FakeGenerationIo();211      configure(io);212      expect(await mintDecision(io, 1_000), label).toBe("REFUSE_RESET_REQUIRED");213      expect(io.record?.state, label).toBe(RESET_REQUIRED);214      expect(io.identityMints, label).toBe(0);215      expect(await assertSyncAllowed(io, 1_000), label).toBe("reset_required");216    }217  });218219  it("mints only on a genuinely fresh installation", async () => {220    const io = new FakeGenerationIo();221    expect(await mintDecision(io, 1_000)).toBe("MINT");222    expect(io.record).toBeNull();223  });224});225226describe("sync generation — the reset", () => {227  it("archives, clears, mints, then flips the pointer — in that order", async () => {228    const io = new FakeGenerationIo();229    io.pairedDevices = true;230    io.revocations = true;231232    expect(await io.reset()).toBe("V2_ANCHOR");233    expect(io.calls).toEqual(["archive:1", "clear", "identity"]);234    expect(io.record).toMatchObject({235      state: V2_ANCHOR,236      generation: 2,237      anchorDeviceId: "anchor-device",238      legacyArchiveRef: "peach_sync_archive_g1_v1",239    });240    expect(io.cleared).toBe(true);241  });242243  it("does not retire the v2 generation or mint twice when repeated", async () => {244    const io = new FakeGenerationIo();245    io.pairedDevices = true;246    await io.reset();247    const firstArchive = io.record?.legacyArchiveRef;248249    expect(await io.reset()).toBe("reset_not_completed");250    expect(io.record?.legacyArchiveRef).toBe(firstArchive);251    expect(io.identityMints).toBe(1);252  });253254  it("stays in RESET_CONFIRMED and reports the failure when a step fails", async () => {255    for (const configure of [256      (io: FakeGenerationIo) => (io.failArchive = true),257      (io: FakeGenerationIo) => (io.failClear = true),258      (io: FakeGenerationIo) => (io.failIdentity = true),259      (io: FakeGenerationIo) => (io.failWrites = true),260    ]) {261      const io = new FakeGenerationIo();262      io.pairedDevices = true;263      configure(io);264      expect(await io.reset()).toBe("reset_not_completed");265      expect(io.record?.state === RESET_CONFIRMED || io.record === null).toBe(true);266    }267  });268});269270describe("sync generation — crash injection (§11.8)", () => {271  it("leaves the archive durable and the retry reaches V2_ANCHOR from any crash point", async () => {272    for (const name of CHECKPOINTS) {273      const io = new FakeGenerationIo();274      io.pairedDevices = true;275      io.crashAt = name;276277      await expect(io.reset()).rejects.toThrow(CrashAt);278279      // Never a wrong outcome: nothing retired yet, mid-flight, or committed.280      const state = io.record?.state;281      expect([LEGACY_ACTIVE, RESET_CONFIRMED, V2_ANCHOR], name).toContain(state);282      // Trust is never cleared without an archive first.283      expect(io.cleared && io.archiveCount === 0, `${name} cleared without an archive`).toBe(false);284285      io.crashAt = null;286      await io.reset();287      expect(io.record?.state, `retry after ${name}`).toBe(V2_ANCHOR);288      expect(io.record?.generation, `retry after ${name}`).toBe(2);289      expect(io.archiveRef).not.toBeNull();290    }291  });292293  it("blocks sync before the pointer flip and allows it after", async () => {294    const before = new FakeGenerationIo();295    before.pairedDevices = true;296    before.crashAt = "before-generation-write";297    await expect(before.reset()).rejects.toThrow(CrashAt);298    expect(before.record?.state).toBe(RESET_CONFIRMED);299    expect(await assertSyncAllowed(before, 1_000)).toBe("reset_required");300301    const after = new FakeGenerationIo();302    after.pairedDevices = true;303    after.crashAt = "after-generation-write";304    await expect(after.reset()).rejects.toThrow(CrashAt);305    expect(after.record?.state).toBe(V2_ANCHOR);306    expect(await assertSyncAllowed(after, 1_000)).toBe("allowed");307    expect(after.archiveRef).not.toBeNull();308    expect(after.identityMints).toBe(1);309  });310311  it("loses nothing when the crash lands after the archive but before the clear", async () => {312    const io = new FakeGenerationIo();313    io.pairedDevices = true;314    io.revocations = true;315    io.crashAt = "before-clear";316317    await expect(io.reset()).rejects.toThrow(CrashAt);318319    expect(io.archiveCount).toBe(1);320    expect(io.cleared).toBe(false);321    expect(io.pairedDevices).toBe(true);322  });323});324325describe("sync generation — the sync gate (§7)", () => {326  it("allows a legacy device to sync before it resets", async () => {327    const io = new FakeGenerationIo();328    io.pairedDevices = true;329    expect(await assertSyncAllowed(io, 1_000)).toBe("allowed");330    expect(await isPostReset(io, 1_000)).toBe(false);331  });332333  it("allows a device that has already reset to sync and pair again", async () => {334    const io = new FakeGenerationIo();335    io.pairedDevices = true;336    await io.reset();337    expect(await assertSyncAllowed(io, 1_000)).toBe("allowed");338    expect(await isPostReset(io, 1_000)).toBe(true);339  });340341  it("blocks sync from RESET_REQUIRED and never walks a reset device backwards", async () => {342    const legacy = new FakeGenerationIo();343    legacy.pairedDevices = true;344    await enterResetRequired(legacy, 1_000);345    expect(await assertSyncAllowed(legacy, 1_000)).toBe("reset_required");346347    const reset = new FakeGenerationIo();348    reset.pairedDevices = true;349    await reset.reset();350    await enterResetRequired(reset, 2_000);351    expect(reset.record?.state).toBe(V2_ANCHOR);352  });353});354355describe("sync generation — repair progression (§11.3)", () => {356  it("is REPAIRING until a direct peer exists, then V2_ACTIVE", async () => {357    const io = new FakeGenerationIo();358    io.pairedDevices = true;359    await io.reset();360361    await onDirectV2PairingEstablished(io, false, 2_000);362    expect(io.record?.state).toBe(REPAIRING);363    expect(await isPostReset(io, 2_000)).toBe(true);364365    await onDirectV2PairingEstablished(io, true, 3_000);366    expect(io.record?.state).toBe(V2_ACTIVE);367  });368369  it("never disturbs a device that never reset", async () => {370    const io = new FakeGenerationIo();371    io.pairedDevices = true;372    await onDirectV2PairingEstablished(io, true, 2_000);373    expect(io.record?.state).toBe(LEGACY_ACTIVE);374  });375});376377describe("sync generation — §15.4: the reset retires a generation, it does not rotate the root", () => {378  it("reaches storage only through archive, clear and identity, in that order", async () => {379    const io = new FakeGenerationIo();380    io.pairedDevices = true;381    io.revocations = true;382    io.legacyRouteMaterial = true;383384    expect(await io.reset()).toBe("V2_ANCHOR");385386    // The io is the whole surface the reset can reach. It carries no root key,387    // no recovery material, and no vault-id parameter, so no rotation is388    // possible by construction; what is worth pinning is the order that makes389    // the archive safe.390    expect(io.calls).toEqual(["archive:1", "clear", "identity"]);391    expect(io.record?.legacyArchiveRef).toBe("peach_sync_archive_g1_v1");392    expect(io.record?.generation).toBe(2);393  });394});395396397describe("verification issuer archive reset", () => {398  afterEach(() => vi.unstubAllGlobals());399  it("refuses corrupt archive trust without persisting a new generation", async () => {400    const { REVOCATION_ISSUERS_KEY } = await import("./paired-devices");401    const set = vi.fn();402    vi.stubGlobal("chrome", { storage: { local: {403      get: async () => ({ [REVOCATION_ISSUERS_KEY]: "corrupt" }), set,404    } } });405    await expect(hasLegacyTrustState(browserGenerationIo)).rejects.toThrow("trust_data_corrupted");406    await expect(resolveGeneration(browserGenerationIo)).rejects.toThrow("trust_data_corrupted");407    expect(set).not.toHaveBeenCalled();408  });409410  it("counts archive-only trust, copies it into rollback history and verifies its removal", async () => {411    const { REVOCATION_ISSUERS_KEY } = await import("./paired-devices");412    const archive = [{ deviceId: "removed", longTermPublicKeyHex: "a".repeat(64), signingPublicKeys: ["b".repeat(64)] }];413    const stored: Record<string, unknown> = { [REVOCATION_ISSUERS_KEY]: archive };414    let refuseRemoval = true;415    const area = {416      async get(keys: string | string[]) {417        return Object.fromEntries((Array.isArray(keys) ? keys : [keys]).map((key) => [key, stored[key]]));418      },419      async set(values: Record<string, unknown>) { Object.assign(stored, values); },420      async remove(keys: string | string[]) {421        for (const key of Array.isArray(keys) ? keys : [keys]) {422          if (key !== REVOCATION_ISSUERS_KEY || !refuseRemoval) delete stored[key];423        }424      },425    };426    vi.stubGlobal("chrome", { storage: { local: area, session: area } });427    expect(await hasLegacyTrustState(browserGenerationIo)).toBe(true);428    const ref = await browserGenerationIo.archiveLegacyState(1);429    expect(ref).not.toBeNull();430    expect(stored[ref!] as { revocationIssuers: unknown }).toMatchObject({ revocationIssuers: archive });431    expect(await browserGenerationIo.clearLegacyTrustState()).toBe(false);432    refuseRemoval = false;433    expect(await browserGenerationIo.clearLegacyTrustState()).toBe(true);434    expect(stored[REVOCATION_ISSUERS_KEY]).toBeUndefined();435    expect(await hasLegacyTrustState(browserGenerationIo)).toBe(false);436  });437});