Compare commits

..
Author SHA1 Message Date
taodengandClaude Sonnet 4.6 91e1f0d18e fix(security): namespace sessions Map by keyId — close cross-key conversation collision
**Bug**: the sessions Map used the raw client-supplied conversationId string as
its key. Two callers with different API keys (or one anonymous + one
authenticated) using the same session_id="default" collided in the Map,
sharing a cli.js subprocess and conversation history — a cross-tenant context leak.

**Fix**: introduce _sessionKey(conversationId, keyName) → "${keyName}|${conversationId}".
Replace every sessions Map site (has / set / get / delete) with the namespaced key.
keyName comes from req._authKeyName (set by auth middleware). Anonymous callers
produce "anon|<id>"; admin produces "admin|<id>"; per-key callers produce
"<keyName>|<id>" — matching the convention used by cacheHash() for per-key cache
isolation (D1, v3.13.0).

**cli.js citation — not applicable**: This PR changes OCP-internal session lifecycle
bookkeeping (the sessions Map that OCP maintains to thread --resume flags across
requests). There is no corresponding cli.js operation to cite. ALIGNMENT.md Rule 2
(limiting OCP to operations cli.js performs) does not constrain in-process state
representation. Same pattern as #75.

**Scope of changes (server.mjs only)**:
- New helper: _sessionKey() — 3 lines after sessions Map declaration
- spawnClaudeProcess(): accepts keyName param; all 4 sessions Map calls → _sessionKey
- handleSessionFailure(): uses sessionKey (not raw conversationId) for sessions.delete
- callClaude(): accepts and forwards keyName to spawnClaudeProcess
- callClaudeStreaming(): forwards authInfo.keyName to spawnClaudeProcess
- Request handler: both callClaude() call sites pass req._authKeyName
- Cleanup interval + GET /health + GET /sessions: strip "keyName|" prefix before log/display

**Smoke test**:
- node --check server.mjs → SYNTAX OK
- npm test → 43/43 passed, 0 failed
- Hand-traced has/set/get/delete paths: cross-key collision absent ✓

