From 0c319dc7aeacc898c3fc94a9445ce1a376ad1150 Mon Sep 17 00:00:00 2001 From: K <61059522+kahme247@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:43:18 +0200 Subject: [PATCH] =?UTF-8?q?fix(security):=20close=20round-1=20bug-hunt=20f?= =?UTF-8?q?indings=20=E2=80=94=20auth-material=20disclosure=20(rework=20of?= =?UTF-8?q?=20#295)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/models-config/route.ts | 21 +++- app/api/models-config/test/route.ts | 19 ++-- app/api/plugins/route.ts | 7 ++ app/api/sessions/[id]/export/route.ts | 17 ++- components/AppShell.tsx | 14 ++- components/ModelsConfig.tsx | 1 + components/ui/field.tsx | 10 +- lib/file-access.test.mjs | 34 ++++++ lib/file-access.ts | 28 +++++ lib/file-authorization.test.mjs | 119 +++++++++++++++++++++ lib/models-config-route.test.mjs | 116 ++++++++++++++++++++ lib/omp/models-config.test.mjs | 123 +++++++++++++++++++++ lib/omp/models-config.ts | 147 ++++++++++++++++++++++++++ lib/omp/settings-config.test.mjs | 36 +++++++ lib/omp/settings-config.ts | 61 ++++++++++- lib/plugins-route.test.mjs | 52 +++++++++ lib/session-export-route.test.mjs | 71 +++++++++++++ 17 files changed, 855 insertions(+), 21 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 a9ecb4b33..750df3135 100644 --- a/app/api/models-config/route.ts +++ b/app/api/models-config/route.ts @@ -3,11 +3,14 @@ import { invalidateModelsCache } from "@/lib/models-cache"; import { disposeUtilityRpc } from "@/lib/omp/rpc-utility"; import { ModelsConfigParseError, + maskModelsConfigApiKeys, readModelsConfigFile, + restoreModelsConfigApiKeys, validateModelsConfig, writeModelsConfig, type ModelsFileConfig, } from "@/lib/omp/models-config"; +import { isRecord } from "@/lib/type-guards"; export async function GET() { const file = readModelsConfigFile(); @@ -21,7 +24,9 @@ export async function GET() { code: "models_config_unparseable", }); } - return Response.json(file.config); + // Never emit a real credential: the file API denies models.yml outright, + // and this route is the scoped alternative to that denial. + return Response.json(maskModelsConfigApiKeys(file.config)); } // PUT /api/models-config[?overwrite=true] @@ -30,13 +35,23 @@ export async function PUT(req: Request) { try { const overwriteUnparseable = new URL(req.url).searchParams.get("overwrite") === "true"; const body = await req.json() as ModelsFileConfig; + // A null body is a client error, not a server one: the restore step + // below used to throw on it, turning a 400 into a 500. + if (!isRecord(body)) { + return Response.json({ error: "Config must be an object" }, { status: 400 }); + } + // The editor echoes masked credentials back on every save; restore the + // stored values 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 Response.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 Response.json( diff --git a/app/api/models-config/test/route.ts b/app/api/models-config/test/route.ts index e576c1091..8520b62ed 100644 --- a/app/api/models-config/test/route.ts +++ b/app/api/models-config/test/route.ts @@ -2,10 +2,12 @@ import { mkdtempSync, rmSync, writeFileSync } from "fs"; import { tmpdir } from "os"; import { join } from "path"; import { - type ModelDefinition, - type ProviderConfig, + readModelsConfigFile, + restoreModelsConfigApiKeys, serializeModelsConfig, validateModelsConfig, + type ModelDefinition, + type ProviderConfig, } from "@/lib/omp/models-config"; import { type OmpModel, runIsolatedUtilityCommand } from "@/lib/omp/rpc-utility"; import { isRecord } from "@/lib/type-guards"; @@ -31,12 +33,17 @@ export async function POST(req: Request) { const modelId = typeof body.model.id === "string" ? body.model.id.trim() : ""; if (!modelId) return Response.json({ ok: false, error: "Model ID is required", code: "model_id_required" }, { status: 400 }); + // The editor shows masked placeholders for stored credentials; testing a + // provider without retyping its key must still test the real ones. + const restored = restoreModelsConfigApiKeys( + { providers: { [providerName]: { ...(body.provider as ProviderConfig), models: [{ ...(body.model as ModelDefinition), id: modelId }] } } }, + readModelsConfigFile().config, + ); + const restoredProvider = restored.providers?.[providerName]; + if (!restoredProvider) return Response.json({ ok: false, error: "provider is required", code: "provider_required" }, { status: 400 }); const config = { providers: { - [providerName]: { - ...(body.provider as ProviderConfig), - models: [{ ...(body.model as ModelDefinition), id: modelId }], - }, + [providerName]: restoredProvider, }, }; try { diff --git a/app/api/plugins/route.ts b/app/api/plugins/route.ts index 2e76178d6..70794407d 100644 --- a/app/api/plugins/route.ts +++ b/app/api/plugins/route.ts @@ -294,6 +294,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 Response.json({ error: "Invalid plugin source", code: "plugin_source_invalid" }, { status: 400 }); + } const scopeArgs = scope === "project" ? ["--scope", "project"] : []; const dir = cwd ?? ensureAgentDir(); diff --git a/app/api/sessions/[id]/export/route.ts b/app/api/sessions/[id]/export/route.ts index 657016bd6..445320654 100644 --- a/app/api/sessions/[id]/export/route.ts +++ b/app/api/sessions/[id]/export/route.ts @@ -1,6 +1,5 @@ import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; import { getContentDisposition } from "@/lib/content-disposition"; -import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; /** Render a session to self-contained HTML with the omp binary on its host (`omp --export`). */ export async function GET( @@ -8,19 +7,27 @@ 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 resolveSessionHostOr404(id); if ("response" in resolved) return resolved.response; const result = await resolved.host.sessionOps.exportSession(id); if (!result.ok) return opErrorResponse(result); - // Another host's HTML is untrusted: opened inline it would run on this origin. This machine's daemon is the server's own. - const asInline = inline && resolved.host.id === LOCAL_HOST_ID; + // 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. That holds for this machine's daemon too, not just remote + // hosts: the HTML is the exporter's output either way. A route-level + // sandboxed CSP cannot fix this: finalizeResponse (server/http.ts) + // overwrites a handler's security headers with the global CSP, whose + // `script-src` includes `unsafe-inline`. Downloading keeps the feature + // working without ever rendering untrusted HTML as omp-web. return new Response(result.value.html, { headers: { "Content-Type": "text/html; charset=utf-8", - "Content-Disposition": getContentDisposition(result.value.fileName, asInline, "session.html"), + "Content-Disposition": getContentDisposition(result.value.fileName, false, "session.html"), "Cache-Control": "no-cache", }, }); diff --git a/components/AppShell.tsx b/components/AppShell.tsx index 85795fb82..9fdefd1d6 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -1876,11 +1876,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/components/ModelsConfig.tsx b/components/ModelsConfig.tsx index dd82b9833..81d7572c9 100644 --- a/components/ModelsConfig.tsx +++ b/components/ModelsConfig.tsx @@ -245,6 +245,7 @@ function ProviderDetail({ name, provider, onChange, onRename, onDelete }: { onBlurValidate={apiKeyV.onBlur} showLabel={t("modelsConfig.showApiKey")} hideLabel={t("modelsConfig.hideApiKey")} + selectAllOnFocus /> diff --git a/components/ui/field.tsx b/components/ui/field.tsx index 39379f96f..c2525c54c 100644 --- a/components/ui/field.tsx +++ b/components/ui/field.tsx @@ -372,6 +372,10 @@ interface SecretInputProps { showLabel: string; hideLabel: string; id?: string; + /** Select the whole value on focus, so typing replaces it instead of + * appending to it — a stored credential is shown as its masked + * placeholder, and appending a new key to the placeholder corrupts it. */ + selectAllOnFocus?: boolean; } export function SecretInput({ @@ -385,6 +389,7 @@ export function SecretInput({ showLabel, hideLabel, id, + selectAllOnFocus, }: SecretInputProps) { const [visible, setVisible] = useState(false); const [focused, setFocused] = useState(false); @@ -406,7 +411,10 @@ export function SecretInput({ autoComplete="off" spellCheck={false} aria-invalid={isInvalid || undefined} - onFocus={() => setFocused(true)} + onFocus={(e) => { + setFocused(true); + if (selectAllOnFocus) e.currentTarget.select(); + }} onBlur={() => { setFocused(false); onBlurValidate?.(); diff --git a/lib/file-access.test.mjs b/lib/file-access.test.mjs index 57ef74436..38ede71ea 100644 --- a/lib/file-access.test.mjs +++ b/lib/file-access.test.mjs @@ -335,6 +335,40 @@ test("only omp's own credential files are denied, not files of the same name els assert.equal(isOmpSecretFile(path.join(getConfigRoot(), "profiles", "work", "agent", "sessions", "agent.db")), false); }); +test("denies omp-web's own auth material under the agent dir, not the viewable neighbours", async (t) => { + // Bug hunt round 1 (#295): the generic file API served the session-signing + // key, the daemon bearer token, the VAPID private key's database and the + // password hash straight out of the agent dir, whose root is browsable. + // Scoped by name AND location: the same names in a workspace, an upload or + // a package dir stay readable, as do omp-web's deliberately viewable files. + const { agent, profile, workspace, put } = await secretFileFixture(t); + const secrets = [ + "omp-web/web-auth-secret.json", + "omp-web/web-auth-secret.json.bak", + "omp-web/notifications.db", + "omp-web/notifications.db-wal", + "omp-web/notifications.db-shm", + "omp-web/notifications.db-journal", + "omp-web/host.json", + "web-service.env", + ]; + for (const name of secrets) { + for (const dir of [agent, profile]) { + const file = put(dir, name); + for (const type of ["read", "download", "meta"]) { + assert.equal((await secretFileRoute(file, type)).status, 403, `${file} ${type}`); + } + } + } + for (const name of ["hosts.json", "transport-metrics.jsonl", "upload-retention.json", "host-running.json"]) { + assert.equal((await secretFileRoute(put(agent, `omp-web/${name}`))).status, 200, `omp-web/${name} stays viewable`); + } + for (const name of ["notifications.db", "web-auth-secret.json", "host.json", "web-service.env"]) { + assert.equal((await secretFileRoute(put(workspace, name))).status, 200, `workspace/${name} stays readable`); + assert.equal((await secretFileRoute(put(agent, `sessions/p/s/local/uploads/${name}`))).status, 200, `uploads/${name} stays readable`); + } +}); + test("a symlinked agent dir does not let its credential files through under their real path", async (t) => { const { authorizeFileAccess } = await import("./file-authorization.ts"); const previousAgentDir = process.env.PI_CODING_AGENT_DIR; diff --git a/lib/file-access.ts b/lib/file-access.ts index 04911c387..193dce5ee 100644 --- a/lib/file-access.ts +++ b/lib/file-access.ts @@ -88,6 +88,17 @@ export function getConfigAgentRoots(): string[] { */ const OMP_ENV_NAME = /^\.env(?:\.|$)/i; const OMP_SECRET_NAME = /^(?:\.?agent\.db(?:[-.~].*)?|\.?models\.(?:yml|yaml|json)(?:[.~].*|-(?:backup|bak|old)(?:[.~-].*)?)?|\.env(?:\..*)?)$/i; +/** omp-web's own auth material (#295): the session-signing key + * (`web-auth-secret.json`), the daemon bearer token (`host.json`), the VAPID + * private key's database (`notifications.db`, SQLite sidecars included) and + * the password hash (`web-service.env`). They live one level below the + * directories the loop below scans — `/omp-web/`, with + * `web-service.env` directly in the agent dir — so they need their own + * scoped check. Deliberately NOT a blanket ".db under a config root" rule: + * an unrelated database under a config root stays readable (#394), and the + * deliberately viewable omp-web files (`hosts.json`, + * `transport-metrics.jsonl`, ...) keep their names out of this list. */ +const OMP_WEB_SECRET_NAME = /^(?:web-auth-secret\.json|host\.json|notifications\.db|web-service\.env)(?:[-.~].*)?$/i; const credentialPolicyUnavailable = () => new HostOpError(503, "credential_policy_unavailable", "Credential exclusions cannot be verified while their filesystem metadata is unreadable"); /** Request metadata failures retain a 404; incomplete credential ownership metadata throws a 503. */ @@ -106,6 +117,23 @@ export function isOmpSecretFile(filePath: string): boolean { const agentDirs = [getAgentDir(), ...configDirs.map((dir) => path.join(dir, "agent"))]; const requestedIdentity = fileIdentity(filePath, markRequestUnavailable); const identity = requestedIdentity && requestedIdentity.nlink > 1 && requestedIdentity.ino > 0 ? requestedIdentity : null; + if (OMP_WEB_SECRET_NAME.test(name)) { + const parent = comparablePath(path.dirname(requested)); + if (name.toLowerCase().startsWith("web-service.env")) { + // web-service.env lives directly in the agent dir (bin/service-env.js: + // PI_CODING_AGENT_DIR, else ~/.omp/agent) — never in a workspace. + for (const dir of new Set([...agentDirs, ...configDirs])) { + if (parent === comparablePath(resolvedOrSelf(dir, markUnavailable))) return true; + } + } else { + // The signing key, the daemon token and the notification store live in + // /omp-web/ (lib/web-auth-secret.ts, lib/hosts/host-login.ts, + // lib/notification-store.ts), including profile agent dirs. + for (const dir of agentDirs) { + if (parent === comparablePath(resolvedOrSelf(path.join(dir, "omp-web"), markUnavailable))) return true; + } + } + } for (const dir of new Set([...agentDirs, ...configDirs])) { const agentDir = agentDirs.includes(dir); const namePattern = agentDir ? OMP_SECRET_NAME : OMP_ENV_NAME; diff --git a/lib/file-authorization.test.mjs b/lib/file-authorization.test.mjs new file mode 100644 index 000000000..ae78ea668 --- /dev/null +++ b/lib/file-authorization.test.mjs @@ -0,0 +1,119 @@ +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"; + +// Regression tests for bug hunt round 1 (#295), security area: the generic +// file API must never serve omp's credential files, and a symlink — or a +// symlinked config root — must not launder a denied file into a browsable +// one. Synthetic fixtures only. +const { authorizeFileAccess } = await import("./file-authorization.ts"); +const { invalidateSessionListCache } = await import("./session-reader.ts"); + +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`); +} + +const segs = (p) => p.split("/").filter(Boolean); + +test("denies a session-referenced models.yml under a symlinked config root", async (t) => { + // Review item 5 (#295): getConfigAgentRoots() used to return lexical + // paths, so a denied file under a symlinked configured root could slip + // past the denied check and be admitted by the session-reference branch. + // The secret policy is canonical now (resolved-path/inode checks, #394); + // this pins that a symlinked root still denies. + const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "omp-web-file-authz-"))); + const realConfig = path.join(base, "real-config"); + const agentDir = path.join(realConfig, "agent"); + const ws = path.join(base, "ws"); + fs.mkdirSync(path.join(agentDir, "sessions", "-project"), { recursive: true }); + fs.mkdirSync(ws, { recursive: true }); + fs.symlinkSync(realConfig, path.join(base, "config"), "dir"); + const previous = { + agentDir: process.env.PI_CODING_AGENT_DIR, + home: process.env.HOME, + configDir: process.env.PI_CONFIG_DIR, + xdg: process.env.XDG_DATA_HOME, + }; + delete process.env.PI_CODING_AGENT_DIR; + process.env.HOME = base; + process.env.PI_CONFIG_DIR = "config"; + delete process.env.XDG_DATA_HOME; + t.after(() => { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + invalidateSessionListCache(); + fs.rmSync(base, { recursive: true, force: true }); + }); + + // The file lives under the real root; the session references the lexical + // (symlinked) spelling, which is outside every lexical config root. + const modelsYml = path.join(agentDir, "models.yml"); + fs.writeFileSync(modelsYml, "apiKey: sk-SECRET\n"); + const lexical = path.join(base, "config", "agent", "models.yml"); + 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 ${lexical}` }] } }, + ]); + invalidateSessionListCache(); + const decision = await authorizeFileAccess(segs(lexical), sessionId, true, new Set([ws])); + assert.equal(decision.ok, false, "session-referenced models.yml under a symlinked root must be denied"); + assert.equal(decision.status, 403); +}); + +test("denies a denied file reached through a session-referenced symlink outside any root", async (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(ws, { recursive: true }); + fs.mkdirSync(outside, { recursive: true }); + const previous = { + agentDir: process.env.PI_CODING_AGENT_DIR, + home: process.env.HOME, + configDir: process.env.PI_CONFIG_DIR, + xdg: process.env.XDG_DATA_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(() => { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + invalidateSessionListCache(); + fs.rmSync(base, { recursive: true, force: true }); + }); + + 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). + 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 authorizeFileAccess(segs(link), sessionId, true, new Set([ws])); + assert.equal(decision.ok, false, "session-referenced symlink to agent.db must be denied"); + assert.equal(decision.status, 403); +}); diff --git a/lib/models-config-route.test.mjs b/lib/models-config-route.test.mjs new file mode 100644 index 000000000..0d51b8ff4 --- /dev/null +++ b/lib/models-config-route.test.mjs @@ -0,0 +1,116 @@ +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"; + +// Real /api/models-config against a throwaway agent dir. Bug hunt round 1 +// (#295): GET returned provider apiKeys — and credential headers — in +// plaintext; PUT must preserve the stored credentials when the client +// echoes the masked placeholders back. +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 import("../app/api/models-config/route.ts"); +const lib = await import("./omp/models-config.ts"); + +const MODELS_YML = `providers: + acme: + baseUrl: https://example.invalid/v1 + apiKey: sk-LIVE-KEY-123 + headers: + Authorization: Bearer LIVE-TOKEN + models: + - id: acme-1 + api: openai-completions + headers: + X-Model-Key: MODEL-SECRET +`; + +function put(body, init = {}) { + return route.PUT(new Request("http://localhost/api/models-config", { + method: "PUT", + headers: { "content-type": "application/json" }, + body: typeof body === "string" ? body : JSON.stringify(body), + ...init, + })); +} + +test("GET masks apiKey and headers, and PUT with the placeholders preserves the stored credentials", 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.headers.Authorization, lib.MASKED_API_KEY); + assert.equal(got.providers.acme.models[0].headers["X-Model-Key"], lib.MASKED_API_KEY); + assert.equal(got.providers.acme.baseUrl, "https://example.invalid/v1"); + assert.doesNotMatch(JSON.stringify(got), /sk-LIVE-KEY-123|LIVE-TOKEN|MODEL-SECRET/); + + // Save an unrelated edit while echoing the placeholders back. + const res = await put({ + ...got, + providers: { acme: { ...got.providers.acme, models: [{ id: "acme-1", api: "openai-completions", maxTokens: 2048, headers: got.providers.acme.models[0].headers }] } }, + }); + assert.equal(res.status, 200); + const onDisk = readFileSync(join(agentDir, "models.yml"), "utf8"); + assert.match(onDisk, /sk-LIVE-KEY-123/); + assert.match(onDisk, /Bearer LIVE-TOKEN/); + assert.match(onDisk, /MODEL-SECRET/); + assert.match(onDisk, /maxTokens: 2048/); + + // A genuinely new key overwrites the stored one. + const res2 = await put({ providers: { acme: { baseUrl: "https://example.invalid/v1", apiKey: "sk-NEW-KEY-456", models: [{ id: "acme-1", api: "openai-completions", maxTokens: 2048 }] } } }); + assert.equal(res2.status, 200); + assert.match(readFileSync(join(agentDir, "models.yml"), "utf8"), /sk-NEW-KEY-456/); +}); + +test("PUT never persists the masked placeholder as a credential", 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 value to + // restore, so the placeholder must be dropped rather than written. + const res = await put({ providers: { brand: { baseUrl: "https://example.invalid/v1", apiKey: lib.MASKED_API_KEY, auth: "none", headers: { Authorization: lib.MASKED_API_KEY } } } }); + assert.equal(res.status, 200); + assert.doesNotMatch(readFileSync(join(agentDir, "models.yml"), "utf8"), new RegExp(lib.MASKED_API_KEY)); +}); + +test("PUT with a null body is a 400, not a 500", async () => { + const res = await put("null"); + assert.equal(res.status, 400); +}); + +test("PUT rejects a key with the placeholder and a replacement appended", async (t) => { + mkdirSync(agentDir, { recursive: true }); + writeFileSync(join(agentDir, "models.yml"), MODELS_YML, "utf8"); + t.after(() => rmSync(join(agentDir, "models.yml"), { force: true })); + const res = await put({ providers: { acme: { baseUrl: "https://example.invalid/v1", apiKey: `${lib.MASKED_API_KEY}sk-NEW`, models: [{ id: "acme-1", api: "openai-completions" }] } } }); + assert.equal(res.status, 400); + assert.match(readFileSync(join(agentDir, "models.yml"), "utf8"), /sk-LIVE-KEY-123/); +}); + +test("PUT preserves the key when the provider is renamed", 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(); + const res = await put({ providers: { renamed: got.providers.acme } }); + assert.equal(res.status, 200); + const onDisk = readFileSync(join(agentDir, "models.yml"), "utf8"); + assert.match(onDisk, /sk-LIVE-KEY-123/); + assert.match(onDisk, /renamed:/); + assert.doesNotMatch(onDisk, /acme:/); +}); + +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 c3cd4e0bc..80ca4782e 100644 --- a/lib/omp/models-config.test.mjs +++ b/lib/omp/models-config.test.mjs @@ -5,8 +5,11 @@ import { join } from "node:path"; import test from "node:test"; const { + MASKED_API_KEY, ModelsConfigParseError, + maskModelsConfigApiKeys, readModelsConfigFile, + restoreModelsConfigApiKeys, serializeModelsConfig, validateModelsConfig, writeModelsConfig, @@ -227,3 +230,123 @@ 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 and header values for GET and restores the stored values on PUT", () => { + // Bug hunt round 1 (#295): GET /api/models-config returned models.yml + // verbatim, defeating the file API's models.yml denial — the route must + // redact every credential, headers included. + const stored = { + providers: { + acme: { + baseUrl: "https://example.invalid/v1", + apiKey: "sk-LIVE-KEY-123", + headers: { Authorization: "Bearer LIVE-TOKEN", "X-Custom": "keep-me" }, + models: [{ id: "acme-1", api: "openai-completions", headers: { "X-Model-Key": "MODEL-SECRET" } }], + }, + 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.headers.Authorization, MASKED_API_KEY); + assert.equal(masked.providers.acme.headers["X-Custom"], MASKED_API_KEY); + assert.equal(masked.providers.acme.models[0].headers["X-Model-Key"], MASKED_API_KEY); + 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"); + assert.equal(stored.providers.acme.headers.Authorization, "Bearer LIVE-TOKEN"); + + // Sending the placeholders back preserves the stored values. + const restored = restoreModelsConfigApiKeys(masked, stored); + assert.equal(restored.providers.acme.apiKey, "sk-LIVE-KEY-123"); + assert.equal(restored.providers.acme.headers.Authorization, "Bearer LIVE-TOKEN"); + assert.equal(restored.providers.acme.headers["X-Custom"], "keep-me"); + assert.equal(restored.providers.acme.models[0].headers["X-Model-Key"], "MODEL-SECRET"); + // A genuinely new value overwrites. + const changed = restoreModelsConfigApiKeys( + { providers: { acme: { ...masked.providers.acme, apiKey: "sk-NEW-KEY-456", headers: { Authorization: "Bearer NEW-TOKEN", "X-Custom": MASKED_API_KEY } } } }, + stored, + ); + assert.equal(changed.providers.acme.apiKey, "sk-NEW-KEY-456"); + assert.equal(changed.providers.acme.headers.Authorization, "Bearer NEW-TOKEN"); + assert.equal(changed.providers.acme.headers["X-Custom"], "keep-me"); + // A placeholder with no stored value must never be persisted as one. + const fresh = restoreModelsConfigApiKeys( + { providers: { brand: { baseUrl: "https://example.invalid/v1", apiKey: MASKED_API_KEY, headers: { Authorization: MASKED_API_KEY } } } }, + stored, + ); + assert.equal("apiKey" in fresh.providers.brand, false); + assert.equal("Authorization" in fresh.providers.brand.headers, false); +}); + +test("a masked round trip through writeModelsConfig keeps the real credentials 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 headers:\n Authorization: Bearer LIVE-TOKEN\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.match(reread, /Bearer LIVE-TOKEN/); + assert.doesNotMatch(reread, new RegExp(MASKED_API_KEY.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); + assert.match(reread, /maxTokens: 4096/); + }); +}); + +test("rejects a masked placeholder with text appended instead of persisting it", () => { + // Maintainer review (#295): the editor shows the mask as the field value, + // so typing a replacement after it yields e.g. eight bullets + sk-NEW. + // That corrupted value must be refused, never saved as the key. + const corrupted = { + providers: { + acme: { + baseUrl: "https://example.invalid/v1", + apiKey: `${MASKED_API_KEY}sk-NEW`, + models: [{ id: "acme-1", api: "openai-completions" }], + }, + }, + }; + assert.throws(() => validateModelsConfig(corrupted), /masked placeholder/); + const corruptedHeader = { + providers: { + acme: { + baseUrl: "https://example.invalid/v1", + apiKey: "sk-LIVE-KEY-123", + headers: { Authorization: `${MASKED_API_KEY}Bearer NEW` }, + models: [{ id: "acme-1", api: "openai-completions" }], + }, + }, + }; + assert.throws(() => validateModelsConfig(corruptedHeader), /masked placeholder/); +}); + +test("restores the masked key when a provider is renamed", () => { + // Maintainer review (#295): rename kept the provider object — mask + // included — under the new name, and the restore lost the key because no + // stored provider had the new id. + const stored = { + providers: { + old: { baseUrl: "https://example.invalid/v1", apiKey: "sk-LIVE-KEY-123", models: [{ id: "m1", api: "openai-completions" }] }, + }, + }; + const renamed = restoreModelsConfigApiKeys( + { providers: { new: { baseUrl: "https://example.invalid/v1", apiKey: MASKED_API_KEY, models: [{ id: "m1", api: "openai-completions" }] } } }, + stored, + ); + assert.equal(renamed.providers.new.apiKey, "sk-LIVE-KEY-123"); + // Ambiguous when two stored providers are missing from the submission: + // restore nothing rather than adopting a stranger's key. + const ambiguous = restoreModelsConfigApiKeys( + { providers: { brand: { baseUrl: "https://example.invalid/v1", apiKey: MASKED_API_KEY, models: [{ id: "m1", api: "openai-completions" }] } } }, + { providers: { + a: { baseUrl: "https://example.invalid/v1", apiKey: "sk-A", models: [{ id: "m1", api: "openai-completions" }] }, + b: { baseUrl: "https://example.invalid/v1", apiKey: "sk-B", models: [{ id: "m1", api: "openai-completions" }] }, + } }, + ); + assert.equal("apiKey" in ambiguous.providers.brand, false); +}); diff --git a/lib/omp/models-config.ts b/lib/omp/models-config.ts index 282a7e0bf..f2596a876 100644 --- a/lib/omp/models-config.ts +++ b/lib/omp/models-config.ts @@ -70,6 +70,14 @@ export function validateModelsConfig(config: ModelsFileConfig): void { throw new Error(`Provider ${providerName}: "apiKey" is required when defining custom models unless auth is "none".`); } } + // A value that merely CONTAINS the masked placeholder is a corrupted + // credential, not a key: the editor shows the placeholder as the field + // value, so typing a replacement after it produces e.g. eight bullets + // followed by sk-NEW, and persisting that would destroy the real key. + // The placeholder itself never reaches validation — restore drops it + // when there is nothing stored to restore. + assertNoMaskedSentinel(provider.apiKey, `Provider ${providerName}: "apiKey"`); + assertNoMaskedSentinel(provider.headers, `Provider ${providerName}: "headers"`); for (const model of models) { if (!isRecord(model) || typeof model.id !== "string" || !model.id) { throw new Error(`Provider ${providerName}: model missing "id"`); @@ -77,6 +85,7 @@ export function validateModelsConfig(config: ModelsFileConfig): void { if (!provider.api && !model.api) { throw new Error(`Provider ${providerName}, model ${model.id}: no "api" specified. Set at provider or model level.`); } + assertNoMaskedSentinel(model.headers, `Provider ${providerName}, model ${model.id}: "headers"`); if (typeof model.contextWindow === "number" && model.contextWindow <= 0) { throw new Error(`Provider ${providerName}, model ${model.id}: invalid contextWindow`); } @@ -135,6 +144,144 @@ function sanitizeModelsConfig(config: ModelsFileConfig): ModelsFileConfig { return { ...config, providers }; } +/** + * Placeholder GET /api/models-config returns in place of a real credential + * value. The file API denies models.yml outright on the grounds that the + * purpose-built route "redacts what it returns" — returning keys verbatim + * defeated that denial, so the route must never emit a real credential. The + * placeholder is never a valid credential: PUT restores the stored value + * 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 = "••••••••"; + +/** Reject a credential value that contains the placeholder without being it. */ +function assertNoMaskedSentinel(value: unknown, label: string): void { + if (typeof value === "string" && value.includes(MASKED_API_KEY)) { + throw new Error(`${label} contains the masked placeholder — clear the field and type the full value`); + } + if (isRecord(value)) { + for (const [key, entry] of Object.entries(value)) { + if (typeof entry === "string" && entry.includes(MASKED_API_KEY)) { + throw new Error(`${label}.${key} contains the masked placeholder — clear the field and type the full value`); + } + } + } +} + +/** Copy of a headers record with every value replaced by the placeholder. */ +function maskHeaders(headers: Record | undefined): Record | undefined { + if (!isRecord(headers)) return headers; + return Object.fromEntries(Object.entries(headers).map(([key, value]) => ( + [key, typeof value === "string" && value !== "" ? MASKED_API_KEY : value] + ))); +} + +/** Copy of a config with every provider `apiKey` and every provider/model + * header value replaced by the placeholder. Header values are credentials + * by construction (Authorization, X-Api-Key, Cookie, ...), so masking the + * apiKey alone still returned them in plaintext. */ +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)) return [providerId, provider]; + const masked: Record = { ...provider }; + if (typeof provider.apiKey === "string" && provider.apiKey !== "") masked.apiKey = MASKED_API_KEY; + if (isRecord(provider.headers)) masked.headers = maskHeaders(provider.headers as Record); + if (Array.isArray(provider.models)) { + masked.models = provider.models.map((model) => ( + isRecord(model) && isRecord(model.headers) + ? { ...model, headers: maskHeaders(model.headers as Record) } + : model + )); + } + return [providerId, masked]; + })); + return { ...config, providers }; +} + +/** Undo masking for one credential-bearing record (a provider or a model): + * an exact placeholder echoes the stored value back, a genuinely new value + * overwrites it, and a placeholder with no stored value is dropped + * (validation then rejects providers that need a key rather than saving the + * placeholder as one). */ +function restoreMaskedRecord( + record: Record, + stored: unknown, +): Record { + const out: Record = { ...record }; + if (record.apiKey === MASKED_API_KEY) { + const storedKey = isRecord(stored) ? stored.apiKey : undefined; + if (typeof storedKey === "string" && storedKey !== "") out.apiKey = storedKey; + else delete out.apiKey; + } + if (isRecord(record.headers)) { + const storedHeaders = isRecord(stored) && isRecord(stored.headers) ? stored.headers : {}; + const headers: Record = { ...(record.headers as Record) }; + for (const [key, value] of Object.entries(headers)) { + if (value !== MASKED_API_KEY) continue; + const storedValue = storedHeaders[key]; + if (typeof storedValue === "string" && storedValue !== "") headers[key] = storedValue; + else delete headers[key]; + } + out.headers = headers; + } + return out; +} + +/** + * Undo masking on a client-submitted config. + * + * A record is matched to its stored counterpart by id; when a submitted id + * has no stored counterpart and exactly one stored record is absent from the + * submission, that orphan is the match — that is a rename, which otherwise + * loses the masked key (the editor keeps the provider object, mask included, + * under the new name). Two or more orphans make the match ambiguous, so no + * restore happens and validation fails safe instead of adopting a stranger's + * key. + */ +export function restoreModelsConfigApiKeys(config: ModelsFileConfig, stored: ModelsFileConfig): ModelsFileConfig { + if (!isRecord(config) || !isRecord(config.providers)) return config; + const storedProviders = isRecord(stored?.providers) ? stored.providers : {}; + const submittedIds = new Set(Object.keys(config.providers)); + const orphanProviders = Object.entries(storedProviders) + .filter(([id, provider]) => !submittedIds.has(id) && isRecord(provider)); + const providers = Object.fromEntries(Object.entries(config.providers).map(([providerId, provider]) => { + if (!isRecord(provider)) return [providerId, provider]; + const storedProvider = isRecord(storedProviders[providerId]) + ? storedProviders[providerId] + : orphanProviders.length === 1 ? orphanProviders[0][1] : undefined; + let restored = restoreMaskedRecord(provider as Record, storedProvider); + if (Array.isArray(provider.models) && isRecord(storedProvider) && Array.isArray(storedProvider.models)) { + const storedModels = storedProvider.models as unknown[]; + const submittedModelIds = new Set( + (provider.models as unknown[]).map((m) => (isRecord(m) ? m.id : undefined)).filter((id): id is string => typeof id === "string"), + ); + const orphanModels = storedModels.filter((m) => ( + isRecord(m) && typeof m.id === "string" && !submittedModelIds.has(m.id) + )); + restored = { + ...restored, + models: (provider.models as unknown[]).map((model) => { + if (!isRecord(model)) return model; + const storedModel = storedModels.find((m) => isRecord(m) && m.id === model.id) + ?? (orphanModels.length === 1 ? orphanModels[0] : undefined); + return restoreMaskedRecord(model as Record, storedModel); + }), + }; + } else if (Array.isArray(provider.models)) { + restored = { + ...restored, + models: (provider.models as unknown[]).map((model) => ( + isRecord(model) ? restoreMaskedRecord(model as Record, undefined) : model + )), + }; + } + return [providerId, restored]; + })); + 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 7ddeda16d..cf31d97e0 100644 --- a/lib/omp/settings-config.test.mjs +++ b/lib/omp/settings-config.test.mjs @@ -130,3 +130,39 @@ test("invalid Auto source input is rejected before touching config", () => { }); }); + +test("refuses unvalidated keys instead of writing them into omp's config.yml", () => { + // Bug hunt round 1 (#295): 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 2acbd20ee..8634571c0 100644 --- a/lib/omp/settings-config.ts +++ b/lib/omp/settings-config.ts @@ -174,6 +174,60 @@ 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 } : {}), + } } : {}), + }; + } + 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"); @@ -234,12 +288,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) { const temp = `${path}.tmp-${process.pid}-${Date.now()}`; - writeFileSync(temp, stringify(settings), "utf8"); + // An empty document used to stringify the caller's object verbatim, + // persisting every unknown key with it; write only the allowlisted copy. + 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..d45d600a7 --- /dev/null +++ b/lib/plugins-route.test.mjs @@ -0,0 +1,52 @@ +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"; + +// Real /api/plugins POST against a throwaway cwd. Bug hunt round 1 (#295): 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). The guard fires before any omp +// call, so no runner binary is needed here. +const route = await import("../app/api/plugins/route.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 = { roots: new Set([cwd]), expiresAt: Date.now() + 60_000 }; + 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..2ba165c52 --- /dev/null +++ b/lib/session-export-route.test.mjs @@ -0,0 +1,71 @@ +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"; + +// Real /api/sessions/[id]/export against a fake live session host. Bug hunt +// round 1 (#295): 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 — including +// for this machine's own daemon, whose HTML is the exporter's output either +// way. The fake host keeps this test platform-independent: the original +// omp-stub.sh approach could not run on Windows CI (review item 7). +const exportRoute = await import("../app/api/sessions/[id]/export/route.ts"); +const { invalidateSessionListCache } = await import("./session-reader.ts"); +const { closeHostLink } = await import("./hosts/hub.ts"); +const { closeOutboxStore } = await import("./message-outbox.ts"); + +const EXPORT_HTML = ""; + +async function withAgentDir(run) { + const agentDir = mkdtempSync(join(tmpdir(), "omp-web-export-route-")); + mkdirSync(join(agentDir, "sessions", "-project"), { recursive: true }); + const previous = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = agentDir; + invalidateSessionListCache(); + globalThis.__ompHostLists = undefined; + try { + await run(); + } finally { + closeHostLink("local"); + if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previous; + invalidateSessionListCache(); + closeOutboxStore(); + rmSync(agentDir, { recursive: true, force: true }); + } +} + +test("serves exports as attachments even when inline is requested", async (t) => { + const id = "0a000000-0000-4000-8000-000000000022"; + const exported = []; + const host = { + id: "local", + label: "This machine", + status: () => "online", + sessionOps: { + async exportSession(sessionId) { + exported.push(sessionId); + return { ok: true, value: { html: EXPORT_HTML, fileName: "live.html" } }; + }, + }, + }; + const previousSessions = globalThis.__ompSessions; + globalThis.__ompSessions = new Map([[id, { isAlive: () => true, host }]]); + t.after(() => { globalThis.__ompSessions = previousSessions; }); + + await withAgentDir(async () => { + for (const query of ["?inline=1", ""]) { + const res = await exportRoute.GET( + new Request(`http://localhost/api/sessions/${id}/export${query}`), + { params: Promise.resolve({ id }) }, + ); + 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(), EXPORT_HTML); + } + assert.deepEqual(exported, [id, id]); + }); +});