Repository navigation
feat(security): encryption.ts failclosed on crypto failure (audit F3) #549
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,10 @@ | ||
| import { createHash, randomUUID } from "crypto"; | ||
|
|
||
| import { getDbInstance, rowToCamel } from "./core"; | ||
| import { decrypt, encrypt } from "./encryption"; | ||
| import { decrypt, encrypt, EncryptionRuntimeError } from "./encryption"; | ||
| import { createLogger } from "@/shared/utils/logger"; | ||
|
|
||
| const log = createLogger("db:commandCodeAuth"); | ||
|
|
||
| export type CommandCodeAuthStatus = "pending" | "received" | "applied" | "expired"; | ||
|
|
||
|
|
@@ -139,7 +142,25 @@ export function markCommandCodeAuthSessionReceived(input: { | |
| ...(input.metadata || {}), | ||
| receivedAt: now, | ||
| }; | ||
| const encryptedApiKey = encrypt(input.apiKey); | ||
| let encryptedApiKey: string | null; | ||
| try { | ||
| encryptedApiKey = encrypt(input.apiKey) ?? null; | ||
| } catch (err: unknown) { | ||
| if (err instanceof EncryptionRuntimeError) { | ||
| // FAIL-CLOSED: encryption layer is broken (key configured but crypto | ||
| // pipeline threw). Refuse to write apiKey plaintext; surface the | ||
| // failure to the caller as "session not found". | ||
| log.error( | ||
| { err: err.message, op: "markCommandCodeAuthSessionReceived", stateHash: input.stateHash }, | ||
| `[commandCodeAuth] Refusing to store apiKey — encryption layer failed.` | ||
| ); | ||
| return null; | ||
|
Comment on lines
+145
to
+157
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Suggestion: The encryption failure is collapsed into Severity Level: Major
|
||
| } | ||
| throw err; | ||
| } | ||
| if (encryptedApiKey === null) { | ||
| return null; | ||
| } | ||
| db() | ||
| .prepare( | ||
| `UPDATE command_code_auth_sessions | ||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -42,6 +42,8 @@ | |||||
| const AUTH_TAG_LENGTH = 16; | ||||||
| const PREFIX = "enc:v1:"; | ||||||
| const STATIC_SALT = "omniroute-field-encryption-v1"; | ||||||
| /** Canary plaintext for the startup round-trip check. Never written to disk. */ | ||||||
| const STARTUP_CANARY_PLAINTEXT = "omniroute-startup-canary-do-not-use"; | ||||||
|
|
||||||
| let _staticKey: Buffer | null = null; | ||||||
| let _legacyDynamicKey: Buffer | null = null; | ||||||
|
|
@@ -83,6 +85,41 @@ | |||||
| } | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * Thrown when `encrypt()` was supposed to encrypt (key configured) but the | ||||||
| * crypto pipeline threw. Carries the original error as `.cause`. | ||||||
| * | ||||||
| * This is FAIL-CLOSED behaviour — callers must NOT swallow this and write | ||||||
| * the plaintext; that would re-introduce the State-B bug fixed by | ||||||
| * `encryption-failclosed`. See `plans/encryption-failclosed-spec.md` for | ||||||
| * the audit and remediation. | ||||||
| */ | ||||||
| export class EncryptionRuntimeError extends Error { | ||||||
| override readonly name = "EncryptionRuntimeError"; | ||||||
| constructor(message: string, options?: { cause?: unknown }) { | ||||||
| super(message); | ||||||
| if (options?.cause !== undefined) { | ||||||
| (this as Error & { cause?: unknown }).cause = options.cause; | ||||||
| } | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * Thrown by `validateEncryptionAtStartup()` when the encrypt/decrypt | ||||||
| * round-trip canary fails. Distinct from `EncryptionRuntimeError` so | ||||||
| * operators can grep for the startup-specific path and the runtime-specific | ||||||
| * path separately. | ||||||
| */ | ||||||
| export class StartupEncryptionError extends Error { | ||||||
| override readonly name = "StartupEncryptionError"; | ||||||
| constructor(message: string, options?: { cause?: unknown }) { | ||||||
|
Check warning on line 115 in src/lib/db/encryption.ts
|
||||||
| super(message); | ||||||
| if (options?.cause !== undefined) { | ||||||
| (this as Error & { cause?: unknown }).cause = options.cause; | ||||||
| } | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * Classify a Node crypto error as an auth-tag validation failure (the | ||||||
| * most security-relevant case) vs other malformed-input errors. | ||||||
|
|
@@ -187,13 +224,30 @@ | |||||
|
|
||||||
| return `${PREFIX}${iv.toString("hex")}:${encrypted}:${authTag}`; | ||||||
| } catch (err: unknown) { | ||||||
| // FAIL-CLOSED: when a key is configured but the crypto pipeline throws | ||||||
| // (broken native bindings, key length drift after a Node upgrade, OOM | ||||||
| // under randomBytes, etc.) we MUST NOT silently return plaintext — that | ||||||
| // re-introduces the State-B bug. Log loudly, then throw a typed error | ||||||
| // so callers (encryptConnectionFields, providers, commandCodeAuth) can | ||||||
| // refuse to write to the DB. | ||||||
| const message = err instanceof Error ? err.message : String(err); | ||||||
| encryptionLog.error( | ||||||
| { err }, | ||||||
| `[Encryption] Encryption failed: ${message}. ` + | ||||||
| `Check your STORAGE_ENCRYPTION_KEY — generate one with: openssl rand -base64 32` | ||||||
| { | ||||||
| err, | ||||||
| op: "encrypt", | ||||||
| envSet: !!process.env.STORAGE_ENCRYPTION_KEY, | ||||||
| // _staticKey is a Buffer; never log the key material itself. | ||||||
| keyBytes: _staticKey?.length ?? null, | ||||||
| }, | ||||||
| `[Encryption] STORAGE_ENCRYPTION_KEY is set but encrypt() failed. ` + | ||||||
| `Refusing to write plaintext. Regenerate with: openssl rand -base64 32` | ||||||
| ); | ||||||
| throw new EncryptionRuntimeError( | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [WARNING]:
Reply with |
||||||
| `Encryption failed at runtime: ${message}. ` + | ||||||
| `Refusing to write plaintext. Check your STORAGE_ENCRYPTION_KEY — ` + | ||||||
| `regenerate one with: openssl rand -base64 32`, | ||||||
| { cause: err } | ||||||
| ); | ||||||
| return plaintext; // fallback to plaintext rather than crashing | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
|
|
@@ -417,16 +471,36 @@ | |||||
| * Encrypt sensitive fields in a connection object (mutates in-place). | ||||||
| * After decryption that required legacy key, re-encrypt with static key | ||||||
| * to migrate tokens automatically. | ||||||
| * | ||||||
| * FAIL-CLOSED: when any inner `encrypt()` throws `EncryptionRuntimeError` | ||||||
| * (i.e. a key is configured but the crypto pipeline failed), this function | ||||||
| * returns `null` and logs the failure. Callers MUST check for `null` and | ||||||
| * refuse to write plaintext to the DB. State A (no key) is preserved — the | ||||||
| * connection object is returned unchanged. | ||||||
| */ | ||||||
| export function encryptConnectionFields<T extends ConnectionFields | null | undefined>(conn: T): T { | ||||||
| export function encryptConnectionFields<T extends ConnectionFields | null | undefined>( | ||||||
| conn: T, | ||||||
| ): T | null { | ||||||
| if (!isEncryptionEnabled()) return conn; | ||||||
| if (!conn) return conn; | ||||||
|
|
||||||
| if (conn.apiKey) conn.apiKey = encrypt(conn.apiKey); | ||||||
| if (conn.accessToken) conn.accessToken = encrypt(conn.accessToken); | ||||||
| if (conn.refreshToken) conn.refreshToken = encrypt(conn.refreshToken); | ||||||
| if (conn.idToken) conn.idToken = encrypt(conn.idToken); | ||||||
| return conn; | ||||||
| try { | ||||||
| if (conn.apiKey) conn.apiKey = encrypt(conn.apiKey) ?? conn.apiKey; | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [SUGGESTION]: Dead Since
Suggested change
Reply with |
||||||
| if (conn.accessToken) conn.accessToken = encrypt(conn.accessToken) ?? conn.accessToken; | ||||||
| if (conn.refreshToken) conn.refreshToken = encrypt(conn.refreshToken) ?? conn.refreshToken; | ||||||
| if (conn.idToken) conn.idToken = encrypt(conn.idToken) ?? conn.idToken; | ||||||
|
Comment on lines
+488
to
+491
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When AGENTS.md reference: src/lib/db/AGENTS.md:L45-L50 Useful? React with 👍 / 👎. |
||||||
| return conn; | ||||||
| } catch (err: unknown) { | ||||||
| if (err instanceof EncryptionRuntimeError) { | ||||||
| encryptionLog.error( | ||||||
| { err: err.message, op: "encryptConnectionFields" }, | ||||||
| `[Encryption] encryptConnectionFields() refused to write plaintext. ` + | ||||||
| `Refusing to insert/update connection row.` | ||||||
| ); | ||||||
| return null; | ||||||
| } | ||||||
| throw err; // Unexpected error; bubble up so the caller can see a stack trace. | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
|
|
@@ -506,3 +580,72 @@ | |||||
| // 3. Un-decryptable or corrupted, leave it alone | ||||||
| return { updated: false, value: ciphertext }; | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * Run a known-plaintext encrypt/decrypt round-trip to detect broken | ||||||
| * encryption config BEFORE the first request hits a DB write. | ||||||
| * | ||||||
| * Behaviour: | ||||||
| * - No `STORAGE_ENCRYPTION_KEY` set (State A / passthrough mode): log a | ||||||
| * warn and return — operator has opted out of encryption. | ||||||
| * - Key set but `encrypt(canary)` throws: log fatal, throw | ||||||
| * `StartupEncryptionError` so the caller can `process.exit(1)`. | ||||||
| * - Key set and round-trip succeeds: log info, return. | ||||||
| * | ||||||
| * Designed to be invoked from `src/instrumentation.ts` (Next.js) or any | ||||||
| * other entry point that wants fail-fast at boot. | ||||||
| */ | ||||||
| export function validateEncryptionAtStartup(): void { | ||||||
| if (!isEncryptionEnabled()) { | ||||||
| encryptionLog.warn( | ||||||
| "[Encryption] No STORAGE_ENCRYPTION_KEY set — passthrough mode active. " + | ||||||
| "Sensitive fields will be stored as plaintext. " + | ||||||
| "Generate a key with: openssl rand -base64 32" | ||||||
| ); | ||||||
| return; | ||||||
| } | ||||||
|
|
||||||
| let encrypted: string; | ||||||
| try { | ||||||
| encrypted = encrypt(STARTUP_CANARY_PLAINTEXT) ?? ""; | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [SUGGESTION]: Dead Since
Suggested change
Reply with |
||||||
| } catch (err: unknown) { | ||||||
| const message = err instanceof Error ? err.message : String(err); | ||||||
|
Check warning on line 612 in src/lib/db/encryption.ts
|
||||||
| encryptionLog.fatal( | ||||||
| { err: message, op: "startup-canary-encrypt" }, | ||||||
| `[Encryption] FATAL — STORAGE_ENCRYPTION_KEY is set but encrypt() threw at startup. ` + | ||||||
| `Server refusing to start. Regenerate with: openssl rand -base64 32` | ||||||
| ); | ||||||
| throw new StartupEncryptionError( | ||||||
| `encryption startup check failed: encrypt() threw — ${message}`, | ||||||
| { cause: err } | ||||||
| ); | ||||||
| } | ||||||
|
|
||||||
| if (!encrypted || !encrypted.startsWith(PREFIX)) { | ||||||
|
Check warning on line 624 in src/lib/db/encryption.ts
|
||||||
| encryptionLog.fatal( | ||||||
| { encrypted }, | ||||||
| `[Encryption] FATAL — encryption returned no prefix at startup (broken crypto). ` + | ||||||
| `Server refusing to start.` | ||||||
| ); | ||||||
| throw new StartupEncryptionError( | ||||||
| "encrypt() returned plaintext at startup despite a key being set" | ||||||
| ); | ||||||
| } | ||||||
|
|
||||||
| const decrypted = decrypt(encrypted); | ||||||
| if (decrypted !== STARTUP_CANARY_PLAINTEXT) { | ||||||
| encryptionLog.fatal( | ||||||
| { decrypted }, | ||||||
| `[Encryption] FATAL — encrypt/decrypt round-trip mismatch at startup. ` + | ||||||
| `Server refusing to start.` | ||||||
| ); | ||||||
| throw new StartupEncryptionError( | ||||||
| `round-trip mismatch: expected ${JSON.stringify(STARTUP_CANARY_PLAINTEXT)}, ` + | ||||||
| `got ${JSON.stringify(decrypted)}` | ||||||
| ); | ||||||
| } | ||||||
|
|
||||||
| encryptionLog.info( | ||||||
| "[Encryption] Startup validation passed — encrypt/decrypt round-trip OK" | ||||||
| ); | ||||||
| } | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| /** | ||
| * Startup-canary entry point for field-level encryption. | ||
| * | ||
| * Wraps `validateEncryptionAtStartup()` (in `./encryption.ts`) in a thin | ||
| * async seam so non-Node entry points (CLI scripts, worker processes, | ||
| * Next.js `instrumentation.ts`) can call it uniformly. | ||
| * | ||
| * Behaviour mirrors §4.3 / §6.7 of `plans/encryption-failclosed-spec.md`: | ||
| * - No `STORAGE_ENCRYPTION_KEY` set: warn and continue (State A). | ||
| * - Key set and canary fails: log fatal and `process.exit(1)`. | ||
| * - Key set and canary passes: log info and continue. | ||
| * | ||
| * The `process.exit(1)` lives here (not in `validateEncryptionAtStartup`) | ||
| * so unit tests can call the canary directly and assert on the throw | ||
| * without the test runner being killed. | ||
| */ | ||
|
|
||
| import { | ||
| StartupEncryptionError, | ||
| validateEncryptionAtStartup, | ||
| } from "./encryption"; | ||
|
|
||
| /** | ||
| * Run the startup encryption canary. If the canary throws and the failure | ||
| * is `StartupEncryptionError`, log a final fatal line and `process.exit(1)`. | ||
| * | ||
| * Non-Node runtimes (Edge) should not call this; the entry point in | ||
| * `src/instrumentation.ts` already gates on `NEXT_RUNTIME === "nodejs"`. | ||
| */ | ||
| export function runEncryptionStartupCheck(): void { | ||
| try { | ||
| validateEncryptionAtStartup(); | ||
| } catch (err: unknown) { | ||
| if (err instanceof StartupEncryptionError) { | ||
| // Re-log the fatal so the line is unambiguous in the log stream | ||
| // even if the canary's own log was buffered/redirected. | ||
| // eslint-disable-next-line no-console | ||
| console.error( | ||
| `[Encryption] FATAL — startup canary failed: ${err.message}. ` + | ||
| `Refusing to start. Regenerate STORAGE_ENCRYPTION_KEY with: ` + | ||
| `openssl rand -base64 32` | ||
| ); | ||
| if (typeof process !== "undefined" && typeof process.exit === "function") { | ||
| process.exit(1); | ||
| } | ||
| return; | ||
| } | ||
| throw err; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Async wrapper for callers that prefer `await`. Throws `StartupEncryptionError` | ||
| * on failure rather than calling `process.exit` — useful for test contexts | ||
| * and for callers that want to handle the failure themselves. | ||
| */ | ||
| export async function runEncryptionStartupCanary(): Promise<void> { | ||
| validateEncryptionAtStartup(); | ||
| } | ||
|
|
||
| export { StartupEncryptionError, validateEncryptionAtStartup }; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[SUGGESTION]: Dead
?? nullfallback —encrypt()now throws on failureSince
encrypt()throwsEncryptionRuntimeErrorinstead of returning plaintext, the?? nullfallback is unreachable.Reply with
@kilocode-bot fix itto have Kilo Code address this issue.