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
40 changes: 35 additions & 5 deletions pm-stack/aggregator/scripts/backfill-usage-snapshots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,42 @@ import type { SnapshotRecord } from "../src/model.ts";

const PKG = join(dirname(fileURLToPath(import.meta.url)), "..");
const HOME = homedir();
const dirArg = process.argv.indexOf("--dir");
const dirValue = dirArg >= 0 ? process.argv[dirArg + 1] : undefined;
if (dirArg >= 0 && (!dirValue?.trim() || dirValue.trimStart().startsWith("--"))) {
console.error("backfill-usage-snapshots: --dir requires a directory value (not another option)");
process.exit(2);
// Strict operator-argument contract (#6973): the only accepted forms are
// no arguments or one documented separated `--dir <storeDir>`. Every other
// token - an unknown or misspelled flag, a positional, the joined
// `--dir=<path>` form, or a duplicate `--dir` - is a usage error (exit 2)
// raised here, before any input is read or any store is written: a typo'd
// `--dirr <dir>` used to fall through to the default store and seed the
// rebuilt history there, exit 0. Mirrors rejectUnknownArgs in
// append-usage-snapshots.ts (#6961) / compact-usage-snapshots.ts (#6967);
// the `--dir` value guard itself is #3330.
function parseStoreDirArg(): string | undefined {
const args = process.argv.slice(2);
let dir: string | undefined;
for (let i = 0; i < args.length; i++) {
const arg = args[i] as string;
if (arg === "--dir") {
if (dir !== undefined) {
console.error("backfill-usage-snapshots: duplicate --dir; the documented form is a single --dir <storeDir>");
process.exit(2);
}
const value: string | undefined = args[i + 1];
if (!value?.trim() || value.trimStart().startsWith("--")) {
console.error("backfill-usage-snapshots: --dir requires a directory value (not another option)");
process.exit(2);
}
dir = value;
i++;
continue;
}
console.error(
"backfill-usage-snapshots: unknown argument '" + arg + "' (usage: [--dir <storeDir>]); refusing to run, store untouched",
);
process.exit(2);
}
return dir;
}
const dirValue = parseStoreDirArg();
const storeDir = dirValue ?? process.env.PM_AGG_SNAPSHOTS_DIR ?? join(PKG, "snapshots");
const quotaViewPath =
process.env.QUOTA_VIEW_PATH ??
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Pinning test for #6973: backfill-usage-snapshots must reject every
// argument other than a single separated `--dir <storeDir>` with a usage
// error (exit 2), before reading inputs or creating/writing any store.
// A typo'd `--dirr <dir>` used to be silently ignored and the rebuilt
// history was appended to the DEFAULT store, exit 0. The `--dir` value
// guard itself is pinned by backfill-usage-snapshots-dir-3330.test.ts.
import { describe, expect, test } from "bun:test";
import { mkdtemp, readdir, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const script = join(import.meta.dir, "../scripts/backfill-usage-snapshots.ts");

async function runScript(cwd: string, args: string[]): Promise<{ code: number; stderr: string; stdout: string }> {
const proc = Bun.spawn([process.execPath, script, ...args], {
cwd,
env: {
...process.env,
PM_AGG_SNAPSHOTS_DIR: join(cwd, "default-store"),
QUOTA_VIEW_PATH: join(cwd, "quota-view.md"),
QUOTA_REGISTRY_PATH: join(cwd, "registry.md"),
},
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 };
}

describe("backfill-usage-snapshots strict argv (#6973)", () => {
test("unknown, misspelled, positional, joined, and duplicate arguments exit 2 before any store is created", async () => {
const cwd = await mkdtemp(join(tmpdir(), "backfill-argv-6973-"));
try {
// Deliberately absent inputs prove validation precedes file reads.
const cases: { args: string[]; named: string }[] = [
{ args: ["--bogus"], named: "--bogus" },
{ args: ["--dirr", join(cwd, "intended-store")], named: "--dirr" },
{ args: ["somefile"], named: "somefile" },
{ args: [`--dir=${join(cwd, "joined-store")}`], named: "--dir=" },
{ args: ["--dir", join(cwd, "dup-a"), "--dir", join(cwd, "dup-b")], named: "--dir" },
];
for (const { args, named } of cases) {
const { code, stderr } = await runScript(cwd, args);
expect(code, `args ${JSON.stringify(args)}`).toBe(2);
expect(stderr, `args ${JSON.stringify(args)}`).toContain(named);
}
// No store directory was created by any rejected invocation: neither
// the env default nor any operator-named directory.
for (const dir of ["default-store", "intended-store", "joined-store", "dup-a", "dup-b"]) {
await expect(readdir(join(cwd, dir))).rejects.toMatchObject({ code: "ENOENT" });
}
} finally {
await rm(cwd, { recursive: true, force: true });
}
}, 30000);
});
Loading