From 747a42aa293604191f6e9d7605a1759a00012efb Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 23:40:32 -0600 Subject: [PATCH] fix(aggregator): validate collect-github-billing --year/--month/--user before any gh call (#3419) Malformed explicit values (banana, month 13/0, fractional, flag-as-value, trailing flag) flowed straight into the billing API URL and failures were misreported as gh token-scope problems. Explicit values are now validated up front: --year integer 2000..current UTC year, --month integer 1..12, --user non-empty and not flag-like; violations are usage errors (exit 2) with zero gh calls, mirroring the #3295 --by precedent. Omitted flags keep their defaults; the token-scope hint now only fires for validated API calls. Adds Bun stub-gh tests pinning exit code, zero gh calls, the valid control API path, and defaults. --- .../scripts/collect-github-billing.ts | 54 +++++++- .../collect-github-billing-args-3419.test.ts | 123 ++++++++++++++++++ 2 files changed, 174 insertions(+), 3 deletions(-) create mode 100644 pm-stack/aggregator/test/collect-github-billing-args-3419.test.ts diff --git a/pm-stack/aggregator/scripts/collect-github-billing.ts b/pm-stack/aggregator/scripts/collect-github-billing.ts index 539c8696d..414dc23b0 100644 --- a/pm-stack/aggregator/scripts/collect-github-billing.ts +++ b/pm-stack/aggregator/scripts/collect-github-billing.ts @@ -44,6 +44,54 @@ function argValue(flag: string): string | undefined { return i >= 0 ? process.argv[i + 1] : undefined; } +// Validate explicit --year/--month/--user values BEFORE any gh call +// (#3419). Malformed values used to flow straight into the billing API +// URL (month=NaN, month=13, users/--print) and the failure was then +// misreported as a gh token-scope problem. A missing, flag-like, or +// out-of-range value is a usage error (exit 2); omitted flags keep +// their defaults, and the token-scope hint in fetchUsageItems is only +// reachable with validated values. +function usageError(message: string): never { + console.error(`collect-github-billing: ${message}; refusing to run, no gh call made`); + process.exit(2); +} + +function explicitArg(flag: string): string { + const value: string | undefined = process.argv[process.argv.indexOf(flag) + 1]; + if (value === undefined || value.startsWith("--")) + usageError( + `${flag} requires a value (got ${value === undefined ? "no value" : JSON.stringify(value)})`, + ); + return value; +} + +function resolveYear(now: Date): number { + if (!process.argv.includes("--year")) return now.getUTCFullYear(); + const raw = explicitArg("--year"); + const year = /^\d+$/.test(raw.trim()) ? Number(raw.trim()) : NaN; + if (!Number.isInteger(year) || year < 2000 || year > now.getUTCFullYear()) + usageError( + `--year must be an integer from 2000 through ${now.getUTCFullYear()} (got ${JSON.stringify(raw)})`, + ); + return year; +} + +function resolveMonth(now: Date): number { + if (!process.argv.includes("--month")) return now.getUTCMonth() + 1; + const raw = explicitArg("--month"); + const month = /^\d+$/.test(raw.trim()) ? Number(raw.trim()) : NaN; + if (!Number.isInteger(month) || month < 1 || month > 12) + usageError(`--month must be an integer from 1 through 12 (got ${JSON.stringify(raw)})`); + return month; +} + +function resolveUser(): string { + if (!process.argv.includes("--user")) return process.env.GH_BILLING_USER ?? "dezren39"; + const raw = explicitArg("--user"); + if (raw.trim() === "") usageError(`--user requires a non-empty name (got ${JSON.stringify(raw)})`); + return raw; +} + function fetchUsageItems(user: string, year: number, month: number): BillingUsageItem[] { let out: string; try { @@ -66,9 +114,9 @@ function fetchUsageItems(user: string, year: number, month: number): BillingUsag async function main(): Promise { const now = new Date(); - const year = Number(argValue("--year") ?? now.getUTCFullYear()); - const month = Number(argValue("--month") ?? now.getUTCMonth() + 1); - const user = argValue("--user") ?? process.env.GH_BILLING_USER ?? "dezren39"; + const year = resolveYear(now); + const month = resolveMonth(now); + const user = resolveUser(); const observedBy = argValue("--by") ?? "collect-github-billing"; const items = fetchUsageItems(user, year, month); const totals = summarizeBillingDays(aggregateBillingUsage(items)); diff --git a/pm-stack/aggregator/test/collect-github-billing-args-3419.test.ts b/pm-stack/aggregator/test/collect-github-billing-args-3419.test.ts new file mode 100644 index 000000000..56fc17f69 --- /dev/null +++ b/pm-stack/aggregator/test/collect-github-billing-args-3419.test.ts @@ -0,0 +1,123 @@ +// Pinning test for #3419: collect-github-billing must validate explicit +// --year/--month/--user values BEFORE any gh call. Malformed values used +// to flow straight into the billing API URL (month=NaN, month=13, +// users/--print) and the failure was then misreported as a gh +// token-scope problem. Invalid values are a usage error (exit 2) with +// zero gh calls; omitted flags keep their defaults and a valid control +// calls the expected API path. +import { describe, expect, test } from "bun:test"; +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const script = join(import.meta.dir, "../scripts/collect-github-billing.ts"); + +async function setupStubGh(dir: string): Promise { + const binDir = join(dir, "bin"); + const logPath = join(dir, "gh-calls.log"); + const { mkdir } = await import("node:fs/promises"); + await mkdir(binDir, { recursive: true }); + const stub = join(binDir, "gh"); + await writeFile( + stub, + '#!/bin/sh\necho "$@" >> "$GH_STUB_LOG"\nprintf \'{"usageItems":[]}\'\n', + ); + await chmod(stub, 0o755); + return logPath; +} + +async function runScript( + dir: string, + logPath: string, + args: string[], +): Promise<{ code: number; stderr: string; stdout: string }> { + const env = { ...process.env }; + delete env.GH_BILLING_USER; + const proc = Bun.spawn([process.execPath, script, ...args], { + env: { + ...env, + PATH: `${join(dir, "bin")}:${process.env.PATH}`, + GH_STUB_LOG: logPath, + }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]); + return { code: await proc.exited, stdout, stderr }; +} + +async function ghCalls(logPath: string): Promise { + try { + return await readFile(logPath, "utf8"); + } catch { + return ""; + } +} + +describe("collect-github-billing argument validation (#3419)", () => { + test("invalid explicit values exit 2 with zero gh calls and no token-scope blame", async () => { + const dir = await mkdtemp(join(tmpdir(), "billing-args-3419-")); + try { + const logPath = await setupStubGh(dir); + const badArgSets: string[][] = [ + ["--year", "banana"], + ["--month", "13"], + ["--month", "0"], + ["--year", "2026.5"], + ["--month", "2.5"], + ["--month", "--print"], + ["--user", "--print"], + ["--user"], + ["--year"], + ["--month"], + ["--year", "1999"], + ["--user", " "], + ]; + for (const args of badArgSets) { + const { code, stderr } = await runScript(dir, logPath, args); + expect(code, `args ${JSON.stringify(args)}`).toBe(2); + expect(stderr, `args ${JSON.stringify(args)}`).toContain("collect-github-billing:"); + expect(stderr, `args ${JSON.stringify(args)}`).not.toContain("scope"); + expect(await ghCalls(logPath), `args ${JSON.stringify(args)}`).toBe(""); + } + } finally { + await rm(dir, { recursive: true, force: true }); + } + }, 60000); + + test("valid control calls the expected API path and derives records", async () => { + const dir = await mkdtemp(join(tmpdir(), "billing-args-3419-ok-")); + try { + const logPath = await setupStubGh(dir); + const { code, stdout } = await runScript(dir, logPath, [ + "--year", "2026", "--month", "10", "--user", "octocat", "--print", + ]); + expect(code).toBe(0); + expect(await ghCalls(logPath)).toContain( + "api users/octocat/settings/billing/usage?year=2026&month=10", + ); + expect(stdout).toContain("0 record(s) (dry run, outbox untouched)"); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }, 60000); + + test("omitted flags keep their defaults", async () => { + const dir = await mkdtemp(join(tmpdir(), "billing-args-3419-defaults-")); + try { + const logPath = await setupStubGh(dir); + const { code } = await runScript(dir, logPath, ["--print"]); + expect(code).toBe(0); + const now = new Date(); + const expected = + `api users/dezren39/settings/billing/usage?year=${now.getUTCFullYear()}` + + `&month=${now.getUTCMonth() + 1}`; + expect(await ghCalls(logPath)).toContain(expected); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }, 60000); +});