139 lines
6.8 KiB
JavaScript
139 lines
6.8 KiB
JavaScript
"use strict";
|
||
|
||
const { resolveClampedInt } = require("./clamped-int");
|
||
|
||
const WAIT_TIMEOUT_MS = 8000;
|
||
|
||
// adpanel:login-bcrypt-admission — unauthenticated login-path bcrypt work is
|
||
// admission-controlled TWICE, because the throttle budgets alone bound only
|
||
// the per-attempt rate and — since the login-throttle reservation — the
|
||
// COUNT of compare-bearing attempts per window, never how many of them
|
||
// occupy libuv threads AT ONCE. Pre-fix, every failure paid its 2^15 work
|
||
// units (BCRYPT_COST_PARITY_FLOOR) in an UNBOUNDED number of concurrent
|
||
// compares: withTimeout is Promise.race, so a timed-out compare is abandoned
|
||
// (never cancelled) and keeps its threadpool thread to completion — a
|
||
// parallel burst from one /56 injected ~120 threadpool-seconds, saturated
|
||
// the default 4-thread pool permanently, and pushed legitimate logins (and
|
||
// the step-up/recovery verifies) past their 8 s windows. This module is the
|
||
// CONCURRENCY half of the fix: a FIFO promise semaphore capping how many
|
||
// login-path bcrypt compares run simultaneously (default 2,
|
||
// BCRYPT_LOGIN_MAX_CONCURRENT), so at least two pool threads stay free for
|
||
// the application no matter how large the admitted burst is. The COUNT half
|
||
// lives in utils/login-throttle.js (reserveCredentialAttempt — over-budget
|
||
// reservations are refused before any compare is ever queued here).
|
||
//
|
||
// Contract:
|
||
// - acquire() resolves with a release function once a slot is held; run(fn)
|
||
// is the safe wrapper (release in finally, fn's verdict/rejection
|
||
// propagates unchanged). The semaphore wait counts INSIDE the caller's
|
||
// 8 s withTimeout window: queued admissions expire at that deadline and
|
||
// never start work for a request that has already timed out — since
|
||
// adpanel:login-id-refusal-parity (L4) every LOGIN-path compare breach
|
||
// settles through the ONE uniform failure path: the outstanding
|
||
// reservation is finalized (failCredentials — the admission-finalized
|
||
// failure record, the same machinery refuseRowResolvedUniformFailure
|
||
// routes the row-resolved refusals through) and the response is the
|
||
// uniform unknown-email 400, never a 500. The pre-existing T1-B 500
|
||
// posture NARROWS to compare consumers OUTSIDE the login surface —
|
||
// each reached only by an ALREADY-AUTHENTICATED caller, so no pre-auth
|
||
// oracle — and none of them answers a 500 on a slow compare: the
|
||
// recovery-code check (index.js /api/account/recovery/verify, the
|
||
// compare at ~48279) carries NO 8 s window at all — it blocks on the
|
||
// compare, swallows a compare error as a non-match, and only ever
|
||
// compares hashes the panel itself minted at the configured cost, so
|
||
// an above-ceiling row cannot occur there; the step-up consumers DO
|
||
// carry 8 s windows — verifyPasswordForUser (~2643) and
|
||
// verifyAdminProvisioningStepUp (~47334) wrap their compares in
|
||
// withTimeout(…, 8000) whose breach settles FAIL-CLOSED (verdict
|
||
// false / step-up refused), stricter than a 500 — post-auth callers
|
||
// this semaphore deliberately does not wire. The semaphore's
|
||
// own contract is unchanged by that reshape: the concurrency cap, the
|
||
// FIFO wait inside the caller's 8 s window and the fail-open direction
|
||
// all stand. The slot is released only when the compare actually
|
||
// settles (bcrypt work cannot be cancelled), so the accounting tracks
|
||
// real threadpool occupancy and stays bounded by maxConcurrent.
|
||
// - FIFO waiters: the earliest admitted attempt goes first, no starvation.
|
||
// - ONLY the POST /login compares are wired through it (the unknown-email
|
||
// floor dummy, the real credential compare, the parity-pad sequence as
|
||
// ONE acquisition — the pad is a single logical parity unit per failed
|
||
// attempt, up to FLOOR−4 compares, so per-compare acquisition would
|
||
// multiply queue traffic without changing the bounded-work property —
|
||
// and the rehash-CAS re-proof, which is also a pre-auth login-path
|
||
// compare). Post-auth verify surfaces (verifyPasswordForUser and the
|
||
// password-change/recovery compares) are deliberately NOT wired: their
|
||
// callers are already authenticated (session or a proven credential), so
|
||
// they are not part of the unauthenticated amplification chain — and
|
||
// semaphore-waiting them would let a login burst starve step-up,
|
||
// password change and recovery, the exact starvation this fix removes.
|
||
function createBcryptLoginAdmission(deps = {}) {
|
||
const env = deps.env || process.env;
|
||
const setTimer = deps.setTimeout || setTimeout;
|
||
const clearTimer = deps.clearTimeout || clearTimeout;
|
||
const now = deps.now || Date.now;
|
||
// adpanel:env-int-clamp — resolves through the ONE shared clamped-int
|
||
// helper (floor policy): a parsed "0" or negative is nonsense for a
|
||
// concurrency cap and clamps to the floor of 1 — it can never disable the
|
||
// control. The ceiling keeps a mistyped value from silently re-opening the
|
||
// unbounded-concurrency hole; operators raising it should raise
|
||
// UV_THREADPOOL_SIZE with it.
|
||
const maxConcurrent = resolveClampedInt(env, "BCRYPT_LOGIN_MAX_CONCURRENT", { fallback: 2, min: 1, max: 32 });
|
||
let active = 0;
|
||
const waiters = [];
|
||
const release = () => {
|
||
while (waiters.length) {
|
||
const waiter = waiters.shift();
|
||
if (now() >= waiter.deadline) {
|
||
waiter.expire();
|
||
continue;
|
||
}
|
||
waiter.admit();
|
||
return;
|
||
}
|
||
active -= 1;
|
||
};
|
||
const acquire = () => {
|
||
if (active < maxConcurrent) {
|
||
active += 1;
|
||
return Promise.resolve(release);
|
||
}
|
||
// adpanel:login-bcrypt-queue-expiry - abandoned requests must not keep
|
||
// scheduling comparisons after their response deadline. Running bcrypt
|
||
// retains its slot; only waiters that have not started are expired.
|
||
return new Promise((resolve, reject) => {
|
||
let settled = false;
|
||
let timer;
|
||
const waiter = {
|
||
deadline: now() + WAIT_TIMEOUT_MS,
|
||
admit() {
|
||
if (settled) return;
|
||
settled = true;
|
||
clearTimer(timer);
|
||
resolve(release);
|
||
},
|
||
expire() {
|
||
if (settled) return;
|
||
settled = true;
|
||
clearTimer(timer);
|
||
const position = waiters.indexOf(waiter);
|
||
if (position !== -1) waiters.splice(position, 1);
|
||
reject(new Error("bcrypt-admission-wait-timeout"));
|
||
},
|
||
};
|
||
waiters.push(waiter);
|
||
timer = setTimer(() => waiter.expire(), WAIT_TIMEOUT_MS);
|
||
});
|
||
};
|
||
const run = async (fn) => {
|
||
if (typeof fn !== "function") throw new TypeError("bcrypt-admission: run(fn) requires a function");
|
||
const releaseSlot = await acquire();
|
||
try {
|
||
return await fn();
|
||
} finally {
|
||
releaseSlot();
|
||
}
|
||
};
|
||
return { run, acquire, maxConcurrent };
|
||
}
|
||
|
||
module.exports = { createBcryptLoginAdmission };
|