Files
SeedPass/js/packages/core/test/highRiskPartition.test.ts
T
thePR0M3TH3ANandClaude Opus 5 0c48c1f9dc feat(agent): port high-risk partitions and approval gates
High-risk partitions move ssh/pgp/seed/nostr/managed_account records out of
the vault index into a separately encrypted file, so those kinds need a SECOND
factor beyond the master password. The index keeps a stub carrying kind, label
and archived — enough to list, nothing more.

Both file formats are byte-compatible with Python and verified bidirectionally:
TS unwraps a Python-written key envelope and reads a Python-written partition,
and Python unwraps a TS-written envelope and reads a TS-written partition. That
matters more than usual here — the entries are SSH keys, PGP keys and seeds, so
a partition only one implementation can open is lost secrets, not an
inconvenience. This required a Fernet encryptor in core, which had been
decrypt-only by design; the header now says why that exception exists and that
no other Fernet payload should ever be written.

**One deliberate divergence, and it is the reason this is not a straight port.**
Python records an unlock session in agent_high_risk_unlock.json, and that record
contains the partition_key_tag — the value the partition file's encryption key
is derived from. So for the life of any Python unlock session the partition is
decryptable from disk alone, with no factor, by anything that can read the app
directory; both files live in the same directory, so "can read one" implies "can
read the other". That voids the guarantee the partition exists to provide.
Verified empirically before writing any of this.

Here the tag lives only in the session agent's memory, beside the parent seeds
it already holds, with the same TTL discipline — and in the API process's memory
for the API. Nothing derived from the factor reaches disk, asserted by a test
that scans every file in the app directory for the tag, and confirmed on a live
install. No file format or interop changes; only where the live session lives.

Other properties the tests pin:
  - a locked partition refuses reveal rather than deriving from the stub, which
    would return a plausible wrong secret
  - locking the vault drops the high-risk grant, which is scoped to it
  - the grant expires on its own clock, typically much shorter than the seed's
  - unlock is owner-gated: a scoped token cannot reach it
  - the tag is absent from the audit log, which records only that an unlock
    happened
  - the factor comes from the environment, never argv
  - factor-set refuses to replace an existing factor, since a new partition key
    would make an existing partition permanently unreadable
  - migrate writes the partition BEFORE the index, so a crash between them
    cannot leave stubs pointing at records that were never stored

Approval gates port straight across: one-shot (or N-use) authorizations for
export / reveal_parent_seed / private_key_retrieval, consumed under the store
lock so two callers cannot both spend the last use, with every failure mode
getting its own reason string matching Python's. A corrupt store reads as empty,
which fails closed.

API: /api/v1/high-risk/{status,unlock,lock} are real rather than 501. Unlock
needs the bearer token, the master password header AND the factor header; a
wrong factor gets one indistinguishable reason so probing cannot tell failures
apart.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vtx94nXDmNgXEeThUZP4QN
2026-08-19 10:19:39 -04:00

135 lines
5.0 KiB
TypeScript

