From 14ec144a485b7a1ff54680b2afd7b96cfed2ce60 Mon Sep 17 00:00:00 2001 From: Abdel Fane <32418586+thebenignhacker@users.noreply.github.com> Date: Wed, 7 Oct 2026 16:37:39 -0600 Subject: [PATCH] Refuse mistyped npm dry-run flags, answer --help, roll up on every early stop, and stop passing Google credentials to cron collectors (#63) Fixes #63 --- README.md | 16 +++-- lib/cron.js | 37 +++++++++++ pages/api/cron/collect.js | 29 +------- scripts/collect-pypi-country-stats.js | 96 ++++++++++++++++++++++----- test/cron.test.js | 33 +++++++++ test/pypi-country-collector.test.js | 34 ++++++++++ test/pypi-country-estimate.test.js | 50 ++++++++++++++ test/telemetry-collector.test.js | 31 ++++++++- 8 files changed, 277 insertions(+), 49 deletions(-) create mode 100644 lib/cron.js create mode 100644 test/cron.test.js diff --git a/README.md b/README.md index 23ab5c1c..32391410 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,9 @@ dry run first, then sent to BigQuery as `maximumBytesBilled`, so BigQuery refuse would bill more; such a refusal bills nothing and ends the run with status `refused_cap`) and 768 GiB per calendar month (a ledger in `data/pypi-country-budget.json`). The month-to-date figure is never lower than the bytes the database's fetch records show billed -that month, so a checkout without the ledger file still counts the month's earlier queries. +that month, so a checkout without the ledger file still counts the days landed earlier that month. +Without the ledger file it does not count a billed query that failed, since only the ledger +records that charge. To see what the next run would scan before paying for it: @@ -116,10 +118,14 @@ This issues only BigQuery dry runs, which are not billed, prints each day's scan both caps, and writes nothing. It exits 0 only when the next run would clear both caps. When every day in the window is already fetched, the next run bills nothing; the dry run then measures yesterday as a sample and reports whether a new day of that size would clear both caps. -`npm run collect:pypi-countries --dry-run` (without the `--`) is also a dry run. Any other -argument after the `--` is refused with a usage message and exit code 2. A flag given without -the `--` goes to npm, not to the collector's arguments, so a mistyped -`npm run collect:pypi-countries --dryrun` is not refused: the run collects as normal. +`npm run collect:pypi-countries --dry-run` (without the `--`) is also a dry run, and +`npm run collect:pypi-countries -- --help` prints the usage and exits 0. Any other argument after +the `--` is refused with a usage message and exit code 2. A flag given without the `--` goes to +npm, which passes it on as an `npm_config_` variable rather than as an argument; one that looks +like a mistyped `--dry-run`, such as `npm run collect:pypi-countries --dryrun`, is refused the +same way before anything runs. Any other flag given without the `--` is left to npm, and the +run collects as normal. npm 11 warns that the next major version of npm will stop accepting unknown +flags, which would change how these arrive. ## Automated daily collection diff --git a/lib/cron.js b/lib/cron.js new file mode 100644 index 00000000..50e6051d --- /dev/null +++ b/lib/cron.js @@ -0,0 +1,37 @@ +/** + * What the cron route (pages/api/cron/collect.js) runs, and the environment it + * hands each collector, kept apart from the handler so both can be tested. + */ + +const CRON_COLLECTORS = [ + { name: 'github', script: 'collect-stats.js', needsToken: true }, + { name: 'npm', script: 'collect-npm-stats.js', needsToken: false }, + { name: 'pypi', script: 'collect-pypi-stats.js', needsToken: false }, + { name: 'docker', script: 'collect-docker-stats.js', needsToken: false }, + { name: 'huggingface', script: 'collect-huggingface-stats.js', needsToken: false }, + { name: 'telemetry', script: 'collect-telemetry-stats.js', needsToken: false }, +]; + +// Pass only the variables the collectors actually need to the child processes, +// rather than spreading the entire environment (which would leak unrelated +// secrets into every subprocess). Add new collector config keys here. No +// Google Cloud credentials: only the BigQuery country collector reads them, +// and the route does not run it. +const COLLECTOR_ENV_KEYS = [ + 'PATH', 'NODE_ENV', 'HOME', + 'GITHUB_TOKEN', 'GITHUB_ORG', 'REPOS_TO_TRACK', + 'NPM_AUTHOR', 'NPM_PACKAGES', + 'PYPI_PACKAGES', + 'DOCKER_IMAGES', + 'HF_AUTHOR', 'HF_MODELS', 'HF_TOKEN', + 'REGISTRY_URL', +]; + +/** The allowlisted subset of `env` that a collector child process receives. */ +function collectorEnv(env = process.env) { + return Object.fromEntries( + COLLECTOR_ENV_KEYS.filter(k => env[k] !== undefined).map(k => [k, env[k]]) + ); +} + +module.exports = { CRON_COLLECTORS, COLLECTOR_ENV_KEYS, collectorEnv }; diff --git a/pages/api/cron/collect.js b/pages/api/cron/collect.js index 0ecd0cc0..3561bd72 100644 --- a/pages/api/cron/collect.js +++ b/pages/api/cron/collect.js @@ -1,5 +1,6 @@ const { execSync } = require('child_process'); const path = require('path'); +const { CRON_COLLECTORS, collectorEnv } = require('../../../lib/cron'); export default async function handler(req, res) { const authHeader = req.headers.authorization; @@ -10,33 +11,9 @@ export default async function handler(req, res) { const results = { timestamp: new Date().toISOString(), collectors: {} }; const scriptsDir = path.join(process.cwd(), 'scripts'); - // Pass only the variables the collectors actually need to the child processes, - // rather than spreading the entire environment (which would leak unrelated - // secrets into every subprocess). Add new collector config keys here. - const ALLOWED_ENV = [ - 'PATH', 'NODE_ENV', 'HOME', - 'GITHUB_TOKEN', 'GITHUB_ORG', 'REPOS_TO_TRACK', - 'NPM_AUTHOR', 'NPM_PACKAGES', - 'PYPI_PACKAGES', - 'DOCKER_IMAGES', - 'HF_AUTHOR', 'HF_MODELS', 'HF_TOKEN', - 'GOOGLE_APPLICATION_CREDENTIALS', 'GOOGLE_APPLICATION_CREDENTIALS_JSON', - 'REGISTRY_URL', - ]; - const childEnv = Object.fromEntries( - ALLOWED_ENV.filter(k => process.env[k] !== undefined).map(k => [k, process.env[k]]) - ); + const childEnv = collectorEnv(); - const collectors = [ - { name: 'github', script: 'collect-stats.js', needsToken: true }, - { name: 'npm', script: 'collect-npm-stats.js', needsToken: false }, - { name: 'pypi', script: 'collect-pypi-stats.js', needsToken: false }, - { name: 'docker', script: 'collect-docker-stats.js', needsToken: false }, - { name: 'huggingface', script: 'collect-huggingface-stats.js', needsToken: false }, - { name: 'telemetry', script: 'collect-telemetry-stats.js', needsToken: false }, - ]; - - for (const collector of collectors) { + for (const collector of CRON_COLLECTORS) { if (collector.needsToken && !process.env.GITHUB_TOKEN) { results.collectors[collector.name] = { status: 'skipped', reason: 'no GITHUB_TOKEN' }; continue; diff --git a/scripts/collect-pypi-country-stats.js b/scripts/collect-pypi-country-stats.js index 7f397ea8..d437dcb2 100644 --- a/scripts/collect-pypi-country-stats.js +++ b/scripts/collect-pypi-country-stats.js @@ -8,14 +8,15 @@ * and a job it refuses there ends the run as refused_cap) * - 768 GiB per month (a persisted ledger of billed bytes, data/pypi-country-budget.json, * floored by the bytes the store's fetch records show billed this month, - * so a checkout that lacks the ledger file still counts the month's spend) + * so a checkout that lacks the ledger file still counts the days landed + * this month, though not a billed call that failed) * * Per run it fetches at most three missing closed days (newest first, from the * 30 most recent closed days; no backfill beyond that window), lands the rows * in pypi_country_daily keyed by the closed day itself, then rewrites the * 30-day rollup in pypi_country_downloads as a local SUM — no query. A run - * that stops early (a cap, a refusal, an error) still rewrites the rollup - * when it landed at least one day. + * that stops early (a cap, a refusal, an error) still rewrites the rollup, + * whether or not it landed a day. * * Every run ends by persisting data/pypi-country-run.json with a status from * {ok, empty, skipped_no_credentials, refused_cap, capped_month, error}. A @@ -29,8 +30,10 @@ * caps; when every candidate day is already fetched, it measures D-1 as a * sample and exits 0 only when a new day of that size would clear them. * npm_config_dry_run=true, which npm sets for - * `npm run collect:pypi-countries --dry-run`, selects it as well; any other - * argument exits 2 with a usage message before anything runs. + * `npm run collect:pypi-countries --dry-run`, selects it as well. `--help` + * prints the usage and exits 0; any other argument, and an npm option that + * looks like a mistyped --dry-run (npm_config_dryrun from `--dryrun`), exits 2 + * with a usage message before anything runs. * * The client port this module consumes: one async `query(options)` that * resolves to { rows, totalBytesProcessed } for both dry and billed runs. A @@ -253,7 +256,9 @@ function storeMonthBytes(db, month) { * because either one can be stale. The ledger file is not committed, so a * checkout may lack it or carry one older than the store's fetch records; * the store never sees the reservation the ledger keeps for a billed call - * that failed. Taking the larger can over-count, never under-count. + * that failed. Taking the larger never reads below either source, but it can + * still under-count: once the ledger file is gone, so is the reservation for + * a billed call that failed, since the store records only days that landed. */ function monthToDate(db, dataDir, month) { return Math.max(readBudget(dataDir, month), storeMonthBytes(db, month)); @@ -439,10 +444,11 @@ async function collect({ }); let rowsLanded = 0; - // A run that stops early still rolls up the days it already landed, so - // the 30-day total never lags the daily rows. + // A run that stops early still rewrites the rollup, whether or not it + // landed a day: the daily rows may hold days an earlier run stored and + // never rolled up, and the asOf it reports must have its 30-day total. const stop = (status) => finish(status, { - asOf: daysFetched > 0 ? rollupCountryDownloads(db, now) : newestStoredDay(db), + asOf: rollupCountryDownloads(db, now), daysFetched, bytesBilled: runBytes, exitCode: 1, }); for (const day of missingDays) { @@ -513,9 +519,10 @@ async function collect({ console.error('PyPI country collection failed: %s', error.message); let asOf = null; if (db) { - // Days that landed before the failure still reach the rollup. + // Stored days, including any this run landed before the failure, still + // reach the rollup. try { - asOf = daysFetched > 0 ? rollupCountryDownloads(db, now) : newestStoredDay(db); + asOf = rollupCountryDownloads(db, now); } catch { try { asOf = newestStoredDay(db); } catch { /* keep null */ } } @@ -643,25 +650,79 @@ async function estimate({ } } -const USAGE = 'Usage: npm run collect:pypi-countries -- [--dry-run]'; +const USAGE = 'Usage: npm run collect:pypi-countries -- [--dry-run | --help]'; + +const HELP = `${USAGE} + +Without an argument it collects up to ${MAX_DAYS_PER_RUN} missing closed days from BigQuery, +within a ${PER_QUERY_CAP_BYTES / 1073741824} GiB per-query cap and a ${MONTH_CAP_BYTES / 1073741824} GiB monthly cap. + + --dry-run measure what the next run would scan against both caps; + bills nothing and writes nothing + --help print this message`; + +/** Levenshtein distance between two short strings. */ +function editDistance(a, b) { + let prev = Array.from({ length: b.length + 1 }, (_, j) => j); + for (let i = 1; i <= a.length; i++) { + const row = [i]; + for (let j = 1; j <= b.length; j++) { + row[j] = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); + } + prev = row; + } + return prev[b.length]; +} + +/** + * npm options in `env` that look like a mistyped --dry-run. A flag given + * without the `--` separator goes to npm, not to the collector's arguments, + * and npm passes even one it does not know on as npm_config_, lowercased: + * `npm run collect:pypi-countries --dryrun` arrives only as + * npm_config_dryrun=true. Read as no argument, it would start the billed run + * the flag was meant to measure. npm_config_dry_run is the dry run itself. + */ +function mistypedDryRunOptions(env) { + return Object.keys(env).filter(key => { + if (!key.toLowerCase().startsWith('npm_config_')) return false; + const name = key.slice('npm_config_'.length).toLowerCase(); + if (name === 'dry_run') return false; + const bare = name.replace(/[-_]/g, ''); + return bare.startsWith('dry') || editDistance(bare, 'dryrun') <= 2; + }); +} /** - * Read the command line. `--dry-run` is the only argument; anything else is - * refused, never read as a request for a billed collection. Without the `--` - * separator, `npm run collect:pypi-countries --dry-run` keeps the flag for - * npm, which passes it on as npm_config_dry_run=true, so that is a dry run - * too. Returns { dryRun } or { error }. + * Read the command line. `--dry-run` is the only argument besides `--help` + * (or `-h`); anything else is refused, never read as a request for a billed + * collection. Without the `--` separator, `npm run collect:pypi-countries + * --dry-run` keeps the flag for npm, which passes it on as + * npm_config_dry_run=true, so that is a dry run too, and an npm option that + * looks like a mistyped --dry-run is refused. Returns { help }, { dryRun } or + * { error }. */ function parseArgs(argv, env = process.env) { + if (argv.includes('--help') || argv.includes('-h')) return { help: true }; const unknown = argv.filter(arg => arg !== '--dry-run'); if (unknown.length > 0) { return { error: `Unrecognised argument(s): ${unknown.join(' ')}` }; } + const mistyped = mistypedDryRunOptions(env); + if (mistyped.length > 0) { + return { + error: `Unrecognised npm option(s): ${mistyped.join(' ')}. A flag given without the -- separator ` + + 'goes to npm, which passed it on under that name; the dry-run flag is --dry-run.', + }; + } return { dryRun: argv.includes('--dry-run') || env.npm_config_dry_run === 'true' }; } async function main() { const args = parseArgs(process.argv.slice(2)); + if (args.help) { + console.log(HELP); + return; + } if (args.error) { console.error(args.error); console.error(USAGE); @@ -696,4 +757,5 @@ module.exports = { BUDGET_FILE, RUN_FILE, readByteFigure, + parseArgs, }; diff --git a/test/cron.test.js b/test/cron.test.js new file mode 100644 index 00000000..83c8b91a --- /dev/null +++ b/test/cron.test.js @@ -0,0 +1,33 @@ +const { test } = require('node:test'); +const assert = require('node:assert'); +const { readFileSync } = require('node:fs'); +const { join } = require('node:path'); + +const { CRON_COLLECTORS, COLLECTOR_ENV_KEYS, collectorEnv } = require('../lib/cron'); + +const SCRIPTS = join(__dirname, '..', 'scripts'); +const PROCESS_KEYS = ['PATH', 'NODE_ENV', 'HOME']; + +test('the cron route hands its collectors no Google Cloud credential variable', () => { + const env = collectorEnv({ + PATH: '/usr/bin', + NPM_PACKAGES: 'hackmyagent', + GOOGLE_APPLICATION_CREDENTIALS: '/keys/service-account.json', + GOOGLE_APPLICATION_CREDENTIALS_JSON: '{"type":"service_account"}', + GOOGLE_CLOUD_PROJECT: 'example-project', + CRON_SECRET: 'not-for-collectors', + }); + assert.deepEqual(env, { PATH: '/usr/bin', NPM_PACKAGES: 'hackmyagent' }); +}); + +test('every config variable the cron route passes on is read by a collector it runs', () => { + const sources = CRON_COLLECTORS.map(c => readFileSync(join(SCRIPTS, c.script), 'utf8')); + const unread = COLLECTOR_ENV_KEYS + .filter(key => !PROCESS_KEYS.includes(key)) + .filter(key => !sources.some(source => source.includes(key))); + assert.deepEqual(unread, [], 'a variable no collector reads is a secret handed out for nothing'); +}); + +test('the cron route does not run the BigQuery country collector', () => { + assert.ok(!CRON_COLLECTORS.some(c => c.script === 'collect-pypi-country-stats.js')); +}); diff --git a/test/pypi-country-collector.test.js b/test/pypi-country-collector.test.js index 677c4744..ce6a78d5 100644 --- a/test/pypi-country-collector.test.js +++ b/test/pypi-country-collector.test.js @@ -565,6 +565,40 @@ for (const [label, status, second, ledger] of [ }); } +for (const [label, status, second, ledger] of [ + ['its dry run is over the per-query cap', 'refused_cap', { dryBytes: PER_QUERY_CAP_BYTES + 1 }], + ['BigQuery refuses its billed job at the ceiling', 'refused_cap', { billedError: ceilingRefusal() }], + ['its estimate would pass the monthly cap', 'capped_month', { dryBytes: 1000 }, MONTH_CAP_BYTES - 500], + ['its dry run is unreadable', 'error', { dryBytes: 'abc' }], + ['its billed call fails', 'error', { billedError: new Error('backend error') }], +]) { + test(`a run that lands nothing and stops because ${label} still rolls up the days already stored`, async () => { + const dir = tmp(); + try { + // D-1 is stored and fetched but its rollup is empty; only D-2 is missing. + const dbPath = makeStore(dir, { + fetchedDays: ALL_CANDIDATES.filter(d => d !== dayBefore(2)), + daily: [{ pkg: 5, date: dayBefore(1), cc: 'DE', dl: 7 }], + }); + if (ledger !== undefined) { + writeFileSync(join(dir, BUDGET_FILE), JSON.stringify({ month: '2026-09', bytesBilled: ledger })); + } + const res = await runCollect(dbPath, secondDayStops(second)); + assert.equal(res.status, status); + assert.equal(res.exitCode, 1); + assert.equal(res.daysFetched, 0); + assert.equal(res.asOf, dayBefore(1)); + const db = new Database(dbPath, { readonly: true }); + const rows = db.prepare('SELECT package_id, date, country_code, downloads FROM pypi_country_downloads').all(); + db.close(); + assert.deepEqual(rows, [{ package_id: 5, date: dayBefore(1), country_code: 'DE', downloads: 7 }], + 'the reported as-of day has its 30-day total'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +} + // --------------------------------------------------------------------------- // AC7 — scheduled run without credentials exits 1; population needs no env // --------------------------------------------------------------------------- diff --git a/test/pypi-country-estimate.test.js b/test/pypi-country-estimate.test.js index 482aab8b..21078ca4 100644 --- a/test/pypi-country-estimate.test.js +++ b/test/pypi-country-estimate.test.js @@ -13,6 +13,7 @@ const { MONTH_CAP_BYTES, BUDGET_FILE, RUN_FILE, + parseArgs, } = require('../scripts/collect-pypi-country-stats'); const SCRIPT = join(__dirname, '..', 'scripts', 'collect-pypi-country-stats.js'); @@ -319,6 +320,55 @@ for (const args of [['--dryrun'], ['--dry-run', 'extra'], ['--dry-run=true']]) { }); } +for (const args of [['--help'], ['-h'], ['--help', '--dry-run']]) { + test(`\`${args.join(' ')}\` prints the usage and exits 0 without starting a run`, async () => { + const dir = tmp(); + try { + const dbPath = makeStore(dir); + const before = snapshot(dir); + const res = await runScript(args, dbPath); + assert.equal(res.status, 0, `expected exit 0; stdout:\n${res.stdout}\nstderr:\n${res.stderr}`); + assert.match(res.stdout, /usage:/i); + assert.match(res.stdout, /--dry-run/); + assert.equal(res.stderr, ''); + assert.doesNotMatch(res.stdout, /credentials not configured/i, 'no collection was started'); + assert.deepEqual(snapshot(dir), before, 'no run status is written'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +} + +// What npm 11 passes on for `npm run collect:pypi-countries --dryrun`, +// `--dry_rn` and `--dyrrun`: an unknown flag given without the -- arrives as an +// npm_config_ variable, never as an argument. +for (const key of ['npm_config_dryrun', 'npm_config_dry_rn', 'npm_config_dyrrun']) { + test(`${key}=true, a mistyped dry-run flag that npm passed on, is refused and starts nothing`, async () => { + const dir = tmp(); + try { + const dbPath = makeStore(dir); + const before = snapshot(dir); + const res = await runScript([], dbPath, { [key]: 'true' }); + assert.equal(res.status, 2, `expected exit 2; stdout:\n${res.stdout}\nstderr:\n${res.stderr}`); + assert.ok(res.stderr.includes(key), `the refusal names ${key}; stderr:\n${res.stderr}`); + assert.match(res.stderr, /usage:/i); + assert.doesNotMatch(res.stdout, /credentials not configured/i, 'no collection was started'); + assert.deepEqual(snapshot(dir), before, 'no run status is written'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +} + +test('the npm options npm 11 sets for every `npm run` are not read as a mistyped dry-run flag', () => { + const npmEnv = Object.fromEntries([ + 'allow_scripts', 'cache', 'global_prefix', 'globalconfig', 'init_module', 'local_prefix', + 'loglevel', 'node_gyp', 'noproxy', 'npm_version', 'prefix', 'user_agent', 'userconfig', + ].map(name => [`npm_config_${name}`, 'x'])); + assert.deepEqual(parseArgs([], npmEnv), { dryRun: false }); + assert.deepEqual(parseArgs([], { ...npmEnv, npm_config_dry_run: 'true' }), { dryRun: true }); +}); + test('npm_config_dry_run=true, which `npm run collect:pypi-countries --dry-run` sets, is a dry run', async () => { const dir = tmp(); try { diff --git a/test/telemetry-collector.test.js b/test/telemetry-collector.test.js index 717a212f..609eb733 100644 --- a/test/telemetry-collector.test.js +++ b/test/telemetry-collector.test.js @@ -2,7 +2,7 @@ const { test } = require('node:test'); const assert = require('node:assert'); const { spawn } = require('node:child_process'); const { mkdtempSync, rmSync, writeFileSync } = require('node:fs'); -const { join } = require('node:path'); +const { join, dirname } = require('node:path'); const { tmpdir } = require('node:os'); const http = require('node:http'); const Database = require('better-sqlite3'); @@ -45,6 +45,10 @@ function makeDb(dir, rows = []) { * Async on purpose: spawnSync blocks this process's event loop, so the * in-process fixture server below could never accept the child's connection — * the child would hang until its feed timeout. Use spawn and await. + * + * The child runs in the fixture database's temporary directory, so the .env it + * loads is the test's, never the one at the repository root, which may name a + * real Registry. An `env` value of undefined drops that variable. */ function run(env, dbFile) { return new Promise((resolve) => { @@ -59,6 +63,7 @@ function run(env, dbFile) { TELEMETRY_FEED_TIMEOUT_MS: '5000', ...env, }, + cwd: dirname(dbFile), }); let stdout = ''; let stderr = ''; @@ -270,6 +275,30 @@ test('a brand-new deployment reporting zero is not an outage', async () => { } }); +test('the spawned collector loads .env from the test directory, not the repository root', async () => { + const dir = tmp(); + try { + let requests = 0; + await withServer( + (req, res) => { + requests += 1; + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ totalInstalls: 0, wau: 0, mau: 0, tools: [], byCountry: [] })); + }, + async (url) => { + // REGISTRY_URL is dropped from the child's environment, so only the + // test directory's .env can point the collector at this server. + writeFileSync(join(dir, '.env'), `REGISTRY_URL=${url}\n`); + const res = await run({ REGISTRY_URL: undefined }, makeDb(dir)); + assert.equal(requests, 1, `the test directory's .env was not loaded; stdout:\n${res.stdout}`); + assert.equal(res.status, 0, `expected exit 0; stdout:\n${res.stdout}\nstderr:\n${res.stderr}`); + } + ); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + test('importing the script does not execute it', () => { // require.main === module guards every side effect; without it, importing for // a unit test would run a collection and possibly process.exit the test runner.