Files
Kelx/tests/sid-tombstone-dead-letter.test.js
2026-11-30 16:32:37 +00:00

741 lines
36 KiB
JavaScript

"use strict";
// adpanel:sid-tombstone-dead-letter — Finding (Medium, revocation asymmetry):
// the sid tombstone closes the in-flight-save resurrection race, but on
// tombstone WRITE FAILURE (the 1s-bounded Redis op) logout / suspension /
// stale-account teardown WARN AND PROCEED while only the admin revoke path
// fails closed (503). The local map write in writeRevokedSidTombstone
// protects the SAME worker; the resurrect window is CROSS-WORKER
// (degraded-but-readable Redis + an in-flight save landing on worker B, or
// any save after this worker restarts) and the residue is a stolen sid-cookie
// that keeps working for up to the 370-day tombstone TTL. Logout still
// answers success:true — the client could not see the degradation.
//
// The fix (mirroring the established remember-revoke dead-letter queue):
// 1. Every failed durable tombstone write is dead-lettered (Redis mode
// only — file-store mode's local Map IS the durable tombstone for that
// process) and the ~30s freshness poller re-issues
// writeRevokedSidTombstone(sid) until Redis confirms, then logs
// recovery. The queue only ever RE-WRITES the tombstone — it
// strengthens revocation and cannot resurrect anything. ONE-TRUE-HOME
// inside the tombstone machinery: every caller (logout, suspension,
// stale-account teardown, the binder via its injected dep, the restore
// backstop) gains the retry automatically.
// 2. The logout response carries `sessionRevocationDegraded` (worker-global,
// captured AFTER the awaited tombstone, unconditional on both paths) so
// the client can see the degradation.
// 3. Boot guard: SESSION_STORE=file + a PROVABLE second panel worker
// (pm2's NODE_APP_INSTANCE instance index > 0) exits(1) — pm_id is
// deliberately NOT the predicate (global daemon counter, false-positives
// for instances:1 cohabiting a daemon); instance 0 keeps the warn.
//
// This file pins that contract: source pins on index.js (drift guards for
// the enqueue-before-warn insertion, the poller wiring, the logout response
// field, the boot guard predicate) plus functional pins that run the
// extracted tombstone machinery in a vm sandbox against stubbed Redis
// plumbing — the same style as tests/remember-revoke-dead-letter.test.js.
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 INDEX_JS = path.join(ROOT, "index.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
function extractRegion(source, startMarker, endMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `region start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start + startMarker.length);
assert.ok(end > start, `region end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
// The tombstone machinery with the DLQ inside it: constants, local map
// helpers, writeRevokedSidTombstone (whose failure branch enqueues) and the
// dead-letter queue + drain. ONE-TRUE-HOME: all of it lives in one region
// between the tombstone header and the isSessionSidRevoked comment.
const TOMBSTONE_MACHINERY_SOURCE = extractRegion(
indexSource,
"// ---- Revoked-sid tombstones (anti-resurrection) ----",
"// Consult BOTH layers before trusting a sid:"
);
const POLLER_SOURCE = extractRegion(
indexSource,
"// Freshness poller (single-flight, sticky):",
"REMEMBER_LOGIN_REGISTRY_FRESH_POLL_MS).unref();"
);
const LOGOUT_SOURCE = extractRegion(
indexSource,
'app.post("/logout"',
"const ENV_FILE_PATH"
);
// The session-path tombstone block exactly as it sits between the hoisted
// flag declaration and the destroy call (the appended runner closes nothing —
// this snippet is brace-balanced on its own). Run in a sandbox below with the
// REAL tombstone machinery + DLQ so the enqueue-then-capture ordering is
// exercised end to end.
const LOGOUT_SID_FLAG_SNIPPET_SOURCE = extractRegion(
indexSource,
"let logoutTombstoneWritten = false;",
"req.session.destroy(err => {"
);
// The boot guard (comment + predicate + exit) sits inside the file-store
// branch, BEFORE the store construction. Runnable in a vm sandbox with a
// stubbed process.
const FILE_STORE_GUARD_SOURCE = extractRegion(
indexSource,
"// adpanel:file-store-cluster-guard —",
"sessionStore = new (getLazyFileStore())("
);
// The file-store branch itself (for placement pins).
const FILE_STORE_BRANCH_SOURCE = extractRegion(
indexSource,
"if (!sessionStore) {",
"// ── db-proxy token store backing"
);
// The Redis branch (for the negative placement pin).
const REDIS_BRANCH_SOURCE = extractRegion(
indexSource,
"if (REDIS_SESSION_REQUIRED) {",
'console.log("[session] File-based sessions forced via SESSION_STORE=file");'
);
// ---------------------------------------------------------------------------
// Source pins: the contract is in the text (these are the drift guards)
// ---------------------------------------------------------------------------
test("the sid-tombstone dead-letter queue exists, is FIFO-capped and paired with a capped attempt map", () => {
assert.match(
TOMBSTONE_MACHINERY_SOURCE,
/const REVOKED_SID_TOMBSTONE_DEAD_LETTER_MAX = 1000;/,
"the queue cap must be a named constant (~1000, LOGIN_MAP_MAX_SIZE eviction style)"
);
assert.match(
TOMBSTONE_MACHINERY_SOURCE,
/const REVOKED_SID_TOMBSTONE_DEAD_LETTER_DRAIN_MAX = 25;/,
"each drain round must be bounded (~25 sids per 30s tick)"
);
assert.match(
TOMBSTONE_MACHINERY_SOURCE,
/const REVOKED_SID_TOMBSTONE_ATTEMPT_MAP_MAX = scaleForMemory\(10000\);/,
"the attempt map must be capped through the shared memory scaler"
);
assert.match(
TOMBSTONE_MACHINERY_SOURCE,
/const REVOKED_SID_TOMBSTONE_ESCALATE_EVERY = 10;/,
"escalation must be bounded to every 10th attempt"
);
assert.match(
TOMBSTONE_MACHINERY_SOURCE,
/const revokedSidTombstoneDeadLetter = new Set\(\);/,
"the queue itself is a Set of failed sids"
);
assert.match(
TOMBSTONE_MACHINERY_SOURCE,
/const revokedSidTombstoneDeadLetterAttempts = new Map\(\);/,
"attempt counts live in a Map (escalation bookkeeping)"
);
// FIFO eviction: when full, the OLDEST sid is dropped before inserting.
const capIdx = TOMBSTONE_MACHINERY_SOURCE.indexOf("revokedSidTombstoneDeadLetter.size >= REVOKED_SID_TOMBSTONE_DEAD_LETTER_MAX");
const evictIdx = TOMBSTONE_MACHINERY_SOURCE.indexOf("revokedSidTombstoneDeadLetter.values().next().value");
assert.ok(capIdx >= 0 && evictIdx > capIdx, "the FIFO eviction (oldest-first) must guard the insert");
assert.match(
TOMBSTONE_MACHINERY_SOURCE,
/adpanel:sid-tombstone-dead-letter — a failed \(1s-bounded\) durable tombstone\s*\n\s*\/\/ write must RETRY until Redis confirms the SET/,
"the AGENTS-style comment must state the constraint (retry until confirmed, not a console.warn)"
);
assert.match(
TOMBSTONE_MACHINERY_SOURCE,
/only ever RE-WRITES the tombstone/,
"the comment must document why the queue cannot resurrect an entry"
);
assert.match(
TOMBSTONE_MACHINERY_SOURCE,
/best-effort\s*\n\s*\/\/ per-worker by design/,
"the comment must document that the queue is lost on worker restart"
);
assert.match(
TOMBSTONE_MACHINERY_SOURCE,
/File-mode marker\s*\n\s*\/\/ write failures use the same retry path/,
"file-mode marker failures must retain the durable retry contract"
);
});
test("writeRevokedSidTombstone's failure branch dead-letters BEFORE the loud warn — every caller gains the retry", () => {
// Exactly one enqueue CALL site: inside the write function's catch (Redis
// mode only reaches it — file-store mode returns true earlier; the
// empty-sid caller-bug return false sits before the try and must NOT
// enqueue). The helper itself is defined exactly once in index.js.
assert.strictEqual(
(TOMBSTONE_MACHINERY_SOURCE.match(/enqueueSidTombstoneDeadLetter\(id\);/g) || []).length,
1,
"exactly one enqueue call site — the catch of writeRevokedSidTombstone (one true home)"
);
assert.strictEqual(
(indexSource.match(/function enqueueSidTombstoneDeadLetter\(/g) || []).length,
1,
"the enqueue helper must be defined exactly once — never forked"
);
assert.match(
TOMBSTONE_MACHINERY_SOURCE,
/enqueueSidTombstoneDeadLetter\(id\);\s*\n\s*console\.warn\(`\[security\] Failed to write revoked-sid tombstone/,
"the failed write must enqueue BEFORE the existing loud [security] warn (remember-DLQ ordering)"
);
// The original contracts stay intact: local fast path, bounded write,
// fail-closed false, and the file-store local-Map shortcut.
assert.match(TOMBSTONE_MACHINERY_SOURCE, /rememberRevokedSidTombstoneLocally\(id\);/);
assert.match(TOMBSTONE_MACHINERY_SOURCE, /await withTimeout\(\s*redisClient\.set\(/);
assert.match(TOMBSTONE_MACHINERY_SOURCE, /if \(!redisClient\) return fileSessionRevocations\.write\(id\);/, "file-store mode must confirm its durable marker write");
assert.match(TOMBSTONE_MACHINERY_SOURCE, /if \(!id\) return false;/, "an empty sid stays a caller bug — no retry can fix it");
// The drain re-issues the SAME tombstone write — it can never resurrect.
assert.match(
TOMBSTONE_MACHINERY_SOURCE,
/durable = await writeRevokedSidTombstone\(sid\);/,
"the drain must retry through the shared write helper"
);
// The drain is the tail of the machinery region (it sits between the DLQ
// constants and the isSessionSidRevoked comment).
const drainStart = TOMBSTONE_MACHINERY_SOURCE.indexOf("async function drainSidTombstoneDeadLetter() {");
assert.ok(drainStart >= 0, "the drain must live inside the tombstone machinery (one true home)");
const drainFn = TOMBSTONE_MACHINERY_SOURCE.slice(drainStart);
assert.doesNotMatch(
drainFn,
/redisClient\.(del|hDel|unlink)/,
"the drain must never delete anything — dead-lettering a tombstone is write-only"
);
assert.match(
drainFn,
/REVOKED_SID_TOMBSTONE_DEAD_LETTER_DRAIN_MAX/,
"the drain round must be bounded"
);
assert.match(
TOMBSTONE_MACHINERY_SOURCE,
/function isSidTombstoneDegraded\(\)/,
"the worker-global degradation getter must exist (logout flag capture)"
);
});
test("the ~30s freshness poller drains BOTH dead-letter queues, best-effort", () => {
assert.match(
POLLER_SOURCE,
/ensureRememberLoginRegistryFresh\(\)\.catch\(\(\) => false\);/,
"the existing freshness work must be preserved"
);
assert.match(
POLLER_SOURCE,
/drainRememberRevocationDeadLetter\(\)\.catch\(\(\) => false\);/,
"the remember-revoke DLQ drain must be untouched"
);
assert.match(
POLLER_SOURCE,
/drainSidTombstoneDeadLetter\(\)\.catch\(\(\) => false\);/,
"the sid-tombstone DLQ drain must run on the same tick, rejection-guarded so it never throws out of the interval callback"
);
const freshIdx = POLLER_SOURCE.indexOf("ensureRememberLoginRegistryFresh().catch(() => false);");
const rememberIdx = POLLER_SOURCE.indexOf("drainRememberRevocationDeadLetter().catch(() => false);");
const sidIdx = POLLER_SOURCE.indexOf("drainSidTombstoneDeadLetter().catch(() => false);");
assert.ok(freshIdx >= 0 && rememberIdx > freshIdx && sidIdx > rememberIdx, "the sid drain runs after the existing freshness work and the remember drain");
assert.match(
indexSource,
/const REMEMBER_LOGIN_REGISTRY_FRESH_POLL_MS = 30_000;/,
"the poller cadence constant must stay untouched"
);
});
test("logout answers with an additive sessionRevocationDegraded field on BOTH paths, captured after the awaited tombstone", () => {
assert.match(
LOGOUT_SOURCE,
/return res\.json\(\{ success: true, revocationDegraded: logoutRevocationDegraded, sessionRevocationDegraded: logoutSessionRevocationDegraded \}\);/,
"the session-path success response must include the sid-tombstone degradation flag"
);
assert.match(
LOGOUT_SOURCE,
/return res\.json\(\{ success: true, revocationDegraded: isRememberLoginRevocationDegraded\(\), sessionRevocationDegraded: isSidTombstoneDegraded\(\) \}\);/,
"the no-session success response must report the worker-global sid-tombstone degradation state"
);
assert.match(
LOGOUT_SOURCE,
/let logoutSessionRevocationDegraded = false;/,
"the flag defaults to false (healthy worker answers sessionRevocationDegraded: false)"
);
// Exactly one capture site, AFTER the awaited tombstone write and its
// warn-on-false, UNCONDITIONALLY within the session path (worker-global
// semantics — a logout whose own tombstone succeeded still reports an
// earlier pending failure).
assert.strictEqual(
(LOGOUT_SOURCE.match(/logoutSessionRevocationDegraded = isSidTombstoneDegraded\(\);/g) || []).length,
1,
"exactly one capture site — the unconditional post-await read"
);
const awaitIdx = LOGOUT_SOURCE.indexOf("logoutTombstoneWritten = await writeRevokedSidTombstone(req.sessionID);");
const warnIdx = LOGOUT_SOURCE.indexOf("Could not durably tombstone logged-out session");
const captureIdx = LOGOUT_SOURCE.indexOf("logoutSessionRevocationDegraded = isSidTombstoneDegraded();");
const destroyIdx = LOGOUT_SOURCE.indexOf("req.session.destroy(err => {");
assert.ok(awaitIdx >= 0 && warnIdx > awaitIdx && captureIdx > warnIdx && destroyIdx > captureIdx, "the capture must sit after the awaited tombstone + warn and before the destroy");
assert.match(
LOGOUT_SOURCE,
/\/\/ adpanel:sid-tombstone-dead-letter — read AFTER the awaited tombstone\s*\n\s*\/\/ write/,
"the capture's comment must state the post-await, unconditional, worker-global read semantics"
);
// Additive only: the pre-existing success/error shapes must survive.
assert.match(LOGOUT_SOURCE, /success: true, revocationDegraded/);
assert.match(LOGOUT_SOURCE, /res\.status\(500\)\.json\(\{ error: "Failed to logout" \}\)/);
});
// adpanel:logout-destroy-error-clear — the destroy-ERROR branch is on the
// far side of the tombstone + remember revocation, so the sid is already
// dead server-side (the revoked-sid gate consults the tombstone written
// before the destroy ran) and clearing the cookies there is truthful; the
// pre-flight branch (tombstone write failure, before the destroy) must keep
// its no-clearing behavior because the session record is still fully alive.
test("the destroy-error branch clears the cookies and echoes the degraded flags; the pre-flight branch clears nothing", () => {
const destroyIdx = LOGOUT_SOURCE.indexOf("req.session.destroy(err => {");
assert.ok(destroyIdx >= 0, "the destroy call must exist");
const destroyBlock = LOGOUT_SOURCE.slice(destroyIdx, LOGOUT_SOURCE.indexOf("} else {", destroyIdx));
assert.match(
destroyBlock,
/if \(err\) \{\s*\n\s*\/\/ adpanel:logout-destroy-error-clear — the tombstone above precedes/,
"the destroy-error branch carries the boundary comment (tombstone precedes destroy — clearing is truthful)"
);
assert.match(
destroyBlock,
/if \(err\) \{[^]*?clear\(\);\s*\n\s*return res\.status\(500\)\.json\(\{ error: "Failed to logout", revocationDegraded: logoutRevocationDegraded, sessionRevocationDegraded: logoutSessionRevocationDegraded \}\);/,
"the destroy-error branch performs the FULL cookie clear and echoes BOTH degraded flags on the 500 exactly as the success path echoes them"
);
// The pre-flight failure branch (tombstone write failure) stays clear-free:
// nothing has been revoked yet and the session is still fully alive.
const preflightIdx = LOGOUT_SOURCE.indexOf("[/logout] pre-flight failed:");
assert.ok(preflightIdx >= 0 && preflightIdx < destroyIdx, "the pre-flight branch precedes the destroy");
const preflightBlock = LOGOUT_SOURCE.slice(preflightIdx, LOGOUT_SOURCE.indexOf("if (!logoutTombstoneWritten)", preflightIdx));
assert.ok(preflightBlock.includes('if (!res.headersSent) return res.status(500).json({ error: "Failed to logout" });'), "the pre-flight 500 keeps its bare shape");
assert.strictEqual((preflightBlock.match(/clear\(/g) || []).length, 0, "the pre-flight branch must clear NOTHING (nothing has been revoked yet — a clear would falsely log out a live session)");
});
test("the file-store cluster guard exits on a PROVABLE second instance and keys on NODE_APP_INSTANCE, never pm_id", () => {
assert.match(
FILE_STORE_GUARD_SOURCE,
/const pm2InstanceRaw = String\(process\.env\.NODE_APP_INSTANCE \?\? ""\)\.trim\(\);/,
"the predicate must read the pm2 instance index"
);
assert.match(
FILE_STORE_GUARD_SOURCE,
/const pm2InstanceNumber = Number\.parseInt\(pm2InstanceRaw, 10\);/,
"the index must be parsed as an integer"
);
assert.match(
FILE_STORE_GUARD_SOURCE,
/if \(Number\.isFinite\(pm2InstanceNumber\) && pm2InstanceNumber > 0\) \{/,
"exit ONLY when the 0-based instance index proves a sibling (index > 0)"
);
assert.match(
FILE_STORE_GUARD_SOURCE,
/process\.exit\(1\);/,
"a provable second instance must fail-fast at boot (secret-strength boot-check style)"
);
assert.match(
FILE_STORE_GUARD_SOURCE,
/console\.error\(`\[session\] SESSION_STORE=file cannot run with more than one panel worker/,
"the exit message must name the deployment fix (single worker or Redis)"
);
// pm_id is a daemon-global counter (God.getNewId() across ALL apps) — it
// must NOT appear in the predicate, and the comment must document why.
assert.doesNotMatch(
FILE_STORE_GUARD_SOURCE.replace(/\/\/[^\n]*/g, ""),
/pm_id/,
"the CODE must never key on pm_id (false-exit trap for instances:1 cohabiting a daemon)"
);
assert.match(
FILE_STORE_GUARD_SOURCE,
/pm_id was evaluated and deliberately REJECTED as the predicate/,
"the comment must document the pm_id rejection"
);
assert.match(
FILE_STORE_GUARD_SOURCE,
/DETECTION LIMITATION \(documented, not silently absorbed\)/,
"the comment must honestly document the instance-0 / non-pm2 detection limitation"
);
// Placement: inside the file-store branch, before the store construction;
// the Redis branch must carry no instance check (Redis tombstones are
// cluster-shared — multi-worker is the supported mode there).
assert.ok(
FILE_STORE_BRANCH_SOURCE.includes("// adpanel:file-store-cluster-guard —"),
"the guard must live in the file-store branch (one true home of the file-store posture)"
);
const guardIdx = FILE_STORE_BRANCH_SOURCE.indexOf("const pm2InstanceRaw");
const storeIdx = FILE_STORE_BRANCH_SOURCE.indexOf("sessionStore = new (getLazyFileStore())(");
assert.ok(guardIdx >= 0 && storeIdx > guardIdx, "the guard must run BEFORE the file store is constructed");
assert.doesNotMatch(
REDIS_BRANCH_SOURCE,
/NODE_APP_INSTANCE/,
"the Redis branch must not gate on the instance index (multi-worker is supported with Redis)"
);
// The original warn (instance 0 / non-pm2 backstop) must survive.
assert.match(
FILE_STORE_BRANCH_SOURCE,
/console\.warn\("\[security\] File session store: keep \.sessions-revoked persistent and run a single panel worker; consumed-action-token markers remain process-local/,
"the file-store warn must still explain the remaining single-worker requirement"
);
});
// ---------------------------------------------------------------------------
// Functional pins: the extracted machinery runs against stubbed Redis plumbing
// ---------------------------------------------------------------------------
// Same race the remember-dead-letter test implements: the extracted tombstone
// machinery calls withTimeout, so the sandbox must provide the REAL
// semantics, not a passthrough.
function sandboxWithTimeout(promise, ms, label = "timeout") {
let timer;
return Promise.race([
Promise.resolve(promise),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(label)), ms);
}),
]).finally(() => clearTimeout(timer));
}
function makeTombstoneSandbox({ redisClient } = {}) {
const warnings = [];
const sandbox = {
console: {
warn: (...args) => warnings.push(args.map(String).join(" ")),
log: () => {},
error: () => {},
},
process: { env: {} },
scaleForMemory: (base) => base,
redisClient: redisClient === undefined ? { isOpen: true, set: async () => "OK" } : redisClient,
fileSessionRevocations: { write: () => true, has: () => false },
withTimeout: sandboxWithTimeout,
getSessionDisplayId: (id) => `sess:${id}`,
};
vm.createContext(sandbox);
vm.runInContext(TOMBSTONE_MACHINERY_SOURCE, sandbox, { filename: "sid-tombstone-sandbox.js" });
return {
sandbox,
warnings,
// Realm-safe readers: top-level const declarations live in the context's
// global lexical environment, so subsequent scripts can read them.
queue: () => Array.from(vm.runInContext("[...revokedSidTombstoneDeadLetter]", sandbox)),
attempts: (sid) => vm.runInContext("revokedSidTombstoneDeadLetterAttempts.get(" + JSON.stringify(String(sid)) + ")", sandbox),
degraded: () => vm.runInContext("isSidTombstoneDegraded()", sandbox),
size: () => vm.runInContext("revokedSidTombstoneDeadLetter.size", sandbox),
write: (sid) => vm.runInContext("writeRevokedSidTombstone(" + JSON.stringify(String(sid)) + ")", sandbox),
};
}
test("a failed durable tombstone write is dead-lettered and answers the fail-closed false", async () => {
// Failure mode 1: the Redis SET throws.
const throwing = makeTombstoneSandbox({
redisClient: { isOpen: true, set: async () => { throw new Error("ECONNRESET"); } },
});
const r1 = await throwing.write("sid-a");
assert.strictEqual(r1, false, "a failed Redis write must keep returning false (callers fail closed — contract unchanged)");
assert.deepStrictEqual(throwing.queue(), ["sid-a"], "the failed sid must be dead-lettered for the poller's retry");
assert.strictEqual(throwing.degraded(), true, "a non-empty queue means sid revocation is degraded");
assert.strictEqual(throwing.attempts("sid-a"), 0, "enqueue initializes the attempt count at 0");
assert.strictEqual(
throwing.warnings.filter((w) => w.includes("[security] Failed to write revoked-sid tombstone") && w.includes("sess:sid-a")).length,
1,
"the loud [security] warn (and its wording) is unchanged"
);
// Failure mode 2: the Redis client buffers the write forever (the REAL
// outage shape) — the 1s-bounded withTimeout inside the write must reject,
// and the timeout must dead-letter exactly like a thrown error. (The
// sandbox cannot lower the Math.max(100, ...) floor, so this costs ~100ms.)
let settled = false;
const buffered = makeTombstoneSandbox({
redisClient: { isOpen: true, set: () => new Promise(() => {}) },
});
const r2 = await buffered.write("sid-b").then((v) => { settled = true; return v; });
assert.strictEqual(settled, true, "the bounded write must settle even when the client buffers forever");
assert.strictEqual(r2, false);
assert.deepStrictEqual(buffered.queue(), ["sid-b"], "the timeout path dead-letters too");
// Success: nothing is queued, the worker stays healthy.
const healthy = makeTombstoneSandbox();
assert.strictEqual(await healthy.write("sid-ok"), true);
assert.strictEqual(healthy.size(), 0, "success must not enqueue");
assert.strictEqual(healthy.degraded(), false);
});
test("a successful durable file-marker write needs no dead-letter retry", async () => {
const box = makeTombstoneSandbox({
redisClient: null,
});
// The local map helper must still fire (the wrapper's read path consults it).
const localCached = await vm.runInContext(
"(async () => { const ok = await writeRevokedSidTombstone('sid-file'); return { ok, cached: isRevokedSidTombstoneCachedLocally('sid-file') }; })()",
box.sandbox
);
assert.strictEqual(localCached.ok, true, "the file marker write confirmed durability");
assert.strictEqual(localCached.cached, true, "the local fast path must still be populated");
assert.strictEqual(box.size(), 0, "file-store mode never dead-letters — no Redis failure exists to retry");
assert.strictEqual(box.warnings.filter((w) => w.includes("[security]")).length, 0, "no alarm in file-store mode");
});
test("failed file-marker persistence reports degraded revocation and retries the same SID", async () => {
const box = makeTombstoneSandbox({ redisClient: null });
box.sandbox.fileSessionRevocations.write = () => { throw new Error("disk-full"); };
assert.strictEqual(await box.write("test-file-sid"), false);
assert.deepStrictEqual(box.queue(), ["test-file-sid"]);
assert.strictEqual(box.degraded(), true);
const writes = [];
box.sandbox.fileSessionRevocations.write = (sid) => { writes.push(sid); return true; };
assert.strictEqual(await vm.runInContext("drainSidTombstoneDeadLetter()", box.sandbox), 1);
assert.deepStrictEqual(writes, ["test-file-sid"]);
assert.strictEqual(box.degraded(), false);
});
test("an empty sid returns false but is never dead-lettered (caller bug, not a Redis failure)", async () => {
const box = makeTombstoneSandbox();
assert.strictEqual(await box.write(""), false, "the empty-sid contract is unchanged");
assert.strictEqual(box.size(), 0, "no retry can fix an empty sid — it must not enter the queue");
assert.strictEqual(box.degraded(), false);
});
test("poller drain: a Redis recovery re-writes the tombstone, removes the sid and logs recovery", async () => {
const box = makeTombstoneSandbox({
redisClient: { isOpen: true, set: async () => { throw new Error("blip"); } },
});
await box.write("sid-x");
assert.strictEqual(box.size(), 1, "still queued while Redis fails");
// Drain round while Redis is still down: the sid stays queued.
let recovered = await vm.runInContext("drainSidTombstoneDeadLetter()", box.sandbox);
assert.strictEqual(recovered, 0, "a failing retry is not a recovery");
assert.strictEqual(box.size(), 1);
assert.strictEqual(box.degraded(), true);
assert.strictEqual(box.attempts("sid-x"), 1, "attempt counts increment per drain round");
// Redis recovers: the drain re-writes the durable tombstone.
box.sandbox.redisClient = { isOpen: true, set: async () => "OK" };
recovered = await vm.runInContext("drainSidTombstoneDeadLetter()", box.sandbox);
assert.strictEqual(recovered, 1, "the successful re-SET counts as one recovery");
assert.strictEqual(box.size(), 0, "a confirmed tombstone removes the sid from the queue");
assert.strictEqual(box.degraded(), false, "the worker is no longer degraded");
assert.strictEqual(box.attempts("sid-x"), undefined, "the attempt entry is cleaned up with the sid");
assert.ok(
box.warnings.some((w) => w.includes("[security] Revoked-sid tombstone recovered") && w.includes("sess:sid-x")),
"recovery must be logged loudly on the [security] channel"
);
assert.ok(box.warnings.some((w) => w.includes("dead-letter fully drained")), "an emptied queue logs the all-clear");
// Draining an empty queue is a no-op.
assert.strictEqual(await vm.runInContext("drainSidTombstoneDeadLetter()", box.sandbox), 0);
});
test("drain escalation: a persistently failing sid warns again every 10th attempt", async () => {
// Only a REJECTED withTimeout (a thrown or timed-out SET) reaches the
// write's catch — use a throwing client for the persistent-failure shape.
const throwing = makeTombstoneSandbox({
redisClient: { isOpen: true, set: async () => { throw new Error("ETIMEDOUT"); } },
});
await throwing.write("sid-stuck");
for (let round = 1; round <= 20; round += 1) {
await vm.runInContext("drainSidTombstoneDeadLetter()", throwing.sandbox);
const escalated = throwing.warnings.filter((w) => w.includes("dead-letter still failing")).length;
assert.strictEqual(escalated, Math.floor(round / 10), `escalation at attempt ${round}`);
assert.strictEqual(throwing.size(), 1, "the sid stays queued across rounds");
assert.strictEqual(throwing.attempts("sid-stuck"), round);
}
assert.ok(
throwing.warnings.some((w) => w.includes("ETIMEDOUT")),
"the thrown error's message surfaces in the escalation"
);
assert.ok(
throwing.warnings.every((w) => !w.includes("recovered")),
"no recovery log without a successful write"
);
});
test("drain round cap (functional): 30 queued sids, 25 re-written per round, FIFO head priority", async () => {
const throwing = makeTombstoneSandbox({
redisClient: { isOpen: true, set: async () => { throw new Error("down"); } },
});
vm.runInContext(`
for (let i = 0; i < 30; i += 1) {
enqueueSidTombstoneDeadLetter("cap-" + String(i).padStart(2, "0"));
}
`, throwing.sandbox);
assert.strictEqual(throwing.size(), 30);
await vm.runInContext("drainSidTombstoneDeadLetter()", throwing.sandbox);
assert.strictEqual(throwing.size(), 30, "failed retries stay queued for the next tick");
assert.strictEqual(throwing.attempts("cap-00"), 1, "the oldest 25 sids were processed this round");
assert.strictEqual(throwing.attempts("cap-29"), 0, "the tail is not reached while the head keeps failing");
// Redis recovers: the head clears and the tail drains in bounded rounds.
throwing.sandbox.redisClient = { isOpen: true, set: async () => "OK" };
let rounds = 0;
while (throwing.size() > 0 && rounds < 5) {
await vm.runInContext("drainSidTombstoneDeadLetter()", throwing.sandbox);
rounds += 1;
}
assert.strictEqual(throwing.size(), 0, "recovery drains the whole queue (2 surviving rounds of 5 + 25)");
assert.strictEqual(vm.runInContext("isSidTombstoneDegraded()", throwing.sandbox), false);
});
test("FIFO cap: the queue never grows past 1000 and evicts the oldest sid", () => {
const box = makeTombstoneSandbox();
vm.runInContext(`
for (let i = 0; i < 1005; i += 1) {
enqueueSidTombstoneDeadLetter("cap-" + String(i).padStart(4, "0"));
}
`, box.sandbox);
assert.strictEqual(box.size(), 1000, "the cap holds");
assert.strictEqual(box.degraded(), true);
assert.strictEqual(vm.runInContext('revokedSidTombstoneDeadLetter.has("cap-0000")', box.sandbox), false, "the OLDEST sid was evicted");
assert.strictEqual(vm.runInContext('revokedSidTombstoneDeadLetter.has("cap-0004")', box.sandbox), false, "eviction is FIFO, not random");
assert.strictEqual(vm.runInContext('revokedSidTombstoneDeadLetter.has("cap-1004")', box.sandbox), true, "the newest sid survived");
assert.strictEqual(
vm.runInContext("revokedSidTombstoneDeadLetterAttempts.size", box.sandbox),
1000,
"the attempt map stays in lockstep with the queue (capped too)"
);
});
// ---------------------------------------------------------------------------
// Behavior pin: the logout capture reads the worker-global state after the
// awaited tombstone
// ---------------------------------------------------------------------------
function makeLogoutFlagSandbox({ redisClient } = {}) {
const warnings = [];
const sandbox = {
console: {
warn: (...args) => warnings.push(args.map(String).join(" ")),
log: () => {},
error: () => {},
},
process: { env: {} },
scaleForMemory: (base) => base,
redisClient: redisClient === undefined ? { isOpen: true, set: async () => "OK" } : redisClient,
fileSessionRevocations: { write: () => true, has: () => false },
withTimeout: sandboxWithTimeout,
getSessionDisplayId: (id) => `sess:${id}`,
};
vm.createContext(sandbox);
vm.runInContext(TOMBSTONE_MACHINERY_SOURCE, sandbox, { filename: "logout-sid-flag-machinery.js" });
return { sandbox, warnings };
}
async function runLogoutSidFlagPath(sandbox, req) {
const runner =
"(async (req) => {\n" +
" let logoutSessionRevocationDegraded = false;\n" +
LOGOUT_SID_FLAG_SNIPPET_SOURCE +
" return logoutSessionRevocationDegraded;\n" +
"})";
const compute = vm.runInContext(runner, sandbox, { filename: "logout-sid-flag-runner.js" });
return compute(req, { headersSent: false, status: () => ({ json: () => {} }), json: () => {} });
}
test("logout's sessionRevocationDegraded capture: this-call failure, worker-global pending, healthy stays false", async () => {
// THIS logout's tombstone fails (synchronous enqueue inside the awaited
// write) → the client must see sessionRevocationDegraded: true.
const thisCallFails = makeLogoutFlagSandbox({
redisClient: { isOpen: true, set: async () => { throw new Error("down"); } },
});
assert.strictEqual(
await runLogoutSidFlagPath(thisCallFails.sandbox, { sessionID: "sid-logout-1" }),
true,
"a this-call tombstone failure must be captured after the awaited write"
);
// Healthy write on a clean worker → false.
const healthy = makeLogoutFlagSandbox();
assert.strictEqual(
await runLogoutSidFlagPath(healthy.sandbox, { sessionID: "sid-logout-2" }),
false,
"a successful tombstone on an empty DLQ stays healthy"
);
// THE worker-global regression guard: an earlier pending failure on this
// worker degrades a logout whose own tombstone write succeeded.
const earlierPending = makeLogoutFlagSandbox();
vm.runInContext("enqueueSidTombstoneDeadLetter('earlier-sid')", earlierPending.sandbox);
assert.strictEqual(
await runLogoutSidFlagPath(earlierPending.sandbox, { sessionID: "sid-logout-3" }),
true,
"an earlier pending tombstone failure degrades a logout whose own write succeeded (worker-global)"
);
});
// ---------------------------------------------------------------------------
// Behavior pin: the file-store cluster boot guard (stubbed exit)
// ---------------------------------------------------------------------------
function runBootGuard(env) {
const calls = { errors: [], warns: [], exits: [] };
const sandbox = {
console: {
error: (...args) => calls.errors.push(args.map(String).join(" ")),
warn: (...args) => calls.warns.push(args.map(String).join(" ")),
log: () => {},
},
process: {
env,
exit: (code) => calls.exits.push(code),
},
};
vm.createContext(sandbox);
vm.runInContext(FILE_STORE_GUARD_SOURCE, sandbox, { filename: "file-store-cluster-guard.js" });
return calls;
}
test("boot guard: pm2 instance index > 0 + file-store exits(1) with the operator fix", () => {
const calls = runBootGuard({ NODE_APP_INSTANCE: "2", pm_id: "2" });
assert.deepStrictEqual(calls.exits, [1], "a provable second instance must exit(1)");
assert.ok(
calls.errors.some((w) => w.includes("SESSION_STORE=file") && w.includes("instance index 2")),
"the error must name the store mode and the detected instance index"
);
assert.ok(
calls.errors.some((w) => w.includes("pm2 scale adpanel 1") || w.includes("REDIS_URL")),
"the error must tell the operator the fix (single worker or Redis)"
);
});
test("boot guard: instance 0, unset instance, non-numeric instance and pm_id-only never exit", () => {
// THE instances:1 deployment (this repo's ecosystem.config.js): PM2 sets
// NODE_APP_INSTANCE=0 — no exit, the strengthened warn is the backstop.
let calls = runBootGuard({ NODE_APP_INSTANCE: "0", pm_id: "0" });
assert.deepStrictEqual(calls.exits, [], "instance 0 must NOT exit (indistinguishable from a single worker)");
assert.strictEqual(calls.errors.length, 0);
// Non-pm2 (docker/systemd/plain node): no marker at all — no exit.
calls = runBootGuard({});
assert.deepStrictEqual(calls.exits, [], "no instance marker must not exit");
assert.strictEqual(calls.errors.length, 0);
// Non-numeric garbage must degrade to unknown, not exit.
calls = runBootGuard({ NODE_APP_INSTANCE: "abc" });
assert.deepStrictEqual(calls.exits, [], "a non-numeric instance marker must not exit");
// THE false-exit trap: pm_id is a daemon-global counter — a single-instance
// adpanel cohabiting a daemon with any other app reports pm_id > 0 while
// NODE_APP_INSTANCE is unset/0. The predicate must key on NODE_APP_INSTANCE
// ONLY: this process is NOT provably a second instance, so no exit.
calls = runBootGuard({ pm_id: "7" });
assert.deepStrictEqual(calls.exits, [], "pm_id > 0 alone must never exit (global daemon counter)");
calls = runBootGuard({ NODE_APP_INSTANCE: "0", pm_id: "7" });
assert.deepStrictEqual(calls.exits, [], "pm_id > 0 with instance 0 must never exit (instances:1 in a busy daemon)");
// Proves the predicate is the instance INDEX, not pm_id: a high instance
// index with a low pm_id still exits.
calls = runBootGuard({ NODE_APP_INSTANCE: "3", pm_id: "0" });
assert.deepStrictEqual(calls.exits, [1], "instance index > 0 proves a sibling regardless of pm_id");
});