/**
* High-risk partition file format.
*
* The load-bearing tests are the interop ones: the fixtures were produced by
* Python, so "TS reads them" proves the format is genuinely shared rather
* than merely self-consistent. A partition only either implementation can
* open would be worse than none — the entries are SSH keys, PGP keys and
* seeds, and a user who cannot open them has lost them.
*/
import { describe, expect, it } from "vitest";
import { base64 } from "@scure/base";
import {
decryptPartition,
encryptPartition,
buildPartitionEnvelope,
unwrapPartitionKey,
generatePartitionKey,
partitionKeyTag,
partitionStub,
isPartitionStub,
HighRiskError,
} from "@seedpass/core";
import { highRiskFixture as fx } from "@seedpass/test-vectors";
describe("interop with Python", () => {
it("derives the same partition key tag", () => {
expect(partitionKeyTag(fx.partition_key)).toBe(fx.tag);
});
it("unwraps an envelope Python wrapped", async () => {
expect(await unwrapPartitionKey(fx.envelope, fx.factor)).toBe(fx.partition_key);
});
it("reads a partition file Python wrote", async () => {
const entries = await decryptPartition(base64.decode(fx.partition_file_b64), fx.tag);
expect(entries).toEqual(fx.entries);
});
it("writes a partition file that round-trips", async () => {
// Byte-identical output is impossible — the Fernet IV is random — so the
// check is that the payload survives, with the canonical JSON shape both
// implementations serialize.
const blob = await encryptPartition(fx.entries, fx.tag, { updatedAt: 1700000000 });
expect(await decryptPartition(blob, fx.tag)).toEqual(fx.entries);
});
});
describe("the factor is what protects the partition", () => {
it("refuses the wrong factor with Python's reason string", async () => {
await expect(unwrapPartitionKey(fx.envelope, "not-the-factor")).rejects.toMatchObject({
reason: "high_risk_factor_invalid",
});
});
it("refuses to decrypt a partition under the wrong tag", async () => {
const blob = base64.decode(fx.partition_file_b64);
const wrongTag = partitionKeyTag(generatePartitionKey());
await expect(decryptPartition(blob, wrongTag)).rejects.toMatchObject({
reason: "invalid_partition_key_tag",
});
});
it("gives a different tag for every generated key", () => {
const tags = new Set(Array.from({ length: 16 }, () => partitionKeyTag(generatePartitionKey())));
expect(tags.size).toBe(16);
});
it("rejects an envelope of an unknown version rather than guessing", async () => {
await expect(
unwrapPartitionKey({ ...fx.envelope, version: 99 }, fx.factor),
).rejects.toMatchObject({ reason: "unsupported_partition_envelope_version" });
});
it("rejects a truncated envelope", async () => {
for (const missing of ["salt_b64", "wrapped_partition_key"]) {
const envelope = { ...fx.envelope, [missing]: "" };
await expect(unwrapPartitionKey(envelope, fx.factor)).rejects.toBeInstanceOf(HighRiskError);
}
});
it("round-trips a freshly built envelope", async () => {
const key = generatePartitionKey();
// Low iteration count purely to keep the test quick; production uses the
// PARTITION_KDF_ITERATIONS default.
const envelope = await buildPartitionEnvelope(key, "correct horse", { iterations: 1000 });
expect(await unwrapPartitionKey(envelope, "correct horse")).toBe(key);
await expect(unwrapPartitionKey(envelope, "wrong horse")).rejects.toBeInstanceOf(
HighRiskError,
);
});
});
describe("index stubs", () => {
const entry = {
kind: "ssh",
type: "ssh",
label: "prod-server",
index: 3,
notes: "deployment key",
archived: false,
modified_ts: 1700000000,
secret: "THE-ACTUAL-KEY-MATERIAL",
};
it("keeps nothing secret in the stub", () => {
const stub = partitionStub("3", entry, "ssh", 1700000000);
// A stub is what stays in the vault index, which is readable with the
// master password alone. It must disclose that a high-risk entry exists
// and nothing more — otherwise moving the entry bought nothing.
const serialized = JSON.stringify(stub);
expect(serialized).not.toContain("THE-ACTUAL-KEY-MATERIAL");
expect(serialized).not.toContain("deployment key");
expect(stub["label"]).toBe("prod-server");
expect(stub["kind"]).toBe("ssh");
expect(stub["partition"]).toBe("high_risk");
expect(stub["partition_ref"]).toBe("3");
});
it("is recognizable as a stub", () => {
expect(isPartitionStub(partitionStub("3", entry, "ssh", 1700000000))).toBe(true);
expect(isPartitionStub(entry)).toBe(false);
expect(isPartitionStub({})).toBe(false);
});
it("matches the shape Python leaves behind", () => {
// Python's migrate writes exactly these keys; a listing that reads one
// implementation's stub must not find the other's malformed.
const stub = partitionStub("3", entry, "ssh", 1700000000);
expect(Object.keys(stub).sort()).toEqual(
["archived", "index", "kind", "label", "modified_ts", "partition", "partition_ref", "type"],
);
});
});