diff --git a/pm-stack/dispatch/src/github.ts b/pm-stack/dispatch/src/github.ts index b4d3472074..d14d4716d7 100644 --- a/pm-stack/dispatch/src/github.ts +++ b/pm-stack/dispatch/src/github.ts @@ -20,6 +20,73 @@ export class GitHubError extends Error { status = 502; } +/** + * A 2xx response body whose shape does not match the endpoint's contract + * (#7101). The dispatch sibling of the projector fix in #6954: a + * wrong-shape body must surface as a GitHubError naming the endpoint and + * the malformed field — never a raw TypeError/SyntaxError, never a + * coerced or undefined value flowing downstream. + */ +export class MalformedBodyError extends GitHubError {} + +/** The app create-issue call answered 2xx with a malformed body: the + * issue may already exist server-side, so the gh fallback create must + * NOT run (it would file a duplicate tracking issue). */ +class MalformedCreateBodyError extends MalformedBodyError {} + +function describeValue(v: unknown): string { + if (v === null) return "null"; + if (Array.isArray(v)) return "array"; + return typeof v; +} + +async function jsonBody(res: Response, endpoint: string): Promise { + try { + return await res.json(); + } catch { + throw new MalformedBodyError(`github ${endpoint} returned a non-JSON body`); + } +} + +function bodyObject(body: unknown, endpoint: string): Record { + if (body === null || typeof body !== "object" || Array.isArray(body)) { + throw new MalformedBodyError( + `github ${endpoint} returned a malformed body: expected a JSON object, got ${describeValue(body)}`, + ); + } + return body as Record; +} + +function reqPositiveInt(obj: Record, field: string, endpoint: string): number { + const v = obj[field]; + if (typeof v !== "number" || !Number.isInteger(v) || v <= 0) { + throw new MalformedBodyError( + `github ${endpoint} returned a malformed body: field '${field}' must be a positive integer, got ${describeValue(v)}`, + ); + } + return v; +} + +function reqInt(obj: Record, field: string, endpoint: string): number { + const v = obj[field]; + if (typeof v !== "number" || !Number.isInteger(v)) { + throw new MalformedBodyError( + `github ${endpoint} returned a malformed body: field '${field}' must be an integer, got ${describeValue(v)}`, + ); + } + return v; +} + +function reqString(obj: Record, field: string, endpoint: string, nonEmpty = false): string { + const v = obj[field]; + if (typeof v !== "string" || (nonEmpty && v === "")) { + throw new MalformedBodyError( + `github ${endpoint} returned a malformed body: field '${field}' must be a ${nonEmpty ? "non-empty " : ""}string, got ${describeValue(v)}`, + ); + } + return v; +} + /** Label -> color/description when dispatch has to create it. Colors match * the fleet taxonomy as used in developing-today/code. */ export const LABEL_DEFS: Record = { @@ -101,15 +168,25 @@ export class GitHubClient { `github app installation lookup for ${repo} failed (HTTP ${res.status}) — app not installed there?`, ); } - const data = (await res.json()) as { id: number }; - installationId = data.id; + const endpoint = `GET /repos/${repo}/installation`; + const data = bodyObject(await jsonBody(res, endpoint), endpoint); + installationId = reqPositiveInt(data, "id", endpoint); this.installationIdCache.set(repo, installationId); } const res = await this.appApi("POST", `/app/installations/${installationId}/access_tokens`, jwt); if (!res.ok) throw new GitHubError(`github app token mint failed (HTTP ${res.status})`); - const data = (await res.json()) as { token: string; expires_at: string }; - this.tokenCache.set(repo, { token: data.token, expiresAt: Date.parse(data.expires_at) }); - return data.token; + const endpoint = `POST /app/installations/${installationId}/access_tokens`; + const data = bodyObject(await jsonBody(res, endpoint), endpoint); + const token = reqString(data, "token", endpoint, true); + const expiresAtRaw = reqString(data, "expires_at", endpoint, true); + const expiresAt = Date.parse(expiresAtRaw); + if (Number.isNaN(expiresAt)) { + throw new MalformedBodyError( + `github ${endpoint} returned a malformed body: field 'expires_at' is not a parseable timestamp`, + ); + } + this.tokenCache.set(repo, { token, expiresAt }); + return token; } // --- gh CLI fallback ------------------------------------------------------- @@ -180,9 +257,31 @@ export class GitHubClient { if (!res.ok) { throw new GitHubError(`github issue create failed (HTTP ${res.status}): ${(await res.text()).slice(0, 200)}`); } - const data = (await res.json()) as { number: number; html_url: string }; - return { number: data.number, url: data.html_url }; + const endpoint = `POST /repos/${repo}/issues`; + let data: Record; + try { + data = bodyObject(await jsonBody(res, endpoint), endpoint); + } catch (shapeErr) { + throw new MalformedCreateBodyError( + shapeErr instanceof Error ? shapeErr.message : String(shapeErr), + ); + } + let number: number; + let url: string; + try { + number = reqInt(data, "number", endpoint); + url = reqString(data, "html_url", endpoint); + } catch (shapeErr) { + throw new MalformedCreateBodyError( + shapeErr instanceof Error ? shapeErr.message : String(shapeErr), + ); + } + return { number, url }; } catch (e) { + // A malformed 2xx create body is NOT a fallback case: the app + // POST may already have created the issue server-side, so a gh + // create would file a duplicate tracking issue (#7101). + if (e instanceof MalformedCreateBodyError) throw e; // Fall through to gh with the app error preserved in the message // if gh fails too. try { @@ -227,17 +326,13 @@ export class GitHubClient { const res = await this.appApi("GET", `/repos/${repo}/issues/${issueNumber}`, token); if (res.status === 404) return null; if (!res.ok) throw new GitHubError(`github issue lookup failed (HTTP ${res.status})`); - const data = (await res.json()) as { - number: number; - state: string; - html_url: string; - pull_request?: unknown; - }; + const endpoint = `GET /repos/${repo}/issues/${issueNumber}`; + const data = bodyObject(await jsonBody(res, endpoint), endpoint); return { - number: data.number, - state: data.state, + number: reqInt(data, "number", endpoint), + state: reqString(data, "state", endpoint), isPullRequest: Boolean(data.pull_request), - url: data.html_url, + url: reqString(data, "html_url", endpoint), }; } catch (e) { appError = e; @@ -246,17 +341,19 @@ export class GitHubClient { } try { const out = await this.gh(["api", `repos/${repo}/issues/${issueNumber}`]); - const data = JSON.parse(out) as { - number: number; - state: string; - html_url: string; - pull_request?: unknown; - }; + const endpoint = `gh api repos/${repo}/issues/${issueNumber}`; + let parsed: unknown; + try { + parsed = JSON.parse(out); + } catch { + throw new MalformedBodyError(`github ${endpoint} returned a non-JSON body`); + } + const data = bodyObject(parsed, endpoint); return { - number: data.number, - state: data.state, + number: reqInt(data, "number", endpoint), + state: reqString(data, "state", endpoint), isPullRequest: Boolean(data.pull_request), - url: data.html_url, + url: reqString(data, "html_url", endpoint), }; } catch (e) { const msg = e instanceof Error ? e.message : String(e); diff --git a/pm-stack/dispatch/test/github.test.ts b/pm-stack/dispatch/test/github.test.ts new file mode 100644 index 0000000000..661f5188c6 --- /dev/null +++ b/pm-stack/dispatch/test/github.test.ts @@ -0,0 +1,226 @@ +// Issue #7101: pm-dispatch's GitHub App client must validate every API +// response body before use. A wrong-shape 2xx used to be shape-trusted: +// an installation {} minted against /installations/undefined, a token {} +// was sent as "Bearer undefined", a create {} returned a phantom issue +// as success, a lookup {} fabricated an issue state, and null bodies +// escaped as raw TypeErrors (the create one then duplicated the issue +// via the gh fallback). These tests stub fetch in the style of +// test/attach_verify.test.ts. The repo slug is a nonexistent one, so +// the gh CLI fallback fails deterministically (and can never create a +// real issue) in any environment. +// +// Oracle: the #7101 acceptance — every malformed body raises GitHubError +// naming the endpoint and the malformed field; a malformed 2xx create +// never triggers the gh fallback create; malformed installation/token +// replies still fall back with the reason preserved; well-formed +// controls are unchanged. +import { describe, expect, test } from "bun:test"; +import { generateKeyPairSync } from "node:crypto"; +import { GitHubClient, GitHubError } from "../src/github.ts"; + +const REPO = "pm-dispatch-7101/nonexistent"; // a slug no gh route can succeed on: the CLI fallback fails deterministically and can never create anything, in any environment +const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 }); +const pem = privateKey.export({ format: "pem", type: "pkcs8" }) as string; +const realFetch = globalThis.fetch; + +// --- fetch stub ---------------------------------------------------------- +interface Bodies { + installation?: unknown; + token?: unknown; + create?: unknown; + lookup?: unknown; +} +const FUTURE = new Date(Date.now() + 3_600_000).toISOString(); +const GOOD: Required = { + installation: { id: 42 }, + token: { token: "test-token", expires_at: FUTURE }, + create: { number: 123, html_url: `https://github.com/${REPO}/issues/123` }, + lookup: { number: 3007, state: "open", html_url: `https://github.com/${REPO}/issues/3007` }, +}; +let seenUrls: string[] = []; +let seenAuth: string[] = []; + +function stub(bodies: Bodies) { + const b: Required = { ...GOOD, ...bodies }; + seenUrls = []; + seenAuth = []; + globalThis.fetch = (async (input: unknown, init?: { headers?: Record }) => { + const url = String(input); + seenUrls.push(url); + const auth = init?.headers?.Authorization; + if (typeof auth === "string") seenAuth.push(auth); + const reply = (body: unknown, status = 200) => + new Response(body === undefined ? "null" : JSON.stringify(body), { status }); + if (url.endsWith(`/repos/${REPO}/installation`)) return reply(b.installation); + if (url.includes("/app/installations/")) return reply(b.token, 201); + if (url.endsWith(`/repos/${REPO}/issues`)) return reply(b.create, 201); + if (url.includes(`/repos/${REPO}/issues/`)) return reply(b.lookup); + throw new Error(`unexpected fetch in test: ${url}`); + }) as typeof fetch; +} + +async function withStub(bodies: Bodies, fn: () => Promise): Promise { + stub(bodies); + try { + return await fn(); + } finally { + globalThis.fetch = realFetch; + } +} + +const client = () => new GitHubClient("12345", pem); + +describe("GitHubClient response-shape validation (#7101)", () => { + test("well-formed control: create returns the real issue ref", async () => { + const out = await withStub({}, () => client().createIssue(REPO, "t", "b", [])); + expect(out).toEqual({ number: 123, url: `https://github.com/${REPO}/issues/123` }); + expect(seenAuth.some((a) => a === "Bearer test-token")).toBe(true); + }); + + test("well-formed control: lookup returns the issue info", async () => { + const info = await withStub({}, () => client().getIssue(REPO, 3007)); + expect(info).toEqual({ + number: 3007, + state: "open", + isPullRequest: false, + url: `https://github.com/${REPO}/issues/3007`, + }); + }); + + test("installation {} raises GitHubError naming the endpoint and 'id'; no mint to undefined", async () => { + const err = await withStub({ installation: {} }, () => + client().createIssue(REPO, "t", "b", []).then( + () => null, + (e: unknown) => e, + ), + ); + // installation/token malformation may fall back to gh; the fake gh + // fails, so the combined error must preserve the malformed reason. + expect(err).toBeInstanceOf(GitHubError); + expect((err as Error).message).toContain("installation"); + expect((err as Error).message).toContain("'id'"); + expect(seenUrls.some((u) => u.includes("undefined"))).toBe(false); + }); + + test("installation null body raises GitHubError, not a raw TypeError", async () => { + const err = await withStub({ installation: undefined }, () => + client().createIssue(REPO, "t", "b", []).then( + () => null, + (e: unknown) => e, + ), + ); + expect(err).toBeInstanceOf(GitHubError); + expect(err).not.toBeInstanceOf(TypeError); + expect((err as Error).message).toContain("malformed"); + }); + + test("token {} raises naming 'token'; no Bearer undefined is ever sent", async () => { + const err = await withStub({ token: {} }, () => + client().createIssue(REPO, "t", "b", []).then( + () => null, + (e: unknown) => e, + ), + ); + expect(err).toBeInstanceOf(GitHubError); + expect((err as Error).message).toContain("'token'"); + expect(seenAuth.some((a) => a.includes("undefined"))).toBe(false); + }); + + test("token numeric raises naming 'token'", async () => { + const err = await withStub({ token: { token: 123, expires_at: FUTURE } }, () => + client().createIssue(REPO, "t", "b", []).then( + () => null, + (e: unknown) => e, + ), + ); + expect(err).toBeInstanceOf(GitHubError); + expect((err as Error).message).toContain("'token'"); + expect(seenAuth.some((a) => a === "Bearer 123")).toBe(false); + expect(seenUrls.some((u) => u.endsWith(`/repos/${REPO}/issues`))).toBe(false); + }); + + test("token with unparseable expires_at raises naming 'expires_at'", async () => { + const err = await withStub({ token: { token: "test-token", expires_at: "not-a-date" } }, () => + client().createIssue(REPO, "t", "b", []).then( + () => null, + (e: unknown) => e, + ), + ); + expect(err).toBeInstanceOf(GitHubError); + expect((err as Error).message).toContain("'expires_at'"); + }); + + test("create {} surfaces a malformed-body GitHubError and does NOT fall back to a gh create", async () => { + const err = await withStub({ create: {} }, () => + client().createIssue(REPO, "t", "b", []).then( + () => null, + (e: unknown) => e, + ), + ); + // A gh fallback would wrap the failure in a combined "failed via + // app ... and via gh" GitHubError; the bare malformed-body error + // (no "via gh" text) proves the fallback never ran. + expect(err).toBeInstanceOf(GitHubError); + expect((err as Error).message).toContain("malformed"); + expect((err as Error).message).toContain("'number'"); + expect((err as Error).message).not.toContain("via gh"); + }); + + test("create with wrong-typed fields surfaces a malformed-body GitHubError, no gh create", async () => { + const err = await withStub({ create: { number: "abc", html_url: 42 } }, () => + client().createIssue(REPO, "t", "b", []).then( + () => null, + (e: unknown) => e, + ), + ); + expect(err).toBeInstanceOf(GitHubError); + expect((err as Error).message).toContain("malformed"); + }); + + test("create null body surfaces a malformed-body GitHubError, no gh create, no TypeError", async () => { + const err = await withStub({ create: undefined }, () => + client().createIssue(REPO, "t", "b", []).then( + () => null, + (e: unknown) => e, + ), + ); + expect(err).toBeInstanceOf(GitHubError); + expect((err as Error).message).toContain("malformed"); + expect(err).not.toBeInstanceOf(TypeError); + }); + + test("lookup {} does not fabricate an issue", async () => { + const out = await withStub({ lookup: {} }, () => + client().getIssue(REPO, 3007).then( + (v) => ({ v }), + (e: unknown) => ({ e }), + ), + ); + // Never a fabricated IssueInfo and never a raw TypeError: either the + // gh route's definitive 404 governs (null) or the combined + // GitHubError preserves the malformed-body reason. + if ("v" in out) { + expect(out.v).toBeNull(); + } else { + expect(out.e).toBeInstanceOf(GitHubError); + expect((out.e as Error).message).toContain("malformed"); + expect((out.e as Error).message).toContain("'number'"); + } + }); + + test("lookup null body never escapes as a raw TypeError", async () => { + const out = await withStub({ lookup: undefined }, () => + client().getIssue(REPO, 3007).then( + (v) => ({ v }), + (e: unknown) => ({ e }), + ), + ); + if ("v" in out) { + expect(out.v).toBeNull(); + } else { + expect(out.e).toBeInstanceOf(GitHubError); + expect(out.e).not.toBeInstanceOf(TypeError); + expect((out.e as Error).message).toContain("malformed"); + } + }); +});