From 97acc4716e6fe4f91b3bb3499c029c75363d8b50 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sat, 7 Nov 2026 21:21:37 -0600 Subject: [PATCH] fix(dispatch): validate opencode auth-file and response JSON at the boundary (#7085) authHeader() parsed the OpenCode server state file with a bare JSON.parse + cast outside its readFile guard: a null document threw a raw TypeError, malformed JSON a raw SyntaxError, and a non-string password was silently coerced into the Basic credential (a numeric password was sent verbatim; an object became [object Object]). api() likewise let a non-JSON 200 escape as a raw SyntaxError. Both now throw OpenCodeError naming the problem, the password must be a non-empty string, and a new test/opencode.test.ts pins all probe cases (8 tests; 5 fail pre-fix). Full dispatch suite: 139/139 on the laptop. --- pm-stack/dispatch/src/opencode.ts | 27 +++++- pm-stack/dispatch/test/opencode.test.ts | 104 ++++++++++++++++++++++++ 2 files changed, 128 insertions(+), 3 deletions(-) create mode 100644 pm-stack/dispatch/test/opencode.test.ts diff --git a/pm-stack/dispatch/src/opencode.ts b/pm-stack/dispatch/src/opencode.ts index ef96a9045..6b572f4a9 100644 --- a/pm-stack/dispatch/src/opencode.ts +++ b/pm-stack/dispatch/src/opencode.ts @@ -22,8 +22,24 @@ export class OpenCodeClient { } catch { throw new OpenCodeError(`opencode auth file unreadable: ${this.authFile}`); } - const data = JSON.parse(raw) as { password?: string }; - if (!data.password) throw new OpenCodeError("opencode auth file carries no password"); + // The parse and the shape are part of the boundary (#7085): a + // truncated/mid-write state file, a non-object document, or a + // non-string password must surface as an OpenCodeError naming the + // problem - never a raw Type/SyntaxError, and never a credential + // silently coerced from a number or object. + let parsedAuth: unknown; + try { + parsedAuth = JSON.parse(raw); + } catch { + throw new OpenCodeError(`opencode auth file is not valid JSON: ${this.authFile}`); + } + if (typeof parsedAuth !== "object" || parsedAuth === null || Array.isArray(parsedAuth)) { + throw new OpenCodeError(`opencode auth file does not hold a JSON object: ${this.authFile}`); + } + const data = parsedAuth as { password?: unknown }; + if (typeof data.password !== "string" || !data.password) { + throw new OpenCodeError("opencode auth file carries no password"); + } return `Basic ${Buffer.from(`opencode:${data.password}`).toString("base64")}`; } @@ -41,7 +57,12 @@ export class OpenCodeClient { throw new OpenCodeError(`opencode ${method} ${path} failed (HTTP ${res.status}): ${text.slice(0, 200)}`); } if (!text.trim()) return null; - const parsed: unknown = JSON.parse(text); + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + throw new OpenCodeError(`opencode ${method} ${path} returned a non-JSON response (HTTP ${res.status})`); + } // The v2 API wraps responses in a {data: …} envelope. if (typeof parsed === "object" && parsed !== null && "data" in parsed) { return (parsed as { data: unknown }).data; diff --git a/pm-stack/dispatch/test/opencode.test.ts b/pm-stack/dispatch/test/opencode.test.ts new file mode 100644 index 000000000..10595fd93 --- /dev/null +++ b/pm-stack/dispatch/test/opencode.test.ts @@ -0,0 +1,104 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { OpenCodeClient, OpenCodeError } from "../src/opencode.ts"; + +// Pinning tests for #7085: the OpenCode client parses two JSON inputs — +// the server state/auth file and every 2xx response body. Both parses +// are boundary validations: wrong-shape or malformed input must surface +// as OpenCodeError, never a raw Type/SyntaxError, and a non-string +// password must never be coerced into the Basic credential. + +let mode: "ok" | "nonjson" = "ok"; +let lastAuth = ""; +let server: ReturnType; +let baseUrl = ""; +let dir = ""; + +function authFile(name: string, content: string): string { + const path = join(dir, name); + writeFileSync(path, content); + return path; +} + +beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), "dispatch-opencode-test-")); + server = Bun.serve({ + port: 0, + fetch(req) { + lastAuth = req.headers.get("authorization") ?? ""; + if (mode === "nonjson") { + return new Response("not json", { status: 200, headers: { "content-type": "text/html" } }); + } + return Response.json({ data: { id: "sess-control" } }); + }, + }); + baseUrl = `http://127.0.0.1:${server.port}`; +}); + +afterAll(() => { + server.stop(true); + rmSync(dir, { recursive: true, force: true }); +}); + +async function create(file: string) { + const client = new OpenCodeClient(baseUrl, file); + return client.createSession({ directory: "/tmp", title: "t", model: null }); +} + +describe("OpenCodeClient auth file boundary (#7085)", () => { + test("control: a valid auth file resolves and sends the password verbatim", async () => { + mode = "ok"; + const session = await create(authFile("valid.json", JSON.stringify({ password: "pw123" }))); + expect(session.id).toBe("sess-control"); + expect(Buffer.from(lastAuth.replace("Basic ", ""), "base64").toString()).toBe("opencode:pw123"); + }); + + test("control: an object without a password yields the no-password OpenCodeError", async () => { + await expect(create(authFile("empty.json", "{}"))).rejects.toThrow(OpenCodeError); + await expect(create(authFile("empty.json", "{}"))).rejects.toThrow(/carries no password/); + }); + + test("a null auth file is an OpenCodeError, not a raw TypeError", async () => { + const err = await create(authFile("null.json", "null")).catch((e: unknown) => e); + expect(err).toBeInstanceOf(OpenCodeError); + expect(String((err as Error).message)).toContain("does not hold a JSON object"); + }); + + test("an array auth file is an OpenCodeError, not a raw error", async () => { + const err = await create(authFile("array.json", "[]")).catch((e: unknown) => e); + expect(err).toBeInstanceOf(OpenCodeError); + }); + + test("a malformed auth file is an OpenCodeError, not a raw SyntaxError", async () => { + const err = await create(authFile("bad.json", "{not json")).catch((e: unknown) => e); + expect(err).toBeInstanceOf(OpenCodeError); + expect(String((err as Error).message)).toContain("not valid JSON"); + }); + + test("a numeric password is rejected, never coerced into the credential", async () => { + lastAuth = ""; + const err = await create(authFile("num.json", JSON.stringify({ password: 12345 }))).catch((e: unknown) => e); + expect(err).toBeInstanceOf(OpenCodeError); + expect(lastAuth).toBe(""); + }); + + test("an object password is rejected, never sent as [object Object]", async () => { + lastAuth = ""; + const err = await create(authFile("obj.json", JSON.stringify({ password: { x: 1 } }))).catch((e: unknown) => e); + expect(err).toBeInstanceOf(OpenCodeError); + expect(lastAuth).toBe(""); + }); +}); + +describe("OpenCodeClient response body boundary (#7085)", () => { + test("a non-JSON 200 body is an OpenCodeError, not a raw SyntaxError", async () => { + mode = "nonjson"; + const err = await create(authFile("valid2.json", JSON.stringify({ password: "pw123" }))).catch((e: unknown) => e); + expect(err).toBeInstanceOf(OpenCodeError); + expect(String((err as Error).message)).toContain("non-JSON response"); + mode = "ok"; + }); +});