Public: anyone can read this; the crew can change it.

Crypto agility: sealed values, the edge file and cost bills name their algorithm #16919

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

feat/crypto-alg-tags → main 0 commits 2 threads · 2 unresolved

  • Merged. feat/crypto-alg-tags was merged into main as 730b9ed.

Review

Sign in to review this change.
20 files changed +147 −56
docs/CACHE.md +3 −2
@@ -43,8 +43,9 @@ Routes that predate the helper still set their own headers
4343 ## The edge rung
4444
4545 Every write produces one snapshot id. Each process that learns of it
46 publishes `<data>/edge/config/<name>.json`, an Ed25519-signed
47 `{ payload, sig }`, served at `/edge/config/<name>.json` (`forge`, or
46 publishes `<data>/edge/config/<name>.json`, a signed `{ alg, payload, sig }`
47 (`alg` is `ed25519`; a file with none is read as ed25519, any other alg is
48 refused), served at `/edge/config/<name>.json` (`forge`, or
4849 `app-<id>` for an app whose repository anyone can read). The public key is
4950 at `/edge/config/key.pem`. With `FORGE_CF_ACCOUNT`, `FORGE_CF_KV_NAMESPACE`
5051 and `FORGE_CF_API_TOKEN` set, the same bytes are also `PUT` to that KV
docs/ORIGINS.md +9 −6
@@ -1061,12 +1061,15 @@ carries token material, a `state`, or a `code`.
10611061 protected repository keeps its credential until the next refresh or the
10621062 next daily sweep, whichever is first.
10631063 - **Key rotation keeps one key behind.** A sealed value is
1064 `v2:<keyid>:<iv>:<ciphertext>`, keyid the first 8 hex of SHA-256 of the key
1065 that sealed it. To rotate, move `secret.key` to `secret.key.old` (keep it
1066 0600 — the forge refuses either file wider than that) and restart: a fresh
1067 `secret.key` is minted, new values seal under it, and `open` uses whichever
1068 key a value names. Values from before the format change (`v1:<iv>:<ct>`)
1069 name no key and try the current key, then the old one.
1064 `v3:aes-256-gcm:<keyid>:<iv>:<ciphertext>`, naming its scheme and its key
1065 (keyid the first 8 hex of SHA-256 of the key that sealed it); `v2:<keyid>:…`
1066 values from before the scheme was named read as aes-256-gcm, and a scheme
1067 the forge does not know is refused. To rotate, move `secret.key` to
1068 `secret.key.old` (keep it 0600 — the forge refuses either file wider than
1069 that) and restart: a fresh `secret.key` is minted, new values seal under
1070 it, and `open` uses whichever key a value names. Values from before the
1071 format change (`v1:<iv>:<ct>`) name no key and try the current key, then
1072 the old one.
10701073 `bun scripts/rotate-secret-key.ts --apply` (forge stopped) re-seals every
10711074 sealed column under the newest key in one transaction and says how many it
10721075 moved per table — see docs/RECOVERY.md, "Rotating the secret key". Until it
docs/features/cost-ledger.md +1 −1
@@ -69,7 +69,7 @@ The person who claimed a hosted forge (the first person admin in its own databas
6969
7070 The file (`src/core/ledger_bill.ts`, access in `src/actions/forge_bill.ts`):
7171
72 - Line 1 is a JSON header `{bill, forge, month, own, key, signature}`.
72 - Line 1 is a JSON header `{bill, alg, forge, month, own, key, signature}`. `alg` names the signature scheme (`sshsig-ed25519`); a bill with none is read as that, and any other is refused as an unknown scheme.
7373 - The next `own` lines are the entries of the forge's own ledger directory, a hash chain.
7474 - The lines after them are the entries in this forge's spool whose `repo` is one of the apps the forge follows. They come out of a chain shared with other forges, so each is checked on its own.
7575 - This forge signs the forge name, the month, `own` and all entry lines with its SSH host key (namespace `forge-bill`).
scripts/rotate-secret-key.ts +2 −4
@@ -28,6 +28,7 @@ import {
2828 type NamedKey,
2929 openWith,
3030 previousKeyPath,
31 looksSealed,
3132 sealedKeyId,
3233 sealWith,
3334 secretKeyPath,
@@ -121,9 +122,6 @@ function writeKey(path: string, key: Buffer): void {
121122 chmodSync(path, 0o600);
122123 }
123124
124 const looksSealed = (v: unknown): v is string =>
125 typeof v === "string" && (v.startsWith("v1:") || v.startsWith("v2:"));
126
127125 function hasTable(db: Database, table: string): boolean {
128126 return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1").get(table) !== null;
outdated

Delete this wrapper and use the kernel's looksSealed directly. Two functions with the same name is confusing.

129127 }
@@ -162,7 +160,7 @@ export function rotateSecretKey(dataDir: string, apply: boolean): Rotation {
162160 const update = db.query(`UPDATE "${col.table}" SET "${col.column}" = ?1 WHERE rowid = ?2`);
163161 for (const row of rows) {
164162 const value = row[col.column];
165 if (!looksSealed(value)) continue;
163 if (typeof value !== "string" || !looksSealed(value)) continue;
166164 if (sealedKeyId(value) === target.id) {
167165 count.kept++;
168166 continue;
src/cloud/edge.ts +27 −6
@@ -7,9 +7,12 @@
77 * that URL). Where the forge runs behind Cloudflare, the same bytes are also
88 * written to a KV namespace, so Workers read flags at the edge itself.
99 *
10 * The file is `{ payload, sig }`: `payload` is the snapshot as a JSON
11 * string, `sig` an Ed25519 signature over exactly those bytes, so nothing
12 * between the forge and the reader can alter it. The public key is served at
10 * The file is `{ alg, payload, sig }`: `payload` is the snapshot as a JSON
11 * string, `sig` a signature over exactly those bytes, so nothing between the
12 * forge and the reader can alter it, and `alg` names its scheme (`ed25519`,
13 * the only one), so another can be added beside it. A file with no `alg`
14 * (written before it was named) is read as ed25519; an alg this forge does
15 * not know is refused, never guessed. The public key is served at
1316 * `/edge/config/key.pem`; the private key lives in the data directory and
1417 * never leaves it.
1518 *
@@ -61,7 +64,11 @@ export function edgeName(scope: string): string | undefined {
6164 return m ? `app-${m[1]}` : undefined;
6265 }
6366
67 /** The signature schemes an edge file may name; the first is what `signSnapshot` writes. */
68 export const EDGE_ALGS = ["ed25519"] as const;
69
6470 export interface EdgeFile {
71 readonly alg: (typeof EDGE_ALGS)[number];
6572 readonly payload: string;
6673 readonly sig: string;
6774 }
@@ -100,14 +107,28 @@ export function signSnapshot(priv: KeyObject, snap: Snapshot): EdgeFile {
100107 at: snap.updatedAt,
101108 };
102109 const payload = JSON.stringify(published);
103 return { payload, sig: sign(null, Buffer.from(payload), priv).toString("base64") };
110 return { alg: EDGE_ALGS[0], payload, sig: sign(null, Buffer.from(payload), priv).toString("base64") };
104111 }
105112
106 /** The snapshot a file carries, if its signature holds under `publicPem`. */
113 /**
114 * Why `verifyEdgeFile` refused a file whose scheme it does not know: said rather than read as a
115 * bad signature, so a reader can tell "a scheme I lack" from "tampered".
116 */
117 export class UnknownEdgeAlg extends Error {
118 constructor(readonly alg: string) {
119 super(`edge file names an unknown signature scheme: ${alg.slice(0, 40)}`);
120 }
121 }
122
123 /**
124 * The snapshot a file carries, if its signature holds under `publicPem`. A file naming a scheme
125 * outside `EDGE_ALGS` throws `UnknownEdgeAlg`; one with no `alg` is read as ed25519.
126 */
107127 export function verifyEdgeFile(file: unknown, publicPem: string): Published | undefined {
108128 if (typeof file !== "object" || file === null) return undefined;
109 const { payload, sig } = file as Record<string, unknown>;
129 const { payload, sig, alg } = file as Record<string, unknown>;
110130 if (typeof payload !== "string" || typeof sig !== "string") return undefined;
131 if (alg !== undefined && !(EDGE_ALGS as readonly unknown[]).includes(alg)) throw new UnknownEdgeAlg(String(alg));
111132 try {
112133 const good = verify(null, Buffer.from(payload), createPublicKey(publicPem), Buffer.from(sig, "base64"));
113134 return good ? (JSON.parse(payload) as Published) : undefined;
src/core/ledger_bill.ts +15 −8
@@ -1,12 +1,11 @@
11 /**
22 * A client's bill: one month of their forge's cost ledger and the hosting
33 * forge's public key, in one file (#12276). Line 1 is a JSON header
4 * `{bill, forge, month, own, key, signature}`; every later line is one ledger
5 * entry, byte for byte as the spool holds it. The signature is the forge's
6 * SSH key's (namespace `forge-bill`) over `forge`, `month` and the entry
7 * lines, so neither the entries nor the name and month they were sold under
8 * can change. `verifyBill` needs no database: the hash chain inside the month
9 * (the first entry's `prev` is whatever the month before ended on), then the
4 * `{bill, alg, forge, month, own, key, signature}` (`alg`: `BILL_ALGS`); every later line is one
5 * ledger entry, byte for byte as the spool holds it. The signature is the forge's SSH key's
6 * (namespace `forge-bill`) over `forge`, `month` and the entry lines, so neither the entries nor
7 * the name and month they were sold under can change. `verifyBill` needs no database: the hash
8 * chain inside the month (the first entry's `prev` is whatever the month before ended on), then the
109 * signature, then — when a key is pinned — that it is that key.
1110 */
1211
@@ -96,9 +95,15 @@ export function makeBill(input: { forge: string; month: string; entries: string;
9695 const { forge, month, entries, key } = input;
9796 const own = input.own ?? entries.split("\n").filter((l) => l !== "").length;
9897 const signature = signMessage(key, signedText(forge, month, own, entries), BILL_NAMESPACE);
99 return `${JSON.stringify({ bill: 1, forge, month, own, key: key.publicKey.line, signature })}\n${entries}`;
98 return `${JSON.stringify({ bill: 1, alg: BILL_ALGS[0], forge, month, own, key: key.publicKey.line, signature })}\n${entries}`;
10099 }
101100
101 /**
102 * The signature schemes a bill header may name (`alg`); the first is what `makeBill` writes. A bill
103 * with no `alg` (made before it was named) is read as `sshsig-ed25519`; any other is refused.
104 */
105 export const BILL_ALGS = ["sshsig-ed25519"] as const;
106
102107 export type BillVerdict =
103108 | { ok: true; entries: number; usd: number; key: string }
104109 | { ok: false; at: string; why: string };
@@ -115,7 +120,9 @@ export function verifyBill(text: string, pinned?: string): BillVerdict {
115120 } catch {
116121 return { ok: false, at: "line 1", why: "not a bill header" };
117122 }
118 const { forge, month, key, signature, own } = head;
123 const { forge, month, key, signature, own, alg } = head;
124 if (alg !== undefined && !(BILL_ALGS as readonly unknown[]).includes(alg))
125 return { ok: false, at: "line 1", why: `unknown signature scheme: ${String(alg).slice(0, 40)}` };
119126 if (head["bill"] !== 1 || typeof own !== "number" || !Number.isInteger(own) || own < 0 || typeof forge !== "string" || typeof month !== "string" || typeof key !== "string" || typeof signature !== "string")
120127 return { ok: false, at: "line 1", why: "not a bill header" };
121128 let prev: string | undefined;
src/kernel/secret.ts +35 −10
@@ -11,8 +11,12 @@
1111 * you the tokens (reconnect the origin), never the repositories.
1212 *
1313 * Sealed values are opaque strings, base64url:
14 * `v2:<keyid>:<iv>:<ciphertext+tag>` — written today; keyid is the first
15 * 8 hex of SHA-256(key), so a value names the key that sealed it;
14 * `v3:<alg>:<keyid>:<iv>:<ciphertext+tag>` — written today; `alg` names the
15 * scheme (`aes-256-gcm`, the only one), so a second can be added and read
16 * beside it, and an alg this forge does not know is refused, never guessed;
17 * keyid is the first 8 hex of SHA-256(key), so a value names its key;
18 * `v2:<keyid>:<iv>:<ciphertext+tag>` — written before the alg was named;
19 * read as aes-256-gcm;
1620 * `v1:<iv>:<ciphertext+tag>` — written before rotation existed; still read.
1721 *
1822 * Rotation: the data directory may hold a previous key beside the current
@@ -46,8 +50,13 @@ import { err, ok, type Result } from "./result.ts";
4650 const KEY_BYTES = 32; // AES-256
4751 const IV_BYTES = 12; // GCM standard nonce
4852 const TAG_BYTES = 16;
49 const VERSION = "v2";
53 const VERSION = "v3";
54 /** Written before the scheme was named: read as `aes-256-gcm`. */
55 const KEYED = "v2";
5056 const LEGACY = "v1";
57 /** The schemes a sealed value may name; the first is what `seal` writes. */
58 export const SEAL_ALGS = ["aes-256-gcm"] as const;
59 const SEAL_ALG = SEAL_ALGS[0];
5160 const KEY_ID = /^[0-9a-f]{8}$/;
5261
5362 /** A key and the id a sealed value names it by. */
@@ -204,16 +213,23 @@ export function sealWith(named: NamedKey, plain: string, aad: string): string {
204213 cipher.final(),
205214 cipher.getAuthTag(),
206215 ]);
207 return `${VERSION}:${named.id}:${iv.toString("base64url")}:${body.toString("base64url")}`;
216 return `${VERSION}:${SEAL_ALG}:${named.id}:${iv.toString("base64url")}:${body.toString("base64url")}`;
208217 }
209218
210 /** The key id a sealed value names: a v2 value's id, null for a v1 value or anything else. */
219 /** The key id a sealed value names: a v3 or v2 value's id, null for a v1 value or anything else. */
211220 export function sealedKeyId(sealed: string): string | null {
212221 const parts = sealed.split(":");
213 return parts.length === 4 && parts[0] === VERSION && KEY_ID.test(parts[1]!) ? parts[1]! : null;
222 if (parts.length === 5 && parts[0] === VERSION && KEY_ID.test(parts[2]!)) return parts[2]!;
223 return parts.length === 4 && parts[0] === KEYED && KEY_ID.test(parts[1]!) ? parts[1]! : null;
214224 }
215225
216 export type OpenError = "bad_format" | "bad_key";
226 /** Whether a string is a sealed value of any version this forge reads. */
227 export const looksSealed = (v: string): boolean => [LEGACY, KEYED, VERSION].some((p) => v.startsWith(`${p}:`));
228
229 /**
230 * `unknown_alg`: a v3 value naming a scheme this forge does not know, refused rather than guessed.
231 */
232 export type OpenError = "bad_format" | "bad_key" | "unknown_alg";
217233
218234 /**
219235 * Decrypt a sealed value. A wrong key, a tampered ciphertext, and a value
@@ -226,14 +242,15 @@ export function open(
226242 aad: string,
227243 ): Result<string, OpenError> {
228244 // Only a sealed-looking value costs a key read.
229 if (!sealed.startsWith(`${LEGACY}:`) && !sealed.startsWith(`${VERSION}:`)) return err("bad_format");
245 if (!looksSealed(sealed)) return err("bad_format");
230246 const ring = loadKeys(dataDir);
231247 return openWith(ring.previous ? [ring.current, ring.previous] : [ring.current], sealed, aad);
232248 }
233249
234250 /**
235251 * `open` with the keys the caller holds, tried in order for a v1 value; a
236 * v2 value opens only with the key it names.
252 * v2 or v3 value opens only with the key it names, and a v3 value only under
253 * a scheme in `SEAL_ALGS`.
237254 */
238255 export function openWith(
239256 keys: readonly NamedKey[],
@@ -250,13 +267,21 @@ export function openWith(
250267 candidates = keys.map((k) => k.key);
251268 ivText = parts[1]!;
252269 bodyText = parts[2]!;
253 } else if (parts.length === 4 && parts[0] === VERSION && KEY_ID.test(parts[1]!)) {
270 } else if (parts.length === 4 && parts[0] === KEYED && KEY_ID.test(parts[1]!)) {
254271 const named = keys.find((k) => k.id === parts[1]);
255272 // The value names a key this directory no longer holds.
256273 if (!named) return err("bad_key");
257274 candidates = [named.key];
258275 ivText = parts[2]!;
259276 bodyText = parts[3]!;
277 } else if (parts.length === 5 && parts[0] === VERSION && KEY_ID.test(parts[2]!)) {
278 // A scheme this forge does not know is said as such, never tried as aes-256-gcm.
279 if (!(SEAL_ALGS as readonly string[]).includes(parts[1]!)) return err("unknown_alg");
280 const named = keys.find((k) => k.id === parts[2]);
281 if (!named) return err("bad_key");
282 candidates = [named.key];
283 ivText = parts[3]!;
284 bodyText = parts[4]!;
260285 } else {
261286 return err("bad_format");
262287 }
test/app-env.test.ts +1 −1
@@ -123,7 +123,7 @@ describe("an app's environment", () => {
123123 expect(JSON.stringify(set.value)).not.toContain("horse");
124124
125125 const sealed = stored(hello.id, "ADMIN_PASSWORD");
126 expect(sealed).toStartWith("v2:");
126 expect(sealed).toStartWith("v3:aes-256-gcm:");
127127 expect(sealed).not.toContain("horse");
128128 expect(Buffer.from(sealed!, "utf8").toString("base64")).not.toContain(
129129 Buffer.from(secret).toString("base64"),
test/apps-api.test.ts +1 −1
@@ -646,7 +646,7 @@ printf '%s\\n' '{"is_error":false,"result":"{\\"summary\\":\\"Build it\\",\\"che
646646 const row = app.db
647647 .query<{ value_enc: string }, []>("SELECT value_enc FROM app_env")
648648 .get();
649 expect(row?.value_enc).toStartWith("v2:");
649 expect(row?.value_enc).toStartWith("v3:aes-256-gcm:");
650650 expect(row?.value_enc).not.toContain(secret);
651651 const event = app.db
652652 .query<
test/boundary-secrets-store.test.ts +1 −1
@@ -50,7 +50,7 @@ describe("the key file", () => {
5050 test("is 32 bytes in a file only its owner reads, made on first use", () => {
5151 const dir = mkdtempSync(join(tmpdir(), "boundary-key-"));
5252 expect(existsSync(secretKeyPath(dir))).toBe(false);
53 expect(seal(dir, "plain", "aad")).toStartWith("v2:");
53 expect(seal(dir, "plain", "aad")).toStartWith("v3:aes-256-gcm:");
5454 expect(statSync(secretKeyPath(dir)).size).toBe(32);
5555 expect(mode(secretKeyPath(dir))).toBe(0o600);
5656 forgetKey(dir);
test/boundary-tokens-follow.test.ts +1 −1
@@ -251,7 +251,7 @@ describe("the credential a child holds for a private app", () => {
251251 const secret = secretOf(kid, "kid", "vault");
252252 // Sealed: the column is not the secret, and opens for this repository's row only, with this forge's key only.
253253 expect(row.credentialEnc).not.toContain(secret);
254 expect(row.credentialEnc.startsWith("v2:")).toBe(true);
254 expect(row.credentialEnc.startsWith("v3:aes-256-gcm:")).toBe(true);
255255 expect(
256256 openSealed(
257257 kid.dataDir,
test/config-store.test.ts +7
@@ -21,6 +21,7 @@ import {
2121 EdgePublisher,
2222 edgeName,
2323 kvFromEnv,
24 UnknownEdgeAlg,
2425 verifyEdgeFile,
2526 } from "../src/cloud/edge.ts";
2627 import {
@@ -122,6 +123,12 @@ describe("config store", () => {
122123 // altered bytes do not verify
123124 const forged = { ...file, payload: file.payload.replace('"edge":1', '"edge":2') };
124125 expect(verifyEdgeFile(forged, app.edge().publicPem)).toBeUndefined();
126 // The file names its scheme; one without (written before) is read as ed25519; an unknown one
127 // is refused by name, never tried as ed25519.
128 expect(file.alg).toBe("ed25519");
129 const { alg: _alg, ...untagged } = file;
130 expect(verifyEdgeFile(untagged, app.edge().publicPem)!.snapshot).toBe(wrote.value.id);
131 expect(() => verifyEdgeFile({ ...file, alg: "ml-dsa-65" }, app.edge().publicPem)).toThrow(UnknownEdgeAlg);
125132 // the private key stays in the data directory and is not world readable
126133 expect(existsSync(join(dir, "edge", "signing.pem"))).toBe(true);
127134 });
test/forge-bill.test.ts +12
@@ -155,6 +155,18 @@ test("a bill's first entry may continue the month before; entries picked from th
155155 expect(verifyBill(bill.replace('"own":1', '"own":3'), pub)).toMatchObject({ ok: false });
156156 });
157157
158 test("a bill names its signature scheme; one without (made before) still verifies, and an unknown scheme is refused by name", () => {
159 const key = loadOrCreateHostKey(join(dir, "ssh"));
160 const bill = makeBill({ forge: "acme", month: "2026-11", entries: entries(2), key });
161 expect(JSON.parse(bill.split("\n")[0]!).alg).toBe("sshsig-ed25519");
162 expect(verifyBill(bill, pub)).toMatchObject({ ok: true, entries: 2 });
163 // The header as it was before `alg` (the signature covers the entries, not the header's keys).
164 const old = bill.replace('"alg":"sshsig-ed25519",', "");
165 expect(old).not.toContain('"alg"');
166 expect(verifyBill(old, pub)).toMatchObject({ ok: true, entries: 2 });
167 expect(verifyBill(bill.replace('"alg":"sshsig-ed25519"', '"alg":"ml-dsa-65"'), pub)).toEqual({ ok: false, at: "line 1", why: "unknown signature scheme: ml-dsa-65" });
168 });
169
158170 test("one changed entry breaks the bill at its line; another key and another name break it too", async () => {
159171 const key = loadOrCreateHostKey(join(dir, "ssh"));
160172 const bill = makeBill({ forge: "acme", month: "2026-11", entries: entries(3), key });
test/oidc.test.ts +1 −1
@@ -91,7 +91,7 @@ describe("oidc keys", () => {
9191 const rows = db.query<{ private_jwk: string }, []>("SELECT private_jwk FROM oidc_key").all();
9292 expect(rows.length).toBe(1);
9393 for (const r of rows) {
94 expect(r.private_jwk.startsWith("v2:")).toBe(true);
94 expect(r.private_jwk.startsWith("v3:aes-256-gcm:")).toBe(true);
9595 expect(r.private_jwk).not.toContain('"d"');
9696 expect(() => JSON.parse(r.private_jwk)).toThrow();
9797 }
test/origins.test.ts +1 −1
@@ -179,7 +179,7 @@ describe("origins: connecting, mirroring, writing through", () => {
179179
180180 test("a sealed token is unreadable, and bound to its own row", () => {
181181 const sealed = seal(dataDir, "s3cret-token", "origin-a");
182 expect(sealed).toStartWith("v2:");
182 expect(sealed).toStartWith("v3:aes-256-gcm:");
183183 expect(sealed).not.toContain("s3cret-token");
184184 expect(open(dataDir, sealed, "origin-a")).toEqual({
185185 ok: true,
test/prompts.test.ts +1 −1
@@ -596,7 +596,7 @@ describe("prompts from Instagram", () => {
596596 >("SELECT token_enc FROM prompt_source WHERE id = ?1")
597597 .get(sourceId)!;
598598 expect(row.token_enc).not.toContain(TOKEN);
599 expect(row.token_enc.startsWith("v2:")).toBe(true);
599 expect(row.token_enc.startsWith("v3:aes-256-gcm:")).toBe(true);
600600 expect(openPromptToken(app.db, dataDir, sourceId)).toEqual({
601601 ok: true,
602602 value: TOKEN,
test/rotate-secret-key.test.ts +2 −2
@@ -15,7 +15,7 @@ import { setSecret } from "../src/core/secret_store.ts";
1515 import { sealSetting } from "../src/apps/feature_env.ts";
1616 import { signingKey } from "../src/core/oidc.ts";
1717 import { openDb } from "../src/kernel/db.ts";
18 import { forgetKey, keyId, loadKey, open, previousKeyPath, seal, secretKeyPath } from "../src/kernel/secret.ts";
18 import { forgetKey, keyId, loadKey, open, previousKeyPath, seal, secretKeyPath, sealedKeyId } from "../src/kernel/secret.ts";
1919 import { describeRotation, exitCode, nextKeyPath, rotateSecretKey, SEALED_COLUMNS } from "../scripts/rotate-secret-key.ts";
2020
2121 /** A row in `table` with every required column filled, `column` sealed under the current key. */
@@ -106,7 +106,7 @@ describe("rotate-secret-key", () => {
106106 expect(keyId(loadKey(dir))).toBe(done.keyId);
107107 for (const p of PLANTED) {
108108 const value = read(db, p);
109 expect(value.split(":")[1]).toBe(done.keyId);
109 expect(sealedKeyId(value)).toBe(done.keyId);
110110 expect(open(dir, value, p.aad)).toEqual({ ok: true, value: p.plain });
111111 }
112112 const secret = db.query<{ v: string }, []>("SELECT value_enc AS v FROM secret").get()!.v;
test/secret-rotation.test.ts +24 −7
@@ -18,6 +18,7 @@ import {
1818 previousKeyPath,
1919 seal,
2020 secretKeyPath,
outdated

Put secretKeyPath, and sealedKeyId, on separate lines, then close with } from.

21 sealedKeyId,
2122 } from "../src/kernel/secret.ts";
2223
2324 /** A v1 value exactly as the old `seal` wrote it: `v1:<iv>:<ct+tag>`. */
@@ -45,18 +46,33 @@ describe("secret key rotation", () => {
4546 rmSync(dir, { recursive: true, force: true });
4647 });
4748
48 test("seal writes v2:<keyid>:<iv>:<ct>, keyid the first 8 hex of SHA-256(key)", () => {
49 test("seal writes v3:aes-256-gcm:<keyid>:<iv>:<ct>, keyid the first 8 hex of SHA-256(key)", () => {
4950 const key = loadKey(dir);
5051 const sealed = seal(dir, "tok-1", "row-1");
5152 const parts = sealed.split(":");
52 expect(parts.length).toBe(4);
53 expect(parts[0]).toBe("v2");
53 expect(parts.length).toBe(5);
54 expect(parts[0]).toBe("v3");
55 expect(parts[1]).toBe("aes-256-gcm");
5456 // Hand calculation: hash the key bytes and take 8 hex characters.
55 expect(parts[1]).toBe(createHash("sha256").update(key).digest("hex").slice(0, 8));
56 expect(keyId(key)).toBe(parts[1]!);
57 expect(parts[2]).toBe(createHash("sha256").update(key).digest("hex").slice(0, 8));
58 expect(keyId(key)).toBe(parts[2]!);
59 expect(sealedKeyId(sealed)).toBe(parts[2]!);
5760 expect(sealed).not.toContain("tok-1");
5861 });
5962
63 test("a v2 value (no alg named) still opens as aes-256-gcm, and a v3 value naming an unknown alg is refused as such", () => {
64 loadKey(dir);
65 const [, , id, iv, body] = seal(dir, "tok-2", "row-1").split(":");
66 // The same ciphertext in the older form: what a value written before the alg was named holds.
67 const v2 = `v2:${id}:${iv}:${body}`;
68 expect(open(dir, v2, "row-1")).toEqual({ ok: true, value: "tok-2" });
69 expect(sealedKeyId(v2)).toBe(id!);
70 expect(open(dir, `v3:aes-256-gcm:${id}:${iv}:${body}`, "row-1")).toEqual({ ok: true, value: "tok-2" });
71 // Never tried as aes-256-gcm under another name: said, not read as a wrong key.
72 expect(open(dir, `v3:chacha20-poly1305:${id}:${iv}:${body}`, "row-1")).toEqual({ ok: false, error: "unknown_alg" });
73 expect(open(dir, `v3:ml-kem-768:${id}:${iv}:${body}`, "row-1")).toEqual({ ok: false, error: "unknown_alg" });
74 });
75
6076 test("a value sealed under A opens after B is current with A kept old, and is bad_key once A is gone", () => {
6177 const a = loadKey(dir);
6278 const sealed = seal(dir, "tok-A", "row-1");
@@ -67,7 +83,7 @@ describe("secret key rotation", () => {
6783 const opened = open(dir, sealed, "row-1");
6884 expect(opened.ok && opened.value).toBe("tok-A");
6985 // New values go under B.
70 expect(seal(dir, "tok-B", "row-2").split(":")[1]).toBe(ring.current.id);
86 expect(sealedKeyId(seal(dir, "tok-B", "row-2"))).toBe(ring.current.id);
7187 // The AAD still binds under the previous key.
7288 expect(open(dir, sealed, "row-2")).toMatchObject({ ok: false, error: "bad_key" });
7389
@@ -95,10 +111,11 @@ describe("secret key rotation", () => {
95111 test("a malformed value is bad_format, and an unknown key id is bad_key", () => {
96112 loadKey(dir);
97113 const sealed = seal(dir, "tok", "row");
98 const [, , iv, body] = sealed.split(":");
114 const [, , , iv, body] = sealed.split(":");
99115 expect(open(dir, `v2:XYZ:${iv}:${body}`, "row")).toMatchObject({ ok: false, error: "bad_format" });
100116 expect(open(dir, `v2:${iv}:${body}`, "row")).toMatchObject({ ok: false, error: "bad_format" });
101117 expect(open(dir, `v3:00000000:${iv}:${body}`, "row")).toMatchObject({ ok: false, error: "bad_format" });
118 expect(open(dir, `v4:aes-256-gcm:00000000:${iv}:${body}`, "row")).toMatchObject({ ok: false, error: "bad_format" });
102119 expect(open(dir, `v2:00000000:${iv}:${body}`, "row")).toMatchObject({ ok: false, error: "bad_key" });
103120 });
104121
test/secret-store.test.ts +1 −1
@@ -93,7 +93,7 @@ describe("forge-level secrets", () => {
9393 const set = setSecret(app.db, dataDir, "forge", "", "CF_TOKEN", "s3cret-1");
9494 expect(set.ok).toBe(true);
9595 const sealed = stored("CF_TOKEN", "forge")!;
96 expect(sealed).toStartWith("v2:");
96 expect(sealed).toStartWith("v3:aes-256-gcm:");
9797 expect(sealed).not.toContain("s3cret-1");
9898 const right = open(dataDir, sealed, "secret:forge:CF_TOKEN");
9999 expect(right.ok && right.value).toBe("s3cret-1");

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs