Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,623 @@
|
||||
"use strict";
|
||||
|
||||
// adpanel:stealth-mint-cap — behavior + source pins for the pre-gate session
|
||||
// MINT cap on the stealth bootstrap:
|
||||
//
|
||||
// The finding (F1, Medium — availability): with STEALTH_MODE on (the
|
||||
// default), a gateless GET /login ends in sendStealthBootstrap — the stealth
|
||||
// gate answers BEFORE loginRequestLimiter (that limiter mounts on /login far
|
||||
// below the gate), so nothing throttled the path. The bootstrap mutates
|
||||
// req.session.stealthBootstrap and calls req.session.save() EXPLICITLY: one
|
||||
// Redis session record per pre-gate request. The 30-min preauth TTL caps
|
||||
// each entry's lifetime, not the aggregate rate, and with
|
||||
// `maxmemory-policy noeviction` a flood self-arrests fail-closed (Redis
|
||||
// fills, saves 500, logins stop) — while on an external `allkeys-lru` Redis
|
||||
// the flood additionally EVICTS live sessions and sid tombstones.
|
||||
//
|
||||
// The fix (index.js, adpanel:stealth-mint-cap): sendStealthBootstrap runs a
|
||||
// per-source (20 / 10 min, /56-bucketed via the house ipKeyGenerator) and a
|
||||
// global (2000 / 10 min) fixed-window counter over two RateLimitRedisStore
|
||||
// instances built by the ONE shared factory with fallbackHits 0 (the
|
||||
// documented 0-on-error sentinel), checked BEFORE any session work.
|
||||
// Over-cap requesters get the plain stealth decoy (sendStealthNotFound —
|
||||
// the same static 404-empty the gate already serves protected assets) with
|
||||
// ZERO session work; the state token /_stealth/authorize validates never
|
||||
// exists for them, and that step fails closed. Counter store errors fail
|
||||
// CLOSED (a full Redis outage already fails the explicit save — same
|
||||
// client — so refusing the mint degrades nothing). No new mount was added,
|
||||
// so the pre-gate census is untouched. Under the same tag the SECOND
|
||||
// pre-gate stealth write amplifier is closed: /_stealth/authorize's
|
||||
// explicit save is now conditional on the request actually consuming a
|
||||
// bootstrap state — stateless garbage probes (unthrottled: the gate skips
|
||||
// /_stealth/ paths) no longer persist one orphan EMPTY session record per
|
||||
// probe, with a byte-identical response. The authorize VALIDATION is
|
||||
// byte-identical.
|
||||
//
|
||||
// Technique: the REAL stealth machinery (the cap block, the state helpers,
|
||||
// the bootstrap sender, the decoy senders and the /_stealth/authorize route)
|
||||
// is sliced byte-identical out of index.js and evaluated with injected
|
||||
// fixture globals — the same evaluate-the-extracted-source technique as
|
||||
// tests/pre-gate-mount-census.test.js, tests/force-https-coverage.test.js and
|
||||
// tests/stealth-favicon-decoy.test.js. The only fixture in the counter path
|
||||
// is the store transport: a RateLimitRedisStore-contract double implementing
|
||||
// increment/get/init over a Map, with the factory's documented error
|
||||
// fallback (totalHits = fallbackHits) as the controllable failure mode. The
|
||||
// budget arithmetic, the admission decision, the fail-closed direction, the
|
||||
// over-cap response and the session-write suppression all run the SHIPPED
|
||||
// code.
|
||||
|
||||
process.env.STEALTH_RESPONSE_FLOOR_MS = "1"; // fastest real floor value (0 falls back to 90 — parseInt(...) || 90)
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const crypto = require("node:crypto");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const INDEX_JS = path.join(ROOT, "index.js");
|
||||
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
||||
const { ipKeyGenerator } = require("express-rate-limit");
|
||||
|
||||
function indexOfOrThrow(needle, from = 0) {
|
||||
const idx = indexSource.indexOf(needle, from);
|
||||
assert.ok(idx >= 0, `expected source pin not found: ${needle}`);
|
||||
return idx;
|
||||
}
|
||||
|
||||
// Slice [startMarker, endMarker) — the shipped text, byte-identical.
|
||||
function sliceBetween(startMarker, endMarker) {
|
||||
const start = indexOfOrThrow(startMarker);
|
||||
const end = indexOfOrThrow(endMarker, start + startMarker.length);
|
||||
assert.ok(end > start, `slice must be bounded: ${startMarker}`);
|
||||
return indexSource.slice(start, end);
|
||||
}
|
||||
|
||||
const FLOOR_CONST_SRC = sliceBetween("const STEALTH_RESPONSE_FLOOR_MS = ", "const STEALTH_BOOTSTRAP_TTL_MS = ");
|
||||
const TTL_CONST_SRC = `${sliceBetween("const STEALTH_BOOTSTRAP_TTL_MS = ", "const STEALTH_COOKIE_TTL_DAYS = ")}\n`;
|
||||
const SAFECOMPARE_SRC = sliceBetween("function safeCompare(a, b) {", "const ACTION_TOKEN_SECRET =");
|
||||
const loadTimeout = new Function("setTimeout", "clearTimeout", `${sliceBetween("function withTimeout(promise, ms, label", "const TRUSTED_PROXY_IPS =")}\nreturn withTimeout;`);
|
||||
// This slice CONTAINS the whole adpanel:stealth-mint-cap block (it sits
|
||||
// between applyStealthResponseFloor and getStealthBootstrapState) plus the
|
||||
// return-to/gate-token helpers, delay and the response floor.
|
||||
const HELPERS_A_SRC = sliceBetween("function sanitizeStealthReturnTo(value) {", "function getStealthBootstrapState(req) {");
|
||||
const HELPERS_B_SRC = sliceBetween("function getStealthBootstrapState(req) {", "async function hasStealthAccess(req) {");
|
||||
// The REAL authorize route registration (validation + consumption + cookie
|
||||
// grant/clear + conditional save).
|
||||
const AUTHORIZE_ROUTE_SRC = sliceBetween('app.get("/_stealth/authorize", (req, res) => {', 'app.all("/_stealth/nginx-auth"');
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fixtures
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// RateLimitRedisStore-contract double over a Map. `fail` mirrors the shared
|
||||
// factory's sendCommand error fallback: increment resolves with
|
||||
// { totalHits: fallbackHits } (fallbackHits is 0 for the mint counters — the
|
||||
// fail-closed sentinel).
|
||||
function makeCounterFixture({ fail = false } = {}) {
|
||||
const counters = new Map(); // full key -> { hits, expireAt }
|
||||
const constructed = [];
|
||||
const increments = [];
|
||||
const buildSharedRateLimitRedisStore = (prefix, windowMs, client, fallbackHits) => {
|
||||
const store = {
|
||||
prefix,
|
||||
windowMs,
|
||||
fallbackHits,
|
||||
init(opts) { store.windowMs = opts.windowMs; },
|
||||
async increment(key) {
|
||||
increments.push({ prefix, key, failed: fail });
|
||||
if (fail) return { totalHits: fallbackHits, resetTime: new Date() };
|
||||
const full = `${prefix}${key}`;
|
||||
const now = Date.now();
|
||||
const entry = counters.get(full);
|
||||
if (!entry || entry.expireAt <= now) {
|
||||
counters.set(full, { hits: 1, expireAt: now + store.windowMs });
|
||||
return { totalHits: 1 };
|
||||
}
|
||||
entry.hits += 1;
|
||||
return { totalHits: entry.hits };
|
||||
},
|
||||
async get(key) {
|
||||
const entry = counters.get(`${prefix}${key}`);
|
||||
if (!entry || entry.expireAt <= Date.now()) return { totalHits: 0, resetTime: new Date() };
|
||||
return { totalHits: entry.hits, resetTime: new Date(entry.expireAt) };
|
||||
},
|
||||
};
|
||||
constructed.push({ prefix, fallbackHits });
|
||||
return store;
|
||||
};
|
||||
return { counters, constructed, increments, buildSharedRateLimitRedisStore };
|
||||
}
|
||||
|
||||
function makeSession(initial = {}) {
|
||||
const sess = { ...initial };
|
||||
const calls = { save: 0, saveErrors: 0 };
|
||||
sess.save = (cb) => {
|
||||
calls.save += 1;
|
||||
if (sess.__saveError) { calls.saveErrors += 1; cb(sess.__saveError); return; }
|
||||
if (cb) cb(null);
|
||||
};
|
||||
return { sess, calls };
|
||||
}
|
||||
|
||||
function makeRes() {
|
||||
const res = {
|
||||
statusCode: 0,
|
||||
body: null,
|
||||
bodyType: null,
|
||||
redirectCode: null,
|
||||
redirectedTo: null,
|
||||
locals: {},
|
||||
headers: {},
|
||||
cookies: [],
|
||||
clearedCookies: [],
|
||||
setHeader(name, value) { res.headers[String(name).toLowerCase()] = value; },
|
||||
status(code) { res.statusCode = code; return res; },
|
||||
type(t) { res.bodyType = t; return res; },
|
||||
send(b) { res.body = b; return res; },
|
||||
end(b) { res.body = b === undefined ? null : b; return res; },
|
||||
redirect(code, target) {
|
||||
if (typeof code === "string") { res.redirectedTo = code; return res; }
|
||||
res.redirectCode = code;
|
||||
res.redirectedTo = target;
|
||||
return res;
|
||||
},
|
||||
cookie(name, value, opts) { res.cookies.push({ name, value, opts }); return res; },
|
||||
clearCookie(name, opts) { res.clearedCookies.push({ name, opts }); return res; },
|
||||
};
|
||||
return res;
|
||||
}
|
||||
|
||||
// Evaluates the SHIPPED stealth machinery with injected fixtures. The only
|
||||
// fixture inside the counter path is the store transport (see above); every
|
||||
// function under test is index.js's own text.
|
||||
function buildHarness({ fail = false, redisClient: clientOverride, clock = { setTimeout, clearTimeout } } = {}) {
|
||||
const fixture = makeCounterFixture({ fail });
|
||||
const captured = { authorize: null, authorizeRegistrations: 0 };
|
||||
const deps = {
|
||||
crypto,
|
||||
safeCompare: null, // set below (evaluated from the shipped slice)
|
||||
cookieSecureForRequest: () => true,
|
||||
STEALTH_CONFIG: { enabled: true, cookieTtlDays: 30, htmlVariantSalt: "unit-test-salt", cookieName: "adpanel_gate" },
|
||||
buildSharedRateLimitRedisStore: fixture.buildSharedRateLimitRedisStore,
|
||||
redisClient: clientOverride !== undefined ? clientOverride : { isUnitFixtureClient: true },
|
||||
STEALTH_ACTIVE: true,
|
||||
ipKeyGenerator,
|
||||
withTimeout: loadTimeout(clock.setTimeout, clock.clearTimeout),
|
||||
getRequestIp: (req) => String(req.__testIp || "unknown"),
|
||||
app: {
|
||||
get(p, handler) {
|
||||
assert.equal(p, "/_stealth/authorize", "the authorize slice must register exactly the /_stealth/authorize route");
|
||||
captured.authorize = handler;
|
||||
captured.authorizeRegistrations += 1;
|
||||
},
|
||||
},
|
||||
STEALTH_COOKIE_NAME: "adpanel_gate",
|
||||
};
|
||||
const src = [
|
||||
FLOOR_CONST_SRC,
|
||||
TTL_CONST_SRC,
|
||||
SAFECOMPARE_SRC,
|
||||
HELPERS_A_SRC,
|
||||
HELPERS_B_SRC,
|
||||
AUTHORIZE_ROUTE_SRC,
|
||||
"\nreturn { sendStealthBootstrap, buildStealthBootstrapHtml, admitStealthBootstrapMint, getStealthBootstrapState, setStealthBootstrapState, createStealthGateToken, STEALTH_MINT_WINDOW_MS, STEALTH_MINT_SOURCE_MAX, STEALTH_MINT_GLOBAL_MAX, safeCompare };",
|
||||
].join("\n");
|
||||
const names = Object.keys(deps);
|
||||
const exported = new Function(...names, src)(...names.map((n) => deps[n]));
|
||||
assert.equal(captured.authorizeRegistrations, 1, "exactly one authorize registration expected");
|
||||
assert.ok(exported.safeCompare, "the shipped safeCompare must be evaluated");
|
||||
return { ...exported, fixture, authorize: captured.authorize };
|
||||
}
|
||||
|
||||
function makeReq({ ip = "203.0.113.10", url = "/login", session = null, query = null } = {}) {
|
||||
return {
|
||||
method: "GET",
|
||||
path: url,
|
||||
originalUrl: url,
|
||||
__testIp: ip,
|
||||
session: session ? session.sess : undefined,
|
||||
query: query || {},
|
||||
};
|
||||
}
|
||||
|
||||
async function mintOnce(harness, opts = {}) {
|
||||
const session = opts.session || makeSession();
|
||||
const req = makeReq({ ...opts, session });
|
||||
const res = makeRes();
|
||||
await harness.sendStealthBootstrap(req, res, opts.returnTo || "/login");
|
||||
return { session, req, res };
|
||||
}
|
||||
|
||||
function nonceFromRes(res) {
|
||||
const csp = String(res.headers["content-security-policy"] || "");
|
||||
const m = /'nonce-([^']+)'/.exec(csp);
|
||||
assert.ok(m, "bootstrap response must carry a CSP nonce header");
|
||||
return m[1];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Under-cap behavior: the mint path is byte-identical to the pre-fix response
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("under-cap mint: real bootstrap page, session minted + saved once, body byte-identical to buildStealthBootstrapHtml over the same captured inputs", async () => {
|
||||
const harness = buildHarness();
|
||||
const { session, res } = await mintOnce(harness, { ip: "203.0.113.10", url: "/login" });
|
||||
|
||||
assert.equal(res.statusCode, 200);
|
||||
assert.equal(res.bodyType, "html");
|
||||
assert.ok(session.sess.stealthBootstrap && typeof session.sess.stealthBootstrap === "object", "a bootstrap state must be minted in the session");
|
||||
assert.equal(session.calls.save, 1, "exactly one explicit session save on the mint path");
|
||||
const state = session.sess.stealthBootstrap;
|
||||
assert.match(state.id, /^[A-Za-z0-9_-]{24}$/, "state id keeps the 24-char base64url shape (safeCompare census)");
|
||||
assert.equal(state.returnTo, "/login");
|
||||
assert.ok(Math.abs(Date.now() - state.issuedAt) < 5000);
|
||||
|
||||
// Byte-identical: the response is EXACTLY the shipped HTML builder over the
|
||||
// nonce the handler set and the minted state id — the cap added nothing and
|
||||
// changed nothing on the normal response.
|
||||
const nonce = nonceFromRes(res);
|
||||
const authorizeUrl = `/_stealth/authorize?id=${encodeURIComponent(state.id)}&r=${encodeURIComponent("/login")}`;
|
||||
const expected = harness.buildStealthBootstrapHtml({ locals: { cspNonce: nonce } }, authorizeUrl, state.id);
|
||||
assert.equal(res.body, expected, "under-cap response must be byte-identical to the shipped bootstrap page");
|
||||
assert.equal(res.headers["cache-control"], "no-store, private");
|
||||
assert.equal(res.headers.pragma, "no-cache");
|
||||
assert.equal(res.headers.vary, "Accept, Cookie");
|
||||
|
||||
// Wiring: this mint incremented BOTH counters (source + global).
|
||||
const srcEntry = harness.fixture.counters.get("stealth-mint-src:203.0.113.10");
|
||||
const globalEntry = harness.fixture.counters.get("stealth-mint-global:global");
|
||||
assert.equal(srcEntry && srcEntry.hits, 1);
|
||||
assert.equal(globalEntry && globalEntry.hits, 1);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Per-source over-cap: static decoy, zero session writes, authorize fails closed
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("per-source over-cap: source exhausted at 20 mints, request 21 gets the static decoy with ZERO session work; authorize then fails closed", async () => {
|
||||
const harness = buildHarness();
|
||||
const IP = "203.0.113.10";
|
||||
const stateIds = [];
|
||||
for (let i = 0; i < harness.STEALTH_MINT_SOURCE_MAX; i += 1) {
|
||||
const { session, res } = await mintOnce(harness, { ip: IP });
|
||||
assert.equal(res.statusCode, 200, `mint ${i + 1} must be under cap`);
|
||||
stateIds.push(session.sess.stealthBootstrap.id);
|
||||
}
|
||||
|
||||
// The flood breaker at the source level: 21st request.
|
||||
const over = await mintOnce(harness, { ip: IP });
|
||||
assert.equal(over.res.statusCode, 404, "over-cap request must get the plain stealth decoy status");
|
||||
assert.equal(over.res.bodyType, "text/plain");
|
||||
assert.equal(over.res.body, "", "the decoy body stays byte-identical (empty static 404)");
|
||||
assert.equal(over.res.headers["cache-control"], "no-store, private", "decoy headers (same response class the gate serves assets)");
|
||||
assert.equal(over.res.headers["x-content-type-options"], "nosniff");
|
||||
assert.equal(over.session.calls.save, 0, "over-cap request must NOT touch the session (no save)");
|
||||
assert.equal(over.session.sess.stealthBootstrap, undefined, "over-cap request must NOT mint a state");
|
||||
// Nothing about the request may leak into the store: the only counter
|
||||
// movements are the two admission bumps (recorded below), never a session.
|
||||
assert.equal(harness.fixture.counters.get("stealth-mint-src:" + IP).hits, harness.STEALTH_MINT_SOURCE_MAX + 1, "refused mints consume budget too (fixed window, decays on its own TTL)");
|
||||
|
||||
// Global wiring proven on the same loop: every mint (admitted or not) bumped
|
||||
// the global breaker exactly once.
|
||||
assert.equal(harness.fixture.counters.get("stealth-mint-global:global").hits, harness.STEALTH_MINT_SOURCE_MAX + 1);
|
||||
|
||||
// Fail-closed at the authorize step: NO state exists for the over-cap
|
||||
// requester, so even a replayed earlier-shaped id must not fall through.
|
||||
const stateless = makeSession();
|
||||
const req = makeReq({ ip: IP, session: stateless, query: { id: stateIds[0], r: "/login" } });
|
||||
const res = makeRes();
|
||||
await harness.authorize(req, res);
|
||||
assert.equal(res.redirectCode, 303);
|
||||
assert.equal(res.redirectedTo, "/login", "invalid/missing state must redirect to /login (fail closed)");
|
||||
assert.equal(res.cookies.length, 0, "no gate cookie may be granted without a valid state");
|
||||
assert.equal(res.clearedCookies.length, 1, "the gate cookie is cleared (existing invalid-state shape)");
|
||||
assert.equal(res.clearedCookies[0].name, "adpanel_gate");
|
||||
assert.equal(stateless.calls.save, 0, "stateless authorize probes must not write the session (no state consumed)");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Global cap: the fleet breaker binds across fresh sources
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("global over-cap: once the global breaker exceeds its budget a FRESH source is refused too; per-source wiring proven by construction pins", async () => {
|
||||
const harness = buildHarness();
|
||||
const globalKey = "stealth-mint-global:global";
|
||||
// Preload the SAME counter the shipped admission path increments (the
|
||||
// per-mint increment wiring is proven by the counter assertions above).
|
||||
harness.fixture.counters.set(globalKey, { hits: harness.STEALTH_MINT_GLOBAL_MAX, expireAt: Date.now() + harness.STEALTH_MINT_WINDOW_MS });
|
||||
|
||||
const over = await mintOnce(harness, { ip: "198.51.100.77" });
|
||||
assert.equal(over.res.statusCode, 404, "the global breaker refuses a fresh source once exhausted");
|
||||
assert.equal(over.session.calls.save, 0, "global over-cap must leave the session untouched");
|
||||
assert.equal(over.session.sess.stealthBootstrap, undefined);
|
||||
assert.equal(harness.fixture.counters.get(globalKey).hits, harness.STEALTH_MINT_GLOBAL_MAX + 1, "the refused mint still counted against the global window");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Per-source isolation: one exhausted source cannot affect another
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("per-source isolation: an exhausted source leaves a different source fully served", async () => {
|
||||
const harness = buildHarness();
|
||||
for (let i = 0; i < harness.STEALTH_MINT_SOURCE_MAX + 1; i += 1) {
|
||||
await mintOnce(harness, { ip: "203.0.113.10" });
|
||||
}
|
||||
const other = await mintOnce(harness, { ip: "203.0.113.20" });
|
||||
assert.equal(other.res.statusCode, 200, "a fresh source is unaffected by another source's exhaustion");
|
||||
assert.equal(other.session.calls.save, 1);
|
||||
assert.ok(other.session.sess.stealthBootstrap);
|
||||
// IPv4 keys pass through the house /56 bucketing unchanged (the same
|
||||
// bucketing the login throttle uses), so the two sources hold separate
|
||||
// budgets.
|
||||
assert.ok(harness.fixture.counters.has("stealth-mint-src:203.0.113.20"));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Counter store error: fail closed (and the outage case: the save fails anyway)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("counter store error fails CLOSED: even the first request gets the decoy with zero session work", async () => {
|
||||
const harness = buildHarness({ fail: true });
|
||||
const { session, res } = await mintOnce(harness, { ip: "203.0.113.30" });
|
||||
assert.equal(res.statusCode, 404, "an unaccountable counter must not grant the mint (same direction as the login reservation)");
|
||||
assert.equal(session.calls.save, 0);
|
||||
assert.equal(session.sess.stealthBootstrap, undefined);
|
||||
assert.ok(harness.fixture.increments.every((i) => i.failed), "the increments were attempted (fail-closed, not fail-silent-skip)");
|
||||
});
|
||||
|
||||
test("save failure (Redis down) still 500s: the mint fails naturally through the session store — existing behavior, now pinned", async () => {
|
||||
const harness = buildHarness();
|
||||
const session = makeSession();
|
||||
session.sess.__saveError = new Error("redis down");
|
||||
const { res } = await mintOnce(harness, { ip: "203.0.113.40", session });
|
||||
assert.equal(res.statusCode, 500);
|
||||
assert.equal(res.bodyType, "text/plain");
|
||||
assert.equal(res.body, "Service unavailable");
|
||||
});
|
||||
|
||||
function preparePendingSave(route) {
|
||||
let publishTimer;
|
||||
const armed = new Promise((resolve) => { publishTimer = resolve; });
|
||||
const clock = {
|
||||
setTimeout(callback, ms) {
|
||||
const timer = { callback, ms, cleared: false };
|
||||
publishTimer(timer);
|
||||
return timer;
|
||||
},
|
||||
clearTimeout(timer) { timer.cleared = true; },
|
||||
};
|
||||
const harness = buildHarness({ clock });
|
||||
const session = makeSession();
|
||||
let finishSave;
|
||||
session.sess.save = (callback) => { finishSave = callback; };
|
||||
const req = makeReq({ session });
|
||||
const res = makeRes();
|
||||
let response;
|
||||
if (route === "bootstrap") {
|
||||
response = harness.sendStealthBootstrap(req, res, "/servers");
|
||||
} else {
|
||||
const { id } = harness.setStealthBootstrapState(req, "/servers");
|
||||
req.query = { id, r: "/servers" };
|
||||
response = harness.authorize(req, res);
|
||||
}
|
||||
return { armed, response, res, finishSave: (error) => finishSave(error) };
|
||||
}
|
||||
|
||||
function assertUnavailable(res) {
|
||||
assert.equal(res.statusCode, 500);
|
||||
assert.equal(res.bodyType, "text/plain");
|
||||
assert.equal(res.body, "Service unavailable");
|
||||
assert.equal(res.redirectedTo, null);
|
||||
assert.equal(res.cookies.length, 0);
|
||||
}
|
||||
|
||||
for (const route of ["bootstrap", "authorize"]) {
|
||||
test(`save-bounded (${route}): a stalled save fails closed at the deadline`, { timeout: 5000 }, async () => {
|
||||
const pending = preparePendingSave(route);
|
||||
const timer = await pending.armed;
|
||||
assert.equal(timer.ms, 5000);
|
||||
assert.equal(pending.res.body, null);
|
||||
assert.equal(pending.res.redirectedTo, null);
|
||||
assert.equal(pending.res.cookies.length, 0);
|
||||
timer.callback();
|
||||
await pending.response;
|
||||
assertUnavailable(pending.res);
|
||||
assert.equal(timer.cleared, true);
|
||||
});
|
||||
}
|
||||
|
||||
test("save-bounded: an authorize save error never redirects or issues a gate cookie", { timeout: 5000 }, async () => {
|
||||
const pending = preparePendingSave("authorize");
|
||||
const timer = await pending.armed;
|
||||
pending.finishSave(new Error("store unavailable"));
|
||||
await pending.response;
|
||||
assertUnavailable(pending.res);
|
||||
assert.equal(timer.cleared, true);
|
||||
});
|
||||
|
||||
test("save-bounded: a confirmed save retains the bootstrap and authorize success responses", { timeout: 5000 }, async () => {
|
||||
for (const route of ["bootstrap", "authorize"]) {
|
||||
const pending = preparePendingSave(route);
|
||||
const timer = await pending.armed;
|
||||
assert.equal(pending.res.redirectedTo, null);
|
||||
assert.equal(pending.res.body, null);
|
||||
assert.equal(pending.res.cookies.length, 0);
|
||||
pending.finishSave(null);
|
||||
await pending.response;
|
||||
assert.equal(timer.cleared, true);
|
||||
if (route === "bootstrap") {
|
||||
assert.equal(pending.res.statusCode, 200);
|
||||
assert.equal(pending.res.bodyType, "html");
|
||||
assert.match(pending.res.body, /\/_stealth\/authorize/);
|
||||
} else {
|
||||
assert.equal(pending.res.redirectCode, 303);
|
||||
assert.equal(pending.res.redirectedTo, "/servers");
|
||||
assert.equal(pending.res.cookies[0]?.name, "adpanel_gate");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// File-store mode: no Redis client, no counters, cap inert
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("no Redis client (SESSION_STORE=file): the counters are not built and the cap does not run (no amplifier to bound, single-worker enforced)", async () => {
|
||||
const harness = buildHarness({ redisClient: null });
|
||||
assert.equal(harness.fixture.constructed.length, 0, "no counter store may be constructed without a Redis client");
|
||||
const { session, res } = await mintOnce(harness, { ip: "203.0.113.50" });
|
||||
assert.equal(res.statusCode, 200, "file-store mode keeps today's behavior (the finding is about the Redis amplifier)");
|
||||
assert.equal(session.calls.save, 1);
|
||||
assert.equal(await harness.admitStealthBootstrapMint({ __testIp: "203.0.113.50" }), true, "admission without counters is open by design (worker-local counters are not trusted cluster-wide)");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The authorize conditional save: byte-identical responses, no orphan writes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("authorize: valid bootstrap state grants the gate cookie + persists the consumption; stateless probes write nothing and replay fails closed", async () => {
|
||||
const harness = buildHarness();
|
||||
|
||||
// (a) stateless garbage probe (the flood shape): identical response shape,
|
||||
// zero store writes.
|
||||
const stateless = makeSession();
|
||||
const reqA = makeReq({ ip: "203.0.113.10", session: stateless, query: { id: "garbage", r: "/login" } });
|
||||
const resA = makeRes();
|
||||
await harness.authorize(reqA, resA);
|
||||
assert.equal(resA.redirectCode, 303);
|
||||
assert.equal(resA.redirectedTo, "/login");
|
||||
assert.equal(stateless.calls.save, 0, "nothing to persist -> no save (the orphan empty-session write is gone)");
|
||||
assert.equal(resA.cookies.length, 0);
|
||||
|
||||
// (b) the legit bootstrap -> authorize flow: state consumed, consumption
|
||||
// durably persisted, gate cookie granted, redirect to returnTo.
|
||||
const { session, res: boot } = await mintOnce(harness, { ip: "203.0.113.10", url: "/login", returnTo: "/servers" });
|
||||
const state = session.sess.stealthBootstrap;
|
||||
const reqB = makeReq({ ip: "203.0.113.10", session, query: { id: state.id, r: "/servers" } });
|
||||
const resB = makeRes();
|
||||
await harness.authorize(reqB, resB);
|
||||
assert.equal(resB.redirectCode, 303);
|
||||
assert.equal(resB.redirectedTo, "/servers");
|
||||
assert.equal(resB.cookies.length, 1, "valid state grants the gate cookie");
|
||||
assert.equal(resB.cookies[0].name, "adpanel_gate");
|
||||
assert.ok(harness.createStealthGateToken && typeof resB.cookies[0].value === "string" && resB.cookies[0].value.length > 20);
|
||||
assert.equal(session.calls.save, 2, "bootstrap mint save + the consumption save (single-use durability kept)");
|
||||
|
||||
// (c) replay of the consumed state: validation unchanged (fails closed) and
|
||||
// no second save (nothing was cleared).
|
||||
const reqC = makeReq({ ip: "203.0.113.10", session, query: { id: state.id, r: "/servers" } });
|
||||
const resC = makeRes();
|
||||
await harness.authorize(reqC, resC);
|
||||
assert.equal(resC.redirectedTo, "/login");
|
||||
assert.equal(resC.cookies.length, 0);
|
||||
assert.equal(resC.clearedCookies.length, 1);
|
||||
assert.equal(session.calls.save, 2, "a stateless replay must not write the session again");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source pins: cap placement, mechanism contract, decoy content, boot advisory
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("source: the admission check sits BEFORE every session mutation in sendStealthBootstrap", () => {
|
||||
const fnStart = indexOfOrThrow("async function sendStealthBootstrap(req, res, returnTo) {");
|
||||
const fnEnd = indexOfOrThrow("async function sendStealthNotFound(res) {", fnStart);
|
||||
const body = indexSource.slice(fnStart, fnEnd);
|
||||
const admitIdx = body.indexOf("if (!(await admitStealthBootstrapMint(req))) {");
|
||||
const setStateIdx = body.indexOf("const state = setStealthBootstrapState(req, returnTo);");
|
||||
const saveIdx = body.indexOf("req.session.save((err) =>");
|
||||
assert.ok(admitIdx > 0, "the cap check must be present in sendStealthBootstrap");
|
||||
assert.ok(setStateIdx > admitIdx, "the session state write must come after the admission check");
|
||||
assert.ok(saveIdx > setStateIdx, "the explicit session save must come after the admission check");
|
||||
assert.ok(body.includes("return sendStealthNotFound(res);"), "over-cap must serve the plain stealth decoy");
|
||||
// The over-cap branch returns BEFORE any session work can run.
|
||||
const overCapBranchEnd = body.indexOf("}", body.indexOf("return sendStealthNotFound(res);"));
|
||||
assert.ok(overCapBranchEnd < setStateIdx, "the over-cap return must precede the state write");
|
||||
});
|
||||
|
||||
test("source: the cap block lives inside the stealth region and honors the store-factory contract", () => {
|
||||
const tagIdx = indexOfOrThrow("// adpanel:stealth-mint-cap —");
|
||||
assert.ok(tagIdx > indexOfOrThrow("const STEALTH_LOGIN_PATHS = new Set("), "the cap block must live in the stealth/bootstrap region");
|
||||
assert.ok(tagIdx < indexOfOrThrow("function getStealthBootstrapState(req) {"), "the cap block must precede the state helpers it guards");
|
||||
// Two counters, distinct prefixes, one shared factory, one store instance
|
||||
// each, the 0-on-error sentinel, and Redis+stealth-conditional construction.
|
||||
const blockEnd = indexOfOrThrow("function getStealthBootstrapState(req) {", tagIdx);
|
||||
const block = indexSource.slice(tagIdx, blockEnd);
|
||||
assert.ok(block.includes('const stealthMintCounters = redisClient && STEALTH_ACTIVE ? {'), "counters must only be built for a Redis-backed stealth deployment");
|
||||
assert.equal(block.split('"stealth-mint-src:').length - 1, 1, "exactly one per-source counter prefix");
|
||||
assert.equal(block.split('"stealth-mint-global:').length - 1, 1, "exactly one global counter prefix");
|
||||
assert.ok(block.includes('buildSharedRateLimitRedisStore("stealth-mint-src:", STEALTH_MINT_WINDOW_MS, redisClient, 0)'), "per-source counter: shared factory, own instance, distinct prefix, fallbackHits 0 (fail-closed sentinel)");
|
||||
assert.ok(block.includes('buildSharedRateLimitRedisStore("stealth-mint-global:", STEALTH_MINT_WINDOW_MS, redisClient, 0)'), "global counter: shared factory, own instance, distinct prefix, fallbackHits 0 (fail-closed sentinel)");
|
||||
assert.ok(block.includes('stealthMintCounterStore.init({ windowMs: STEALTH_MINT_WINDOW_MS })'), "standalone stores must be init'd (no express-rate-limit middleware calls init for us)");
|
||||
assert.ok(block.includes("if (sourceHits < 1 || globalHits < 1) return false; // counter store error: fail closed"), "the fail-closed direction must be explicit");
|
||||
assert.ok(block.includes("ipKeyGenerator(String(getRequestIp(req) || \"unknown\"))"), "the source key must ride the house /56 bucketing");
|
||||
// Budgets pinned (sizing rationale documented in the block comment).
|
||||
assert.ok(block.includes("const STEALTH_MINT_SOURCE_MAX = 20;"));
|
||||
assert.ok(block.includes("const STEALTH_MINT_GLOBAL_MAX = 2000;"));
|
||||
assert.ok(block.includes("const STEALTH_MINT_WINDOW_MS = 10 * 60 * 1000;"));
|
||||
// The comment must carry the constraint story (AGENTS.md convention).
|
||||
for (const phrase of ["noeviction", "allkeys-lru", "revoked-sid", "FAIL CLOSED", "sendStealthNotFound", "closed (a missing/invalid stealthBootstrap state"]) {
|
||||
assert.ok(block.includes(phrase), `the cap comment must document: ${phrase}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("source: the gate answers before loginRequestLimiter (the premise the cap closes), and the decoy content is untouched", () => {
|
||||
assert.ok(
|
||||
indexOfOrThrow("return sendStealthBootstrap(req, res, req.originalUrl || pathName).catch(next);") <
|
||||
indexOfOrThrow('app.use("/login", loginRequestLimiter);'),
|
||||
"the stealth gate bootstrap leg must stay registered before the /login request limiter"
|
||||
);
|
||||
// The decoy the over-cap path serves is the SAME static 404 the gate has
|
||||
// always served — its body/headers are pinned byte-identical.
|
||||
const decoyStart = indexOfOrThrow("async function sendStealthNotFound(res) {");
|
||||
const decoyEnd = indexOfOrThrow("async function sendStealthEmptyFavicon(", decoyStart);
|
||||
const decoy = indexSource.slice(decoyStart, decoyEnd);
|
||||
assert.ok(decoy.includes('res.setHeader("Cache-Control", "no-store, private");'));
|
||||
assert.ok(decoy.includes('res.setHeader("X-Content-Type-Options", "nosniff");'));
|
||||
assert.ok(decoy.includes('res.status(404).type("text/plain").send("")'), "the 404-empty decoy body stays byte-identical");
|
||||
});
|
||||
|
||||
test("source: the authorize consumption save is conditional on a consumed state; the validation and the unconditional clear are byte-identical", () => {
|
||||
const routeStart = indexOfOrThrow('app.get("/_stealth/authorize", (req, res) => {');
|
||||
const routeEnd = indexOfOrThrow('app.all("/_stealth/nginx-auth"', routeStart);
|
||||
const route = indexSource.slice(routeStart, routeEnd);
|
||||
assert.ok(route.includes("const consumedStealthState = !!currentState;"), "the consumption flag must be captured");
|
||||
assert.ok(route.includes("if (consumedStealthState && req.session?.save) {"), "the save must be gated on an actually consumed state");
|
||||
// The validation shape is untouched (ledger: do not reopen the authorize
|
||||
// validation) — the same five-clause validState conjunction.
|
||||
assert.ok(route.includes("safeCompare(stateId, String(currentState.id || \"\")) &&"));
|
||||
assert.ok(route.includes("sanitizeStealthReturnTo(currentState.returnTo) === returnTo &&"));
|
||||
assert.ok(route.includes("(Date.now() - Number(currentState.issuedAt || 0)) <= STEALTH_BOOTSTRAP_TTL_MS"));
|
||||
assert.equal(route.split("clearStealthBootstrapState(req);").length - 1, 1, "the clear stays unconditional");
|
||||
assert.equal(route.split("const validState = !!(").length - 1, 1);
|
||||
});
|
||||
|
||||
test("source: both response-gating session saves use the shared deadline before finalizing", () => {
|
||||
const bootstrap = sliceBetween("async function sendStealthBootstrap(req, res, returnTo) {", "async function sendStealthNotFound(res) {");
|
||||
for (const [source, label] of [[bootstrap, "stealth-bootstrap-save"], [AUTHORIZE_ROUTE_SRC, "stealth-authorize-save"]]) {
|
||||
assert.ok(source.includes("adpanel:stealth-save-bounded"), `${label}: document the persistence constraint`);
|
||||
const boundedSave = source.match(/return withTimeout\(\s*new Promise\(\(resolve, reject\) => req\.session\.save\([^\n]+\n\s*5000,\s*"([a-z-]+)"\s*\)\.then\(\(\) => \{\s*return finalize\(\)/);
|
||||
assert.equal(boundedSave?.[1], label, `${label}: finalize only after the bounded store save`);
|
||||
const catchStart = source.lastIndexOf("}).catch(() => {");
|
||||
const catchEnd = source.indexOf("\n });", catchStart);
|
||||
assert.ok(catchStart >= 0 && catchEnd > catchStart, `${label}: bound the failure handler`);
|
||||
const failure = source.slice(catchStart, catchEnd);
|
||||
assert.ok(failure.includes('res.status(500).type("text/plain").send("Service unavailable")'));
|
||||
assert.ok(!failure.includes("return finalize()"), `${label}: save failure must not ship success`);
|
||||
}
|
||||
});
|
||||
|
||||
test("source: the Redis boot advisory pins the noeviction deployment requirement", () => {
|
||||
const advisoryIdx = indexOfOrThrow("let redisMaxmemoryPolicyAdvisoryPrinted = false;");
|
||||
const readyIdx = indexOfOrThrow('redisClient.on("ready", () => {');
|
||||
assert.ok(advisoryIdx > indexOfOrThrow("let redisApiLimiterMounted = false;") && advisoryIdx < readyIdx, "the advisory flag lives in the Redis boot region");
|
||||
const readyEnd = indexOfOrThrow("redisReadyPromise = redisClient.connect()", readyIdx);
|
||||
const readyBlock = indexSource.slice(readyIdx, readyEnd);
|
||||
assert.ok(readyBlock.includes("// adpanel:redis-maxmemory-policy-advisory — boot advisory"), "the ready handler owns the advisory");
|
||||
assert.ok(readyBlock.includes('redisClient.sendCommand(["CONFIG", "GET", "maxmemory-policy"])'), "the advisory must best-effort read the live policy");
|
||||
assert.ok(readyBlock.includes('policyValue !== "noeviction"'), "the advisory warns on any policy other than noeviction");
|
||||
assert.ok(readyBlock.includes("allkeys-lru"), "the comment must name the evicting policies");
|
||||
assert.ok(readyBlock.includes("revoked-sid"), "the comment must name the tombstone durability consequence");
|
||||
assert.ok(readyBlock.includes("adpanel:stealth-mint-cap"), "the comment must cross-reference the mint cap");
|
||||
assert.ok(readyBlock.includes("redisMaxmemoryPolicyAdvisoryPrinted"), "the advisory must be once-per-process");
|
||||
assert.ok(indexSource.split("redisMaxmemoryPolicyAdvisoryPrinted").length - 1 >= 2, "flag declared and used");
|
||||
});
|
||||
Reference in new issue
Block a user