From b1ef099b67383d940a15753512b020c1f313ce1f Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 2 Nov 2026 11:11:59 -0600 Subject: [PATCH] pm-stack(quota-exporters): strict single-pass argv validation in all three exporters (#3469) Replace the unchecked opt() helper (flag token accepted as a value and consumed twice via indexOf) with an exported single-pass parseArgs(): a value flag followed by another flag or by nothing is a usage error naming the flag (stderr + exit 2) before any directory creation, token resolution, or API/CDP call; unknown flags and bare positionals are usage errors; meta --cdp-port must be a decimal integer in 1-65535. Regression tests in each exporter's *.test.mjs cover flag-as-value, trailing flag, double consumption, port range (meta), unknown flags, and the control invocation. --- .../cloudflare-quota-export.mjs | 62 ++++++++++++++-- .../cloudflare-quota-export.test.mjs | 53 +++++++++++++ pm-stack/meta-exporter/meta-quota-export.mjs | 74 +++++++++++++++++-- .../meta-exporter/meta-quota-export.test.mjs | 62 ++++++++++++++++ .../supabase-export/supabase-quota-export.mjs | 62 ++++++++++++++-- .../supabase-quota-export.test.mjs | 53 +++++++++++++ 6 files changed, 344 insertions(+), 22 deletions(-) diff --git a/pm-stack/cloudflare-export/cloudflare-quota-export.mjs b/pm-stack/cloudflare-export/cloudflare-quota-export.mjs index 1b6cc37325..b076dd55f5 100755 --- a/pm-stack/cloudflare-export/cloudflare-quota-export.mjs +++ b/pm-stack/cloudflare-export/cloudflare-quota-export.mjs @@ -41,6 +41,11 @@ * analytics scopes; `missingScopes` names them. Exit 3. * unparseable an endpoint answered an unrecognised shape. Exit 6. * fetch-failed network/other error. Exit 7. + * + * Argv misuse (a value flag followed by another flag or by nothing, or + * an unknown flag) is a usage error naming the flag: stderr + exit 2 + * before anything runs — no directory is created and no document is + * written (#3469). */ import { appendFile, mkdir, rename, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; @@ -553,17 +558,60 @@ async function writeOutputs(outDir, doc) { await appendFile(join(outDir, "history.jsonl"), `${JSON.stringify(doc)}\n`, "utf8"); } -async function main() { - const args = process.argv.slice(2); - const opt = (name, fallback) => { - const i = args.indexOf(name); - return i >= 0 && args[i + 1] ? args[i + 1] : fallback; +/** Strict single-pass argv parsing (#3469). Every value-taking flag must be + * followed by a value token that is not itself a flag: a flag token (or + * nothing) where a value belongs is a usage error naming the flag, raised + * before any directory is created or any API call is made. The parse is + * single-pass — each value token is consumed once — so a flag token can + * never double as both a value and a flag. Unknown flags and bare + * positionals are usage errors too: silently ignoring them is what used + * to redirect output into a directory named after a flag. Throws + * ExportError("usage", 2); main() turns it into stderr + exit 2. */ +const VALUE_FLAGS = new Set(["--out-dir", "--account-id"]); + +function usageError(message) { + throw new ExportError("usage", 2, message); +} + +export function parseArgs(argv) { + const values = {}; + for (let i = 0; i < argv.length; i++) { + const token = argv[i]; + if (!VALUE_FLAGS.has(token)) { + if (token.startsWith("--")) usageError(`unknown flag ${JSON.stringify(token)}`); + else usageError(`unexpected argument ${JSON.stringify(token)} (this exporter takes only --flag value pairs)`); + } + const value = argv[i + 1]; + if (typeof value !== "string" || value === "" || value.startsWith("--")) { + usageError( + `${token} requires a value that is not another flag (got ${value === undefined ? "nothing" : JSON.stringify(value)})`, + ); + } + values[token] = value; + i++; // consume the value: no token is read twice + } + return { + outDir: values["--out-dir"] ?? join(homedir(), "atlas", "cloudflare-export"), + accountId: values["--account-id"], }; - const outDir = opt("--out-dir", join(homedir(), "atlas", "cloudflare-export")); +} + +async function main() { + let options; + try { + options = parseArgs(process.argv.slice(2)); + } catch (error) { + if (error instanceof ExportError && error.status === "usage") { + console.error(`cloudflare-quota-export: ${error.message}; refusing to run, no output written`); + process.exit(2); + } + throw error; + } + const outDir = options.outDir; try { const doc = await run({ token: process.env.CLOUDFLARE_API_TOKEN, - accountId: opt("--account-id", undefined), + accountId: options.accountId, }); await writeOutputs(outDir, doc); console.log(JSON.stringify({ status: doc.status, measuredAt: doc.measuredAt, metrics: doc.metrics.length, outDir })); diff --git a/pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs b/pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs index 5c55b3f085..4fed2d0a5f 100755 --- a/pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs +++ b/pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs @@ -14,6 +14,7 @@ import { ExportError, failureDocument, foldKv, + parseArgs, parseGraphqlUsage, R2_STORAGE_GROUP_LIMIT, run, @@ -492,3 +493,55 @@ test("measurement strings use plain decimals; request counts remain integers (#2 ); } }); + +// Strict argv validation (#3469): a value flag followed by another flag +// (or by nothing) is a usage error naming the flag, raised before any +// directory creation or API call; no token is consumed twice. +function expectUsage(argv, flag) { + assert.throws( + () => parseArgs(argv), + (error) => { + assert.ok(error instanceof ExportError, `expected ExportError, got ${error}`); + assert.equal(error.status, "usage"); + assert.equal(error.exitCode, 2); + assert.match(error.message, new RegExp(flag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); + return true; + }, + `parseArgs(${JSON.stringify(argv)}) should be a usage error naming ${flag}`, + ); +} + +test("parseArgs: the control invocation parses, account-id optional (#3469)", () => { + assert.deepEqual(parseArgs(["--out-dir", "out", "--account-id", "probeacct"]), { + outDir: "out", + accountId: "probeacct", + }); + const def = parseArgs([]); + assert.match(def.outDir, /cloudflare-export$/); + assert.equal(def.accountId, undefined); +}); + +test("parseArgs: flag-as-value is a usage error naming the flag (#3469)", () => { + // The exact probe from the issue: --account-id must not double as the + // out-dir value and the account flag. + expectUsage(["--out-dir", "--account-id", "probeacct"], "--out-dir"); + expectUsage(["--account-id", "--out-dir", "out"], "--account-id"); +}); + +test("parseArgs: a trailing flag with no value is a usage error, not a silent fallback (#3469)", () => { + expectUsage(["--out-dir"], "--out-dir"); + expectUsage(["--out-dir", "out", "--account-id"], "--account-id"); +}); + +test("parseArgs: no token is consumed twice (#3469)", () => { + // Old opt() returned "--account-id" as the out-dir AND "probeacct" as + // the account. Now the single-pass parse refuses outright instead of + // splitting the token stream two ways. + expectUsage(["--out-dir", "--account-id", "probeacct"], "--out-dir"); +}); + +test("parseArgs: unknown flags and bare positionals are usage errors (#3469)", () => { + expectUsage(["--bogus", "x"], "--bogus"); + expectUsage(["--out-dir=out"], "--out-dir=out"); + expectUsage(["out"], "out"); +}); diff --git a/pm-stack/meta-exporter/meta-quota-export.mjs b/pm-stack/meta-exporter/meta-quota-export.mjs index 95c883faf4..8fb35aefd0 100644 --- a/pm-stack/meta-exporter/meta-quota-export.mjs +++ b/pm-stack/meta-exporter/meta-quota-export.mjs @@ -37,6 +37,11 @@ * "laptop-unreachable" is deliberately NOT produced here: if the * laptop is down nothing runs, so consumers derive it from the age of * latest.json (> 2 ticks = > 30 min without a fresh document). + * + * Argv misuse (a value flag followed by another flag or by nothing, an + * unknown flag, or a --cdp-port outside 1-65535) is a usage error naming + * the flag: stderr + exit 2 before anything runs — no directory is + * created and no document is written (#3469). */ import { appendFile, mkdir, rename, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; @@ -510,15 +515,68 @@ export async function run({ }); } -async function main() { - const args = process.argv.slice(2); - const opt = (name, fallback) => { - const i = args.indexOf(name); - return i >= 0 && args[i + 1] ? args[i + 1] : fallback; +/** Strict single-pass argv parsing (#3469). Every value-taking flag must be + * followed by a value token that is not itself a flag: a flag token (or + * nothing) where a value belongs is a usage error naming the flag, raised + * before any directory is created or any CDP call is made. The parse is + * single-pass — each value token is consumed once — so a flag token can + * never double as both a value and a flag. Unknown flags and bare + * positionals are usage errors too: silently ignoring them is what used + * to redirect output into a directory named after a flag. Throws + * ExportError("usage", 2); main() turns it into stderr + exit 2. */ +const VALUE_FLAGS = new Set(["--out-dir", "--cdp-port", "--team-id"]); + +function usageError(message) { + throw new ExportError("usage", 2, message); +} + +function parseCdpPort(raw) { + if (!/^\d+$/.test(raw)) { + usageError(`--cdp-port must be a decimal integer in 1-65535 (got ${JSON.stringify(raw)})`); + } + const port = Number(raw); + if (!Number.isSafeInteger(port) || port < 1 || port > 65535) { + usageError(`--cdp-port must be a decimal integer in 1-65535 (got ${JSON.stringify(raw)})`); + } + return port; +} + +export function parseArgs(argv) { + const values = {}; + for (let i = 0; i < argv.length; i++) { + const token = argv[i]; + if (!VALUE_FLAGS.has(token)) { + if (token.startsWith("--")) usageError(`unknown flag ${JSON.stringify(token)}`); + else usageError(`unexpected argument ${JSON.stringify(token)} (this exporter takes only --flag value pairs)`); + } + const value = argv[i + 1]; + if (typeof value !== "string" || value === "" || value.startsWith("--")) { + usageError( + `${token} requires a value that is not another flag (got ${value === undefined ? "nothing" : JSON.stringify(value)})`, + ); + } + values[token] = value; + i++; // consume the value: no token is read twice + } + return { + outDir: values["--out-dir"] ?? join(homedir(), "atlas", "meta-quota-export"), + cdpPort: parseCdpPort(values["--cdp-port"] ?? "19222"), + teamId: values["--team-id"] ?? process.env.META_TEAM_ID ?? DEFAULT_TEAM_ID, }; - const outDir = opt("--out-dir", join(homedir(), "atlas", "meta-quota-export")); - const cdpPort = Number(opt("--cdp-port", "19222")); - const teamId = opt("--team-id", process.env.META_TEAM_ID ?? DEFAULT_TEAM_ID); +} + +async function main() { + let options; + try { + options = parseArgs(process.argv.slice(2)); + } catch (error) { + if (error instanceof ExportError && error.status === "usage") { + console.error(`meta-quota-export: ${error.message}; refusing to run, no output written`); + process.exit(2); + } + throw error; + } + const { outDir, cdpPort, teamId } = options; const outcome = await exportAndWrite({ cdpPort, outDir, teamId }); if (outcome.exitCode === 0) { const { doc } = outcome; diff --git a/pm-stack/meta-exporter/meta-quota-export.test.mjs b/pm-stack/meta-exporter/meta-quota-export.test.mjs index 3320264373..a5971d1426 100644 --- a/pm-stack/meta-exporter/meta-quota-export.test.mjs +++ b/pm-stack/meta-exporter/meta-quota-export.test.mjs @@ -12,6 +12,7 @@ import { ExportError, exportAndWrite, failureDocument, + parseArgs, parseBillingBanner, parsePaygBalance, parseSubscriptionQuota, @@ -417,3 +418,64 @@ test("connectWs bounds open and rejects every pending command on close or error" assert.ok(results.every((result) => /(closed|failure)/i.test(result.reason.message))); } }); + +// Strict argv validation (#3469): a value flag followed by another flag +// (or by nothing) is a usage error naming the flag, raised before any +// directory creation or CDP call; no token is consumed twice; --cdp-port +// is a decimal integer in 1-65535; the control still parses. +function expectUsage(argv, flag) { + assert.throws( + () => parseArgs(argv), + (error) => { + assert.ok(error instanceof ExportError, `expected ExportError, got ${error}`); + assert.equal(error.status, "usage"); + assert.equal(error.exitCode, 2); + assert.match(error.message, new RegExp(flag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); + return true; + }, + `parseArgs(${JSON.stringify(argv)}) should be a usage error naming ${flag}`, + ); +} + +test("parseArgs: the control invocation parses, defaults intact", () => { + const full = parseArgs(["--out-dir", "out", "--cdp-port", "19222", "--team-id", "team1"]); + assert.deepEqual(full, { outDir: "out", cdpPort: 19222, teamId: "team1" }); + const def = parseArgs([]); + assert.equal(def.cdpPort, 19222); + assert.match(def.outDir, /meta-quota-export$/); +}); + +test("parseArgs: flag-as-value is a usage error naming the flag (#3469)", () => { + // The exact probe from the issue: --cdp-port must not double as the + // out-dir value and the port flag. + expectUsage(["--out-dir", "--cdp-port", "19222"], "--out-dir"); + expectUsage(["--cdp-port", "--team-id", "x"], "--cdp-port"); + expectUsage(["--team-id", "--out-dir", "out"], "--team-id"); +}); + +test("parseArgs: a trailing flag with no value is a usage error, not a silent fallback (#3469)", () => { + expectUsage(["--out-dir"], "--out-dir"); + expectUsage(["--out-dir", "out", "--cdp-port"], "--cdp-port"); + expectUsage(["--team-id"], "--team-id"); +}); + +test("parseArgs: no token is consumed twice (#3469)", () => { + // Old opt() returned "--cdp-port" as the out-dir AND 19222 as the port. + // Now the single-pass parse refuses outright instead of splitting the + // token stream two ways. + expectUsage(["--out-dir", "--cdp-port", "19222"], "--out-dir"); +}); + +test("parseArgs: --cdp-port must be a decimal integer in 1-65535 (#3469)", () => { + for (const bad of ["banana", "", "0", "-1", "65536", "99999", "0x10", "1e2", "12.5", " 19222", "19222 "]) { + expectUsage(["--cdp-port", bad], "--cdp-port"); + } + assert.equal(parseArgs(["--cdp-port", "1"]).cdpPort, 1); + assert.equal(parseArgs(["--cdp-port", "65535"]).cdpPort, 65535); +}); + +test("parseArgs: unknown flags and bare positionals are usage errors (#3469)", () => { + expectUsage(["--bogus", "x"], "--bogus"); + expectUsage(["--out-dir=out"], "--out-dir=out"); + expectUsage(["out"], "out"); +}); diff --git a/pm-stack/supabase-export/supabase-quota-export.mjs b/pm-stack/supabase-export/supabase-quota-export.mjs index 499554506e..e5c8856e1f 100755 --- a/pm-stack/supabase-export/supabase-quota-export.mjs +++ b/pm-stack/supabase-export/supabase-quota-export.mjs @@ -28,6 +28,11 @@ * unparseable an endpoint answered a shape this parser does not know. * Exit 6. * + * Argv misuse (a value flag followed by another flag or by nothing, or + * an unknown flag) is a usage error naming the flag: stderr + exit 2 + * before anything runs — no directory is created, no token is resolved, + * and no document is written (#3469). + * * The management token is resolved by NAME from Bitwarden Secrets Manager at * runtime and sent only to api.supabase.com. Its value is never read into a * document, log line, fixture, or argv. @@ -367,14 +372,57 @@ export async function resolveToken({ secretName = process.env.SUPABASE_TOKEN_SEC } } -async function main() { - const args = process.argv.slice(2); - const opt = (name, fallback) => { - const i = args.indexOf(name); - return i >= 0 && args[i + 1] ? args[i + 1] : fallback; +/** Strict single-pass argv parsing (#3469). Every value-taking flag must be + * followed by a value token that is not itself a flag: a flag token (or + * nothing) where a value belongs is a usage error naming the flag, raised + * before any directory is created, any token is resolved, or any API call + * is made. The parse is single-pass — each value token is consumed once — + * so a flag token can never double as both a value and a flag. Unknown + * flags and bare positionals are usage errors too: silently ignoring them + * is what used to redirect output into a directory named after a flag. + * Throws ExportError("usage", 2); main() turns it into stderr + exit 2. */ +const VALUE_FLAGS = new Set(["--out-dir", "--project-ref"]); + +function usageError(message) { + throw new ExportError("usage", 2, message); +} + +export function parseArgs(argv) { + const values = {}; + for (let i = 0; i < argv.length; i++) { + const token = argv[i]; + if (!VALUE_FLAGS.has(token)) { + if (token.startsWith("--")) usageError(`unknown flag ${JSON.stringify(token)}`); + else usageError(`unexpected argument ${JSON.stringify(token)} (this exporter takes only --flag value pairs)`); + } + const value = argv[i + 1]; + if (typeof value !== "string" || value === "" || value.startsWith("--")) { + usageError( + `${token} requires a value that is not another flag (got ${value === undefined ? "nothing" : JSON.stringify(value)})`, + ); + } + values[token] = value; + i++; // consume the value: no token is read twice + } + return { + outDir: values["--out-dir"] ?? join(homedir(), "atlas", "supabase-export"), + ref: values["--project-ref"] ?? process.env.SUPABASE_PROJECT_REF ?? DEFAULT_PROJECT_REF, }; - const outDir = opt("--out-dir", join(homedir(), "atlas", "supabase-export")); - const ref = opt("--project-ref", process.env.SUPABASE_PROJECT_REF ?? DEFAULT_PROJECT_REF); +} + +async function main() { + let options; + try { + options = parseArgs(process.argv.slice(2)); + } catch (error) { + if (error instanceof ExportError && error.status === "usage") { + console.error(`supabase-quota-export: ${error.message}; refusing to run, no output written`); + process.exit(2); + } + throw error; + } + const outDir = options.outDir; + const ref = options.ref; try { const token = await resolveToken(); const doc = await run({ token, ref }); diff --git a/pm-stack/supabase-export/supabase-quota-export.test.mjs b/pm-stack/supabase-export/supabase-quota-export.test.mjs index bbe8061787..90455750f5 100644 --- a/pm-stack/supabase-export/supabase-quota-export.test.mjs +++ b/pm-stack/supabase-export/supabase-quota-export.test.mjs @@ -8,6 +8,7 @@ import { billedFromAddons, buildMetrics, failureDocument, + parseArgs, parseDbSize, parseRequestCount, run, @@ -154,4 +155,56 @@ describe("supabase-quota-export", () => { const metrics = buildMetrics({ dbBytes: null, bucketCount: null, requestTotal: null }); expect(metrics.every((m) => m.flag === undefined)).toBe(true); }); + + // Strict argv validation (#3469): a value flag followed by another + // flag (or by nothing) is a usage error naming the flag, raised before + // any directory creation, token resolution, or API call; no token is + // consumed twice. + function expectUsage(argv, flag) { + let error = null; + try { + parseArgs(argv); + } catch (e) { + error = e; + } + expect(error).toBeInstanceOf(ExportError); + expect(error.status).toBe("usage"); + expect(error.exitCode).toBe(2); + expect(error.message).toContain(flag); + } + + test("parseArgs: the control invocation parses, project-ref defaults (#3469)", () => { + expect(parseArgs(["--out-dir", "out", "--project-ref", "proberef"])).toEqual({ + outDir: "out", + ref: "proberef", + }); + const def = parseArgs([]); + expect(def.outDir).toMatch(/supabase-export$/); + expect(typeof def.ref).toBe("string"); + }); + + test("parseArgs: flag-as-value is a usage error naming the flag (#3469)", () => { + // The exact probe from the issue: --project-ref must not double as + // the out-dir value and the ref flag. + expectUsage(["--out-dir", "--project-ref", "proberef"], "--out-dir"); + expectUsage(["--project-ref", "--out-dir", "out"], "--project-ref"); + }); + + test("parseArgs: a trailing flag with no value is a usage error, not a silent fallback (#3469)", () => { + expectUsage(["--out-dir"], "--out-dir"); + expectUsage(["--out-dir", "out", "--project-ref"], "--project-ref"); + }); + + test("parseArgs: no token is consumed twice (#3469)", () => { + // Old opt() returned "--project-ref" as the out-dir while the API + // call still used proberef. Now the single-pass parse refuses + // outright instead of splitting the token stream two ways. + expectUsage(["--out-dir", "--project-ref", "proberef"], "--out-dir"); + }); + + test("parseArgs: unknown flags and bare positionals are usage errors (#3469)", () => { + expectUsage(["--bogus", "x"], "--bogus"); + expectUsage(["--out-dir=out"], "--out-dir=out"); + expectUsage(["out"], "out"); + }); });