Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ INITIAL_PASSWORD=CHANGEME
# Encryption key for SQLite database encryption at rest.
# Used by: src/lib/db/encryption.ts — encrypts the entire SQLite database.
# Generate: openssl rand -hex 32 | Leave empty to disable DB encryption.
#
# ── Fail-closed behaviour (encryption-failclosed) ──
# When STORAGE_ENCRYPTION_KEY is set but the crypto layer fails (e.g. broken
# native bindings, key length drift after a Node upgrade, randomBytes OOM),
# OmniRoute refuses to write plaintext and surfaces:
# - EncryptionRuntimeError — runtime calls (encrypt() / encryptConnectionFields);
# surfaces as 500 to the user.
# - StartupEncryptionError — startup-canary in src/instrumentation-node.ts
# runs validateEncryptionAtStartup() at boot;
# process exits non-zero.
# Grep for these names in the logs to diagnose. Regenerate the key with:
# openssl rand -base64 32
STORAGE_ENCRYPTION_KEY=

# Version tag for the encryption key — allows future key rotation.
Expand Down
13 changes: 13 additions & 0 deletions src/instrumentation-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,19 @@
// MeterProvider + Prometheus exporter — same gate as trace SDK.
await initOtelMeter();

// Encryption fail-closed startup canary (encryption-failclosed). Runs the
// known-plaintext encrypt/decrypt round-trip; refuses to start with a
// broken STORAGE_ENCRYPTION_KEY so we never silently fall back to
// plaintext at runtime. Must run BEFORE any DB call.
try {
const { runEncryptionStartupCheck } = await import("@/lib/db/encryptionStartup");
runEncryptionStartupCheck();
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);

Check warning on line 292 in src/instrumentation-node.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'err' will use Object's default stringification format ('[object Object]') when stringified.

See more on https://sonarcloud.io/project/issues?id=KooshaPari_OmniRoute&issues=AZ_jv3xs0MNLI6eJjYfK&open=AZ_jv3xs0MNLI6eJjYfK&pullRequest=549
console.error(`[STARTUP] Encryption startup canary failed: ${msg}`);
throw err;
}

await ensureSecrets();
const { enforceWebRuntimeEnv } = await import("@/lib/env/runtimeEnv");
enforceWebRuntimeEnv();
Expand Down
25 changes: 23 additions & 2 deletions src/lib/db/commandCodeAuth.ts
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";

Expand Down Expand Up @@ -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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SUGGESTION]: Dead ?? null fallback — encrypt() now throws on failure

Since encrypt() throws EncryptionRuntimeError instead of returning plaintext, the ?? null fallback is unreachable.

Suggested change
encryptedApiKey = encrypt(input.apiKey) ?? null;
encryptedApiKey = encrypt(input.apiKey);

Reply with @kilocode-bot fix it to have Kilo Code address this issue.

} 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The encryption failure is collapsed into null, but the callback route treats every null result as an invalid or expired state and returns HTTP 400. A real server-side crypto outage is therefore indistinguishable from bad client input, causing clients to retry authentication and preventing monitoring or callers from recognizing that the server cannot persist the API key. Preserve the fail-closed write behavior, but propagate a distinct error/result so the route can return an appropriate server-error response. [api mismatch]

Severity Level: Major ⚠️
- ❌ Command Code callback reports crypto outages as HTTP 400.
- ⚠️ Valid authentication attempts appear to have expired state.
- ⚠️ Clients may retry instead of surfacing server failure.
- ⚠️ Monitoring cannot distinguish bad state from encryption failure.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/lib/db/commandCodeAuth.ts
**Line:** 145:157
**Comment:**
	*Api Mismatch: The encryption failure is collapsed into `null`, but the callback route treats every `null` result as an invalid or expired state and returns HTTP 400. A real server-side crypto outage is therefore indistinguishable from bad client input, causing clients to retry authentication and preventing monitoring or callers from recognizing that the server cannot persist the API key. Preserve the fail-closed write behavior, but propagate a distinct error/result so the route can return an appropriate server-error response.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

}
throw err;
}
if (encryptedApiKey === null) {
return null;
}
db()
.prepare(
`UPDATE command_code_auth_sessions
Expand Down
163 changes: 153 additions & 10 deletions src/lib/db/encryption.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Update this function so that its implementation is not identical to the one on line 99.

See more on https://sonarcloud.io/project/issues?id=KooshaPari_OmniRoute&issues=AZ_jv3cJ0MNLI6eJjYfG&open=AZ_jv3cJ0MNLI6eJjYfG&pullRequest=549
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.
Expand Down Expand Up @@ -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(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[WARNING]: encrypt() now throws EncryptionRuntimeError, but 9+ external callers are not updated to handle it

encrypt() was changed to throw instead of returning plaintext on crypto failure. These callers still rely on the old fallback behavior and will throw unhandled exceptions at runtime:

  • src/lib/services/apiKey.ts:32 — encrypt(key) ?? key
  • src/lib/webhookDispatcher.ts:25 — encrypt(JSON.stringify(meta)) ?? JSON.stringify(meta)
  • src/lib/db/obsidian.ts:31 — encrypt(token) ?? token (outer try/catch swallows error, token not persisted)
  • src/lib/db/obsidian.ts:190 — encrypt(password) ?? password
  • src/lib/cloudAgent/credentials.ts:71 — const encrypted = encrypt(apiKey);
  • src/app/api/settings/proxy/cloudflare-deploy/route.ts:155 — const encryptedRelayAuth = encrypt(relayAuth);
  • src/app/api/settings/proxy/vercel-deploy/route.ts:236 — same pattern
  • src/app/api/settings/proxy/deno-deploy/route.ts:347 — same pattern
  • src/app/api/services/9router/rotate-key/route.ts:12 — encrypt(newKey) ?? newKey

Reply with @kilocode-bot fix it to have Kilo Code address this issue.

`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
}
}

