Skip to content
Closed
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
62 changes: 55 additions & 7 deletions pm-stack/cloudflare-export/cloudflare-quota-export.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -607,17 +612,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 }));
Expand Down
53 changes: 53 additions & 0 deletions pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
failureDocument,
foldKv,
listR2Buckets,
parseArgs,
parseGraphqlUsage,
R2_STORAGE_GROUP_LIMIT,
run,
Expand Down Expand Up @@ -494,6 +495,58 @@ 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");
});

// #2574: R2 bucket enumeration is explicit — unknown is null plus a
// detail, never a silent [] or a truncated page. Bucket pages are
// consumed in order for /r2/buckets; billing probes and GraphQL stay
Expand Down
74 changes: 66 additions & 8 deletions pm-stack/meta-exporter/meta-quota-export.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down
62 changes: 62 additions & 0 deletions pm-stack/meta-exporter/meta-quota-export.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
ExportError,
exportAndWrite,
failureDocument,
parseArgs,
parseBillingBanner,
parsePaygBalance,
parseSubscriptionQuota,
Expand Down Expand Up @@ -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");
});
62 changes: 55 additions & 7 deletions pm-stack/supabase-export/supabase-quota-export.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 });
Expand Down
Loading