Skip to content

Commit 1e4e9de

Browse files
ralyodioclaude
andauthored
feat(credentials): encrypt the vault at rest (#121)
The vault holds the target's prior values so a bad rotation can be undone — the one place raw credentials touch disk. It was written as plain JSON at mode 0600, and a permission bit is all that was protecting it. That stops another user on the same box. It does nothing about a backup, a synced home directory, a lifted disk, or any process running as the owner, and those are the cases where a credential store is worth reading. Each run is now sealed to this machine's identity: a fresh DEK per write, the payload sealed with it, the DEK sealed to the identity public key. So the file opens with the secret key in identity.json and nothing else. The key names go inside the ciphertext along with the values — knowing that an endpoint holds STRIPE_LIVE_KEY is worth something by itself. A DEK per run rather than one for the store: reusing a key would make a single compromise open every rollback ever captured, and there is nothing to gain by it, since the wrapped DEK travels in the file. Plaintext vaults written before this still open. Refusing them would strand the rollback data they exist to hold, and a vault reader that cannot read yesterday's vault takes away the thing the vault is for. The store's vault methods become async, which the three callers in the engine already sat inside async functions to accommodate. Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 36236eb commit 1e4e9de

3 files changed

Lines changed: 178 additions & 18 deletions

File tree

plugins/credential-sharing/src/engine.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ export class CredentialEngine {
197197
const runId = this.id("cred_run");
198198
if (reversible && !dryRun && target.readValues) {
199199
const preImage = await target.readValues(plan.to, [...upsertKeys, ...deleteKeys]);
200-
this.store.saveVault(runId, preImage);
200+
await this.store.saveVault(runId, preImage);
201201
}
202202

203203
const writeResults = await target.write({ endpoint: plan.to, upserts, deletes: deleteKeys, dryRun });
@@ -272,7 +272,7 @@ export class CredentialEngine {
272272
if (!run.reversible) {
273273
throw new Error(`Run ${runId} was not reversible (no pre-image captured). Rollbacks require a value-readable target.`);
274274
}
275-
const preImage = this.store.getVault(runId);
275+
const preImage = await this.store.getVault(runId);
276276
if (!preImage) {
277277
throw new Error(`No rollback pre-image found for run ${runId}.`);
278278
}
@@ -334,7 +334,7 @@ export class CredentialEngine {
334334
return {};
335335
}
336336
if (plan.rollbackOfRunId) {
337-
const preImage = this.store.getVault(plan.rollbackOfRunId);
337+
const preImage = await this.store.getVault(plan.rollbackOfRunId);
338338
if (!preImage) {
339339
throw new Error(`Rollback plan ${plan.id} references missing vault for run ${plan.rollbackOfRunId}.`);
340340
}

plugins/credential-sharing/src/store.ts

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { mkdirSync, readFileSync, writeFileSync, existsSync, readdirSync } from "node:fs";
22
import { join, resolve } from "node:path";
3-
import { logicsrcHome } from "./identity.js";
3+
import { identityPath, loadOrCreateIdentity, logicsrcHome, readIdentity } from "./identity.js";
4+
import { decryptValue, encryptValue, generateVaultKey, unwrapVaultKey, wrapVaultKey, type SealedValue } from "./crypto.js";
45
import type { CredentialSyncPlan, CredentialSyncRun, CredentialAuditEvent, CredentialValueBag } from "./types.js";
56

67
/**
@@ -11,13 +12,15 @@ import type { CredentialSyncPlan, CredentialSyncRun, CredentialAuditEvent, Crede
1112
* plans/<id>.json redacted sync plans (fingerprints only)
1213
* runs/<id>.json run records (fingerprints only)
1314
* audit/<runId>.json audit events (fingerprints only)
14-
* vault/<runId>.json rollback pre-image — RAW prior target values, mode 0600
15+
* vault/<runId>.json rollback pre-image — sealed to this machine's identity, mode 0600
1516
*
16-
* The vault is the only place raw values touch disk, and only to make rollback
17-
* possible. It is written 0600 and lives in the user's config dir, outside any
18-
* project — so there is nothing for a caller to gitignore, and nothing that
19-
* lands in a repo because the CLI was run from inside one. Audit and plan
20-
* records never contain raw values.
17+
* The vault is the only place prior values touch disk, and only to make
18+
* rollback possible. It is encrypted at rest — sealed to this machine's
19+
* identity key, so the file opens with the secret key in identity.json and
20+
* nothing else — written 0600, and kept in the user's config dir, outside any
21+
* project. Mode 0600 stops another user on the box; the sealing stops a
22+
* backup, a synced home directory or a lifted disk. Audit and plan records
23+
* never contain raw values at all.
2124
*/
2225
export interface CredentialStore {
2326
baseDir: string;
@@ -27,8 +30,29 @@ export interface CredentialStore {
2730
getRun(id: string): CredentialSyncRun | undefined;
2831
saveAudit(runId: string, events: CredentialAuditEvent[]): void;
2932
getAudit(runId: string): CredentialAuditEvent[];
30-
saveVault(runId: string, preImage: CredentialValueBag): void;
31-
getVault(runId: string): CredentialValueBag | undefined;
33+
saveVault(runId: string, preImage: CredentialValueBag): Promise<void>;
34+
getVault(runId: string): Promise<CredentialValueBag | undefined>;
35+
}
36+
37+
/**
38+
* A vault file, sealed to this machine's identity key.
39+
*
40+
* The DEK is fresh per write and sealed to the identity public key, so the
41+
* file is openable by the secret key in `identity.json` and nothing else —
42+
* mode 0600 stops another user on the box reading it, and this stops a backup,
43+
* a synced home directory, or a stolen disk from doing the same.
44+
*
45+
* `version` is what tells a sealed file from the plaintext ones written before
46+
* this existed. Those are still readable; see getVault.
47+
*/
48+
interface SealedVaultFile {
49+
version: 2;
50+
wrappedKey: string;
51+
sealed: SealedValue;
52+
}
53+
54+
function isSealed(value: unknown): value is SealedVaultFile {
55+
return typeof value === "object" && value !== null && (value as { version?: unknown }).version === 2;
3256
}
3357

3458
/**
@@ -95,12 +119,41 @@ export function createFileCredentialStore(baseDir = defaultCredentialHome()): Cr
95119
getAudit(runId) {
96120
return readJson<CredentialAuditEvent[]>(join(dirs.audit, `${runId}.json`)) ?? [];
97121
},
98-
saveVault(runId, preImage) {
122+
async saveVault(runId, preImage) {
99123
ensure(dirs.vault, 0o700);
100-
writeFileSync(join(dirs.vault, `${runId}.json`), JSON.stringify(preImage, null, 2), { mode: 0o600 });
124+
// A fresh DEK per run, sealed to this machine's identity. Reusing one key
125+
// across runs would make a single compromise open every rollback ever
126+
// captured, and there is no reason to: the DEK travels with the file.
127+
const identity = await loadOrCreateIdentity();
128+
const dek = await generateVaultKey();
129+
const file: SealedVaultFile = {
130+
version: 2,
131+
wrappedKey: await wrapVaultKey(dek, identity.keys.publicKey),
132+
sealed: await encryptValue(JSON.stringify(preImage), dek)
133+
};
134+
writeFileSync(join(dirs.vault, `${runId}.json`), JSON.stringify(file, null, 2), { mode: 0o600 });
101135
},
102-
getVault(runId) {
103-
return readJson<CredentialValueBag>(join(dirs.vault, `${runId}.json`));
136+
async getVault(runId) {
137+
const raw = readJson<SealedVaultFile | CredentialValueBag>(join(dirs.vault, `${runId}.json`));
138+
if (!raw) {
139+
return undefined;
140+
}
141+
// Plaintext files written before vaults were sealed still open. Refusing
142+
// them would strand the rollback data they exist to hold — the point of
143+
// the vault is that a bad rotation can be undone, and a reader that
144+
// cannot read yesterday's vault takes that away.
145+
if (!isSealed(raw)) {
146+
return raw as CredentialValueBag;
147+
}
148+
const identity = readIdentity();
149+
if (!identity?.keys?.secretKey) {
150+
throw new Error(
151+
`Vault for run ${runId} is sealed to this machine's identity, which is missing. ` +
152+
`Restore ${identityPath()} to roll this run back.`
153+
);
154+
}
155+
const dek = await unwrapVaultKey(raw.wrappedKey, identity.keys);
156+
return JSON.parse(await decryptValue(raw.sealed, dek)) as CredentialValueBag;
104157
}
105158
};
106159
}
@@ -119,8 +172,8 @@ export function createMemoryCredentialStore(): CredentialStore {
119172
getRun: (id) => runs.get(id),
120173
saveAudit: (runId, events) => void audit.set(runId, events),
121174
getAudit: (runId) => audit.get(runId) ?? [],
122-
saveVault: (runId, preImage) => void vault.set(runId, preImage),
123-
getVault: (runId) => vault.get(runId)
175+
saveVault: async (runId, preImage) => void vault.set(runId, preImage),
176+
getVault: async (runId) => vault.get(runId)
124177
};
125178
}
126179

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
// The vault, at rest.
2+
//
3+
// The vault holds the target's prior values so a bad rotation can be undone —
4+
// the one place raw credentials touch disk. It was written as plain JSON at
5+
// mode 0600, which is a permission bit and nothing more: it stops another user
6+
// on the same box and does nothing about a backup, a synced home directory, a
7+
// stolen laptop, or anything that reads the file as its owner.
8+
//
9+
// It is now sealed to this machine's identity key. These tests exist to fail
10+
// the moment a secret is legible on disk again.
11+
import { describe, it, expect, beforeEach, afterEach } from "vitest";
12+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs";
13+
import { tmpdir } from "node:os";
14+
import { join } from "node:path";
15+
16+
import { createFileCredentialStore } from "./store.js";
17+
import { loadOrCreateIdentity, identityPath } from "./identity.js";
18+
19+
const ENV_KEYS = ["LOGICSRC_HOME", "XDG_CONFIG_HOME", "HOME", "LOGICSRC_CREDENTIAL_HOME", "LOGICSRC_IDENTITY_FILE"] as const;
20+
21+
const SECRET = "sk-live-do-not-write-me-in-the-clear";
22+
const BAG = { API_KEY: SECRET, OTHER: "second-value-also-secret" };
23+
24+
let saved: Record<string, string | undefined>;
25+
let sandbox: string;
26+
27+
beforeEach(() => {
28+
saved = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
29+
sandbox = mkdtempSync(join(tmpdir(), "logicsrc-vault-"));
30+
for (const k of ENV_KEYS) delete process.env[k];
31+
process.env.HOME = sandbox;
32+
});
33+
34+
afterEach(() => {
35+
for (const [k, v] of Object.entries(saved)) {
36+
if (v === undefined) delete process.env[k];
37+
else process.env[k] = v;
38+
}
39+
rmSync(sandbox, { recursive: true, force: true });
40+
});
41+
42+
const vaultFile = (store: { baseDir: string }, runId: string) => join(store.baseDir, "vault", `${runId}.json`);
43+
44+
describe("vault encryption at rest", () => {
45+
it("does not write the secret to disk in the clear", async () => {
46+
const store = createFileCredentialStore();
47+
await store.saveVault("run_1", BAG);
48+
49+
const onDisk = readFileSync(vaultFile(store, "run_1"), "utf8");
50+
expect(onDisk).not.toContain(SECRET);
51+
expect(onDisk).not.toContain("second-value-also-secret");
52+
// The key names are secrets too — knowing an endpoint holds STRIPE_LIVE_KEY
53+
// is worth something on its own.
54+
expect(onDisk).not.toContain("API_KEY");
55+
});
56+
57+
it("round-trips through the seal", async () => {
58+
const store = createFileCredentialStore();
59+
await store.saveVault("run_2", BAG);
60+
expect(await store.getVault("run_2")).toEqual(BAG);
61+
});
62+
63+
it("seals each run under its own key", async () => {
64+
// One DEK across every run would make a single compromise open every
65+
// rollback ever captured.
66+
const store = createFileCredentialStore();
67+
await store.saveVault("run_3", BAG);
68+
await store.saveVault("run_4", BAG);
69+
70+
const a = JSON.parse(readFileSync(vaultFile(store, "run_3"), "utf8"));
71+
const b = JSON.parse(readFileSync(vaultFile(store, "run_4"), "utf8"));
72+
expect(a.wrappedKey).not.toBe(b.wrappedKey);
73+
expect(a.sealed.ciphertext).not.toBe(b.sealed.ciphertext);
74+
});
75+
76+
it("writes the file 0600", async () => {
77+
const store = createFileCredentialStore();
78+
await store.saveVault("run_5", BAG);
79+
const { mode } = await import("node:fs").then((fs) => fs.statSync(vaultFile(store, "run_5")));
80+
expect(mode & 0o777).toBe(0o600);
81+
});
82+
83+
it("still reads a plaintext vault written before this existed", async () => {
84+
// Refusing them would strand the rollback data they exist to hold.
85+
const store = createFileCredentialStore();
86+
mkdirSync(join(store.baseDir, "vault"), { recursive: true });
87+
writeFileSync(vaultFile(store, "legacy"), JSON.stringify(BAG), { mode: 0o600 });
88+
89+
expect(await store.getVault("legacy")).toEqual(BAG);
90+
});
91+
92+
it("says what is wrong when the identity is gone", async () => {
93+
const store = createFileCredentialStore();
94+
await store.saveVault("run_6", BAG);
95+
await loadOrCreateIdentity();
96+
rmSync(identityPath(), { force: true });
97+
98+
// Not a decode error out of libsodium: the operator needs to know the
99+
// rollback is recoverable, and by restoring what.
100+
await expect(store.getVault("run_6")).rejects.toThrow(/identity/i);
101+
});
102+
103+
it("returns undefined for a run with no vault, as before", async () => {
104+
const store = createFileCredentialStore();
105+
expect(await store.getVault("never-happened")).toBeUndefined();
106+
});
107+
});

0 commit comments

Comments
 (0)