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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 28 additions & 6 deletions lib/cron.js
Original file line number Diff line number Diff line change
@@ -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 = [
Expand Down Expand Up @@ -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());
}

/**
Expand Down Expand Up @@ -108,4 +129,5 @@ module.exports = {
summaryEnv,
isAuthorized,
runCron,
cronHandler,
};
9 changes: 2 additions & 7 deletions pages/api/cron/collect.js
Original file line number Diff line number Diff line change
@@ -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;
25 changes: 15 additions & 10 deletions scripts/collect-pypi-country-stats.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()));
}

/**
Expand Down
33 changes: 29 additions & 4 deletions test/cron.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -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);
Expand Down
26 changes: 25 additions & 1 deletion test/pypi-country-estimate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 [
Expand Down Expand Up @@ -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 {
Expand Down
Loading