From 7c7d6eeb71e13e764ce62c9c32ecba9de4c35b5b Mon Sep 17 00:00:00 2001 From: Abdel Fane <32418586+thebenignhacker@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:02:30 -0600 Subject: [PATCH] Load the cron handler without importing the ES-module route, compare CRON_SECRET in constant time, and read any NPM_CONFIG_DRY_RUN value but false, 0 or empty as a dry run (#67) Fixes #67 --- README.md | 3 ++- lib/cron.js | 34 ++++++++++++++++++++++----- pages/api/cron/collect.js | 9 ++----- scripts/collect-pypi-country-stats.js | 25 ++++++++++++-------- test/cron.test.js | 33 ++++++++++++++++++++++---- test/pypi-country-estimate.test.js | 26 +++++++++++++++++++- 6 files changed, 101 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index a20d9687..5d128a32 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,8 @@ both caps, and writes nothing. It exits 0 only when the next run would clear bot 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, as is -`npm_config_dry_run=true` set in the environment in any letter case. +`npm_config_dry_run` set in the environment to any value but `false`, `0` or empty, with the +name and the value in any letter case. `npm run collect:pypi-countries -- --help` (or `-h`) prints the usage and exits 0, even when other arguments are given with it. Without the `--`, `--help` goes to npm, which prints its own usage and runs nothing. Any other argument after the `--` is refused with a usage message and exit diff --git a/lib/cron.js b/lib/cron.js index 5752df49..636855fc 100644 --- a/lib/cron.js +++ b/lib/cron.js @@ -1,10 +1,11 @@ /** - * What the cron route (pages/api/cron/collect.js) runs, who may run it, and - * the environment it hands each child process, kept apart from the handler so - * all of it can be tested. + * What the cron route (pages/api/cron/collect.js) runs, who may run it, the + * environment it hands each child process, and its request handler, kept out + * of the ES-module route file so all of it can be tested with require(). */ const { execSync } = require('child_process'); +const crypto = require('crypto'); const path = require('path'); const CRON_COLLECTORS = [ @@ -48,15 +49,35 @@ function summaryEnv(env = process.env) { return { ...collectorEnv(env), ...pick(env, SUMMARY_ENV_KEYS) }; } +/** SHA-256 of a string: a fixed-length buffer whatever the input's length. */ +function digest(value) { + return crypto.createHash('sha256').update(value).digest(); +} + /** * True when the Authorization header carries CRON_SECRET as a bearer token. * Fails closed: with CRON_SECRET unset or empty nothing is authorized, since - * `Bearer undefined` and `Bearer ` are headers anyone can send. + * `Bearer undefined` and `Bearer ` are headers anyone can send. The header and + * the expected value are compared as equal-length digests with + * crypto.timingSafeEqual, so the time taken tells a caller neither how much + * of the header matched nor how long the secret is. */ function isAuthorized(authorization, env = process.env) { const secret = env.CRON_SECRET; - if (!secret) return false; - return authorization === `Bearer ${secret}`; + if (!secret || typeof authorization !== 'string') return false; + return crypto.timingSafeEqual(digest(authorization), digest(`Bearer ${secret}`)); +} + +/** + * The cron route's request handler: 401 unless isAuthorized, otherwise run + * every collector and answer with the results. It lives here, not in the + * ES-module route file, so tests can load it with require(). + */ +async function cronHandler(req, res) { + if (!isAuthorized(req.headers.authorization)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + return res.status(200).json(runCron()); } /** @@ -108,4 +129,5 @@ module.exports = { summaryEnv, isAuthorized, runCron, + cronHandler, }; diff --git a/pages/api/cron/collect.js b/pages/api/cron/collect.js index 75792a28..51fc0f69 100644 --- a/pages/api/cron/collect.js +++ b/pages/api/cron/collect.js @@ -1,8 +1,3 @@ -import { isAuthorized, runCron } from '../../../lib/cron.js'; +import { cronHandler } from '../../../lib/cron.js'; -export default async function handler(req, res) { - if (!isAuthorized(req.headers.authorization)) { - return res.status(401).json({ error: 'Unauthorized' }); - } - return res.status(200).json(runCron()); -} +export default cronHandler; diff --git a/scripts/collect-pypi-country-stats.js b/scripts/collect-pypi-country-stats.js index a2d0b9ea..40d66208 100644 --- a/scripts/collect-pypi-country-stats.js +++ b/scripts/collect-pypi-country-stats.js @@ -29,12 +29,12 @@ * ledger, no run status). It exits 0 only when the next run would clear both * 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 (in any letter case), which npm sets for - * `npm run collect:pypi-countries --dry-run`, selects it as well. `--help` - * or `-h` prints the usage and exits 0, whatever else is given; 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. + * npm_config_dry_run (in any letter case) set to anything but false, 0 or + * empty, as npm sets it for `npm run collect:pypi-countries --dry-run`, + * selects it as well. `--help` or `-h` prints the usage and exits 0, whatever + * else is given; 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 @@ -706,13 +706,18 @@ function mistypedDryRunOptions(env) { }); } +// The npm_config_dry_run values, in any letter case, that do not ask for a dry run. +const NOT_DRY_RUN = ['', 'false', '0']; + /** - * True when npm_config_dry_run is 'true'. npm reads its npm_config_ variables - * without regard to letter case, so NPM_CONFIG_DRY_RUN=true asks for a dry run - * as well; read as no argument, it would start a billed run. + * True when npm_config_dry_run is set to anything but false, 0 or empty. npm + * reads its npm_config_ variables without regard to letter case, so + * NPM_CONFIG_DRY_RUN=true asks for a dry run as well, and so do TRUE and 1; + * read as no argument, any of them would start a billed run. */ function npmDryRun(env) { - return Object.keys(env).some(key => key.toLowerCase() === 'npm_config_dry_run' && env[key] === 'true'); + return Object.keys(env).some(key => key.toLowerCase() === 'npm_config_dry_run' + && !NOT_DRY_RUN.includes(String(env[key]).trim().toLowerCase())); } /** diff --git a/test/cron.test.js b/test/cron.test.js index 35c54107..04153e9f 100644 --- a/test/cron.test.js +++ b/test/cron.test.js @@ -3,10 +3,10 @@ const assert = require('node:assert'); const { readFileSync, mkdtempSync, rmSync } = require('node:fs'); const { join } = require('node:path'); const { tmpdir } = require('node:os'); -const { pathToFileURL } = require('node:url'); +const crypto = require('node:crypto'); const { - CRON_COLLECTORS, COLLECTOR_ENV_KEYS, SUMMARY_ENV_KEYS, collectorEnv, isAuthorized, runCron, + CRON_COLLECTORS, COLLECTOR_ENV_KEYS, SUMMARY_ENV_KEYS, collectorEnv, isAuthorized, runCron, cronHandler, } = require('../lib/cron'); const SCRIPTS = join(__dirname, '..', 'scripts'); @@ -44,7 +44,6 @@ for (const [label, env, header] of [ ]) { test(`with CRON_SECRET ${label} the cron route answers 401 and runs nothing`, async () => { assert.equal(isAuthorized(header, env), false); - const { default: handler } = await import(pathToFileURL(ROUTE).href); const prevSecret = process.env.CRON_SECRET; const prevCwd = process.cwd(); // An empty directory holds no collector, so a route that let the request @@ -56,7 +55,7 @@ for (const [label, env, header] of [ const res = { statusCode: null, body: null }; res.status = (code) => { res.statusCode = code; return res; }; res.json = (obj) => { res.body = obj; return res; }; - await handler({ headers: { authorization: header } }, res); + await cronHandler({ headers: { authorization: header } }, res); assert.equal(res.statusCode, 401); assert.deepEqual(res.body, { error: 'Unauthorized' }); } finally { @@ -67,6 +66,32 @@ for (const [label, env, header] of [ }); } +// The route file is ES-module syntax in a package without "type": "module"; +// importing it from a test fails on Node before 20.19 and warns after, so the +// tests load its handler from lib/cron.js and check the route serves that one. +test('the cron route serves the handler in lib/cron.js', () => { + const source = readFileSync(ROUTE, 'utf8'); + assert.match(source, /^import \{ cronHandler \} from '\.\.\/\.\.\/\.\.\/lib\/cron\.js';$/m); + assert.match(source, /^export default cronHandler;$/m); +}); + +test('the cron route compares the Authorization header in constant time', () => { + const env = { CRON_SECRET: 's3cret' }; + const original = crypto.timingSafeEqual; + const lengths = []; + crypto.timingSafeEqual = (a, b) => { lengths.push([a.length, b.length]); return original(a, b); }; + try { + assert.equal(isAuthorized('Bearer s3cret', env), true); + assert.equal(isAuthorized('Bearer s3cres', env), false); + assert.equal(isAuthorized('Bearer a-much-longer-wrong-token', env), false); + assert.equal(isAuthorized(['Bearer s3cret'], env), false); + } finally { + crypto.timingSafeEqual = original; + } + assert.equal(lengths.length, 3, 'every string header goes through crypto.timingSafeEqual'); + for (const [a, b] of lengths) assert.equal(a, b, 'the buffers compared are of equal length'); +}); + test('the cron route accepts only the bearer token in CRON_SECRET', () => { const env = { CRON_SECRET: 's3cret' }; assert.equal(isAuthorized('Bearer s3cret', env), true); diff --git a/test/pypi-country-estimate.test.js b/test/pypi-country-estimate.test.js index 59e76054..e9f53e79 100644 --- a/test/pypi-country-estimate.test.js +++ b/test/pypi-country-estimate.test.js @@ -371,7 +371,7 @@ test('the npm options npm 11 sets for every `npm run`, and the loglevel a flag s }); // Each is caught by one clause of the check alone: dry_running only by the -// `dry` prefix (it is 3 edits from dryrun), NPM_CONFIG_DRYRUN only by reading +// `dry` prefix (it is 4 edits from dryrun), NPM_CONFIG_DRYRUN only by reading // the npm_config_ prefix in any letter case, and npm_config_dryrun beside // --dry-run only because the check also runs when --dry-run is given. for (const [argv, key] of [ @@ -406,6 +406,30 @@ test('NPM_CONFIG_DRY_RUN=true, which npm reads as its dry-run option, is a dry r } }); +test('npm_config_dry_run set to anything but false, 0 or empty, in any letter case, is a dry run', () => { + for (const value of ['true', 'TRUE', 'True', '1', 'yes']) { + assert.deepEqual(parseArgs([], { NPM_CONFIG_DRY_RUN: value }), { dryRun: true }, `NPM_CONFIG_DRY_RUN=${value}`); + assert.deepEqual(parseArgs([], { npm_config_dry_run: value }), { dryRun: true }, `npm_config_dry_run=${value}`); + } + for (const value of ['false', 'FALSE', 'False', '0', '']) { + assert.deepEqual(parseArgs([], { NPM_CONFIG_DRY_RUN: value }), { dryRun: false }, `NPM_CONFIG_DRY_RUN=${value}`); + } +}); + +for (const value of ['TRUE', '1']) { + test(`NPM_CONFIG_DRY_RUN=${value} without credentials takes the dry-run path and writes no run status`, async () => { + const dir = tmp(); + try { + const res = await runScript([], join(dir, 'analytics.db'), { NPM_CONFIG_DRY_RUN: value }); + assert.equal(res.status, 1, `expected exit 1; stdout:\n${res.stdout}\nstderr:\n${res.stderr}`); + assert.match(res.stdout, /nothing was measured/i); + assert.ok(!existsSync(join(dir, RUN_FILE)), 'a dry run writes no run status'); + } finally { + rmSync(dir, { recursive: true, force: 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 {