screentinker/server/test/totp-keyrotation.test.js
screentinker 12c0004245
test(ci): OS-assigned ephemeral ports for subprocess suites — kill the port-collision flake (#176)
The subprocess-booting test suites hand-picked fixed ports in a cramped ~3955-4021 range, and
156-schedule-read-path deviated to a RANDOM port (3900 + rand%90) that overlapped those fixed
ports. Under CI load two servers could race on the same port, surfacing as flaky "no such table:
devices" / "FOREIGN KEY constraint failed" (a server answering a request against a half-migrated
or wrong DB). It's environmental — the suites pass locally and in isolation.

Fix: a shared test/helpers/free-port.js (bind :0 on loopback, read the OS-assigned port, release)
called in before() so every suite gets a guaranteed-unique ephemeral port — concurrent suites can
no longer collide, and no one has to hand-assign ports.

- Codemod converted 30 suites: const PORT = <fixed|random> -> let PORT (+ BASE) assigned via
  `PORT = await freePort()` at the top of before().
- 3 hand-fixed (different structure): 148-eviction-storm (lowercase `base`), boot-health (no
  before() — allocates PORT + a throwaway SEED_PORT inside the test, replacing the hardcoded
  3894), totp-keyrotation (no before() — allocates at the test start before bootServer()).

No fixed 39xx/40xx ports remain. Full server suite 435/435; the 4 hand-touched suites pass in
isolation. Pure test-infra change — no app code touched.
2026-07-13 09:51:40 -05:00

80 lines
4.1 KiB
JavaScript

'use strict';
// #100 key-rotation robustness: secretbox derives its key from JWT_SECRET, so an enrolled
// user's totp_secret_enc is bound to it. If the key changes (redeploy with a different
// JWT_SECRET, or a non-persisted .jwt_secret regenerated on a fresh Docker boot), the
// stored TOTP secret becomes undecryptable. Requirement: the user must NOT be hard-locked
// out - recovery codes (hashed, key-independent) must still work, and a TOTP attempt must
// fail CLEANLY (401), never 500. Boots under key A (enroll), reboots under key B (verify).
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { spawn } = require('node:child_process');
const path = require('node:path');
const os = require('node:os');
const fs = require('node:fs');
const crypto = require('node:crypto');
const { authenticator } = require('otplib');
const { freePort } = require('./helpers/free-port');
let PORT, BASE;
const DATA_DIR = path.join(os.tmpdir(), 'st-totp-rot-' + crypto.randomBytes(4).toString('hex'));
function bootServer(jwtSecret) {
const logFd = fs.openSync(path.join(os.tmpdir(), 'st-rot-' + crypto.randomBytes(3).toString('hex') + '.log'), 'w');
return spawn('node', ['server.js'], {
cwd: path.join(__dirname, '..'),
env: { ...process.env, DATA_DIR, SELF_HOSTED: 'true', PORT: String(PORT), NODE_ENV: 'test', JWT_SECRET: jwtSecret },
stdio: ['ignore', logFd, logFd],
});
}
async function waitUp() {
for (let i = 0; i < 80; i++) {
try { const r = await fetch(BASE + '/api/status'); if (r.ok) return; } catch { /* not yet */ }
await new Promise(r => setTimeout(r, 250));
}
throw new Error('server did not boot');
}
async function jfetch(p, opts = {}) {
const res = await fetch(BASE + p, opts);
let body = null; try { body = await res.json(); } catch { /* non-JSON */ }
return { status: res.status, body };
}
const post = (o) => ({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(o || {}) });
const postAuth = (tok, o) => ({ method: 'POST', headers: { Authorization: 'Bearer ' + tok, 'Content-Type': 'application/json' }, body: JSON.stringify(o || {}) });
test('#100 key rotation does NOT brick TOTP: recovery survives; TOTP fails cleanly (no 500)', async () => {
PORT = await freePort();
BASE = `http://127.0.0.1:${PORT}`;
let proc = bootServer('keyA-' + crypto.randomBytes(8).toString('hex'));
try {
await waitUp();
const email = 'rot' + crypto.randomBytes(4).toString('hex') + '@x.local';
const tok = (await jfetch('/api/auth/register', post({ email, password: 'Passw0rd123' }))).body.token;
const secret = (await jfetch('/api/auth/totp/setup', postAuth(tok, {}))).body.secret;
const recovery = (await jfetch('/api/auth/totp/enable', postAuth(tok, { code: authenticator.generate(secret) }))).body.recovery_codes;
assert.equal(recovery.length, 10, 'enrolled under key A');
proc.kill('SIGKILL'); await new Promise(r => setTimeout(r, 600));
// Reboot with a DIFFERENT key (same DATA_DIR) -> totp_secret_enc is now undecryptable.
proc = bootServer('keyB-' + crypto.randomBytes(8).toString('hex'));
await waitUp();
// password login still issues an MFA challenge
const l1 = await jfetch('/api/auth/login', post({ email, password: 'Passw0rd123' }));
assert.equal(l1.body.mfa_required, true, 'still challenged after the key change');
// a TOTP code can't be verified (secret undecryptable) -> CLEAN 401, NEVER 500
const totpTry = await jfetch('/api/auth/totp/verify', post({ mfa_token: l1.body.mfa_token, code: authenticator.generate(secret) }));
assert.equal(totpTry.status, 401, 'TOTP fails cleanly when the secret cannot be decrypted (not 500)');
// a RECOVERY code STILL works (hashed, key-independent) -> the user is not bricked
const l2 = await jfetch('/api/auth/login', post({ email, password: 'Passw0rd123' }));
const rec = await jfetch('/api/auth/totp/verify', post({ mfa_token: l2.body.mfa_token, code: recovery[0] }));
assert.ok(rec.body.token, 'recovery code survives the key change -> NOT hard-locked-out');
} finally {
try { proc.kill('SIGKILL'); } catch { /* ignore */ }
}
});