Expand Down Expand Up @@ -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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SUGGESTION]: Dead ?? conn.apiKey fallback — encrypt() now throws on failure

Since encrypt() throws EncryptionRuntimeError instead of returning plaintext on failure, the ?? conn.apiKey fallback is unreachable and contradicts the fail-closed intent. Lines 489-491 have the same pattern.

Suggested change
if (conn.apiKey) conn.apiKey = encrypt(conn.apiKey) ?? conn.apiKey;
if (conn.apiKey) conn.apiKey = encrypt(conn.apiKey);

Reply with @kilocode-bot fix it to have Kilo Code address this issue.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Refuse plaintext when key derivation fails

When STORAGE_ENCRYPTION_KEY is present but getStaticKey() returns null from its derivation-failure path, encrypt() still returns the original secret instead of throwing, and these assignments treat that plaintext as a successful encryption result. In any entry point that does not run the new startup canary before provider writes, createProviderConnection/updateProviderConnection will pass the new null check and store API keys or OAuth tokens in plaintext even though encryption was configured; distinguish “no key configured” from “configured key failed” or verify encrypted fields get the enc:v1: prefix before returning success.

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.
}
}

/**
Expand Down Expand Up @@ -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) ?? "";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SUGGESTION]: Dead ?? "" fallback — encrypt() now throws on failure

Since encrypt() throws EncryptionRuntimeError instead of returning plaintext, the ?? "" fallback is unreachable.

Suggested change
encrypted = encrypt(STARTUP_CANARY_PLAINTEXT) ?? "";
encrypted = encrypt(STARTUP_CANARY_PLAINTEXT);

Reply with @kilocode-bot fix it to have Kilo Code address this issue.

} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);

Check warning on line 612 in src/lib/db/encryption.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'err' will use Object's default stringification format ('[object Object]') when stringified.

See more on https://sonarcloud.io/project/issues?id=KooshaPari_OmniRoute&issues=AZ_jv3cJ0MNLI6eJjYfH&open=AZ_jv3cJ0MNLI6eJjYfH&pullRequest=549
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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer using an optional chain expression instead, as it's more concise and easier to read.

See more on https://sonarcloud.io/project/issues?id=KooshaPari_OmniRoute&issues=AZ_jv3cJ0MNLI6eJjYfI&open=AZ_jv3cJ0MNLI6eJjYfI&pullRequest=549
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"
);
}
61 changes: 61 additions & 0 deletions src/lib/db/encryptionStartup.ts
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 };
20 changes: 18 additions & 2 deletions src/lib/db/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,15 @@
connection.rateLimitOverrides = sanitizeRateLimitOverrides(connection.rateLimitOverrides);
}

_insertConnectionRow(db, encryptConnectionFields({ ...connection }));
const fieldsToWrite = encryptConnectionFields({ ...connection });
if (fieldsToWrite === null) {
// FAIL-CLOSED: encryption layer is broken (key configured but crypto
// pipeline threw). Refuse to insert plaintext; surface a clear error.
throw new Error(
`[providers] Cannot insert connection for ${String(data.provider)}: encryption layer failed`

Check warning on line 356 in src/lib/db/providers.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'data.provider' will use Object's default stringification format ('[object Object]') when stringified.

See more on https://sonarcloud.io/project/issues?id=KooshaPari_OmniRoute&issues=AZ_jv3wn0MNLI6eJjYfJ&open=AZ_jv3wn0MNLI6eJjYfJ&pullRequest=549
);
}
_insertConnectionRow(db, fieldsToWrite);
const providerId = toStringOrNull(data.provider);
if (providerId) {
_reorderConnections(db, providerId);
Expand Down Expand Up @@ -544,7 +552,15 @@
if ("rateLimitOverrides" in merged) {
merged.rateLimitOverrides = sanitizeRateLimitOverrides(merged.rateLimitOverrides);
}
_updateConnectionRow(db, id, encryptConnectionFields({ ...merged }));
const fieldsToWrite = encryptConnectionFields({ ...merged });
if (fieldsToWrite === null) {
// FAIL-CLOSED: encryption layer is broken (key configured but crypto
// pipeline threw). Refuse to update plaintext; surface a clear error.
throw new Error(
`[providers] Cannot update connection ${String(id)}: encryption layer failed`
);
}
_updateConnectionRow(db, id, fieldsToWrite);
backupDbFile("pre-write");
invalidateDbCache("connections"); // Bust connections read cache
bumpProxyConfigGeneration();
Expand Down
Loading
Loading