From fcbf1992ebe56951686f554d245a5394ad430f4f Mon Sep 17 00:00:00 2001 From: kahme247 <61059522+kahme247@users.noreply.github.com> Date: Mon, 26 Oct 2026 05:27:16 +0000 Subject: [PATCH] fix(security): close round-1 bug-hunt findings (auth material, export XSS, symlink bypass, key exposure, settings allowlist, plugin option injection, db sidecars) --- app/api/models-config/route.ts | 15 ++- app/api/models-config/test/route.ts | 12 ++- app/api/plugins/route.ts | 7 ++ app/api/sessions/[id]/export/route.ts | 12 ++- components/AppShell.tsx | 14 ++- lib/file-access.test.mjs | 28 +++++- lib/file-access.ts | 29 ++++-- lib/file-authorization.test.mjs | 129 ++++++++++++++++++++++++++ lib/file-authorization.ts | 23 ++++- lib/models-config-route.test.mjs | 85 +++++++++++++++++ lib/omp/models-config.test.mjs | 57 ++++++++++++ lib/omp/models-config.ts | 43 +++++++++ lib/omp/settings-config.test.mjs | 36 +++++++ lib/omp/settings-config.ts | 64 ++++++++++++- lib/plugins-route.test.mjs | 60 ++++++++++++ lib/session-export-route.test.mjs | 64 +++++++++++++ 16 files changed, 656 insertions(+), 22 deletions(-) create mode 100644 lib/file-authorization.test.mjs create mode 100644 lib/models-config-route.test.mjs create mode 100644 lib/plugins-route.test.mjs create mode 100644 lib/session-export-route.test.mjs diff --git a/app/api/models-config/route.ts b/app/api/models-config/route.ts index 7249e7b0b..01c99b8b0 100644 --- a/app/api/models-config/route.ts +++ b/app/api/models-config/route.ts @@ -4,7 +4,9 @@ import { invalidateModelsCache } from "@/lib/models-cache"; import { disposeUtilityRpc } from "@/lib/omp/rpc-utility"; import { ModelsConfigParseError, + maskModelsConfigApiKeys, readModelsConfigFile, + restoreModelsConfigApiKeys, validateModelsConfig, writeModelsConfig, type ModelsFileConfig, @@ -24,7 +26,9 @@ export async function GET() { code: "models_config_unparseable", }); } - return NextResponse.json(file.config); + // Never emit a real key: the file API denies models.yml outright, and + // this route is the scoped alternative to that denial. + return NextResponse.json(maskModelsConfigApiKeys(file.config)); } // PUT /api/models-config[?overwrite=true] @@ -33,13 +37,18 @@ export async function PUT(req: Request) { try { const overwriteUnparseable = new URL(req.url).searchParams.get("overwrite") === "true"; const body = await req.json() as ModelsFileConfig; + // The editor echoes masked keys back on every save; restore the stored + // key for those, so an unrelated edit never wipes (or leaks, then + // re-saves) a credential, and a placeholder is never written to disk. + const stored = readModelsConfigFile(); + const restored = restoreModelsConfigApiKeys(body, stored.parseError ? { providers: {} } : stored.config); try { - validateModelsConfig(body); + validateModelsConfig(restored); } catch (error) { return NextResponse.json({ error: error instanceof Error ? error.message : String(error) }, { status: 400 }); } try { - writeModelsConfig(body, { overwriteUnparseable }); + writeModelsConfig(restored, { overwriteUnparseable }); } catch (error) { if (error instanceof ModelsConfigParseError) { return NextResponse.json( diff --git a/app/api/models-config/test/route.ts b/app/api/models-config/test/route.ts index 576572b1d..4d5bdc341 100644 --- a/app/api/models-config/test/route.ts +++ b/app/api/models-config/test/route.ts @@ -3,8 +3,10 @@ import { mkdtempSync, rmSync, writeFileSync } from "fs"; import { tmpdir } from "os"; import { join } from "path"; import { + MASKED_API_KEY, type ModelDefinition, type ProviderConfig, + readModelsConfigFile, serializeModelsConfig, validateModelsConfig, } from "@/lib/omp/models-config"; @@ -34,10 +36,18 @@ export async function POST(req: Request) { const modelId = typeof body.model.id === "string" ? body.model.id.trim() : ""; if (!modelId) return NextResponse.json({ ok: false, error: "Model ID is required", code: "model_id_required" }, { status: 400 }); + // The editor shows the masked placeholder for a stored key; testing a + // provider without retyping its key must still test the real one. + const candidate = { ...(body.provider as ProviderConfig) }; + if (candidate.apiKey === MASKED_API_KEY) { + const storedProvider = readModelsConfigFile().config.providers?.[providerName]; + if (storedProvider?.apiKey) candidate.apiKey = storedProvider.apiKey; + else delete candidate.apiKey; + } const config = { providers: { [providerName]: { - ...(body.provider as ProviderConfig), + ...candidate, models: [{ ...(body.model as ModelDefinition), id: modelId }], }, }, diff --git a/app/api/plugins/route.ts b/app/api/plugins/route.ts index 8b8dd152e..ac0a88f3b 100644 --- a/app/api/plugins/route.ts +++ b/app/api/plugins/route.ts @@ -307,6 +307,13 @@ export async function POST(req: Request) { } const source = body.source?.trim(); + // A source starting with "-" would be parsed as CLI options by + // `omp plugin …` instead of a plugin name (e.g. `--scope` consuming + // the following `--json` as its value) — the same guard the + // skills-install route applies to package names. + if (source?.startsWith("-")) { + return NextResponse.json({ error: "Invalid plugin source", code: "plugin_source_invalid" }, { status: 400 }); + } const scopeArgs = readScope(body.scope) === "project" ? ["--scope", "project"] : []; if (body.action === "install") { diff --git a/app/api/sessions/[id]/export/route.ts b/app/api/sessions/[id]/export/route.ts index 15113e4ba..7d387ee08 100644 --- a/app/api/sessions/[id]/export/route.ts +++ b/app/api/sessions/[id]/export/route.ts @@ -36,7 +36,6 @@ export async function GET( { params }: { params: Promise<{ id: string }> } ) { const { id } = await params; - const inline = new URL(req.url).searchParams.get("inline") === "1"; try { const resolved = await resolveSessionPathOr404(id); @@ -54,10 +53,19 @@ export async function GET( await exportSession(filePath, outputPath); const html = readFileSync(outputPath, "utf8"); + // Attachment-only, even when ?inline=1 is requested: omp embeds + // transcript text into the exported HTML without escaping it, so an + // attacker-influenced message (event-handler attributes survive + // innerHTML parsing) would execute in omp-web's origin if the export + // were rendered inline — with the owner's cookies and same-origin API + // access. A route-level sandboxed CSP cannot fix this: config-level + // headers overwrite same-key route headers (see next.config.ts), so + // the global CSP's `unsafe-inline` would win. Downloading keeps the + // feature working without ever rendering untrusted HTML as omp-web. return new Response(html, { headers: { "Content-Type": "text/html; charset=utf-8", - "Content-Disposition": getContentDisposition(fileName, inline, "session.html"), + "Content-Disposition": getContentDisposition(fileName, false, "session.html"), "Cache-Control": "no-cache", }, }); diff --git a/components/AppShell.tsx b/components/AppShell.tsx index a0ea786a4..e7caad9af 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -1721,11 +1721,15 @@ export function AppShell({ appName }: { appName: string }) { const handleViewFullHistory = useCallback(() => { if (!selectedSession) return; - window.open( - `/api/sessions/${encodeURIComponent(selectedSession.id)}/export?inline=1`, - "_blank", - "noopener,noreferrer", - ); + // Exports are always served as attachments (stored-XSS hardening: omp + // embeds transcript HTML unescaped), so download the file instead of + // opening it in a tab. + const link = document.createElement("a"); + link.href = `/api/sessions/${encodeURIComponent(selectedSession.id)}/export`; + link.download = ""; + document.body.appendChild(link); + link.click(); + link.remove(); }, [selectedSession]); // Show chat area if a session is selected, or if we have a cwd to start a new session in diff --git a/lib/file-access.test.mjs b/lib/file-access.test.mjs index 8f1875f03..5bebba468 100644 --- a/lib/file-access.test.mjs +++ b/lib/file-access.test.mjs @@ -258,4 +258,30 @@ test("keeps POST uploads on the absolute-only path", async (t) => { assert.equal((await post(uploads.replace(/\\/g, "/"))).status, 200); clearAllowedRootsCache(); -}); \ No newline at end of file +}); +test("denies omp-web's own auth material and every sqlite database under a config root", async () => { + const { isConfigRootDeniedFile } = await loadSubject(); + const agentDir = "/fake/agent"; + // Bug hunt round 1: the generic file API served these straight out of the + // agent dir, whose root is browsable so rule files open in the viewer. + for (const name of [ + "agent.db", + "models.yml", + "web-auth-secret.json", + "web-service.env", + "notifications.db", + "agent.db-wal", + "agent.db-shm", + "agent.db-journal", + "agent.db-xyz", + "other.db", + "usage.db", + ]) { + assert.equal(isConfigRootDeniedFile(`${agentDir}/${name}`), true, `${name} must be denied`); + assert.equal(isConfigRootDeniedFile(`${agentDir}/omp-web/${name}`), true, `omp-web/${name} must be denied`); + } + // Ordinary files in the same roots stay browsable. + for (const name of ["AGENTS.md", "config.yml", "sessions.json", "agent.db.txt", "notes.md"]) { + assert.equal(isConfigRootDeniedFile(`${agentDir}/${name}`), false, `${name} must stay allowed`); + } +}); diff --git a/lib/file-access.ts b/lib/file-access.ts index 7fdccad8f..155c48598 100644 --- a/lib/file-access.ts +++ b/lib/file-access.ts @@ -71,19 +71,34 @@ export function getConfigAgentRoots(): string[] { * * `~/.omp/agent/agent.db` is omp's credential store (API keys) and `models.yml` * can carry an `apiKey` for custom models, so making the config root readable - * to view a rule file would also hand out secrets over `?type=download`. Both - * are already reachable through their purpose-built routes - * (`app/api/auth/api-key/*`, `app/api/models-config/route.ts`) which redact or - * scope what they return, so nothing legitimate needs the generic path. + * to view a rule file would also hand out secrets over `?type=download`. The + * same holds for omp-web's own auth material: `web-auth-secret.json` (the + * session-signing key), `web-service.env` (the password hash) and + * `notifications.db` (the VAPID private key) would each let a holder mint + * sessions or forge pushes. The credential stores are already reachable + * through their purpose-built routes (`app/api/auth/api-key/*`, + * `app/api/models-config/route.ts`) which redact or scope what they return, + * so nothing legitimate needs the generic path. */ -const CONFIG_ROOT_DENIED_FILES: ReadonlySet = new Set(["agent.db", "models.yml"]); +const CONFIG_ROOT_DENIED_FILES: ReadonlySet = new Set([ + "agent.db", + "models.yml", + "web-auth-secret.json", + "web-service.env", + "notifications.db", +]); export function isConfigRootDeniedFile(filePath: string): boolean { const base = normalizeSlashes(filePath); const name = base.slice(base.lastIndexOf("/") + 1).toLowerCase(); - // SQLite sidecars carry the same credentials as the db itself. if (CONFIG_ROOT_DENIED_FILES.has(name)) return true; - return CONFIG_ROOT_DENIED_FILES.has(name.split(".").slice(0, -1).join(".")) && name.includes(".db"); + // SQLite sidecars carry the same credentials as the db itself (`agent.db` + // plus `agent.db-*` — the old stem check missed these because the stem of + // `agent.db-wal` is `agent`, not `agent.db`), and any other sqlite + // database under a config root is omp/omp-web state, not a document the + // file viewer has business opening. + if (name.startsWith("agent.db-")) return true; + return name.endsWith(".db"); } /** True when `filePath` lives under one of the omp config/agent roots. */ diff --git a/lib/file-authorization.test.mjs b/lib/file-authorization.test.mjs new file mode 100644 index 000000000..79c5db21e --- /dev/null +++ b/lib/file-authorization.test.mjs @@ -0,0 +1,129 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { createJiti } from "jiti"; + +// Regression tests for bug hunt round 1 (security area): the generic file +// API must never serve omp-web's own auth material, and a symlink must not +// launder a denied file into a browsable one. Synthetic fixtures only. +const jiti = createJiti(import.meta.url, { + alias: { "@/": new URL("../", import.meta.url).pathname }, +}); + +async function setup(t) { + const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "omp-web-file-authz-"))); + const agentDir = path.join(base, "agent"); + const ws = path.join(base, "ws"); + const outside = path.join(base, "outside"); + fs.mkdirSync(path.join(agentDir, "sessions", "-project"), { recursive: true }); + fs.mkdirSync(path.join(agentDir, "omp-web"), { recursive: true }); + fs.mkdirSync(ws, { recursive: true }); + fs.mkdirSync(outside, { recursive: true }); + const previousAgentDir = process.env.PI_CODING_AGENT_DIR; + const previousHome = process.env.HOME; + process.env.PI_CODING_AGENT_DIR = agentDir; + process.env.HOME = base; + delete process.env.PI_CONFIG_DIR; + delete process.env.XDG_DATA_HOME; + t.after(() => { + if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + if (previousHome === undefined) delete process.env.HOME; + else process.env.HOME = previousHome; + globalThis.__piAllowedRootsCache = undefined; + globalThis.__piSessionListCache = undefined; + globalThis.__piSessionListPromise = undefined; + fs.rmSync(base, { recursive: true, force: true }); + }); + const fa = await jiti.import("./file-access.ts"); + const fz = await jiti.import("./file-authorization.ts"); + const { invalidateSessionListCache } = await jiti.import("./session-reader.ts"); + fa.allowFileRoot(ws); + globalThis.__piAllowedRootsCache = undefined; + invalidateSessionListCache(); + const segs = (p) => p.split("/").filter(Boolean); + return { base, agentDir, ws, outside, fa, fz, segs, invalidateSessionListCache }; +} + +function writeSessionFile(dir, name, header, entries = []) { + const lines = [JSON.stringify({ type: "session", version: 3, ...header })]; + for (const entry of entries) lines.push(JSON.stringify(entry)); + fs.writeFileSync(path.join(dir, name), `${lines.join("\n")}\n`); +} + +test("denies direct reads of omp-web auth material under the agent dir", async (t) => { + const { agentDir, fz, segs } = await setup(t); + fs.writeFileSync(path.join(agentDir, "omp-web", "web-auth-secret.json"), JSON.stringify({ salt: "S", key: "K" })); + fs.writeFileSync(path.join(agentDir, "web-service.env"), 'OMP_WEB_PASSWORD_HASH="scrypt$15$8$1$AAAA$BBBB"\n'); + fs.writeFileSync(path.join(agentDir, "omp-web", "notifications.db"), "SQLITE-FAKE"); + for (const p of [ + path.join(agentDir, "omp-web", "web-auth-secret.json"), + path.join(agentDir, "web-service.env"), + path.join(agentDir, "omp-web", "notifications.db"), + ]) { + const decision = await fz.authorizeFileAccess(segs(p), null, false); + assert.equal(decision.ok, false, `${p} must be denied`); + assert.equal(decision.status, 403); + } +}); + +test("denies agent.db sidecars directly", async (t) => { + const { agentDir, fz, segs } = await setup(t); + for (const name of ["agent.db-wal", "agent.db-shm", "agent.db-journal"]) { + fs.writeFileSync(path.join(agentDir, name), "WAL-CREDENTIAL-BYTES"); + const decision = await fz.authorizeFileAccess(segs(path.join(agentDir, name)), null, false); + assert.equal(decision.ok, false, `${name} must be denied`); + assert.equal(decision.status, 403); + } +}); + +test("denies a denied file reached through a workspace symlink, and serves the realpath otherwise", async (t) => { + const { agentDir, ws, fz, segs } = await setup(t); + const agentDb = path.join(agentDir, "agent.db"); + const modelsYml = path.join(agentDir, "models.yml"); + fs.writeFileSync(agentDb, "SECRET-AGENT-DB"); + fs.writeFileSync(modelsYml, "apiKey: sk-SECRET\n"); + const linkDb = path.join(ws, "link.db"); + const linkYml = path.join(ws, "models-link.yml"); + fs.symlinkSync(agentDb, linkDb); + fs.symlinkSync(modelsYml, linkYml); + for (const link of [linkDb, linkYml]) { + const decision = await fz.authorizeFileAccess(segs(link), null, false); + assert.equal(decision.ok, false, `${link} must be denied`); + assert.equal(decision.status, 403); + } + // A benign symlink still resolves, and the decision names the real file. + const target = path.join(ws, "real.txt"); + fs.writeFileSync(target, "hello\n"); + const benignLink = path.join(ws, "alias.txt"); + fs.symlinkSync(target, benignLink); + const allowed = await fz.authorizeFileAccess(segs(benignLink), null, false); + assert.equal(allowed.ok, true); + assert.equal(allowed.filePath, target); +}); + +test("denies a denied file reached through a session-referenced symlink outside any root", async (t) => { + const { agentDir, outside, ws, fz, segs, invalidateSessionListCache } = await setup(t); + const agentDb = path.join(agentDir, "agent.db"); + fs.writeFileSync(agentDb, "SECRET-AGENT-DB"); + const link = path.join(outside, "ref.db"); + fs.symlinkSync(agentDb, link); + // A session whose transcript mentions the link: without the denied check + // running on the realpath first, the session-reference admission alone + // would let this through (it skips the existing-path root check). + // Session ids must be UUIDs for the reference check to run at all. + const sessionId = "123e4567-e89b-12d3-a456-426614174000"; + writeSessionFile(path.join(agentDir, "sessions", "-project"), "2026-01-01_ref.jsonl", { + id: sessionId, + cwd: ws, + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "m1", parentId: null, message: { role: "user", content: [{ type: "text", text: `please look at ${link}` }] } }, + ]); + invalidateSessionListCache(); + const decision = await fz.authorizeFileAccess(segs(link), sessionId, true); + assert.equal(decision.ok, false, "session-referenced symlink to agent.db must be denied"); + assert.equal(decision.status, 403); +}); diff --git a/lib/file-authorization.ts b/lib/file-authorization.ts index 40dd59eb2..fcbd114bc 100644 --- a/lib/file-authorization.ts +++ b/lib/file-authorization.ts @@ -65,7 +65,24 @@ export async function authorizeFileAccess( // store inside an allowed root. Deny those by name before anything can // stat, read or download them. Only paths outside the config roots are // exempt, so a workspace that happens to hold an `agent.db` still opens. - if (isUnderConfigRoot(filePath, getConfigAgentRoots()) && isConfigRootDeniedFile(filePath)) { + // + // Resolve symlinks BEFORE the denied check: a workspace symlink named + // `link.db` pointing at `/agent.db` otherwise passes the + // lexical name check, and the config root it lands in is itself an + // allowed root, so every later check passes too. The check runs on both + // the lexical and the real path, and before the session-reference + // admission below (which skips the existing-path root check), so neither + // route can launder a denied file. + let realFilePath = filePath; + try { + realFilePath = normalizeSlashes(fs.realpathSync(filePath)); + } catch { + // Nonexistent: keep the lexical path so the 404 below still fires. + } + const configRoots = getConfigAgentRoots(); + const underConfigRoot = + isUnderConfigRoot(filePath, configRoots) || isUnderConfigRoot(realFilePath, configRoots); + if (underConfigRoot && (isConfigRootDeniedFile(filePath) || isConfigRootDeniedFile(realFilePath))) { return ACCESS_DENIED; } const allowedByRoot = isFilePathAllowed(filePath, allowedRoots); @@ -85,5 +102,7 @@ export async function authorizeFileAccess( if (!allowedBySessionReference && !isExistingFilePathAllowed(filePath, allowedRoots)) { return ACCESS_DENIED; } - return { ok: true, filePath, stat }; + // Serve the resolved file, not the link: the caller must never observe a + // denied target through a differently-named path. + return { ok: true, filePath: realFilePath, stat }; } diff --git a/lib/models-config-route.test.mjs b/lib/models-config-route.test.mjs new file mode 100644 index 000000000..c35de2db4 --- /dev/null +++ b/lib/models-config-route.test.mjs @@ -0,0 +1,85 @@ +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { createJiti } from "jiti"; + +// Real /api/models-config against a throwaway agent dir. Bug hunt round 1: +// GET returned provider apiKeys in plaintext; PUT must preserve the stored +// key when the client echoes the masked placeholder back. +const jiti = createJiti(import.meta.url, { + tryNative: false, + alias: { "@/": new URL("../", import.meta.url).pathname }, +}); + +const agentDir = mkdtempSync(join(tmpdir(), "omp-web-models-route-")); +const previousAgentDir = process.env.PI_CODING_AGENT_DIR; +const previousXdg = process.env.XDG_DATA_HOME; +process.env.PI_CODING_AGENT_DIR = agentDir; +delete process.env.XDG_DATA_HOME; + +const route = await jiti.import("../app/api/models-config/route.ts"); +const lib = await jiti.import("./omp/models-config.ts"); + +const MODELS_YML = `providers: + acme: + baseUrl: https://example.invalid/v1 + apiKey: sk-LIVE-KEY-123 + models: + - id: acme-1 + api: openai-completions +`; + +test("GET masks apiKey and PUT with the placeholder preserves the stored key", async (t) => { + mkdirSync(agentDir, { recursive: true }); + writeFileSync(join(agentDir, "models.yml"), MODELS_YML, "utf8"); + t.after(() => rmSync(join(agentDir, "models.yml"), { force: true })); + + const got = await (await route.GET()).json(); + assert.equal(got.providers.acme.apiKey, lib.MASKED_API_KEY); + assert.equal(got.providers.acme.baseUrl, "https://example.invalid/v1"); + + // Save an unrelated edit while echoing the placeholder back. + const put = await route.PUT(new Request("http://localhost/api/models-config", { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ ...got, providers: { acme: { ...got.providers.acme, models: [{ id: "acme-1", api: "openai-completions", maxTokens: 2048 }] } } }), + })); + assert.equal(put.status, 200); + const onDisk = readFileSync(join(agentDir, "models.yml"), "utf8"); + assert.match(onDisk, /sk-LIVE-KEY-123/); + assert.match(onDisk, /maxTokens: 2048/); + + // A genuinely new key overwrites the stored one. + const put2 = await route.PUT(new Request("http://localhost/api/models-config", { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ providers: { acme: { baseUrl: "https://example.invalid/v1", apiKey: "sk-NEW-KEY-456", models: [{ id: "acme-1", api: "openai-completions", maxTokens: 2048 }] } } }), + })); + assert.equal(put2.status, 200); + assert.match(readFileSync(join(agentDir, "models.yml"), "utf8"), /sk-NEW-KEY-456/); +}); + +test("PUT never persists the masked placeholder as a key", async (t) => { + mkdirSync(agentDir, { recursive: true }); + writeFileSync(join(agentDir, "models.yml"), MODELS_YML, "utf8"); + t.after(() => rmSync(join(agentDir, "models.yml"), { force: true })); + // A brand-new provider submitted with the placeholder: no stored key to + // restore, so the placeholder must be dropped rather than written. + const put = await route.PUT(new Request("http://localhost/api/models-config", { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ providers: { brand: { baseUrl: "https://example.invalid/v1", apiKey: lib.MASKED_API_KEY, auth: "none" } } }), + })); + assert.equal(put.status, 200); + assert.doesNotMatch(readFileSync(join(agentDir, "models.yml"), "utf8"), new RegExp(lib.MASKED_API_KEY)); +}); + +test("teardown restores the environment", () => { + if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + if (previousXdg === undefined) delete process.env.XDG_DATA_HOME; + else process.env.XDG_DATA_HOME = previousXdg; + rmSync(agentDir, { recursive: true, force: true }); +}); diff --git a/lib/omp/models-config.test.mjs b/lib/omp/models-config.test.mjs index 9e907d969..6a68f4591 100644 --- a/lib/omp/models-config.test.mjs +++ b/lib/omp/models-config.test.mjs @@ -7,8 +7,11 @@ import { createJiti } from "jiti"; const jiti = createJiti(import.meta.url); const { + MASKED_API_KEY, ModelsConfigParseError, + maskModelsConfigApiKeys, readModelsConfigFile, + restoreModelsConfigApiKeys, serializeModelsConfig, validateModelsConfig, writeModelsConfig, @@ -229,3 +232,57 @@ test("ignores blank model rows while preserving non-empty rows", () => { assert.deepEqual(readModelsConfigFile().config.providers.p.models.map((model) => model.id), ["valid"]); }); }); + +test("masks provider apiKeys for GET and restores the stored key on PUT", () => { + // Bug hunt round 1: GET /api/models-config returned models.yml verbatim, + // defeating the file API's models.yml denial — the route must redact. + const stored = { + providers: { + acme: { + baseUrl: "https://example.invalid/v1", + apiKey: "sk-LIVE-KEY-123", + models: [{ id: "acme-1", api: "openai-completions" }], + }, + keyless: { baseUrl: "https://example.invalid/v1", auth: "none" }, + }, + }; + const masked = maskModelsConfigApiKeys(stored); + assert.equal(masked.providers.acme.apiKey, MASKED_API_KEY); + assert.notEqual(masked.providers.acme.apiKey, "sk-LIVE-KEY-123"); + assert.equal(masked.providers.acme.baseUrl, "https://example.invalid/v1"); + assert.equal(masked.providers.acme.models[0].id, "acme-1"); + assert.equal("apiKey" in masked.providers.keyless, false); + // Masking must not mutate the stored config. + assert.equal(stored.providers.acme.apiKey, "sk-LIVE-KEY-123"); + + // Sending the placeholder back preserves the stored key. + const restored = restoreModelsConfigApiKeys(masked, stored); + assert.equal(restored.providers.acme.apiKey, "sk-LIVE-KEY-123"); + // A genuinely new value overwrites. + const changed = restoreModelsConfigApiKeys( + { providers: { acme: { ...masked.providers.acme, apiKey: "sk-NEW-KEY-456" } } }, + stored, + ); + assert.equal(changed.providers.acme.apiKey, "sk-NEW-KEY-456"); + // A placeholder with no stored key must never be persisted as a key. + const fresh = restoreModelsConfigApiKeys( + { providers: { brand: { baseUrl: "https://example.invalid/v1", apiKey: MASKED_API_KEY } } }, + stored, + ); + assert.equal("apiKey" in fresh.providers.brand, false); +}); + +test("a masked round trip through writeModelsConfig keeps the real key on disk", () => { + withAgentDir((dir, path) => { + mkdirSync(dir, { recursive: true }); + writeFileSync(path, "providers:\n acme:\n baseUrl: https://example.invalid/v1\n apiKey: sk-LIVE-KEY-123\n models:\n - id: acme-1\n api: openai-completions\n", "utf8"); + const stored = readModelsConfigFile().config; + const masked = maskModelsConfigApiKeys(stored); + masked.providers.acme.models[0].maxTokens = 4096; + writeModelsConfig(restoreModelsConfigApiKeys(masked, stored)); + const reread = readFileSync(path, "utf8"); + assert.match(reread, /sk-LIVE-KEY-123/); + assert.doesNotMatch(reread, new RegExp(MASKED_API_KEY.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); + assert.match(reread, /maxTokens: 4096/); + }); +}); diff --git a/lib/omp/models-config.ts b/lib/omp/models-config.ts index 282a7e0bf..bd37a62a5 100644 --- a/lib/omp/models-config.ts +++ b/lib/omp/models-config.ts @@ -135,6 +135,49 @@ function sanitizeModelsConfig(config: ModelsFileConfig): ModelsFileConfig { return { ...config, providers }; } +/** + * Placeholder GET /api/models-config returns in place of a real `apiKey`. + * The file API denies models.yml outright on the grounds that the + * purpose-built route "redacts what it returns" — returning the key + * verbatim defeated that denial, so the route must never emit a real key. + * The placeholder is never a valid key: PUT restores the stored key when + * it sees it, and drops it when there is nothing stored to restore, so it + * can never be persisted to disk. + */ +export const MASKED_API_KEY = "••••••••"; + +/** Copy of a config with every provider `apiKey` replaced by the placeholder. */ +export function maskModelsConfigApiKeys(config: ModelsFileConfig): ModelsFileConfig { + if (!isRecord(config.providers)) return config; + const providers = Object.fromEntries(Object.entries(config.providers).map(([providerId, provider]) => { + if (!isRecord(provider) || typeof provider.apiKey !== "string" || provider.apiKey === "") return [providerId, provider]; + return [providerId, { ...provider, apiKey: MASKED_API_KEY }]; + })); + return { ...config, providers }; +} + +/** + * Undo masking on a client-submitted config: a placeholder echoes the stored + * key back, a genuinely new value overwrites it, and a placeholder with no + * stored key is dropped (validation then rejects providers that need a key + * rather than saving the placeholder as one). + */ +export function restoreModelsConfigApiKeys(config: ModelsFileConfig, stored: ModelsFileConfig): ModelsFileConfig { + if (!isRecord(config.providers)) return config; + const storedProviders = isRecord(stored.providers) ? stored.providers : {}; + const providers = Object.fromEntries(Object.entries(config.providers).map(([providerId, provider]) => { + if (!isRecord(provider) || provider.apiKey !== MASKED_API_KEY) return [providerId, provider]; + const storedProvider = storedProviders[providerId]; + if (isRecord(storedProvider) && typeof storedProvider.apiKey === "string" && storedProvider.apiKey !== "") { + return [providerId, { ...provider, apiKey: storedProvider.apiKey }]; + } + const rest = { ...provider }; + delete rest.apiKey; + return [providerId, rest]; + })); + return { ...config, providers }; +} + /** Read models.yml, reporting rather than swallowing parse failures. */ export function readModelsConfigFile(): ModelsConfigFile { const path = getModelsConfigPath(); diff --git a/lib/omp/settings-config.test.mjs b/lib/omp/settings-config.test.mjs index ee78887e8..a2cd8d068 100644 --- a/lib/omp/settings-config.test.mjs +++ b/lib/omp/settings-config.test.mjs @@ -169,3 +169,39 @@ test("does not expose malformed skills.showStartupDiagnostics values", () => { assert.equal(readNativeSettings().settings.skills?.showStartupDiagnostics, undefined); }); }); + +test("refuses unvalidated keys instead of writing them into omp's config.yml", () => { + // Bug hunt round 1: writeNativeSettings looped every key of the advisor, + // retry, compaction, memory, autolearn, mnemopi and mcp sections into the + // document while validation only covered known keys. + withAgentDir((dir) => { + writeFileSync(join(dir, "config.yml"), "defaultThinkingLevel: medium\n", "utf8"); + const before = readFileSync(join(dir, "config.yml"), "utf8"); + for (const settings of [ + { advisor: { evilFlag: true } }, + { mcp: { evilKey: "pwned", notificationDebounceMs: 5 } }, + { retry: { evilRetry: true } }, + { compaction: { evilCompaction: true } }, + { memory: { evilMemory: true } }, + { autolearn: { evilLearn: true } }, + { mnemopi: { evilMnemopi: true } }, + ]) { + assert.throws(() => writeNativeSettings(settings), /Unsupported .* setting/); + } + assert.equal(readFileSync(join(dir, "config.yml"), "utf8"), before, "no unvalidated key may persist"); + // Known keys alongside still write. + writeNativeSettings({ mcp: { notificationDebounceMs: 5 }, advisor: { enabled: true } }); + const after = readFileSync(join(dir, "config.yml"), "utf8"); + assert.match(after, /notificationDebounceMs: 5/); + assert.match(after, /enabled: true/); + }); +}); + +test("refuses unvalidated keys when starting from an empty config document", () => { + withAgentDir((dir) => { + assert.throws(() => writeNativeSettings({ mcp: { evilKey: "pwned" } }), /Unsupported .* setting/); + assert.equal(existsSync(join(dir, "config.yml")), false, "a rejected write must not create the file"); + writeNativeSettings({ hideThinkingBlock: true }); + assert.match(readFileSync(join(dir, "config.yml"), "utf8"), /hideThinkingBlock: true/); + }); +}); diff --git a/lib/omp/settings-config.ts b/lib/omp/settings-config.ts index 13df6fc28..2830a3d80 100644 --- a/lib/omp/settings-config.ts +++ b/lib/omp/settings-config.ts @@ -179,6 +179,63 @@ export function readNativeSettings(): { path: string; settings: NativeSettings } }; } +/** + * The only keys writeNativeSettings may write, per section — mirroring the + * read allowlist in readNativeSettings. Validation below type-checks known + * keys but used to loop every key of these sections straight into the + * document, so an unvalidated key (e.g. `mcp.evilKey`) persisted into omp's + * config.yml. Unknown keys are rejected, never silently written. + */ +const SECTION_KEYS: Record = { + advisor: ["enabled", "subagents", "syncBacklog", "immuneTurns"], + retry: ["enabled", "maxRetries", "modelFallback", "fallbackRevertPolicy", "fallbackChains"], + compaction: ["enabled", "midTurnEnabled", "methodOrder", "autoContinue", "keepRecentTokens"], + memory: ["backend"], + autolearn: ["enabled", "autoContinue", "minToolCalls"], + mnemopi: ["scoping", "autoRecall", "autoRetain", "noEmbeddings"], + mcp: ["enableProjectConfig", "renderMarkdownResults", "notifications", "notificationDebounceMs"], +}; + +function assertSectionKeys(section: string, value: unknown): void { + if (value === undefined) return; + const allowed = new Set(SECTION_KEYS[section]); + for (const key of Object.keys(value as Record)) { + if (!allowed.has(key)) throw new Error(`Unsupported ${section} setting: ${key}`); + } +} + +/** Copy of `settings` containing only keys writeNativeSettings may persist. */ +function filteredSettings(settings: NativeSettings): NativeSettings { + const out: NativeSettings = {}; + for (const key of ["defaultThinkingLevel", "hideThinkingBlock", "externalThinking", "textVerbosity", "personality", "enabledModels", "disabledProviders", "modelProviderOrder"] as const) { + if (settings[key] !== undefined) (out as Record)[key] = settings[key]; + } + if (settings.providers?.autoThinkingSource !== undefined) { + out.providers = { autoThinkingSource: settings.providers.autoThinkingSource }; + } + for (const section of Object.keys(SECTION_KEYS)) { + const value = (settings as Record)[section]; + if (!isRecord(value)) continue; + const allowed = new Set(SECTION_KEYS[section]); + const kept = Object.fromEntries(Object.entries(value).filter(([key]) => allowed.has(key))); + if (Object.keys(kept).length > 0) (out as Record)[section] = kept; + } + if (settings.tools) { + const approval = settings.tools.approval; + out.tools = { + ...(settings.tools.approvalMode !== undefined ? { approvalMode: settings.tools.approvalMode } : {}), + ...(approval && (approval.bash !== undefined || approval.extension !== undefined) ? { approval: { + ...(approval.bash !== undefined ? { bash: approval.bash } : {}), + ...(approval.extension !== undefined ? { extension: approval.extension } : {}), + } } : {}), + }; + } + if (settings.skills?.showStartupDiagnostics !== undefined) { + out.skills = { showStartupDiagnostics: settings.skills.showStartupDiagnostics }; + } + return out; +} + /** Validates and applies a reviewed subset of OMP's global config schema. */ export function writeNativeSettings(settings: NativeSettings): void { if (!isRecord(settings)) throw new Error("Settings must be an object"); @@ -244,12 +301,17 @@ export function writeNativeSettings(settings: NativeSettings): void { for (const [key, values] of Object.entries({ enabledModels: settings.enabledModels, disabledProviders: settings.disabledProviders, modelProviderOrder: settings.modelProviderOrder })) { if (values !== undefined && (!Array.isArray(values) || values.some((value) => typeof value !== "string" || !value.trim()))) throw new Error(`${key} must contain non-empty strings`); } + for (const section of Object.keys(SECTION_KEYS)) { + assertSectionKeys(section, (settings as Record)[section]); + } const { path, doc } = readDocument(); mkdirSync(dirname(path), { recursive: true }); if (doc.contents === null) { + // An empty document used to stringify the caller's object verbatim, + // persisting every unknown key with it; write only the allowlisted copy. const temp = `${path}.tmp-${process.pid}-${Date.now()}`; - writeFileSync(temp, stringify(settings), "utf8"); + writeFileSync(temp, stringify(filteredSettings(settings)), "utf8"); renameSync(temp, path); return; } diff --git a/lib/plugins-route.test.mjs b/lib/plugins-route.test.mjs new file mode 100644 index 000000000..ca383f49b --- /dev/null +++ b/lib/plugins-route.test.mjs @@ -0,0 +1,60 @@ +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { createJiti } from "jiti"; + +// Real /api/plugins POST against a throwaway cwd. Bug hunt round 1: a +// source starting with "-" was passed straight to `omp plugin …`, so it +// was parsed as CLI options instead of a plugin name (same class of bug the +// skills-install route already rejects). +const jiti = createJiti(import.meta.url, { + tryNative: false, + alias: { "@/": new URL("../", import.meta.url).pathname }, +}); + +const route = await jiti.import("../app/api/plugins/route.ts"); +const fa = await jiti.import("./file-access.ts"); + +async function setup(t) { + const base = mkdtempSync(join(tmpdir(), "omp-web-plugins-route-")); + const agentDir = join(base, "agent"); + const cwd = join(base, "ws"); + mkdirSync(join(agentDir, "sessions"), { recursive: true }); + mkdirSync(cwd, { recursive: true }); + const previousAgentDir = process.env.PI_CODING_AGENT_DIR; + const previousXdg = process.env.XDG_DATA_HOME; + process.env.PI_CODING_AGENT_DIR = agentDir; + delete process.env.XDG_DATA_HOME; + globalThis.__piAllowedRootsCache = undefined; + fa.allowFileRoot(cwd); + globalThis.__piAllowedRootsCache = undefined; + t.after(() => { + if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + if (previousXdg === undefined) delete process.env.XDG_DATA_HOME; + else process.env.XDG_DATA_HOME = previousXdg; + globalThis.__piAllowedRootsCache = undefined; + rmSync(base, { recursive: true, force: true }); + }); + const post = (body) => route.POST(new Request("http://localhost/api/plugins", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + })); + return { cwd, post }; +} + +test("rejects a plugin source starting with a dash for every source-taking action", async (t) => { + const { cwd, post } = await setup(t); + for (const action of ["install", "remove", "enable", "disable", "update"]) { + const res = await post({ action, source: "--force", cwd }); + assert.equal(res.status, 400, `${action} with --force source must be 400`); + const body = await res.json(); + assert.equal(body.code, "plugin_source_invalid"); + } + // A bare "-" is equally an option position, not a name. + const res = await post({ action: "install", source: "-", cwd }); + assert.equal(res.status, 400); +}); diff --git a/lib/session-export-route.test.mjs b/lib/session-export-route.test.mjs new file mode 100644 index 000000000..5a209f5ef --- /dev/null +++ b/lib/session-export-route.test.mjs @@ -0,0 +1,64 @@ +import assert from "node:assert/strict"; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { createJiti } from "jiti"; + +// Real /api/sessions/[id]/export against a stub omp binary and a synthetic +// session. Bug hunt round 1: exports were served `inline` from the +// authenticated origin with no sandboxing, so attacker-influenced transcript +// HTML (event-handler attributes) executed in omp-web's origin. Exports +// must now always download as an attachment, even when ?inline=1 is asked. +const jiti = createJiti(import.meta.url, { + tryNative: false, + alias: { "@/": new URL("../", import.meta.url).pathname }, +}); + +const base = mkdtempSync(join(tmpdir(), "omp-web-export-route-")); +const agentDir = join(base, "agent"); +const projectDir = join(agentDir, "sessions", "-project"); +mkdirSync(projectDir, { recursive: true }); +const stubOmp = join(base, "omp-stub.sh"); +writeFileSync(stubOmp, "#!/bin/sh\nprintf '%s' '' > \"$3\"\n"); +chmodSync(stubOmp, 0o755); + +const previousAgentDir = process.env.PI_CODING_AGENT_DIR; +const previousXdg = process.env.XDG_DATA_HOME; +const previousOmpBin = process.env.OMP_WEB_OMP_BIN; +process.env.PI_CODING_AGENT_DIR = agentDir; +delete process.env.XDG_DATA_HOME; +process.env.OMP_WEB_OMP_BIN = stubOmp; + +const route = await jiti.import("../app/api/sessions/[id]/export/route.ts"); +const { invalidateSessionListCache } = await jiti.import("./session-reader.ts"); + +const sessionLines = [ + JSON.stringify({ type: "session", version: 3, id: "exporttest", cwd: join(base, "ws"), timestamp: "2026-01-01T00:00:00.000Z" }), +]; +writeFileSync(join(projectDir, "2026-01-01_exporttest.jsonl"), `${sessionLines.join("\n")}\n`); +invalidateSessionListCache(); + +const getExport = (query) => route.GET( + new Request(`http://localhost/api/sessions/exporttest/export${query}`), + { params: Promise.resolve({ id: "exporttest" }) }, +); + +test("serves exports as attachments even when inline is requested", async () => { + for (const query of ["?inline=1", ""]) { + const res = await getExport(query); + assert.equal(res.status, 200, `export${query} must succeed`); + assert.match(res.headers.get("Content-Disposition") ?? "", /^attachment;/, `export${query} must be attachment-only`); + assert.equal(await res.text(), ""); + } +}); + +test("teardown restores the environment", () => { + if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + if (previousXdg === undefined) delete process.env.XDG_DATA_HOME; + else process.env.XDG_DATA_HOME = previousXdg; + if (previousOmpBin === undefined) delete process.env.OMP_WEB_OMP_BIN; + else process.env.OMP_WEB_OMP_BIN = previousOmpBin; + rmSync(base, { recursive: true, force: true }); +});