Files
Kelx/tests/bcrypt-cost-parity.test.js
2026-11-30 16:32:37 +00:00

545 lines
38 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
// adpanel:bcrypt-cost-parity — source pins for the T1 timing-enumeration fix.
// The cost of a bcrypt comparison is embedded in the STORED hash, so the
// dummy hash POST /login compares unknown accounts against must cost exactly
// what every stored row costs, or login latency becomes an account-existence
// oracle (a cost-10 row answers ~60 ms against a ~215 ms cost-12 dummy —
// well inside the login throttle's 20-probe per-account budget). The pins:
// 1. BCRYPT_ROUNDS resolves through the ONE shared resolver
// (utils/bcrypt-rounds.js) in index.js AND scripts/create-user.js —
// no inline env parsing may survive anywhere.
// 2. scripts/create-user.js carries no hardcoded cost literal: its
// password AND recovery-code hashes use the shared rounds (the shipped
// cost-10 writer that produced the heterogeneous rows).
// 3. POST /login rehashes a row to the configured rounds immediately after
// the real compare succeeds — the self-heal (upgrade cheaper rows up,
// repair pathological above-ceiling legacy rows down; in-band stronger
// rows are never downgraded) — persisted through the same single
// password UPDATE the password-change flows use (a compare-and-set on
// the verified snapshot credential — adpanel:rehash-cas: `AND
// password = ?` decided by affectedRows, so a concurrent reset can
// never be overwritten; a lost CAS re-proofs the submitted password
// against the live row before the login may continue), one update, no
// upsert, and never allowed to fail the login. The caller guard must
// not pre-filter above-ceiling rows: the helper owns the
// upgrade-vs-repair-vs-leave decision.
// 4. adpanel:bcrypt-cost-parity-dummy — the dummy that answers unknown
// accounts is minted at the parity FLOOR (MAX_BCRYPT_ROUNDS), and a
// wrong-password attempt against a cheaper row is padded with per-cost
// dummy compares whose combined work is exactly 2^FLOOR − 2^R cost
// units (the exact binary decomposition), so every credential failure
// — known or unknown email — pays the same 2^FLOOR units and no row
// inside the never-downgrade band answers measurably differently. The
// plain configured-rounds dummy is fallback-only; the cache pre-mints
// at boot (floor cost first) so the request path never mints on-path
// in steady state.
// 5. adpanel:bcrypt-cost-parity — the unknown-email work window fails
// OPEN, carrying the same fail-open catch the wrong-password pad
// carries: the compare is pure parity work (its verdict is never
// read), so under threadpool degradation a breached 8 s window must
// fall through to failCredentials("arm:unknown-email") — the uniform
// 400 — never escape to the handler's outer catch as a 500. A 500 on
// the unknown side while known rows (pad fail-open) answer 400 would
// INVERT the existence oracle in the degraded regime; the module's
// disclosed-residuals comment covers the regime.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const ROOT = path.join(__dirname, "..");
const indexSource = fs.readFileSync(path.join(ROOT, "index.js"), "utf8");
const createUserService = fs.readFileSync(path.join(ROOT, "scripts", "create-user.js"), "utf8");
const moduleSource = fs.readFileSync(path.join(ROOT, "utils", "bcrypt-rounds.js"), "utf8");
function indexOfOrThrow(needle, haystack = indexSource, from = 0) {
const idx = haystack.indexOf(needle, from);
assert.ok(idx >= 0, `expected source pin not found: ${needle}`);
return idx;
}
function countOccurrences(needle, haystack) {
let count = 0;
let pos = 0;
for (;;) {
const idx = haystack.indexOf(needle, pos);
if (idx < 0) return count;
count += 1;
pos = idx + needle.length;
}
}
function loginHandlerRegion() {
const start = indexOfOrThrow('app.post("/login", async (req, res) => {');
const end = indexSource.indexOf('app.post("/logout"', start);
assert.ok(end > start, 'app.post("/logout" must follow app.post("/login"');
return { start, end, body: indexSource.slice(start, end) };
}
test("BCRYPT_ROUNDS resolves only through the shared resolver (index.js and create-user.js)", () => {
assert.strictEqual(countOccurrences("parseInt(process.env.BCRYPT_ROUNDS", indexSource), 0, "no inline BCRYPT_ROUNDS env parsing may remain in index.js");
assert.strictEqual(countOccurrences("parseInt(process.env.BCRYPT_ROUNDS", createUserService), 0, "no inline BCRYPT_ROUNDS env parsing may remain in scripts/create-user.js");
indexOfOrThrow('const { resolveBcryptRounds, parseHashCost, rehashIfStale, BCRYPT_COST_PARITY_FLOOR, getDummyHashForCost, padCompareWorkToParityFloor, premintDummyHashesForParity, loadBcrypt } = require("./utils/bcrypt-rounds");');
indexOfOrThrow("const BCRYPT_ROUNDS = resolveBcryptRounds();");
indexOfOrThrow('const { resolveBcryptRounds, loadBcrypt, bcryptHashInputError } = require("../utils/bcrypt-rounds");', createUserService);
indexOfOrThrow("const BCRYPT_ROUNDS = resolveBcryptRounds();", createUserService);
assert.strictEqual(countOccurrences("resolveBcryptRounds(", moduleSource) >= 1, true, "the resolver lives in the shared module");
assert.ok(moduleSource.includes("adpanel:bcrypt-cost-parity"), "the shared module must carry the parity constraint comment");
});
test("the dummy hash stays built from the shared rounds", () => {
indexOfOrThrow("const DUMMY_BCRYPT_HASH = bcrypt.hashSync(`dummy-${crypto.randomBytes(24).toString(\"hex\")}`, BCRYPT_ROUNDS);");
// adpanel:bcrypt-cost-parity-dummy — the configured-rounds dummy is the
// FALLBACK only (pre-mint window, mint failure). The compare that answers
// unknown accounts consumes the parity-floor dummy minted through
// getDummyHashForCost, and wrong-password attempts against cheaper rows
// are padded to the same work floor — no site may compare against the
// plain dummy directly anymore.
assert.strictEqual(countOccurrences("bcrypt.compare(passStr, DUMMY_BCRYPT_HASH)", indexSource), 0, "the configured-rounds dummy must be fallback-only (no direct compare may remain)");
assert.strictEqual(countOccurrences("bcrypt.compare(passStr, unknownDummyHash)", indexSource), 1, "exactly the one unknown-email compare consumes the floor dummy");
indexOfOrThrow("getDummyHashForCost(BCRYPT_COST_PARITY_FLOOR, { bcrypt, fallbackHash: DUMMY_BCRYPT_HASH })");
indexOfOrThrow("padCompareWorkToParityFloor(parseHashCost(user.password), { bcrypt, password: passStr, fallbackHash: DUMMY_BCRYPT_HASH })");
// The per-cost cache is pre-minted at boot (floor cost first) so the
// request path is a Map hit in steady state.
indexOfOrThrow("premintDummyHashesForParity({ bcrypt }");
});
test("scripts/create-user.js has no hardcoded bcrypt cost literal left", () => {
assert.strictEqual(countOccurrences(", 10)", createUserService), 0, "no `, 10)` cost literal may remain in create-user.js");
for (const site of [
"bcrypt.hashSync(rawPassword, BCRYPT_ROUNDS)",
"bcrypt.hashSync(code, BCRYPT_ROUNDS)",
]) {
assert.ok(createUserService.includes(site), `hash sites must use the shared rounds: ${site}`);
}
assert.ok(countOccurrences("BCRYPT_ROUNDS)", createUserService) >= 3, "password (update + create) and recovery-code paths all hash at the shared cost");
});
test("the sibling CLI writer (reset-recovery-codes.js) also hashes through the shared resolver", () => {
// adpanel:bcrypt-cost-parity — reset-recovery-codes.js was the same
// hardcoded cost-10 writer the review missed; one responsibility, one
// resolver, so this pin keeps it from drifting back.
const resetService = fs.readFileSync(path.join(ROOT, "scripts", "reset-recovery-codes.js"), "utf8");
assert.strictEqual(countOccurrences(", 10)", resetService), 0, "no `, 10)` cost literal may remain in reset-recovery-codes.js");
assert.ok(resetService.includes('require("../utils/bcrypt-rounds")'), "the reset script must use the shared resolver");
assert.ok(resetService.includes("bcrypt.hashSync(code, BCRYPT_ROUNDS)"), "recovery codes must hash at the shared cost");
});
test("POST /login rehashes the row to the configured rounds right after the real compare succeeds", () => {
const { body } = loginHandlerRegion();
const compareIdx = indexOfOrThrow("bcrypt.compare(passStr, user.password)", body);
// adpanel:account-throttle-collation-parity — the resolved-user thread-through
// on the failure call (dual-key recording); the ordering constraints are unchanged.
const wrongPwFailIdx = indexOfOrThrow('failCredentials("arm:wrong-password", user)', body);
const rehashIdx = indexOfOrThrow("await rehashIfStale(user.password, passStr, BCRYPT_ROUNDS)", body);
const totpIdx = indexOfOrThrow("hasTwoFactorEnabled(user)", body);
assert.ok(wrongPwFailIdx < rehashIdx, "the rehash runs only after the password matched (never on a failure path)");
assert.ok(compareIdx < rehashIdx && rehashIdx < totpIdx, "the rehash sits between the successful compare and the 2FA flow");
assert.strictEqual(countOccurrences("rehashIfStale(", body), 1, "exactly ONE rehash call site — the post-match self-heal");
// Persisted through the same single password UPDATE password changes use:
// one update, never an upsert — and a compare-and-set on the snapshot
// credential the compare verified (adpanel:rehash-cas), decided by
// affectedRows: a rehash must never overwrite a credential it did not
// verify against (a concurrent reset's NEW hash would otherwise be
// replaced by a hash of the OLD password).
assert.ok(body.includes('db.query("UPDATE users SET password = ? WHERE id = ? AND password = ?", [upgraded, user.id, user.password])'), "the upgraded hash persists through the compare-and-set UPDATE pinned to the verified snapshot credential");
assert.strictEqual(countOccurrences("ON DUPLICATE KEY UPDATE", body), 0, "no upsert may ever write the password column");
// A failed rehash must not fail the login: the write is try/caught and the
// uniform failure path is untouched.
const rehashBlock = body.slice(rehashIdx, totpIdx);
assert.ok(rehashBlock.includes("catch"), "the rehash+persist must be wrapped in try/catch (log, never fail the login)");
// The dummy-compare branch stays untouched: no rehash in the burn helper,
// in the admission helper, or in the unknown-email branch itself (the
// branch routes through the admission helper — adpanel:uniform-failure-
// admission — so all three are checked).
const dummyIdx = indexOfOrThrow("bcrypt.compare(passStr, unknownDummyHash)", body);
const burnHelperEnd = body.indexOf("\n };", dummyIdx);
const burnHelper = body.slice(dummyIdx, burnHelperEnd);
const refusalHelperStart = body.indexOf("const refuseRowResolvedUniformFailure = async (debugLabel) => {");
const refusalHelperEnd = body.indexOf("\n };", refusalHelperStart);
const refusalHelper = body.slice(refusalHelperStart, refusalHelperEnd);
const unknownBranchStart = body.indexOf("const user = await findUserByEmail(emailStr);");
const unknownRetIdx = body.indexOf('return refuseRowResolvedUniformFailure("arm:unknown-email");', unknownBranchStart);
const unknownBranchEnd = body.indexOf("\n }", unknownRetIdx);
const unknownBranch = body.slice(unknownBranchStart, unknownBranchEnd);
for (const [label, slice] of [["the burn helper", burnHelper], ["the admission helper", refusalHelper], ["the unknown-email branch", unknownBranch]]) {
assert.strictEqual(countOccurrences("rehashIfStale", slice), 0, `${label} must not rehash`);
}
// The constraint lives on the wiring too.
assert.ok(body.includes("adpanel:bcrypt-cost-parity"), "the rehash wiring must carry the parity comment");
});
test("a lost rehash CAS re-proofs the submitted password against the live row before login may continue", () => {
// adpanel:rehash-cas — the CAS exists because the stored credential can
// change between the successful compare and the heal's write (admin
// reset, email-keyed resets, a parallel login's own heal). affectedRows 0
// means the submitted password was proven against a credential that no
// longer exists, so the handler must re-fetch the live row and re-compare
// before continuing: re-proof failure is the ONE uniform credential
// failure (a reset landing mid-login must fail the old password's login,
// never overwrite the reset), re-proof success adopts the live hash and
// never retries the heal.
const { body } = loginHandlerRegion();
const casIdx = indexOfOrThrow('db.query("UPDATE users SET password = ? WHERE id = ? AND password = ?", [upgraded, user.id, user.password])', body);
const catchIdx = indexOfOrThrow("} catch (err) {", body, casIdx);
const totpIdx = indexOfOrThrow("hasTwoFactorEnabled(user)", body);
const reproofIdx = indexOfOrThrow("if (rehashCasLost) {", body, catchIdx);
assert.ok(catchIdx < reproofIdx && reproofIdx < totpIdx, "the re-proof block sits after the heal's try/catch and before the 2FA flow");
const casRegion = body.slice(casIdx, reproofIdx);
assert.ok(casRegion.includes("casResult.affectedRows === 0"), "the CAS outcome is decided by affectedRows (0 = lost)");
assert.ok(casRegion.includes("rehashCasLost = true"), "a lost CAS flags the re-proof path instead of adopting the upgraded hash");
const reproofBlock = body.slice(reproofIdx, totpIdx);
assert.ok(reproofBlock.includes("const latest = await findUserByEmail(user.email);"), "a lost CAS re-fetches the live row");
// adpanel:login-bcrypt-admission — the re-proof is a pre-auth login-path
// compare, so it runs under the admission semaphore inside the same 8 s
// window (the timeout posture is unchanged).
assert.ok(reproofBlock.includes('withTimeout(loginBcryptAdmission.run(() => bcrypt.compare(passStr, latest.password)), 8000, "bcrypt-timeout")'), "the re-proof re-compares against the live hash with the same timeout posture, under the login admission semaphore");
assert.ok(reproofBlock.includes('failCredentials("arm:stale-credential", user)'), "re-proof failure is the uniform credential failure (uniform 400, captcha arming, throttle counting — adpanel:account-throttle-collation-parity: the resolved user records the id key too)");
assert.ok(reproofBlock.includes("user.password = latest.password"), "re-proof success adopts the live hash");
assert.strictEqual(countOccurrences("rehashIfStale(", body), 1, "a lost CAS never retries the heal (the next login heals any residual cost drift)");
// The re-proof is a credential proof, not a heal: it must NOT be covered
// by the heal's swallow-and-continue catch (an error while re-proving
// fails closed through the handler's outer catch, never "login continues"
// on an unproven credential). Structural proof: failCredentials(
// "arm:stale-credential") sits after the catch's closing brace, outside
// the parseHashCost guard block the try/catch lives in.
const staleFailIdx = indexOfOrThrow('failCredentials("arm:stale-credential", user)', body, reproofIdx);
const parseGuardEnd = body.indexOf("\n }", catchIdx);
assert.ok(parseGuardEnd > catchIdx && parseGuardEnd < reproofIdx && staleFailIdx > parseGuardEnd, "the re-proof runs outside the heal's catch (errors fail closed, not into 'login continues')");
});
test("the unknown-email work window fails open into the uniform failure (no inverted oracle under degradation)", () => {
// adpanel:bcrypt-cost-parity — the unknown-email compare is pure parity
// work: its verdict is never read, the branch always fails with unknown-
// email semantics. The 8 s window around it must therefore carry the SAME
// fail-open catch the wrong-password pad carries — under threadpool
// degradation a breach must fall through to failCredentials("arm:unknown-
// email") (the uniform 400), never escape to the handler's outer catch as
// a 500: a 500 on the unknown side while known rows (pad fail-open) still
// answer 400 would INVERT the existence oracle in the degraded regime.
const { body } = loginHandlerRegion();
// adpanel:uniform-failure-admission — the compare lives in the burn
// helper and is reached ONLY through the admission helper's ADMITTED
// branch (reserve → refuse: honest 429, NO burn / admit: burn → uniform
// failure); the unknown-email branch routes through that helper.
const dummyIdx = indexOfOrThrow("bcrypt.compare(passStr, unknownDummyHash)", body);
const refusalStart = body.indexOf("const refuseRowResolvedUniformFailure = async (debugLabel) => {");
const refusalEnd = body.indexOf("\n };", refusalStart);
const refusalHelper = body.slice(refusalStart, refusalEnd);
const unknownFailAnchor = 'return refuseRowResolvedUniformFailure("arm:unknown-email");';
const unknownFailIdx = indexOfOrThrow(unknownFailAnchor, body);
const branch = body.slice(dummyIdx, unknownFailIdx + unknownFailAnchor.length);
indexOfOrThrow(
'await withTimeout(loginBcryptAdmission.run(() => bcrypt.compare(passStr, unknownDummyHash)), 8000, "bcrypt-timeout")\n .catch((err) => console.warn("[security] bcrypt parity unknown-email work window skipped:", err?.message || err));',
body
);
assert.strictEqual(
countOccurrences("= await withTimeout(bcrypt.compare(passStr, unknownDummyHash)", indexSource), 0,
"the unknown-email compare is pure parity work — its verdict is never read (no assignment anywhere)"
);
const catchIdx = branch.indexOf('.catch((err) => console.warn("[security] bcrypt parity unknown-email work window skipped:"');
assert.ok(catchIdx > 0 && catchIdx < branch.length, "the catch sits inside the burn helper the branch reaches (before the uniform failure return)");
assert.ok(refusalHelper.includes("await burnUniformFailureParityWork();") && refusalHelper.includes("loginThrottle.reserveCredentialAttempt(throttleIpKey, emailStr, null)"), "the admission helper reserves fold-only BEFORE the burn — a refused budget answers the honest 429 without ever reaching the compare");
// The known-path pad's fail-open catch stays byte-identical (this fix must
// not fork the pad shape or weaken its catch).
indexOfOrThrow('.catch((err) => console.warn("[security] bcrypt parity pad skipped:", err?.message || err));');
// The degraded-load regime is disclosed among the module's known residuals.
const residualsIdx = moduleSource.indexOf("Known residuals (disclosed");
assert.ok(residualsIdx >= 0, "the disclosed-residuals list must exist in the module header");
const regimeIdx = moduleSource.indexOf("degraded-load regime", residualsIdx);
assert.ok(regimeIdx > residualsIdx, "the degraded-load regime must be disclosed among the known residuals");
});
test("a breached unknown-email work window still reaches the uniform unknown-email failure (behavior pin)", async () => {
// adpanel:bcrypt-cost-parity — the degraded-load regime in action: the 8 s
// window around the unknown-email dummy compare rejects while the
// threadpool-bound compare keeps running. The branch must swallow that
// breach (the fail-open catch) and fall through to the uniform failure;
// no rejection may escape past the await. Harness: the branch source is
// extracted VERBATIM from index.js and run in a vm context against the
// REAL withTimeout (extracted from the same source) with a setTimeout
// that fires immediately (degradation stand-in: the window is already
// exhausted) and a compare that never settles (the threadpool never
// returns).
const { body } = loginHandlerRegion();
const { getDummyHashForCost, BCRYPT_COST_PARITY_FLOOR } = require("../utils/bcrypt-rounds");
const branchStart = body.indexOf("const user = await findUserByEmail(emailStr);");
const retAnchor = 'return refuseRowResolvedUniformFailure("arm:unknown-email");';
const retIdx = body.indexOf(retAnchor, branchStart);
const closeIdx = body.indexOf("\n }", retIdx);
assert.ok(branchStart >= 0 && retIdx > branchStart && closeIdx > retIdx, "the unknown-email branch must be extractable");
const branchCode = body.slice(branchStart, closeIdx + "\n }".length);
// adpanel:uniform-failure-admission — the dummy compare moved into the
// ONE shared parity-work helper, reached ONLY through the admission
// helper's fold-only reservation (the unknown branch routes through it,
// shared verbatim with the row-resolved refusals), so the harness
// extracts and runs BOTH helpers: the fail-open window behavior below is
// the same code every uniform-failure site executes, and the reservation
// arbiter decides whether the burn runs at all.
const burnStart = body.indexOf("const burnUniformFailureParityWork = async () => {");
const burnEnd = body.indexOf("\n };", burnStart);
assert.ok(burnStart >= 0 && burnEnd > burnStart, "the shared parity-work helper must be extractable");
const burnCode = body.slice(burnStart, burnEnd + "\n };".length);
assert.ok(burnCode.includes('await withTimeout(loginBcryptAdmission.run(() => bcrypt.compare(passStr, unknownDummyHash)), 8000, "bcrypt-timeout")'), "the extracted helper carries the fail-open window verbatim");
const refusalStart = body.indexOf("const refuseRowResolvedUniformFailure = async (debugLabel) => {");
const refusalEnd = body.indexOf("\n };", refusalStart);
assert.ok(refusalStart >= 0 && refusalEnd > refusalStart, "the shared admission helper must be extractable");
const refusalCode = body.slice(refusalStart, refusalEnd + "\n };".length);
assert.ok(refusalCode.includes("loginThrottle.reserveCredentialAttempt(throttleIpKey, emailStr, null)"), "the admission helper's fold-only reservation gates the burn");
assert.ok(refusalCode.includes("await burnUniformFailureParityWork();"), "the admission helper burns the shared parity work before the uniform failure");
const wtStart = indexOfOrThrow('function withTimeout(promise, ms, label = "timeout") {');
const wtEnd = indexSource.indexOf("\n}", wtStart);
assert.ok(wtEnd > wtStart, "the withTimeout body must be extractable");
const withTimeoutSource = indexSource.slice(wtStart, wtEnd + 2);
const warns = [];
// The compare's settlement shape is swapped per scenario below; hashSync
// throws so the branch exercises the fallback dummy and this test never
// touches the shared dummy cache (the mint paths are pinned elsewhere).
// adpanel:login-bcrypt-admission — the reservation gate and the settle
// helpers it feeds are stubbed admitted/neutral so this harness isolates
// the fail-open window behavior (the reservation/settle wiring is pinned
// structurally in tests/login-throttle-wiring.test.js).
const compareStub = { fn: () => new Promise(() => {}) };
const reserveStub = { fn: async () => ({ admitted: true, reason: null, ipThresholdReached: false, accountThresholdReached: false }) };
const sandbox = {
findUserByEmail: async () => null, // unknown email
emailStr: "ghost@example.invalid",
passStr: "whatever",
throttleIpKey: "stub-src",
loginThrottle: { reserveCredentialAttempt: (...args) => reserveStub.fn(...args) },
rejectReservation: async (reservation) => `refused:${reservation.reason}`,
admitReservation: () => {},
loginBcryptAdmission: { run: async (fn) => fn() },
bcrypt: {
hashSync: () => { throw new Error("behavior-pin stub does not mint"); },
compare: (...args) => compareStub.fn(...args),
},
getDummyHashForCost,
BCRYPT_COST_PARITY_FLOOR,
DUMMY_BCRYPT_HASH: "$2a$12$" + "a".repeat(53),
failCredentials: async (label) => `uniform-failure:${label}`,
console: { warn: (...parts) => warns.push(parts.map(String).join(" ")) },
setTimeout: (fn) => { fn(); return 0; }, // the 8 s window is ALREADY breached
clearTimeout: () => {},
};
const context = vm.createContext(sandbox);
vm.runInContext(withTimeoutSource, context, { filename: "withTimeout.js" });
vm.runInContext(burnCode, context, { filename: "burn-uniform-failure-parity-work.js" });
vm.runInContext(refusalCode, context, { filename: "refuse-row-resolved-uniform-failure.js" });
const harness = `(async () => {\n${branchCode}\n})()`;
// Scenario 1 — the degraded regime: the compare never settles, the window
// timer fires (rejecting with its label). The branch must proceed to the
// uniform failure; the warn names the breached window.
const breached = await vm.runInContext(harness, context, { filename: "unknown-email-branch.js" });
assert.strictEqual(breached, "uniform-failure:arm:unknown-email", "a breached window must still reach the ONE uniform unknown-email failure — no throw may escape");
assert.strictEqual(warns.length, 1, "exactly one fail-open warn for the breach");
assert.ok(warns[0].includes("[security] bcrypt parity unknown-email work window skipped:"), "the warn carries the fail-open tag");
assert.ok(warns[0].includes("bcrypt-timeout"), "the warn names the breached window (withTimeout's label as err.message)");
// Scenario 2 — a compare that rejects outright (library failure): same
// fail-open shape, same uniform failure. The window timer is silenced so
// the compare's own rejection is what the catch observes (in production a
// fast compare rejection settles the race well before the 8 s bound).
warns.length = 0;
sandbox.setTimeout = () => 0;
compareStub.fn = () => Promise.reject(new Error("boom"));
const rejected = await vm.runInContext(harness, context, { filename: "unknown-email-branch.js" });
assert.strictEqual(rejected, "uniform-failure:arm:unknown-email", "a rejecting compare must still reach the uniform unknown-email failure");
assert.strictEqual(warns.length, 1, "exactly one fail-open warn for the rejection");
assert.ok(warns[0].includes("boom"), "the warn carries the underlying error message");
// Scenario 3 — the admission arbiter's REFUSED branch (adpanel:uniform-
// failure-admission): a fold/source-exhausted budget refuses the
// reservation BEFORE the burn — the honest rejection shape, NO compare
// queued, NO uniform failure. This is the bound that keeps the burn
// budgeted (the previous reservationless shape burned unbudgeted).
warns.length = 0;
const refusedRuns = { reserve: 0, compares: 0, fails: 0 };
reserveStub.fn = async () => { refusedRuns.reserve += 1; return { admitted: false, reason: "source", ipThresholdReached: false, accountThresholdReached: false }; };
compareStub.fn = async () => { refusedRuns.compares += 1; return false; };
sandbox.failCredentials = async (label) => { refusedRuns.fails += 1; return `uniform-failure:${label}`; };
const refused = await vm.runInContext(harness, context, { filename: "unknown-email-branch.js" });
assert.strictEqual(refused, "refused:source", "a refused fold-only reservation answers the honest rejection — never the uniform failure");
assert.strictEqual(refusedRuns.reserve, 1, "exactly one reservation attempt");
assert.strictEqual(refusedRuns.compares, 0, "a refused admission never reaches bcrypt");
assert.strictEqual(refusedRuns.fails, 0, "a refused admission is not a confirmed failure — no finalize");
assert.strictEqual(warns.length, 0, "no warn on the honest refusal path");
});
test("the shared rehash helper is parity-gated and audit-gated", () => {
// Structural pins on the module (the unit suite exercises the behavior):
// refuses malformed rows (cost 0), leaves parity rows untouched, never
// downgrades an IN-BAND stronger row, and — the A-2 amendment — repairs
// pathological ABOVE-ceiling rows (legacy writes from the old unbounded
// env parse) down to the configured rounds instead of refusing them.
assert.ok(moduleSource.includes("if (cost === 0) return null;"), "unparseable rows must be refused (fail closed)");
assert.ok(moduleSource.includes("if (cost === targetRounds) return null;"), "a row already at parity is left untouched");
assert.ok(
moduleSource.includes("if (cost <= MAX_BCRYPT_ROUNDS && cost > targetRounds) return null;"),
"an in-band stronger row (cost <= ceiling) is never downgraded — a legitimate operator choice"
);
assert.ok(
!moduleSource.includes("if (cost >= targetRounds) return null;"),
"the old upgrade-only guard must be gone: above-ceiling rows must reach the repair path"
);
});
test("the POST /login rehash guard does not pre-filter above-ceiling rows (the helper owns the repair decision)", () => {
const { body } = loginHandlerRegion();
indexOfOrThrow("if (parseHashCost(user.password) !== BCRYPT_ROUNDS) {", body);
assert.strictEqual(
countOccurrences("parseHashCost(user.password) < BCRYPT_ROUNDS", body),
0,
"the old upgrade-only caller guard must be gone: a cost > rounds row must reach rehashIfStale (A-2 repair path)"
);
});
// adpanel:bcrypt-cost-parity-dummy — mechanism pins for the floor amendment.
// A dummy minted for cost R must embed EXACTLY cost R (a compare against it
// then costs what a compare against any row of that cost costs), the cache
// must serve one mint process-wide, and the pad plan must decompose the
// missing work EXACTLY so every credential failure pays the same 2^FLOOR
// cost-units as the unknown-account dummy compare.
function fakeBcryptLib(failCosts = []) {
// Shape-correct hashes at the requested cost — no real crypto, so the
// behavior pins stay fast and deterministic.
return {
hashSync: (secret, cost) => {
if (failCosts.includes(cost)) throw new Error("boom");
return `$2a$${String(cost).padStart(2, "0")}$${"a".repeat(53)}`;
},
hash: (secret, cost, cb) => {
if (failCosts.includes(cost)) return setTimeout(() => cb(new Error("boom")), 1);
setTimeout(() => cb(null, `$2a$${String(cost).padStart(2, "0")}$${"a".repeat(53)}`), 1);
},
};
}
test("a dummy minted for cost R parses back at exactly cost R and is cached", () => {
// Real bcrypt (the same library index.js resolves) on cheap costs so the
// pin exercises the production mint path.
const realBcrypt = require("bcrypt");
const { getDummyHashForCost, parseHashCost } = require("../utils/bcrypt-rounds");
for (const cost of [4, 5, 6, 10]) {
const hash = getDummyHashForCost(cost, { bcrypt: realBcrypt });
assert.ok(typeof hash === "string" && hash.length === 60, `a dummy for cost ${cost} must be minted`);
assert.strictEqual(parseHashCost(hash), cost, `the dummy for cost ${cost} must embed exactly that cost`);
assert.strictEqual(getDummyHashForCost(cost, { bcrypt: realBcrypt }), hash, "the cache must return the same minted hash (no re-mint per request)");
}
});
test("a failed or mis-costed dummy mint falls back instead of failing the login", () => {
const { getDummyHashForCost, MAX_BCRYPT_ROUNDS } = require("../utils/bcrypt-rounds");
// Costs 11 and 12 are not minted by the earlier tests, so these hits reach
// the mint path (a cached cost would short-circuit to the cached hash).
assert.strictEqual(getDummyHashForCost(11, { bcrypt: fakeBcryptLib([11]), fallbackHash: "fallback" }), "fallback", "a mint that throws must fall back");
assert.strictEqual(getDummyHashForCost(12, { bcrypt: { hashSync: () => "$2a$10$" + "a".repeat(53) }, fallbackHash: "fallback" }), "fallback", "a mint that parses back at the wrong cost must fall back");
// Out-of-domain costs are refused without minting (the domain guard is
// what bounds the cache): above the ceiling, below the parse floor, and
// non-integers all return the fallback untouched.
for (const bad of [MAX_BCRYPT_ROUNDS + 1, 31, 3, 0, -1, 12.5, Number.NaN, "12", null]) {
assert.strictEqual(getDummyHashForCost(bad, { bcrypt: fakeBcryptLib(), fallbackHash: "fallback" }), "fallback", `cost ${String(bad)} is out of the cache domain and must not mint`);
}
});
test("pad plans decompose the missing work exactly (2^R + Σ 2^pad === 2^FLOOR)", () => {
const { planParityPadCosts, BCRYPT_COST_PARITY_FLOOR, MAX_BCRYPT_ROUNDS } = require("../utils/bcrypt-rounds");
const floor = BCRYPT_COST_PARITY_FLOOR;
assert.strictEqual(floor, MAX_BCRYPT_ROUNDS, "the parity floor is the strongest cost the never-downgrade policy leaves in place");
for (let r = 4; r <= floor; r++) {
const pads = planParityPadCosts(r, floor);
assert.strictEqual(pads.length, floor - r, `row cost ${r}: exactly one compare per missing cost`);
for (const c of pads) {
assert.ok(c >= r && c < floor, `pad cost ${c} must sit inside [R..FLOOR-1] for row ${r}`);
}
const units = 2 ** r + pads.reduce((acc, c) => acc + 2 ** c, 0);
assert.strictEqual(units, 2 ** floor, `row cost ${r}: real compare + pads must total exactly 2^${floor} units`);
}
assert.deepStrictEqual(planParityPadCosts(floor, floor), [], "a row AT the floor needs no pad");
assert.deepStrictEqual(planParityPadCosts(floor + 1, floor), [], "above-floor rows cannot be padded down (disclosed slower-direction residual)");
assert.deepStrictEqual(planParityPadCosts(31, floor), [], "above-ceiling rows cannot be padded down");
assert.deepStrictEqual(planParityPadCosts(0, floor), [], "unparseable rows derive no pad plan");
assert.deepStrictEqual(planParityPadCosts(Number.NaN), [], "non-numeric cost derives no pad plan");
assert.deepStrictEqual(planParityPadCosts(12.5, floor), [], "non-integer cost derives no pad plan");
});
test("the pad executor runs one dummy compare per planned cost and never touches the verdict", async () => {
const { padCompareWorkToParityFloor, parseHashCost } = require("../utils/bcrypt-rounds");
const lib = fakeBcryptLib();
const compared = [];
const record = async (pw, hash) => { compared.push(parseHashCost(hash)); };
await padCompareWorkToParityFloor(14, { bcrypt: lib, password: "pw", compare: record });
assert.deepStrictEqual(compared, [14], "a cost-14 row pads once, at cost 14");
compared.length = 0;
await padCompareWorkToParityFloor(13, { bcrypt: lib, password: "pw", compare: record });
assert.deepStrictEqual(compared, [14, 13], "a cost-13 row pads at costs 14 then 13");
compared.length = 0;
await padCompareWorkToParityFloor(15, { bcrypt: lib, password: "pw", compare: record });
assert.deepStrictEqual(compared, [], "a floor-cost row pads nothing");
compared.length = 0;
await padCompareWorkToParityFloor(16, { bcrypt: lib, password: "pw", compare: record });
assert.deepStrictEqual(compared, [], "an above-floor row pads nothing (cannot be shortened)");
compared.length = 0;
await padCompareWorkToParityFloor(12, { bcrypt: lib, password: null, compare: record });
assert.deepStrictEqual(compared, [], "no password string — no pad work");
});
test("the boot pre-mint mints floor-first, caches, and reports failures without throwing", async () => {
const { premintDummyHashesForParity, MIN_BCRYPT_ROUNDS, BCRYPT_COST_PARITY_FLOOR, getDummyHashForCost, parseHashCost } = require("../utils/bcrypt-rounds");
const mintOrder = [];
const lib = {
hash: (secret, cost, cb) => {
mintOrder.push(cost);
setTimeout(() => cb(null, `$2a$${String(cost).padStart(2, "0")}$${"a".repeat(53)}`), 1);
},
};
const err = await new Promise((resolve) => premintDummyHashesForParity({ bcrypt: lib }, resolve));
assert.strictEqual(err, null, "a clean pre-mint reports no error");
assert.strictEqual(mintOrder[0], BCRYPT_COST_PARITY_FLOOR, "the floor cost (the unknown-account dummy) mints first");
assert.strictEqual(mintOrder[mintOrder.length - 1], MIN_BCRYPT_ROUNDS, "the cheapest in-band cost mints last");
assert.strictEqual(mintOrder.length, BCRYPT_COST_PARITY_FLOOR - MIN_BCRYPT_ROUNDS + 1, "every in-band cost is pre-minted exactly once");
for (let c = MIN_BCRYPT_ROUNDS; c <= BCRYPT_COST_PARITY_FLOOR; c++) {
assert.strictEqual(parseHashCost(getDummyHashForCost(c, { bcrypt: lib })), c, `preminted cost ${c} serves from the cache`);
}
// Failure path: a failing cost is skipped, reported through done(err), and
// the remaining costs still land in the cache.
const failingLib = fakeBcryptLib([MIN_BCRYPT_ROUNDS]);
const minted = [];
failingLib.hash = (secret, cost, cb) => {
minted.push(cost);
if (cost === MIN_BCRYPT_ROUNDS) return setTimeout(() => cb(new Error("boom")), 1);
setTimeout(() => cb(null, `$2a$${String(cost).padStart(2, "0")}$${"a".repeat(53)}`), 1);
};
const failure = await new Promise((resolve) => premintDummyHashesForParity({ bcrypt: failingLib }, resolve));
assert.ok(failure instanceof Error && failure.message.includes(String(MIN_BCRYPT_ROUNDS)), "a failed cost is reported for logging");
assert.strictEqual(minted.length, BCRYPT_COST_PARITY_FLOOR - MIN_BCRYPT_ROUNDS + 1, "one failed cost does not stop the remaining mints");
});
test("the dummy cache stays bounded inside its key domain", () => {
const { getDummyHashForCost, MAX_BCRYPT_ROUNDS, dummyHashCacheSize } = require("../utils/bcrypt-rounds");
const lib = fakeBcryptLib();
for (let c = 4; c <= MAX_BCRYPT_ROUNDS; c++) getDummyHashForCost(c, { bcrypt: lib });
assert.strictEqual(dummyHashCacheSize(), MAX_BCRYPT_ROUNDS - 3, "the whole domain mints once — one entry per cost in [4..MAX]");
assert.ok(dummyHashCacheSize() <= MAX_BCRYPT_ROUNDS + 2, "the cache stays under the documented MAX_BCRYPT_ROUNDS + 2 cap");
// Out-of-domain requests must not grow it further.
getDummyHashForCost(MAX_BCRYPT_ROUNDS + 1, { bcrypt: lib });
getDummyHashForCost(3, { bcrypt: lib });
assert.strictEqual(dummyHashCacheSize(), MAX_BCRYPT_ROUNDS - 3, "out-of-domain costs never mint or cache");
});
test("the floor-dummy machinery lives in the ONE bcrypt-cost home with its constraint comment", () => {
const parity = require("../utils/bcrypt-rounds");
for (const fn of ["getDummyHashForCost", "planParityPadCosts", "padCompareWorkToParityFloor", "premintDummyHashesForParity", "dummyHashCacheSize"]) {
assert.strictEqual(typeof parity[fn], "function", `${fn} must be exported from utils/bcrypt-rounds.js`);
}
assert.strictEqual(parity.BCRYPT_COST_PARITY_FLOOR, parity.MAX_BCRYPT_ROUNDS, "the floor is the module's own ceiling constant, not an index.js copy");
assert.ok(moduleSource.includes("adpanel:bcrypt-cost-parity-dummy"), "the module carries the floor-amendment constraint comment");
assert.ok(indexSource.includes("adpanel:bcrypt-cost-parity-dummy"), "the login wiring carries the floor-amendment constraint comment");
});