feat(encryption): ADR-096 Phase 1 — vault primitives + tests

Implements the cipher primitives portion of the encryption-at-rest
design (ADR-096). No call sites wired yet — that's a separate iteration
to keep blast radius small. With this commit alone, the env vars are
inert and the 1865-test baseline stays green.

src/encryption/vault.ts (new):

  isEncryptionEnabled() — env-var gate (CLAUDE_FLOW_ENCRYPT_AT_REST).
    Truthy: "1" / "true" / "yes" / "on" (case+whitespace tolerant).
    Anything else, including unset, leaves the legacy plaintext path.

  getKey() — resolves a 32-byte key from CLAUDE_FLOW_ENCRYPTION_KEY,
    fail-closed when enabled-but-missing. Phase 1 supports env var only;
    keychain (keytar) and passphrase-with-scrypt land in a follow-up.

  decodeKey(raw) — accepts 64-char hex, 44-char padded base64, or
    43-char unpadded base64. Anything else throws. Trims whitespace.

  encryptBuffer(plain, key) — AES-256-GCM with a fresh random 12-byte
    IV per call. Returns wire-format blob:

      magic(4) || iv(12) || ciphertext(N) || tag(16)

    where magic = "RFE1" (Ruflo File Encrypted v1). Validates inputs
    (Buffer + 32-byte key) so a misuse fails loudly.

  decryptBuffer(blob, key) — verifies magic with timingSafeEqual,
    parses iv/ct/tag, runs GCM decrypt. Lets GCM auth failure
    propagate so tampered ciphertext / wrong key / corrupted IV all
    surface as a thrown error rather than silent garbage.

  isEncryptedBlob(blob) — magic-byte sniff. True iff blob ≥ 32 bytes
    AND starts with "RFE1". Used by readers during the incremental
    migration so legacy plaintext .claude-flow/sessions/*.json files
    pass through unchanged.

__tests__/encryption-vault.test.ts (new) — 45 cases pinning the
contract:
  isEncryptionEnabled: env-var gate w/ truthy/falsy table
  decodeKey: hex / padded b64 / unpadded b64 / wrong-length / garbage /
             whitespace
  getKey: missing-env error message; valid hex returns 32 bytes
  round-trip: empty / small text / JSON / 1MB random / fresh-IV
  wire format: starts with RFE1 / >= 32 bytes
  isEncryptedBlob: detects fresh / rejects JSON / rejects SQLite header
                   / rejects too-short / rejects non-Buffer
  tamper detection: flipped ct byte / flipped tag / flipped IV /
                    flipped magic / too-short / wrong key
  input validation: non-Buffer plaintext / wrong-size key (encrypt &
                    decrypt)

Verified:
  tsc --noEmit clean
  vault tests: 45/45 passing
  full vitest suite: 1910/1910 passing, 46 skipped, 0 failures
  (was 1865; +45 from this commit)

Phase 2 wires this into session/terminal/memory writers behind the env
gate. Phase 3 adds keychain + passphrase resolution.
This commit is contained in:
Reuven committed 2026-05-03 21:00:43 -04:00
1 parent e6478f9ab5
commit cb9a9f346c
2 files changed
+460

No files matched your search

@@ -0,0 +1,268 @@
/**
* Tests for src/encryption/vault.ts (ADR-096 Phase 1).
*
* These pin the wire format + cipher contract so future iterations can't
* silently change either without a coordinated migration. The format is
* meant to be stable across versions — every encrypted file shipped before
* a format change has to keep decrypting under the new code.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { randomBytes } from 'node:crypto';
import {
MAGIC,
decodeKey,
decryptBuffer,
encryptBuffer,
getKey,
isEncryptedBlob,
isEncryptionEnabled,
} from '../src/encryption/vault.js';
// Per-test env reset — these tests mutate process.env and must not leak.
const SAVED_ENV: Record<string, string | undefined> = {};
function saveEnv(...names: string[]) {
for (const n of names) SAVED_ENV[n] = process.env[n];
}
function restoreEnv() {
for (const [n, v] of Object.entries(SAVED_ENV)) {
if (v === undefined) delete process.env[n];
else process.env[n] = v;
}
}
describe('vault (ADR-096 Phase 1)', () => {
beforeEach(() => {
saveEnv('CLAUDE_FLOW_ENCRYPT_AT_REST', 'CLAUDE_FLOW_ENCRYPTION_KEY');
});
afterEach(() => {
restoreEnv();
});
describe('isEncryptionEnabled', () => {
it('is false when the env var is unset', () => {
delete process.env.CLAUDE_FLOW_ENCRYPT_AT_REST;
expect(isEncryptionEnabled()).toBe(false);
});
it.each(['1', 'true', 'TRUE', 'yes', 'on', ' on '])(
'is true for "%s"',
(v) => {
process.env.CLAUDE_FLOW_ENCRYPT_AT_REST = v;
expect(isEncryptionEnabled()).toBe(true);
},
);
it.each(['0', 'false', 'no', 'off', 'maybe', ''])(
'is false for "%s"',
(v) => {
process.env.CLAUDE_FLOW_ENCRYPT_AT_REST = v;
expect(isEncryptionEnabled()).toBe(false);
},
);
});
describe('decodeKey', () => {
it('decodes 64-char hex', () => {
const hex = 'a'.repeat(64);
expect(decodeKey(hex).length).toBe(32);
});
it('decodes 44-char base64 (padded)', () => {
const b64 = randomBytes(32).toString('base64');
expect(b64).toMatch(/=$/);
expect(decodeKey(b64).length).toBe(32);
});
it('decodes 43-char base64 (unpadded)', () => {
const b64 = randomBytes(32).toString('base64').replace(/=+$/, '');
expect(decodeKey(b64).length).toBe(32);
});
it('rejects too-short hex', () => {
expect(() => decodeKey('a'.repeat(63))).toThrow(/Invalid/);
});
it('rejects too-long hex', () => {
expect(() => decodeKey('a'.repeat(65))).toThrow(/Invalid/);
});
it('rejects non-hex / non-base64 garbage', () => {
expect(() => decodeKey('not a key at all!!!')).toThrow(/Invalid/);
});
it('rejects base64 of the wrong length (16 bytes)', () => {
const b64 = randomBytes(16).toString('base64');
expect(() => decodeKey(b64)).toThrow(/Invalid/);
});
it('trims surrounding whitespace before validating', () => {
const hex = 'b'.repeat(64);
expect(decodeKey(` ${hex}\n`).length).toBe(32);
});
});
describe('getKey', () => {
it('throws with a clear message when the env var is unset', () => {
delete process.env.CLAUDE_FLOW_ENCRYPTION_KEY;
expect(() => getKey()).toThrow(/CLAUDE_FLOW_ENCRYPTION_KEY/);
});
it('returns a 32-byte buffer when the env var holds valid hex', () => {
process.env.CLAUDE_FLOW_ENCRYPTION_KEY = 'c'.repeat(64);
expect(getKey().length).toBe(32);
});
});
describe('encrypt / decrypt round-trip', () => {
const key = randomBytes(32);
it('round-trips an empty buffer', () => {
const blob = encryptBuffer(Buffer.alloc(0), key);
expect(decryptBuffer(blob, key).length).toBe(0);
});
it('round-trips small text', () => {
const plain = Buffer.from('hello world', 'utf-8');
expect(decryptBuffer(encryptBuffer(plain, key), key).equals(plain)).toBe(
true,
);
});
it('round-trips JSON the way session-tools writes it', () => {
const obj = { sessionId: 'sess-1', name: 'audit', stats: { tasks: 5 } };
const plain = Buffer.from(JSON.stringify(obj, null, 2), 'utf-8');
const round = JSON.parse(
decryptBuffer(encryptBuffer(plain, key), key).toString('utf-8'),
);
expect(round).toEqual(obj);
});
it('round-trips a large random buffer (megabyte-scale)', () => {
const plain = randomBytes(1_048_576); // 1MB
expect(decryptBuffer(encryptBuffer(plain, key), key).equals(plain)).toBe(
true,
);
});
it('produces different ciphertext for the same plaintext (random IV)', () => {
const plain = Buffer.from('repeated', 'utf-8');
const a = encryptBuffer(plain, key);
const b = encryptBuffer(plain, key);
expect(a.equals(b)).toBe(false);
});
});
describe('wire format', () => {
it('begins with the RFE1 magic', () => {
const blob = encryptBuffer(Buffer.from('x', 'utf-8'), randomBytes(32));
expect(blob.subarray(0, 4)).toEqual(MAGIC);
});
it('has at least magic+iv+tag bytes (32) for any plaintext', () => {
const blob = encryptBuffer(Buffer.alloc(0), randomBytes(32));
// magic(4) + iv(12) + tag(16) = 32 minimum
expect(blob.length).toBeGreaterThanOrEqual(32);
});
});
describe('isEncryptedBlob', () => {
it('detects a freshly-encrypted blob', () => {
const blob = encryptBuffer(Buffer.from('hi', 'utf-8'), randomBytes(32));
expect(isEncryptedBlob(blob)).toBe(true);
});
it('returns false for plaintext JSON', () => {
expect(isEncryptedBlob(Buffer.from('{"a":1}', 'utf-8'))).toBe(false);
});
it('returns false for the SQLite header', () => {
// Real .swarm/memory.db files start with "SQLite format 3\0"
expect(isEncryptedBlob(Buffer.from('SQLite format 3\0', 'utf-8'))).toBe(
false,
);
});
it('returns false for a blob shorter than the magic+iv+tag minimum', () => {
expect(isEncryptedBlob(MAGIC)).toBe(false); // magic alone, but length < 32
});
it('returns false for a non-Buffer input', () => {
expect(isEncryptedBlob('not a buffer' as unknown as Buffer)).toBe(false);
});
});
describe('tamper detection', () => {
const key = randomBytes(32);
it('rejects a blob with a flipped ciphertext byte', () => {
const plain = Buffer.from('sensitive data', 'utf-8');
const blob = Buffer.from(encryptBuffer(plain, key));
// Flip a byte inside the ciphertext region (after magic+iv, before tag)
blob[20] ^= 0xff;
expect(() => decryptBuffer(blob, key)).toThrow();
});
it('rejects a blob with a flipped auth-tag byte', () => {
const blob = Buffer.from(
encryptBuffer(Buffer.from('payload', 'utf-8'), key),
);
blob[blob.length - 1] ^= 0xff;
expect(() => decryptBuffer(blob, key)).toThrow();
});
it('rejects a blob with a flipped IV byte', () => {
const blob = Buffer.from(
encryptBuffer(Buffer.from('payload', 'utf-8'), key),
);
blob[5] ^= 0xff; // inside the IV region (offset 4..15)
expect(() => decryptBuffer(blob, key)).toThrow();
});
it('rejects a blob with a corrupted magic', () => {
const blob = Buffer.from(
encryptBuffer(Buffer.from('payload', 'utf-8'), key),
);
blob[0] = 0x00; // break the magic
expect(() => decryptBuffer(blob, key)).toThrow(/bad magic/);
});
it('rejects a blob shorter than the minimum length', () => {
expect(() => decryptBuffer(Buffer.alloc(10), key)).toThrow(/too short/);
});
it('rejects a wrong-key decrypt (GCM auth fails)', () => {
const blob = encryptBuffer(Buffer.from('payload', 'utf-8'), key);
const wrongKey = randomBytes(32);
expect(() => decryptBuffer(blob, wrongKey)).toThrow();
});
});
describe('input validation', () => {
const key = randomBytes(32);
it('encryptBuffer rejects a non-Buffer plaintext', () => {
expect(() =>
encryptBuffer('string' as unknown as Buffer, key),
).toThrow(/Buffer/);
});
it('encryptBuffer rejects a wrong-size key', () => {
expect(() =>
encryptBuffer(Buffer.from('x'), randomBytes(16)),
).toThrow(/32-byte/);
});
it('decryptBuffer rejects a non-Buffer blob', () => {
expect(() =>
decryptBuffer('string' as unknown as Buffer, key),
).toThrow(/Buffer/);
});
it('decryptBuffer rejects a wrong-size key', () => {
const blob = encryptBuffer(Buffer.from('x'), key);
expect(() => decryptBuffer(blob, randomBytes(16))).toThrow(/32-byte/);
});
});
});
+192
View File
@@ -0,0 +1,192 @@
/**
* Encryption-at-rest vault primitives (ADR-096 Phase 1).
*
* Goal: provide deterministic encrypt/decrypt of arbitrary Buffers with a
* symmetric key, using a magic-byte format so readers of older plaintext
* stores can detect-then-pass-through during the migration window.
*
* Phase 1 deliberately ships only the cipher primitives + the env-var key
* source. Keychain (keytar) and interactive passphrase resolution land in
* a follow-up iteration so the blast radius of this commit is limited to
* a single self-contained module with no native dependencies.
*
* Wire format (output of encryptBuffer):
*
* +---------+-----------+----------------+--------+
* | magic 4 | iv 12 | ciphertext N | tag 16 |
* +---------+-----------+----------------+--------+
* "RFE1" random AES-256-GCM GCM
*
* The magic distinguishes encrypted blobs from plaintext during the
* incremental migration: readers call isEncryptedBlob() and either
* decryptBuffer() or treat the bytes as plaintext, so existing
* .claude-flow/sessions/*.json files keep working unchanged.
*/
import {
createCipheriv,
createDecipheriv,
randomBytes,
timingSafeEqual,
} from 'node:crypto';
// ── Constants ────────────────────────────────────────────────────────────────
/** ASCII "RFE1" — Ruflo File Encrypted v1. 4 bytes. */
export const MAGIC = Buffer.from([0x52, 0x46, 0x45, 0x31]); // "RFE1"
const MAGIC_LEN = MAGIC.length; // 4
const IV_LEN = 12; // GCM-recommended nonce size
const TAG_LEN = 16; // GCM auth tag
const KEY_LEN = 32; // AES-256
const ALG = 'aes-256-gcm' as const;
const MIN_BLOB_LEN = MAGIC_LEN + IV_LEN + TAG_LEN; // empty plaintext still has these
const ENV_ENABLE_FLAG = 'CLAUDE_FLOW_ENCRYPT_AT_REST';
const ENV_KEY_VAR = 'CLAUDE_FLOW_ENCRYPTION_KEY';
// ── Public API ───────────────────────────────────────────────────────────────
/**
* True when at-rest encryption should be applied to writes.
*
* Truthy values: "1", "true", "yes", "on" (case-insensitive). Anything else
* — including unset — keeps the legacy plaintext path. This is the gate
* that lets the 1865-test baseline keep passing unchanged while users opt
* into encryption.
*/
export function isEncryptionEnabled(): boolean {
const v = process.env[ENV_ENABLE_FLAG];
if (typeof v !== 'string') return false;
const norm = v.trim().toLowerCase();
return norm === '1' || norm === 'true' || norm === 'yes' || norm === 'on';
}
/**
* Resolve a 32-byte encryption key from CLAUDE_FLOW_ENCRYPTION_KEY.
*
* Phase 1 supports only the env-var source; keychain and passphrase
* resolution are deferred to a follow-up iteration (see ADR-096). When
* encryption is enabled but no key resolves, this throws with a clear
* message rather than silently falling back to plaintext (fail-closed).
*
* Accepted encodings (auto-detected by length):
* - 64-char hex (32 bytes)
* - 44-char base64 (32 bytes + padding)
* - exactly 32 raw bytes (rare; for callers that pre-decode)
*
* Anything else is rejected — we'd rather fail loudly than encrypt with a
* truncated key.
*/
export function getKey(): Buffer {
const raw = process.env[ENV_KEY_VAR];
if (!raw) {
throw new Error(
`${ENV_ENABLE_FLAG} is set but ${ENV_KEY_VAR} is not. ` +
`Provide a 32-byte key as 64-char hex or 44-char base64. ` +
`See ADR-096 for keychain/passphrase support (coming in a follow-up).`,
);
}
return decodeKey(raw);
}
/**
* Decode a key string. Exposed for testing and for the future passphrase
* resolver, which will scrypt-derive a Buffer and hand it back through here
* to share the same length-check.
*/
export function decodeKey(raw: string): Buffer {
const trimmed = raw.trim();
// Hex first — strict 64 chars [0-9a-fA-F]
if (/^[0-9a-fA-F]{64}$/.test(trimmed)) {
return Buffer.from(trimmed, 'hex');
}
// Base64 — accept padded 44-char or unpadded 43-char forms
if (/^[A-Za-z0-9+/]{43}=?$/.test(trimmed)) {
const buf = Buffer.from(trimmed, 'base64');
if (buf.length === KEY_LEN) return buf;
}
throw new Error(
`Invalid ${ENV_KEY_VAR}: expected 32-byte key as 64-char hex or 44-char base64`,
);
}
/**
* Encrypt a plaintext Buffer with AES-256-GCM. Returns the wire-format
* blob: magic(4) || iv(12) || ciphertext(N) || tag(16).
*
* The IV is freshly randomized per call. Reusing a (key, iv) pair under
* GCM is catastrophic — every call MUST produce a different IV. Node's
* randomBytes is csprng-backed so this is automatic; the function takes
* no IV input deliberately.
*/
export function encryptBuffer(plaintext: Buffer, key: Buffer): Buffer {
if (!Buffer.isBuffer(plaintext)) {
throw new TypeError('encryptBuffer: plaintext must be a Buffer');
}
if (!Buffer.isBuffer(key) || key.length !== KEY_LEN) {
throw new TypeError(`encryptBuffer: key must be a ${KEY_LEN}-byte Buffer`);
}
const iv = randomBytes(IV_LEN);
const cipher = createCipheriv(ALG, key, iv);
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([MAGIC, iv, ciphertext, tag]);
}
/**
* Decrypt a wire-format blob. Verifies the magic byte (sanity), parses
* iv + ciphertext + tag, runs AES-256-GCM decrypt, and lets the GCM
* auth tag fail loudly on tamper (Node throws "Unsupported state or
* unable to authenticate data" — we let that propagate).
*
* Pre-condition: caller has already determined this is an encrypted
* blob via isEncryptedBlob(). decryptBuffer throws on bad magic so a
* mistaken plaintext blob still fails loudly rather than producing
* garbage.
*/
export function decryptBuffer(blob: Buffer, key: Buffer): Buffer {
if (!Buffer.isBuffer(blob)) {
throw new TypeError('decryptBuffer: blob must be a Buffer');
}
if (!Buffer.isBuffer(key) || key.length !== KEY_LEN) {
throw new TypeError(`decryptBuffer: key must be a ${KEY_LEN}-byte Buffer`);
}
if (blob.length < MIN_BLOB_LEN) {
throw new Error(
`decryptBuffer: blob too short (${blob.length}B; need >= ${MIN_BLOB_LEN}B)`,
);
}
const magic = blob.subarray(0, MAGIC_LEN);
// timingSafeEqual to avoid an oracle on the magic bytes specifically;
// not strictly required (the magic isn't secret) but cheap and correct.
if (!timingSafeEqual(magic, MAGIC)) {
throw new Error(
'decryptBuffer: bad magic — blob is not Ruflo-encrypted (RFE1)',
);
}
const iv = blob.subarray(MAGIC_LEN, MAGIC_LEN + IV_LEN);
const tag = blob.subarray(blob.length - TAG_LEN);
const ciphertext = blob.subarray(MAGIC_LEN + IV_LEN, blob.length - TAG_LEN);
const decipher = createDecipheriv(ALG, key, iv);
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
}
/**
* Magic-byte sniff. True iff the blob starts with the RFE1 magic AND is
* long enough to be a valid encrypted blob. Used by readers during the
* incremental migration: legacy plaintext files return false and flow
* through the existing read path unchanged.
*
* Note: this is a heuristic. A plaintext file that happens to start with
* "RFE1" would be misdetected — we accept that vanishingly small risk
* because (a) the four bytes 0x52,0x46,0x45,0x31 are an unusual prefix
* for JSON (`{`, `[`) or SQLite (`SQLite format 3`), and (b) decryption
* will then fail with a clear error rather than silently corrupt.
*/
export function isEncryptedBlob(blob: Buffer): boolean {
if (!Buffer.isBuffer(blob)) return false;
if (blob.length < MIN_BLOB_LEN) return false;
return timingSafeEqual(blob.subarray(0, MAGIC_LEN), MAGIC);
}