Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 51 additions & 3 deletions pm-stack/aggregator/scripts/collect-github-billing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -66,9 +114,9 @@ function fetchUsageItems(user: string, year: number, month: number): BillingUsag

async function main(): Promise<void> {
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));
Expand Down
123 changes: 123 additions & 0 deletions pm-stack/aggregator/test/collect-github-billing-args-3419.test.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
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<string> {
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);
});
Loading