Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+799
View File
@@ -0,0 +1,799 @@
"use strict";
// adpanel:remember-revoke-dead-letter — Finding (Low–Medium): the awaited
// revocations still answered a Redis failure with a console-only [security]
// warn — logout cleared the cookie locally, answered success, and a STOLEN
// 365-day remember cookie stayed valid on every OTHER worker, with no retry
// anywhere. The fix dead-letters every unconfirmed id into an in-memory
// queue that the ~30s freshness poller drains (re-issuing the same idempotent,
// version-bumping HDEL through deleteRememberLoginRegistryFields until Redis
// confirms), surfaces `revocationDegraded` on the logout response, and logs
// recovery / escalates persistent failures. The queue only ever RE-DELETEs —
// it cannot resurrect an entry — and is best-effort per-worker (lost on
// restart; the loud warns and the Confirmed admin-revoke path remain the
// operator-visible backstop). This file pins that contract: source pins on
// index.js (drift guards for the failure-path insertions, the poller wiring,
// the logout response field — captured UNCONDITIONALLY so BOTH logout paths
// report the worker-global DLQ state — and the untouched Confirmed twin /
// shared deleter) plus functional pins that run the extracted machinery and
// revoke helpers in a vm sandbox against stubbed Redis plumbing.
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 DLQ machinery (queue + helpers + drain) between the freshness constants
// and the freshness poller. The poller itself is pinned separately below —
// running it inside a vm sandbox would need the freshness globals it calls.
const DLQ_MACHINERY_SOURCE = extractRegion(
indexSource,
"// adpanel:remember-revoke-dead-letter — a failed cluster-wide revocation of a",
"// Freshness poller (single-flight, sticky):"
);
const REVOKE_ENTRY_SOURCE = extractRegion(
indexSource,
"async function revokeRememberLoginRegistryEntry(rememberId) {",
"// Rotation-race window for confirmed revocations"
);
const REVOKE_FOR_USER_SOURCE = extractRegion(
indexSource,
// Conscious marker update (adpanel:session-inventory-error-propagation):
// the user-wide revoke gained the optional additive options sink.
"async function revokeRememberLoginsForUser(user, options = {}) {",
"function getRememberLoginRegistryEntry(rememberId)"
);
// Conscious addition (adpanel:remember-logout-lineage): logout's revoke was
// upgraded to the lineage-scoped helper, so the logout-flag path below runs
// the REAL lineage revocation too — its failure/dead-letter behavior must be
// exercised end to end alongside the single-entry twin.
const LINEAGE_REVOKE_SOURCE = extractRegion(
indexSource,
"async function revokeRememberLoginLineage(rememberId, hints = null) {",
"function findRememberLoginIdBySessionId(sessionId"
);
// The shared targeted-delete helper must stay free of dead-letter concerns:
// the queue re-issues deletes THROUGH it, never the other way around.
const DELETER_SOURCE = extractRegion(
indexSource,
"async function deleteRememberLoginRegistryFields(fields)",
"function queueRememberLoginRedisPersist("
);
// The Confirmed twin fail-closes with admin retry tokens and must keep its
// own contract — the dead-letter queue is for the fire-and-forget twins only.
const CONFIRMED_SOURCE = extractRegion(
indexSource,
"async function revokeRememberLoginRegistryEntryConfirmed(rememberId, ownerHint = null) {",
// Conscious marker update (adpanel:remember-logout-lineage): the lineage
// revocation machinery now sits BETWEEN the Confirmed twin and
// findRememberLoginIdBySessionId — the region must stop at the lineage
// header comment so this pin keeps meaning exactly the Confirmed twin (the
// lineage helper's own dead-lettering is pinned in
// tests/remember-logout-lineage.test.js).
"// adpanel:remember-logout-lineage — ROTATION LINEAGE REVOCATION"
);
const LOGOUT_SOURCE = extractRegion(
indexSource,
'app.post("/logout"',
"const ENV_FILE_PATH"
);
// The session-path flag computation exactly as it sits between the flag
// declaration and the first statement after the rememberLoginId branch (the
// no-session path answers inline and is pinned in the source tests). Run in
// a sandbox below together with the REAL DLQ machinery and single-entry
// revoke helper; the appended `}` in the runner closes the
// `if (req.session) {` block this extraction cuts open.
const LOGOUT_FLAG_SNIPPET_SOURCE = extractRegion(
indexSource,
"let logoutRevocationDegraded = false;",
"removeActiveBrowserSessionCacheEntry(req.sessionID);"
);
// ---------------------------------------------------------------------------
// Source pins: the contract is in the text (these are the drift guards)
// ---------------------------------------------------------------------------
test("the dead-letter queue exists, is FIFO-capped and paired with a capped attempt map", () => {
assert.match(
DLQ_MACHINERY_SOURCE,
/const REMEMBER_REVOCATION_DEAD_LETTER_MAX = 1000;/,
"the queue cap must be a named constant (~1000, LOGIN_MAP_MAX_SIZE eviction style)"
);
assert.match(
DLQ_MACHINERY_SOURCE,
/const REMEMBER_REVOCATION_DEAD_LETTER_DRAIN_MAX = 25;/,
"each drain round must be bounded (~25 ids per 30s tick)"
);
assert.match(
DLQ_MACHINERY_SOURCE,
/const rememberRevocationDeadLetter = new Set\(\);/,
"the queue itself is a Set of failed ids"
);
assert.match(
DLQ_MACHINERY_SOURCE,
/const rememberRevocationDeadLetterAttempts = new Map\(\);/,
"attempt counts live in a Map (escalation bookkeeping)"
);
// FIFO eviction: when full, the OLDEST id is dropped before inserting.
const capIdx = DLQ_MACHINERY_SOURCE.indexOf("rememberRevocationDeadLetter.size >= REMEMBER_REVOCATION_DEAD_LETTER_MAX");
const evictIdx = DLQ_MACHINERY_SOURCE.indexOf("rememberRevocationDeadLetter.values().next().value");
assert.ok(capIdx >= 0 && evictIdx > capIdx, "the FIFO eviction (oldest-first) must guard the insert");
assert.match(
DLQ_MACHINERY_SOURCE,
/adpanel:remember-revoke-dead-letter — a failed cluster-wide revocation of a\s*\n\s*\/\/ 365-day remember credential must RETRY/,
"the AGENTS-style comment must state the constraint (retry until confirmed, not a console.warn)"
);
assert.match(
DLQ_MACHINERY_SOURCE,
/only ever RE-DELETEs/,
"the comment must document why the queue cannot resurrect an entry"
);
assert.match(
DLQ_MACHINERY_SOURCE,
/Best-effort per-worker by design/,
"the comment must document that the queue is lost on worker restart"
);
});
test("the drain only re-issues the shared targeted delete — it can never resurrect", () => {
assert.match(
DLQ_MACHINERY_SOURCE,
/await deleteRememberLoginRegistryFields\(\[id\]\)/,
"the drain must re-issue the idempotent HDEL through the shared (1s-bounded) helper"
);
assert.doesNotMatch(
DLQ_MACHINERY_SOURCE,
/rememberLoginRegistry\[|hSet|queueRememberLoginRedisPersist|upsertRememberLoginRegistryEntry/,
"the drain must never write/restore an entry — dead-lettering is delete-only"
);
});
test("the ~30s freshness poller drains the queue after the freshness work, best-effort", () => {
const poller = extractRegion(
indexSource,
"// Freshness poller (single-flight, sticky):",
"REMEMBER_LOGIN_REGISTRY_FRESH_POLL_MS).unref();"
);
assert.match(
poller,
/ensureRememberLoginRegistryFresh\(\)\.catch\(\(\) => false\);/,
"the existing freshness work must be preserved"
);
assert.match(
poller,
/drainRememberRevocationDeadLetter\(\)\.catch\(\(\) => false\);/,
"the drain must run on the same tick, rejection-guarded so it never throws out of the interval callback"
);
const freshIdx = poller.indexOf("ensureRememberLoginRegistryFresh().catch(() => false);");
const drainIdx = poller.indexOf("drainRememberRevocationDeadLetter().catch(() => false);");
assert.ok(freshIdx >= 0 && drainIdx > freshIdx, "the drain must come AFTER the existing freshness work");
assert.match(
indexSource,
/const REMEMBER_LOGIN_REGISTRY_FRESH_POLL_MS = 30_000;/,
"the poller cadence constant must stay untouched"
);
});
test("both revoke helpers dead-letter their failed ids BEFORE the loud warn, contracts unchanged", () => {
// Single-entry revoke: both failure branches (throw + false) enqueue, then
// the original loud warn and the existed contract stay intact.
const catchIdx = REVOKE_ENTRY_SOURCE.indexOf("enqueueRememberRevocationDeadLetter(id);");
const throwWarnIdx = REVOKE_ENTRY_SOURCE.indexOf("Remember-login revocation FAILED for ${getRememberLoginDisplayId(id)}: Redis delete errored");
assert.ok(catchIdx >= 0 && throwWarnIdx > catchIdx, "the thrown-error path must enqueue BEFORE the loud warn");
assert.match(
REVOKE_ENTRY_SOURCE,
/enqueueRememberRevocationDeadLetter\(id\);\s*\n\s*console\.warn\(`\[security\] Remember-login revocation FAILED/,
"both failure branches must enqueue before their existing loud [security] warn"
);
assert.strictEqual(
(REVOKE_ENTRY_SOURCE.match(/enqueueRememberRevocationDeadLetter\(id\);/g) || []).length,
2,
"exactly two enqueue sites in the single-entry revoke (throw + false)"
);
assert.match(
REVOKE_ENTRY_SOURCE,
/return existed;/,
"the existed contract must be untouched (eviction call site counts on it)"
);
// User-wide revoke: known-id batch (throw + false) and sweep (throw + false).
assert.strictEqual(
(REVOKE_FOR_USER_SOURCE.match(/enqueueRememberRevocationDeadLetter\(/g) || []).length,
4,
"exactly four enqueue sites in the user-wide revoke (batch throw/false + sweep throw/false)"
);
assert.match(
REVOKE_FOR_USER_SOURCE,
/let sweepStaleIds = \[\];/,
"the sweep must capture the ids it identified so its failure can dead-letter them"
);
assert.match(
REVOKE_FOR_USER_SOURCE,
/sweepStaleIds = staleIds;\s*\n\s*return deleteRememberLoginRegistryFields\(staleIds\);/,
"the capture must happen exactly when the sweep hands its ids to the delete"
);
assert.match(
REVOKE_FOR_USER_SOURCE,
/return revoked;/,
"the count contract (destroyBrowserSessionsForUser's rememberLoginsRevoked) must survive"
);
// The dead-letter insertions must not swallow the existing failure warns.
assert.match(REVOKE_FOR_USER_SOURCE, /\[security\] User-wide remember-login revocation FAILED/);
assert.match(REVOKE_FOR_USER_SOURCE, /\[security\] User-wide remember-login revocation sweep FAILED/);
});
test("the Confirmed twin and the shared deleter stay untouched by the dead-letter concern", () => {
assert.doesNotMatch(
CONFIRMED_SOURCE,
/DeadLetter|dead-letter/,
"the Confirmed twin fail-closes with admin retry tokens — no dead-lettering there"
);
assert.doesNotMatch(
DELETER_SOURCE,
/DeadLetter|dead-letter/,
"the shared delete helper must stay free of dead-letter concerns (the queue calls it, never the reverse)"
);
});
test("logout answers with an additive revocationDegraded field after the awaited revocation", () => {
// Conscious pin update (adpanel:sid-tombstone-dead-letter): the response
// gained the additive sid-tombstone twin `sessionRevocationDegraded` next
// to `revocationDegraded`; this pin is strengthened, not weakened — the
// remember flag must still be present on BOTH paths in its original
// capture shape.
assert.match(
LOGOUT_SOURCE,
/return res\.json\(\{ success: true, revocationDegraded: logoutRevocationDegraded, sessionRevocationDegraded: logoutSessionRevocationDegraded \}\);/,
"the session-path success response must include the degradation flag (and its sid-tombstone twin)"
);
assert.match(
LOGOUT_SOURCE,
/return res\.json\(\{ success: true, revocationDegraded: isRememberLoginRevocationDegraded\(\), sessionRevocationDegraded: isSidTombstoneDegraded\(\) \}\);/,
"the no-session success response must report the worker-global degradation state (and its sid-tombstone twin)"
);
// Conscious text update (adpanel:remember-logout-lineage): the awaited
// revoke is the lineage-scoped helper now; the capture-order contract is
// unchanged (the enqueue still runs synchronously inside the awaited call).
const revokeIdx = LOGOUT_SOURCE.indexOf("await revokeRememberLoginLineage(rememberLoginId, {");
const captureIdx = LOGOUT_SOURCE.indexOf("logoutRevocationDegraded = isRememberLoginRevocationDegraded();");
assert.ok(revokeIdx >= 0 && captureIdx > revokeIdx, "the flag must be captured AFTER the awaited revocation");
// adpanel:remember-revoke-dead-letter — the capture must be UNCONDITIONAL:
// exactly one read site, sitting OUTSIDE the `if (rememberLoginId)` branch
// so a session logout without a remember credential reports the same
// worker-global DLQ state as the no-session path (the comment/code
// contract must not drift apart again).
assert.strictEqual(
(LOGOUT_SOURCE.match(/logoutRevocationDegraded = isRememberLoginRevocationDegraded\(\);/g) || []).length,
1,
"exactly one capture site — the unconditional post-branch read (no in-branch copy)"
);
const branchStartIdx = LOGOUT_SOURCE.indexOf("if (rememberLoginId) {");
assert.ok(branchStartIdx >= 0 && branchStartIdx < captureIdx, "the rememberLoginId branch must precede the capture");
const branchToCapture = LOGOUT_SOURCE.slice(branchStartIdx, captureIdx);
const opens = (branchToCapture.match(/\{/g) || []).length;
const closes = (branchToCapture.match(/\}/g) || []).length;
assert.strictEqual(
opens - closes,
0,
"the capture must sit OUTSIDE the rememberLoginId branch: every brace the branch opened (branch, try, catch) must be closed before the capture — a nested capture would leave the branch brace open (diff >= 1)"
);
assert.match(
LOGOUT_SOURCE,
/\/\/ adpanel:remember-revoke-dead-letter — read[^]*?UNCONDITIONALLY[^]*?worker-global[^]*?logoutRevocationDegraded = isRememberLoginRevocationDegraded\(\);/,
"the capture's comment must state the unconditional, worker-global read semantics"
);
assert.match(
LOGOUT_SOURCE,
/let logoutRevocationDegraded = false;/,
"the flag defaults to false (healthy worker answers revocationDegraded: false)"
);
// 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 remember revocation runs BEFORE
// the destroy, so a destroy ERROR means the 365-day credential is already
// revoked (or its DLQ degradation is already captured): the destroy-error
// branch echoes the captured flag on its 500 exactly as the success path
// does, and clears the cookies (the sid is dead server-side via the
// pre-destroy tombstone). The pre-flight branch stays clear-free.
test("the destroy-error 500 echoes the captured remember revocationDegraded flag alongside the cookie clear", () => {
const destroyIdx = LOGOUT_SOURCE.indexOf("req.session.destroy(err => {");
assert.ok(destroyIdx >= 0, "the destroy call must exist");
const destroyBlock = LOGOUT_SOURCE.slice(destroyIdx);
assert.match(
destroyBlock,
/clear\(\);\s*\n\s*return res\.status\(500\)\.json\(\{ error: "Failed to logout", revocationDegraded: logoutRevocationDegraded, sessionRevocationDegraded: logoutSessionRevocationDegraded \}\);/,
"the destroy-error branch echoes BOTH captured degradation flags on its 500 (the remember flag was captured unconditionally before the destroy)"
);
const captureIdx = LOGOUT_SOURCE.indexOf("logoutRevocationDegraded = isRememberLoginRevocationDegraded();");
const destroyErrIdx = LOGOUT_SOURCE.indexOf("adpanel:logout-destroy-error-clear", destroyIdx);
assert.ok(captureIdx >= 0 && captureIdx < destroyIdx && destroyErrIdx > destroyIdx, "the flag capture (post-revocation) strictly precedes the destroy whose error branch echoes it");
});
// ---------------------------------------------------------------------------
// Functional pins: the extracted machinery runs against stubbed Redis plumbing
// ---------------------------------------------------------------------------
function makeDeadLetterSandbox({ deleteImpl } = {}) {
const warnings = [];
const sandbox = {
console: {
warn: (...args) => warnings.push(args.map(String).join(" ")),
log: () => {},
},
scaleForMemory: (base) => base,
deleteRememberLoginRegistryFields:
deleteImpl ||
(async () => {
throw new Error("deleteImpl not provided");
}),
getRememberLoginDisplayId: (id) => `saved:${id}`,
setInterval: () => ({ unref: () => {} }),
};
vm.createContext(sandbox);
vm.runInContext(DLQ_MACHINERY_SOURCE, sandbox, { filename: "remember-dead-letter-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.
ids: () => Array.from(vm.runInContext("[...rememberRevocationDeadLetter]", sandbox)),
attempts: (id) => vm.runInContext("rememberRevocationDeadLetterAttempts.get(" + JSON.stringify(String(id)) + ")", sandbox),
degraded: () => vm.runInContext("isRememberLoginRevocationDegraded()", sandbox),
size: () => vm.runInContext("rememberRevocationDeadLetter.size", sandbox),
};
}
test("enqueue/degrade helpers: failed ids are queued, success keeps the queue empty", async () => {
const deletes = [];
const box = makeDeadLetterSandbox({
deleteImpl: async (ids) => {
deletes.push(Array.from(ids));
return false;
},
});
assert.strictEqual(box.degraded(), false, "a healthy worker is not degraded");
assert.strictEqual(await vm.runInContext("drainRememberRevocationDeadLetter()", box.sandbox), 0, "draining an empty queue is a no-op");
vm.runInContext("enqueueRememberRevocationDeadLetter(['id-a', 'id-b', ''])", box.sandbox);
assert.deepStrictEqual(box.ids(), ["id-a", "id-b"], "empty/invalid ids must never be queued");
assert.strictEqual(box.degraded(), true, "a non-empty queue means revocation is degraded");
assert.strictEqual(box.attempts("id-a"), 0, "enqueue initializes the attempt count at 0");
// One drain round with Redis still failing: ids are retained, each delete
// is the single-id shared-helper call, and the first round does not
// escalate (attempts 1..N < 10).
const recovered = await vm.runInContext("drainRememberRevocationDeadLetter()", box.sandbox);
assert.strictEqual(recovered, 0);
assert.deepStrictEqual(deletes, [["id-a"], ["id-b"]], "the drain re-deletes one id at a time through the shared helper");
assert.deepStrictEqual(box.ids(), ["id-a", "id-b"], "persistent failure keeps the ids queued");
assert.strictEqual(box.attempts("id-a"), 1, "attempt counts increment per drain round");
assert.strictEqual(box.warnings.filter((w) => w.includes("dead-letter still failing")).length, 0, "no escalation before the 10th attempt");
assert.strictEqual(box.warnings.filter((w) => w.includes("recovered")).length, 0, "no recovery log without a successful delete");
});
test("drain recovery: a Redis recovery re-deletes, removes the id and logs recovery", async () => {
let deleteResult = false;
const box = makeDeadLetterSandbox({ deleteImpl: async () => deleteResult });
vm.runInContext("enqueueRememberRevocationDeadLetter('id-x')", box.sandbox);
await vm.runInContext("drainRememberRevocationDeadLetter()", box.sandbox);
assert.strictEqual(box.size(), 1, "still queued while Redis fails");
assert.strictEqual(box.degraded(), true);
deleteResult = true;
const recovered = await vm.runInContext("drainRememberRevocationDeadLetter()", box.sandbox);
assert.strictEqual(recovered, 1, "the successful re-HDEL counts as one recovery");
assert.strictEqual(box.size(), 0, "a confirmed delete removes the id from the queue");
assert.strictEqual(box.degraded(), false, "the worker is no longer degraded");
assert.strictEqual(box.attempts("id-x"), undefined, "the attempt entry is cleaned up with the id");
assert.ok(
box.warnings.some((w) => w.includes("[security] Remember-login revocation recovered") && w.includes("saved:id-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");
});
test("drain escalation: a persistently failing id warns again every 10th attempt", async () => {
const box = makeDeadLetterSandbox({ deleteImpl: async () => false });
vm.runInContext("enqueueRememberRevocationDeadLetter('id-stuck')", box.sandbox);
for (let round = 1; round <= 20; round += 1) {
await vm.runInContext("drainRememberRevocationDeadLetter()", box.sandbox);
const escalated = box.warnings.filter((w) => w.includes("dead-letter still failing")).length;
assert.strictEqual(escalated, Math.floor(round / 10), `escalation at attempt ${round}`);
assert.strictEqual(box.size(), 1, "the id stays queued across rounds");
assert.strictEqual(box.attempts("id-stuck"), round);
}
// Thrown Redis errors escalate through the same cadence (fresh queue).
const throwing = makeDeadLetterSandbox({
deleteImpl: async () => {
throw new Error("ECONNRESET");
},
});
vm.runInContext("enqueueRememberRevocationDeadLetter('id-thrown')", throwing.sandbox);
for (let round = 1; round <= 10; round += 1) {
await vm.runInContext("drainRememberRevocationDeadLetter()", throwing.sandbox);
}
assert.strictEqual(throwing.warnings.filter((w) => w.includes("dead-letter still failing")).length, 1, "exactly the 10th attempt escalates");
assert.ok(throwing.warnings.some((w) => w.includes("ECONNRESET")), "the thrown error's message surfaces in the escalation");
});
test("drain round cap (functional): 30 queued ids, 25 processed per round", async () => {
const deletes = [];
const box = makeDeadLetterSandbox({
deleteImpl: async (ids) => {
deletes.push(Array.from(ids));
return false;
},
});
vm.runInContext(`
for (let i = 0; i < 30; i += 1) {
enqueueRememberRevocationDeadLetter("cap-" + String(i).padStart(2, "0"));
}
`, box.sandbox);
assert.strictEqual(box.size(), 30);
await vm.runInContext("drainRememberRevocationDeadLetter()", box.sandbox);
assert.strictEqual(deletes.length, 25, "one drain round processes at most REMEMBER_REVOCATION_DEAD_LETTER_DRAIN_MAX ids");
assert.strictEqual(box.size(), 30, "failed retries stay queued for the next tick");
assert.strictEqual(box.attempts("cap-00"), 1, "the oldest 25 ids were processed this round");
assert.strictEqual(box.attempts("cap-29"), 0, "the tail is not reached while the head keeps failing");
// While the deletes keep failing, each round retries the OLDEST 25 (FIFO
// head priority, matching the eviction style) — the tail advances only once
// the head ids succeed and leave the queue, which bounds the full-queue
// drain time after Redis recovers.
await vm.runInContext("drainRememberRevocationDeadLetter()", box.sandbox);
assert.strictEqual(deletes.length, 50, "the second round retries at most 25 again");
assert.strictEqual(box.attempts("cap-00"), 2, "the oldest id is retried first");
assert.strictEqual(box.attempts("cap-29"), 0, "the tail stays queued while the head fails");
// Once Redis recovers, the head clears and the tail drains in bounded rounds.
box.sandbox.deleteRememberLoginRegistryFields = async (ids) => {
deletes.push(Array.from(ids));
return true;
};
let rounds = 0;
while (box.size() > 0 && rounds < 5) {
await vm.runInContext("drainRememberRevocationDeadLetter()", box.sandbox);
rounds += 1;
}
assert.strictEqual(box.size(), 0, "recovery drains the whole queue (2 surviving rounds of 5 + 25)");
assert.strictEqual(vm.runInContext("isRememberLoginRevocationDegraded()", box.sandbox), false);
});
test("FIFO cap: the queue never grows past 1000 and evicts the oldest id", () => {
const box = makeDeadLetterSandbox({ deleteImpl: async () => false });
vm.runInContext(`
for (let i = 0; i < 1005; i += 1) {
enqueueRememberRevocationDeadLetter("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('rememberRevocationDeadLetter.has("cap-0000")', box.sandbox), false, "the OLDEST id was evicted");
assert.strictEqual(vm.runInContext('rememberRevocationDeadLetter.has("cap-0004")', box.sandbox), false, "eviction is FIFO, not random");
assert.strictEqual(vm.runInContext('rememberRevocationDeadLetter.has("cap-1004")', box.sandbox), true, "the newest id survived");
assert.strictEqual(
vm.runInContext("rememberRevocationDeadLetterAttempts.size", box.sandbox),
1000,
"the attempt map stays in lockstep with the queue (capped too)"
);
});
// Same race the durable test implements (copied verbatim): the extracted
// revoke regions call 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));
}
// Sandbox that loads the DLQ machinery FIRST, then a revoke region, so the
// failure paths exercise the REAL enqueue/degrade helpers end to end.
function makeRevokeSandbox({ redisClient, deleteImpl, registry, timeoutMs = 40 }) {
const warnings = [];
const sandbox = {
console: {
warn: (...args) => warnings.push(args.map(String).join(" ")),
log: () => {},
},
rememberLoginRegistry: registry,
matchesAccountForRevocation: require("../utils/session-account-binding").matchesAccountForRevocation,
redisClient: redisClient === undefined ? { isOpen: true } : redisClient,
deleteRememberLoginRegistryFields: deleteImpl,
getRememberLoginDisplayId: (id) => `saved:${id}`,
ensureRememberLoginRedisReady: async () => !!(redisClient && redisClient.isOpen),
setRememberLoginLegacyCutoff: (userId) => sandbox.__legacyCutoffs.push(String(userId)),
REMEMBER_LOGIN_REGISTRY_REDIS_KEY: "adpanel:remember-logins",
REMEMBER_LOGIN_REGISTRY_VERSION_REDIS_KEY: "adpanel:remember-logins-version",
withTimeout: sandboxWithTimeout,
REMEMBER_REVOKE_WRITE_TIMEOUT_MS: timeoutMs,
REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL: "remember-revoke-write-timeout",
scaleForMemory: (base) => base,
setInterval: () => ({ unref: () => {} }),
// Faithful mirror of index.js's stripLogControlChars
// (adpanel:log-email-control-chars): the user-wide revoke warns strip the
// interpolated email before interpolation.
stripLogControlChars: (value) => String(value || "").replace(/[\x00-\x1f\x7f]/g, ""),
__legacyCutoffs: [],
};
vm.createContext(sandbox);
vm.runInContext(DLQ_MACHINERY_SOURCE, sandbox, { filename: "remember-dead-letter-sandbox.js" });
return { sandbox, warnings };
}
test("single-entry revoke failure dead-letters the id, keeps the existed contract and the loud warn", async () => {
// Failure mode 1: the delete helper reports false (Redis unready).
const registry1 = { "abc123": { uid: "u1", email: "a@x" } };
const s1 = makeRevokeSandbox({ registry: registry1, deleteImpl: async () => false });
vm.runInContext(REVOKE_ENTRY_SOURCE, s1.sandbox, { filename: "revoke-entry-sandbox.js" });
const r1 = await s1.sandbox.revokeRememberLoginRegistryEntry("abc123");
assert.strictEqual(r1, true, "the existed contract must survive a failed Redis delete");
assert.ok(!("abc123" in registry1), "the local delete still applied");
assert.deepStrictEqual(
Array.from(vm.runInContext("[...rememberRevocationDeadLetter]", s1.sandbox)),
["abc123"],
"the failed id must be dead-lettered for the poller's retry"
);
assert.strictEqual(vm.runInContext("isRememberLoginRevocationDegraded()", s1.sandbox), true);
assert.strictEqual(
s1.warnings.filter((w) => w.includes("[security] Remember-login revocation FAILED") && w.includes("saved:abc123")).length,
1,
"the loud [security] warn (and its wording) is unchanged"
);
// Failure mode 2: the delete helper throws (Redis error).
const registry2 = { "abc123": { uid: "u1", email: "a@x" } };
const s2 = makeRevokeSandbox({
registry: registry2,
deleteImpl: async () => {
throw new Error("ECONNRESET");
},
});
vm.runInContext(REVOKE_ENTRY_SOURCE, s2.sandbox, { filename: "revoke-entry-sandbox.js" });
const r2 = await s2.sandbox.revokeRememberLoginRegistryEntry("abc123");
assert.strictEqual(r2, true, "a thrown Redis error must not reject the revoke promise");
assert.strictEqual(vm.runInContext("rememberRevocationDeadLetter.size", s2.sandbox), 1, "the thrown-error path dead-letters too");
assert.ok(s2.warnings.some((w) => w.includes("[security] Remember-login revocation FAILED")), "the loud warn fired");
// Success: nothing is queued, the worker stays healthy.
const registry3 = { "abc123": { uid: "u1", email: "a@x" } };
const s3 = makeRevokeSandbox({ registry: registry3, deleteImpl: async () => true });
vm.runInContext(REVOKE_ENTRY_SOURCE, s3.sandbox, { filename: "revoke-entry-sandbox.js" });
const r3 = await s3.sandbox.revokeRememberLoginRegistryEntry("abc123");
assert.strictEqual(r3, true);
assert.strictEqual(vm.runInContext("rememberRevocationDeadLetter.size", s3.sandbox), 0, "success must not enqueue");
assert.strictEqual(vm.runInContext("isRememberLoginRevocationDegraded()", s3.sandbox), false);
// File-store mode: the local delete IS durable — no dead-letter, no alarm.
const registry4 = { "abc123": { uid: "u1", email: "a@x" } };
const s4 = makeRevokeSandbox({
registry: registry4,
redisClient: null,
deleteImpl: async () => {
throw new Error("delete must not be called in file-store mode");
},
});
vm.runInContext(REVOKE_ENTRY_SOURCE, s4.sandbox, { filename: "revoke-entry-sandbox.js" });
const r4 = await s4.sandbox.revokeRememberLoginRegistryEntry("abc123");
assert.strictEqual(r4, true);
assert.strictEqual(vm.runInContext("rememberRevocationDeadLetter.size", s4.sandbox), 0, "file-store mode never dead-letters");
assert.strictEqual(s4.warnings.filter((w) => w.includes("[security]")).length, 0);
});
test("user-wide revoke failure dead-letters the batch AND the sweep's identified ids", async () => {
const registry = {
"id-a": { uid: "u1", email: "a@x" },
"id-b": { uid: "u1", email: "A@X" },
"id-other": { uid: "u2", email: "b@x" },
};
const redisClient = {
isOpen: true,
hGetAll: async () => ({
"id-a": JSON.stringify({ uid: "u1", email: "a@x" }),
"id-remote": JSON.stringify({ uid: "u1", email: "a@x" }),
"id-other": JSON.stringify({ uid: "u2", email: "b@x" }),
}),
};
const s1 = makeRevokeSandbox({ registry, redisClient, deleteImpl: async () => false });
vm.runInContext(REVOKE_FOR_USER_SOURCE, s1.sandbox, { filename: "revoke-user-sandbox.js" });
const revoked = await s1.sandbox.revokeRememberLoginsForUser({ id: "u1", email: "a@x" });
assert.strictEqual(revoked, 2, "the locally-known count contract must survive (id-a and id-b both match)");
assert.deepStrictEqual(
Array.from(vm.runInContext("[...rememberRevocationDeadLetter]", s1.sandbox)).sort(),
["id-a", "id-b", "id-remote"],
"the known-id batch AND the sweep's remotely-identified ids are all dead-lettered (Set-deduplicated)"
);
assert.strictEqual(vm.runInContext("isRememberLoginRevocationDegraded()", s1.sandbox), true);
const securityWarns = s1.warnings.filter((w) => w.includes("[security] User-wide remember-login revocation"));
assert.ok(securityWarns.length >= 2, "both failure warns are unchanged");
assert.ok(!("id-a" in registry) && !("id-b" in registry), "the local deletes still applied");
// A sweep whose hash READ fails has no ids to dead-letter: only the known
// batch lands in the queue (the next successful revoke/re-revoke covers it).
const failingClient = { isOpen: true, hGetAll: async () => { throw new Error("blip"); } };
const registry2 = { "id-a": { uid: "u1", email: "a@x" } };
const s2 = makeRevokeSandbox({ registry: registry2, redisClient: failingClient, deleteImpl: async () => false });
vm.runInContext(REVOKE_FOR_USER_SOURCE, s2.sandbox, { filename: "revoke-user-sandbox.js" });
const revoked2 = await s2.sandbox.revokeRememberLoginsForUser({ id: "u1", email: "a@x" });
assert.strictEqual(revoked2, 1);
assert.deepStrictEqual(
Array.from(vm.runInContext("[...rememberRevocationDeadLetter]", s2.sandbox)),
["id-a"],
"no sweep ids exist when the hash read itself failed — only the known batch is queued"
);
assert.ok(s2.warnings.some((w) => w.includes("[security] User-wide remember-login revocation sweep FAILED")), "the sweep warn fired");
});
test("the drain retries the dead-lettered revoke through the real shared helper semantics", async () => {
// End-to-end on one sandbox: revoke fails → dead-letter → drain recovers
// once Redis returns. The delete stub here mimics the shared helper's
// return contract (true = HDEL + version bump landed).
let redisUp = false;
const registry = { "abc123": { uid: "u1", email: "a@x" } };
const hDels = [];
const s = makeRevokeSandbox({
registry,
redisClient: { isOpen: true },
deleteImpl: async (ids) => {
if (!redisUp) return false;
hDels.push(Array.from(ids));
return true;
},
});
vm.runInContext(REVOKE_ENTRY_SOURCE, s.sandbox, { filename: "revoke-entry-sandbox.js" });
await s.sandbox.revokeRememberLoginRegistryEntry("abc123");
assert.strictEqual(vm.runInContext("rememberRevocationDeadLetter.size", s.sandbox), 1);
assert.strictEqual(hDels.length, 0, "no delete landed while Redis was down");
redisUp = true;
await vm.runInContext("drainRememberRevocationDeadLetter()", s.sandbox);
assert.deepStrictEqual(hDels, [["abc123"]], "the drain re-issued exactly the failed targeted HDEL");
assert.strictEqual(vm.runInContext("rememberRevocationDeadLetter.size", s.sandbox), 0, "the queue drained");
assert.strictEqual(vm.runInContext("isRememberLoginRevocationDegraded()", s.sandbox), false);
assert.ok(s.warnings.some((w) => w.includes("[security] Remember-login revocation recovered")), "recovery is logged");
});
// ---------------------------------------------------------------------------
// Behavior pin: BOTH logout paths compute the flag unconditionally
// ---------------------------------------------------------------------------
// Runs the extracted session-path flag computation against the REAL DLQ
// machinery, the REAL single-entry revoke helper AND the REAL lineage revoke
// helper (stubbed Redis plumbing), so the awaited branch's synchronous enqueue
// and the worker-global read are exercised end to end. Conscious update
// (adpanel:remember-logout-lineage): logout's awaited revoke is the
// lineage-scoped helper now, so failures are simulated through the lineage
// helper's bounded EVAL (sendCommandImpl) — the enqueue still runs
// synchronously inside the awaited call, which is what the capture-order pin
// below proves. The snippet ends right after the capture; the appended `}`
// closes the `if (req.session) {` block it cuts open.
function makeLogoutFlagSandbox({ deleteImpl, sendCommandImpl, registry = {} } = {}) {
const warnings = [];
const sandbox = {
console: {
warn: (...args) => warnings.push(args.map(String).join(" ")),
log: () => {},
},
rememberLoginRegistry: registry,
redisClient: { isOpen: true, sendCommand: sendCommandImpl || (async () => ["1"]) },
deleteRememberLoginRegistryFields: deleteImpl,
isValidRememberLoginId: (id) => !!String(id || "").trim() && String(id).length <= 128 && /^[A-Za-z0-9_-]+$/.test(String(id)),
REMEMBER_LOGIN_LINEAGE_SET_REDIS_PREFIX: "adpanel:remember-lineage:",
REMEMBER_LOGIN_LINEAGE_SET_TTL_SECONDS: 31622400,
REMEMBER_LOGIN_LINEAGE_REVOKE_LUA: "-- lua under test --",
getRevokedRememberLoginRedisKey: require("../utils/remember-login-redis").getRevokedRememberLoginRedisKey,
REVOKED_REMEMBER_LOGIN_TTL_SECONDS: require("../utils/remember-login-redis").REVOKED_REMEMBER_LOGIN_TTL_SECONDS,
REMEMBER_LOGIN_REGISTRY_VERSION_REDIS_KEY: "adpanel:remember-logins-version",
REMEMBER_LOGIN_REGISTRY_REDIS_KEY: "adpanel:remember-logins",
getRememberLoginDisplayId: (id) => `saved:${id}`,
ensureRememberLoginRedisReady: async () => true,
withTimeout: sandboxWithTimeout,
REMEMBER_REVOKE_WRITE_TIMEOUT_MS: 40,
REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL: "remember-revoke-write-timeout",
scaleForMemory: (base) => base,
setInterval: () => ({ unref: () => {} }),
};
vm.createContext(sandbox);
vm.runInContext(DLQ_MACHINERY_SOURCE, sandbox, { filename: "logout-flag-dlq.js" });
vm.runInContext(REVOKE_ENTRY_SOURCE, sandbox, { filename: "logout-flag-revoke.js" });
vm.runInContext(LINEAGE_REVOKE_SOURCE, sandbox, { filename: "logout-flag-lineage.js" });
return { sandbox, warnings };
}
async function runLogoutFlagPath(sandbox, req) {
const runner =
"(async (req) => {\n" +
LOGOUT_FLAG_SNIPPET_SOURCE +
"}\n return logoutRevocationDegraded;\n})";
const compute = vm.runInContext(runner, sandbox, { filename: "logout-flag-runner.js" });
return compute(req);
}
test("a session logout without a rememberLoginId still reports the worker-global degraded state", async () => {
// THE regression: with the capture nested inside the rememberLoginId
// branch, a session logout WITHOUT a remember credential answered
// revocationDegraded: false even while this worker's DLQ still held an
// earlier failed revoke — contradicting the comment's worker-global
// semantics and the no-session path's answer.
const noRemember = makeLogoutFlagSandbox({ deleteImpl: async () => true });
vm.runInContext("enqueueRememberRevocationDeadLetter('earlier-id')", noRemember.sandbox);
assert.strictEqual(
await runLogoutFlagPath(noRemember.sandbox, { session: { rememberLoginId: "", sessionID: "sid-1" } }),
true,
"no rememberLoginId + non-empty DLQ must still answer revocationDegraded: true"
);
// The unconditional hoist must preserve the exact semantics the branch
// capture had: a clean revoke on a healthy worker stays false, a this-call
// failure is still seen after the branch (the enqueue is synchronous
// inside the awaited revoke), and an earlier pending failure degrades a
// logout whose own revoke succeeded (worker-global).
const healthy = makeLogoutFlagSandbox({
deleteImpl: async () => true,
registry: { "abc123": { uid: "u1", email: "a@x" } },
});
assert.strictEqual(
await runLogoutFlagPath(healthy.sandbox, { session: { rememberLoginId: "abc123", sessionID: "sid-2" } }),
false,
"a successful revoke on an empty DLQ stays healthy"
);
// Conscious update (adpanel:remember-logout-lineage): the this-call failure
// is simulated through the lineage revoke's bounded EVAL (the awaited call
// logout now makes); the synchronous-enqueue-inside-the-awaited-call
// contract it proves is unchanged.
const thisCallFails = makeLogoutFlagSandbox({
deleteImpl: async () => false,
sendCommandImpl: async () => {
throw new Error("ECONNRESET");
},
registry: { "abc123": { uid: "u1", email: "a@x" } },
});
assert.strictEqual(
await runLogoutFlagPath(thisCallFails.sandbox, { session: { rememberLoginId: "abc123", sessionID: "sid-3" } }),
true,
"a this-call failure is still captured after the branch (synchronous enqueue inside the awaited revoke)"
);
const earlierPending = makeLogoutFlagSandbox({
deleteImpl: async () => true,
registry: { "abc123": { uid: "u1", email: "a@x" } },
});
vm.runInContext("enqueueRememberRevocationDeadLetter('earlier-id')", earlierPending.sandbox);
assert.strictEqual(
await runLogoutFlagPath(earlierPending.sandbox, { session: { rememberLoginId: "abc123", sessionID: "sid-4" } }),
true,
"an earlier pending failure degrades a logout whose own revoke succeeded (worker-global)"
);
});