Identified during privacy/security positioning brainstorm — `.claude/research/ocp-security-audit.md`

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 23:47:22 +10:00
3 changed files with 46 additions and 72 deletions
+2 -6
View File
@@ -3,13 +3,11 @@
import { DatabaseSync } from "node:sqlite"; import { DatabaseSync } from "node:sqlite";
import { randomBytes, createHash } from "node:crypto"; import { randomBytes, createHash } from "node:crypto";
import { join } from "node:path"; import { join } from "node:path";
import { mkdirSync, chmodSync } from "node:fs"; import { mkdirSync } from "node:fs";
import { homedir } from "node:os"; import { homedir } from "node:os";
const OCP_DIR = join(homedir(), ".ocp"); const OCP_DIR = join(homedir(), ".ocp");
mkdirSync(OCP_DIR, { recursive: true, mode: 0o700 }); mkdirSync(OCP_DIR, { recursive: true });
// Tighten the directory mode in case it already existed with broader permissions.
try { chmodSync(OCP_DIR, 0o700); } catch { /* ignore EPERM on pre-existing dirs */ }
const DB_PATH = join(OCP_DIR, "ocp.db"); const DB_PATH = join(OCP_DIR, "ocp.db");
let db; let db;
@@ -20,8 +18,6 @@ export function getDb() {
db.exec("PRAGMA journal_mode = WAL"); db.exec("PRAGMA journal_mode = WAL");
db.exec("PRAGMA foreign_keys = ON"); db.exec("PRAGMA foreign_keys = ON");
initSchema(); initSchema();
// Tighten mode on the DB file (0600) after creation / first open.
try { chmodSync(DB_PATH, 0o600); } catch { /* ignore — same-user access still works */ }
} }
return db; return db;
} }
+41 -61
View File
@@ -30,7 +30,7 @@
import { createServer } from "node:http"; import { createServer } from "node:http";
import { spawn, execFileSync } from "node:child_process"; import { spawn, execFileSync } from "node:child_process";
import { randomUUID, timingSafeEqual } from "node:crypto"; import { randomUUID, timingSafeEqual } from "node:crypto";
import { readFileSync, readdirSync, accessSync, existsSync, constants, chmodSync, statSync } from "node:fs"; import { readFileSync, readdirSync, accessSync, existsSync, constants } from "node:fs";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path"; import { dirname, join } from "node:path";
import { homedir } from "node:os"; import { homedir } from "node:os";
@@ -167,44 +167,6 @@ function logEvent(level, event, data = {}) {
} }
} }
// ── Startup file-mode reconciliation ───────────────────────────────────
// Idempotently tightens OCP credential-bearing files to 700/600 so that
// existing installs (created before this fix) are hardened on next restart.
// Wrapped in try/catch — chmod failure must never crash startup.
// Does NOT touch systemd units or launchd plists; those are managed by setup.mjs.
function _tightenFileModesIfPossible() {
const ocpDir = join(homedir(), ".ocp");
const targets = [
{ path: ocpDir, mode: 0o700, label: "~/.ocp (dir)" },
{ path: join(ocpDir, "admin-key"), mode: 0o600, label: "~/.ocp/admin-key" },
{ path: join(ocpDir, "ocp.db"), mode: 0o600, label: "~/.ocp/ocp.db" },
];
let tightened = 0;
let alreadyOk = 0;
for (const { path, mode, label } of targets) {
try {
const st = statSync(path);
const current = st.mode & 0o777;
if (current !== mode) {
chmodSync(path, mode);
tightened++;
} else {
alreadyOk++;
}
} catch (e) {
if (e.code !== "ENOENT") {
// File exists but chmod failed (e.g. EPERM) — log and move on
logEvent("warn", "file_mode_tighten_failed", { path: label, error: e.message });
}
// ENOENT is fine — file doesn't exist yet
}
}
if (tightened > 0) {
logEvent("info", "file_modes_tightened", { tightened, alreadyOk });
}
}
_tightenFileModesIfPossible();
// ── Circuit breaker (DISABLED) ────────────────────────────────────────── // ── Circuit breaker (DISABLED) ──────────────────────────────────────────
// Disabled: CLI proxy has its own retry logic, and the breaker was causing // Disabled: CLI proxy has its own retry logic, and the breaker was causing
// cascading failures — once API got briefly slow, ALL agents lost connectivity // cascading failures — once API got briefly slow, ALL agents lost connectivity
@@ -240,25 +202,36 @@ const MODEL_MAP = Object.fromEntries([
const MODELS = modelsConfig.models.map(m => ({ id: m.id, name: m.displayName })); const MODELS = modelsConfig.models.map(m => ({ id: m.id, name: m.displayName }));
// ── Session management ────────────────────────────────────────────────── // ── Session management ──────────────────────────────────────────────────
// Maps conversation IDs (from caller) to Claude CLI session UUIDs. // Maps namespaced session keys to Claude CLI session UUIDs.
// Key format: "${keyName}|${conversationId}" — prevents cross-key collision
// when two callers (different API keys or anon + authenticated) use the same
// session_id string. Anonymous callers use "anon"; admin uses "admin".
// Enables --resume for multi-turn conversations, reducing token waste. // Enables --resume for multi-turn conversations, reducing token waste.
const sessions = new Map(); // conversationId → { uuid, messageCount, lastUsed, model } const sessions = new Map(); // `${keyName}|${conversationId}` → { uuid, messageCount, lastUsed, model }
// Build the namespaced key used for all sessions Map operations.
// Returns null when conversationId is falsy (one-off requests bypass session tracking).
function _sessionKey(conversationId, keyName) {
return conversationId ? `${keyName || "anon"}|${conversationId}` : null;
}
const sessionCleanupInterval = setInterval(() => { const sessionCleanupInterval = setInterval(() => {
const now = Date.now(); const now = Date.now();
for (const [id, s] of sessions) { for (const [id, s] of sessions) {
const idleMs = now - s.lastUsed; const idleMs = now - s.lastUsed;
const ageMs = s.firstSeen ? now - s.firstSeen : null; const ageMs = s.firstSeen ? now - s.firstSeen : null;
// id is "${keyName}|${conversationId}"; strip prefix for log output
const convIdShort = id.includes("|") ? id.slice(id.indexOf("|") + 1, id.indexOf("|") + 13) : id.slice(0, 12);
if (idleMs > SESSION_TTL) { if (idleMs > SESSION_TTL) {
sessions.delete(id); sessions.delete(id);
console.log(`[session] expired ${id.slice(0, 12)}... (idle ${Math.round(idleMs / 60000)}m)`); console.log(`[session] expired ${convIdShort}... (idle ${Math.round(idleMs / 60000)}m)`);
logEvent("info", "session_expired", { conversationId: id.slice(0, 12) + "...", idleMs, ageMs }); logEvent("info", "session_expired", { conversationId: convIdShort + "...", idleMs, ageMs });
} else if (ageMs !== null && ageMs > 4 * SESSION_TTL) { } else if (ageMs !== null && ageMs > 4 * SESSION_TTL) {
// #42 evidence-gathering: a session whose firstSeen is more than 4× TTL old // #42 evidence-gathering: a session whose firstSeen is more than 4× TTL old
// but whose lastUsed keeps getting bumped (never idle long enough to expire) // but whose lastUsed keeps getting bumped (never idle long enough to expire)
// is the suspected bug. Log without action so the pattern can be confirmed // is the suspected bug. Log without action so the pattern can be confirmed
// in /logs. Do NOT enforce an absolute age cap here speculatively. // in /logs. Do NOT enforce an absolute age cap here speculatively.
logEvent("warn", "session_long_lived", { conversationId: id.slice(0, 12) + "...", idleMs, ageMs }); logEvent("warn", "session_long_lived", { conversationId: convIdShort + "...", idleMs, ageMs });
} }
} }
}, 60000); }, 60000);
@@ -465,7 +438,7 @@ function getModelTier(cliModel) {
// ── Spawn claude CLI (shared setup) ───────────────────────────────────── // ── Spawn claude CLI (shared setup) ─────────────────────────────────────
// Resolves session logic, builds CLI args, spawns the process, and sets up // Resolves session logic, builds CLI args, spawns the process, and sets up
// timeouts. Returns context object or throws synchronously. // timeouts. Returns context object or throws synchronously.
function spawnClaudeProcess(model, messages, conversationId) { function spawnClaudeProcess(model, messages, conversationId, keyName) {
if (stats.activeRequests >= MAX_CONCURRENT) { if (stats.activeRequests >= MAX_CONCURRENT) {
throw new Error(`concurrency limit reached (${stats.activeRequests}/${MAX_CONCURRENT})`); throw new Error(`concurrency limit reached (${stats.activeRequests}/${MAX_CONCURRENT})`);
} }
@@ -481,8 +454,11 @@ function spawnClaudeProcess(model, messages, conversationId) {
let prompt; let prompt;
// ── Session logic ── // ── Session logic ──
if (conversationId && sessions.has(conversationId)) { // sessionKey namespaces the Map key by keyName to prevent cross-caller collision
const session = sessions.get(conversationId); // when two callers with different API keys share the same conversationId string.
const sessionKey = _sessionKey(conversationId, keyName);
if (sessionKey && sessions.has(sessionKey)) {
const session = sessions.get(sessionKey);
session.lastUsed = Date.now(); session.lastUsed = Date.now();
sessionInfo = { uuid: session.uuid, resume: true }; sessionInfo = { uuid: session.uuid, resume: true };
stats.sessionHits++; stats.sessionHits++;
@@ -493,17 +469,17 @@ function spawnClaudeProcess(model, messages, conversationId) {
: ""; : "";
session.messageCount = messages.length; session.messageCount = messages.length;
console.log(`[session] resume conv=${conversationId.slice(0, 12)}... uuid=${session.uuid.slice(0, 8)}... msgs=${messages.length} prompt_chars=${prompt.length}`); console.log(`[session] resume conv=${conversationId.slice(0, 12)}... key=${keyName || "anon"} uuid=${session.uuid.slice(0, 8)}... msgs=${messages.length} prompt_chars=${prompt.length}`);
} else if (conversationId) { } else if (sessionKey) {
const uuid = randomUUID(); const uuid = randomUUID();
const now = Date.now(); const now = Date.now();
sessions.set(conversationId, { uuid, messageCount: messages.length, firstSeen: now, lastUsed: now, model: cliModel }); sessions.set(sessionKey, { uuid, messageCount: messages.length, firstSeen: now, lastUsed: now, model: cliModel });
sessionInfo = { uuid, resume: false }; sessionInfo = { uuid, resume: false };
stats.sessionMisses++; stats.sessionMisses++;
prompt = messagesToPrompt(messages); prompt = messagesToPrompt(messages);
console.log(`[session] new conv=${conversationId.slice(0, 12)}... uuid=${uuid.slice(0, 8)}... msgs=${messages.length}`); console.log(`[session] new conv=${conversationId.slice(0, 12)}... key=${keyName || "anon"} uuid=${uuid.slice(0, 8)}... msgs=${messages.length}`);
} else { } else {
stats.oneOffRequests++; stats.oneOffRequests++;
@@ -548,11 +524,11 @@ function spawnClaudeProcess(model, messages, conversationId) {
proc.once("exit", cleanup); proc.once("exit", cleanup);
function handleSessionFailure() { function handleSessionFailure() {
if (sessionInfo?.resume && conversationId) { if (sessionInfo?.resume && sessionKey) {
console.warn(`[session] resume failed for ${conversationId.slice(0, 12)}..., removing stale session`); console.warn(`[session] resume failed for ${conversationId.slice(0, 12)}..., removing stale session`);
logEvent("warn", "session_failure", { mode: "resume", conversationId: conversationId.slice(0, 12) + "...", action: "deleted" }); logEvent("warn", "session_failure", { mode: "resume", conversationId: conversationId.slice(0, 12) + "...", action: "deleted" });
sessions.delete(conversationId); sessions.delete(sessionKey);
} else if (sessionInfo && !sessionInfo.resume && conversationId) { } else if (sessionInfo && !sessionInfo.resume && sessionKey) {
// #41 evidence-gathering: session-create failures currently leave a stale entry // #41 evidence-gathering: session-create failures currently leave a stale entry
// in the sessions map. Log without action so the staleness pattern can be // in the sessions map. Log without action so the staleness pattern can be
// confirmed in /logs before any code change. Do NOT delete here speculatively. // confirmed in /logs before any code change. Do NOT delete here speculatively.
@@ -595,11 +571,11 @@ function spawnClaudeProcess(model, messages, conversationId) {
// On-demand spawning: each request spawns a fresh `claude -p` process. // On-demand spawning: each request spawns a fresh `claude -p` process.
// No pool = no crash loops, no stale workers, no degraded states. // No pool = no crash loops, no stale workers, no degraded states.
// Stdin is written immediately so there's no 3s stdin timeout issue. // Stdin is written immediately so there's no 3s stdin timeout issue.
function callClaude(model, messages, conversationId) { function callClaude(model, messages, conversationId, keyName) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let ctx; let ctx;
try { try {
ctx = spawnClaudeProcess(model, messages, conversationId); ctx = spawnClaudeProcess(model, messages, conversationId, keyName);
} catch (err) { } catch (err) {
return reject(err); return reject(err);
} }
@@ -679,7 +655,7 @@ function callClaudeStreaming(model, messages, conversationId, res, authInfo = {}
let ctx; let ctx;
try { try {
ctx = spawnClaudeProcess(model, messages, conversationId); ctx = spawnClaudeProcess(model, messages, conversationId, authInfo.keyName);
} catch (err) { } catch (err) {
return jsonResponse(res, 500, { error: { message: err.message, type: "proxy_error" } }); return jsonResponse(res, 500, { error: { message: err.message, type: "proxy_error" } });
} }
@@ -1362,7 +1338,7 @@ async function handleChatCompletions(req, res) {
// will re-read the freshly-populated cache entry here rather than spawning. // will re-read the freshly-populated cache entry here rather than spawning.
const recheck = getCachedResponse(req._cacheHash, CACHE_TTL); const recheck = getCachedResponse(req._cacheHash, CACHE_TTL);
if (recheck) return recheck.response; if (recheck) return recheck.response;
const c = await callClaude(model, messages, conversationId); const c = await callClaude(model, messages, conversationId, req._authKeyName);
try { setCachedResponse(req._cacheHash, model, c); } catch (e) { logEvent("error", "cache_write_failed", { error: e.message }); } try { setCachedResponse(req._cacheHash, model, c); } catch (e) { logEvent("error", "cache_write_failed", { error: e.message }); }
return c; return c;
}); });
@@ -1384,7 +1360,7 @@ async function handleChatCompletions(req, res) {
// Fallback: cache disabled (CACHE_TTL=0) or no _cacheHash — original path untouched. // Fallback: cache disabled (CACHE_TTL=0) or no _cacheHash — original path untouched.
try { try {
const content = await callClaude(model, messages, conversationId); const content = await callClaude(model, messages, conversationId, req._authKeyName);
const id = `chatcmpl-${randomUUID()}`; const id = `chatcmpl-${randomUUID()}`;
completionResponse(res, id, model, content); completionResponse(res, id, model, content);
try { recordUsage({ keyId: req._authKeyId, keyName: req._authKeyName, model, promptChars, responseChars: content.length, elapsedMs: Date.now() - t0Usage, success: true }); } catch (e) { logEvent("error", "usage_record_failed", { error: e.message }); } try { recordUsage({ keyId: req._authKeyId, keyName: req._authKeyName, model, promptChars, responseChars: content.length, elapsedMs: Date.now() - t0Usage, success: true }); } catch (e) { logEvent("error", "usage_record_failed", { error: e.message }); }
@@ -1518,8 +1494,10 @@ const server = createServer(async (req, res) => {
const uptimeMs = Date.now() - START_TIME; const uptimeMs = Date.now() - START_TIME;
const sessionList = []; const sessionList = [];
for (const [id, s] of sessions) { for (const [id, s] of sessions) {
// id is "${keyName}|${conversationId}"; expose only the public-facing conversationId
const convId = id.includes("|") ? id.slice(id.indexOf("|") + 1) : id;
sessionList.push({ sessionList.push({
id: id.slice(0, 12) + "...", id: convId.slice(0, 12) + "...",
model: s.model, model: s.model,
messages: s.messageCount, messages: s.messageCount,
idleMs: Date.now() - s.lastUsed, idleMs: Date.now() - s.lastUsed,
@@ -1564,7 +1542,9 @@ const server = createServer(async (req, res) => {
if (req.url === "/sessions" && req.method === "GET") { if (req.url === "/sessions" && req.method === "GET") {
const list = []; const list = [];
for (const [id, s] of sessions) { for (const [id, s] of sessions) {
list.push({ id, uuid: s.uuid, model: s.model, messages: s.messageCount, lastUsed: new Date(s.lastUsed).toISOString() }); // id is "${keyName}|${conversationId}"; expose only the public-facing conversationId
const convId = id.includes("|") ? id.slice(id.indexOf("|") + 1) : id;
list.push({ id: convId, uuid: s.uuid, model: s.model, messages: s.messageCount, lastUsed: new Date(s.lastUsed).toISOString() });
} }
return jsonResponse(res, 200, { sessions: list }); return jsonResponse(res, 200, { sessions: list });
} }
+3 -5
View File
@@ -12,7 +12,7 @@
* 4. Creates start.sh for easy launch * 4. Creates start.sh for easy launch
* 5. Optionally starts the proxy * 5. Optionally starts the proxy
*/ */
import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync, readdirSync, chmodSync } from "node:fs"; import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync, readdirSync } from "node:fs";
import { execSync } from "node:child_process"; import { execSync } from "node:child_process";
import { join, dirname } from "node:path"; import { join, dirname } from "node:path";
import { homedir } from "node:os"; import { homedir } from "node:os";
@@ -425,8 +425,7 @@ if (!DRY_RUN) {
`; `;
writeFileSync(plistPath, plistXml); writeFileSync(plistPath, plistXml);
chmodSync(plistPath, 0o600); log(`Plist written: ${plistPath}`);
log(`Plist written: ${plistPath} (mode 600)`);
// Bootout first (in case it was already loaded) then bootstrap // Bootout first (in case it was already loaded) then bootstrap
try { execSync(`launchctl bootout gui/$(id -u) "${plistPath}" 2>/dev/null`); } catch { /* ignore */ } try { execSync(`launchctl bootout gui/$(id -u) "${plistPath}" 2>/dev/null`); } catch { /* ignore */ }
@@ -460,8 +459,7 @@ WantedBy=default.target
`; `;
writeFileSync(servicePath, serviceUnit); writeFileSync(servicePath, serviceUnit);
chmodSync(servicePath, 0o600); log(`Service file written: ${servicePath}`);
log(`Service file written: ${servicePath} (mode 600)`);
execSync(`systemctl --user daemon-reload`); execSync(`systemctl --user daemon-reload`);
execSync(`systemctl --user enable ocp-proxy`); execSync(`systemctl --user enable ocp-proxy`);