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,522 @@
|
||||
"use strict";
|
||||
|
||||
// adpanel:remember-revoke-durable — Finding (LOW, confirmed): the opportunistic
|
||||
// revocations rode the fire-and-forget write queue, whose failures are
|
||||
// swallowed into a console.warn. A Redis blip at revocation time (logout,
|
||||
// stale-account teardown, suspension, admin session eviction) therefore left
|
||||
// the 365-day remember credential alive on every OTHER worker of the PM2
|
||||
// cluster while only the local in-memory snapshot dropped it. The fix makes
|
||||
// both revoke helpers AWAIT the targeted Redis HDEL directly (bypassing the
|
||||
// error-swallowing queue like the Confirmed twin does), log a loud [security]
|
||||
// line naming the redacted display id on failure, and NEVER reject — callers
|
||||
// (logout, teardowns, eviction) must still complete when Redis fails. This
|
||||
// file pins that contract: source pins on index.js plus functional pins that
|
||||
// extract the two functions into a vm sandbox with stubbed Redis plumbing.
|
||||
// It also pins the stall half of the same contract: node-redis has no command
|
||||
// timeout, so the awaited delete (its MULTI exec) and the cross-worker sweep
|
||||
// read are TIME-BOUNDED by REMEMBER_REVOKE_WRITE_TIMEOUT_MS — a stalled Redis
|
||||
// must degrade to the false "Redis unavailable" signal within the bound
|
||||
// instead of wedging logout/teardown; a late-completing HDEL is the safe
|
||||
// direction (revocation is an idempotent delete).
|
||||
|
||||
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 { getRevokedRememberLoginRedisKey, REVOKED_REMEMBER_LOGIN_TTL_SECONDS } = require("../utils/remember-login-redis");
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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 so its
|
||||
// Redis failures can be threaded into destructive callers' result.errors.
|
||||
"async function revokeRememberLoginsForUser(user, options = {}) {",
|
||||
"function getRememberLoginRegistryEntry(rememberId)"
|
||||
);
|
||||
|
||||
// The shared targeted-delete helper both revoke helpers (and the sync/expiry
|
||||
// paths) call: the one-true-home of the bounded MULTI exec.
|
||||
const DELETER_SOURCE = extractRegion(
|
||||
indexSource,
|
||||
"async function deleteRememberLoginRegistryFields(fields)",
|
||||
"function queueRememberLoginRedisPersist("
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source pins: the contract is in the text (these are the drift guards)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("revokeRememberLoginRegistryEntry is async, awaits the targeted delete and never queues it", () => {
|
||||
assert.match(
|
||||
REVOKE_ENTRY_SOURCE,
|
||||
/^async function revokeRememberLoginRegistryEntry\(rememberId\) \{/,
|
||||
"the opportunistic revoke must be async (callers await it)"
|
||||
);
|
||||
assert.match(
|
||||
REVOKE_ENTRY_SOURCE,
|
||||
/await deleteRememberLoginRegistryFields\(\[id\]\)/,
|
||||
"the targeted Redis HDEL must be awaited, not queued fire-and-forget"
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
REVOKE_ENTRY_SOURCE,
|
||||
/queueRememberLoginRedisPersist/,
|
||||
"the revoke must bypass the error-swallowing write queue (its return value cannot surface failure)"
|
||||
);
|
||||
const localDeleteIdx = REVOKE_ENTRY_SOURCE.indexOf("if (existed) delete rememberLoginRegistry[id];");
|
||||
const awaitIdx = REVOKE_ENTRY_SOURCE.indexOf("await deleteRememberLoginRegistryFields([id])");
|
||||
assert.ok(localDeleteIdx >= 0 && awaitIdx > localDeleteIdx, "the local snapshot delete must stay synchronous, BEFORE the awaited Redis delete");
|
||||
assert.match(
|
||||
REVOKE_ENTRY_SOURCE,
|
||||
/if \(!redisClient\) \{/,
|
||||
"file-store mode must short-circuit: the local delete IS the durable revocation there"
|
||||
);
|
||||
});
|
||||
|
||||
test("revokeRememberLoginRegistryEntry logs a loud [security] warning on every failure path and never rejects", () => {
|
||||
// False return from the delete helper (Redis unready/unavailable): the id is
|
||||
// dead-lettered for the freshness poller's retry BEFORE the warn
|
||||
// (adpanel:remember-revoke-dead-letter); the loud [security] warn text and
|
||||
// its position as the failure branch's visible signal are unchanged.
|
||||
assert.match(
|
||||
REVOKE_ENTRY_SOURCE,
|
||||
/if \(!deleted\) \{\s*\n\s*enqueueRememberRevocationDeadLetter\(id\);\s*\n\s*console\.warn\(`\[security\] Remember-login revocation FAILED for \$\{getRememberLoginDisplayId\(id\)\}/,
|
||||
"a false result from the Redis delete must dead-letter the id, then log the loud [security] warning naming the redacted display id"
|
||||
);
|
||||
// Thrown error from the delete helper:
|
||||
assert.match(
|
||||
REVOKE_ENTRY_SOURCE,
|
||||
/catch \(err\) \{\s*\n\s*\/\/[^\n]*\n\s*\/\/[^\n]*\n\s*enqueueRememberRevocationDeadLetter\(id\);\s*\n\s*console\.warn\(`\[security\] Remember-login revocation FAILED for \$\{getRememberLoginDisplayId\(id\)\}/,
|
||||
"a thrown Redis error must dead-letter the id, then log the same loud [security] warning"
|
||||
);
|
||||
assert.match(
|
||||
REVOKE_ENTRY_SOURCE,
|
||||
/return existed;\s*\n\s*\}\s*\n\s*if \(!deleted\) \{/,
|
||||
"the caught-error path must return the existed boolean, not propagate the rejection"
|
||||
);
|
||||
});
|
||||
|
||||
test("revokeRememberLoginsForUser gets the same durable treatment", () => {
|
||||
// Conscious regex update (adpanel:session-inventory-error-propagation): the
|
||||
// signature gained the optional additive `options` sink (onError); the
|
||||
// awaited/never-rejects/count contracts pinned below are unchanged.
|
||||
assert.match(
|
||||
REVOKE_FOR_USER_SOURCE,
|
||||
/^async function revokeRememberLoginsForUser\(user, options = \{\}\) \{/,
|
||||
"the user-wide revoke must be async (callers await it)"
|
||||
);
|
||||
assert.match(
|
||||
REVOKE_FOR_USER_SOURCE,
|
||||
/await deleteRememberLoginRegistryFields\(revokedIds\)/,
|
||||
"the known-id batch delete must be awaited"
|
||||
);
|
||||
assert.match(
|
||||
REVOKE_FOR_USER_SOURCE,
|
||||
/await sweepStaleForUser\(\)/,
|
||||
"the cross-worker hash sweep must be awaited"
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
REVOKE_FOR_USER_SOURCE,
|
||||
/queueRememberLoginRedisPersist/,
|
||||
"the user-wide revoke must bypass the error-swallowing write queue"
|
||||
);
|
||||
assert.match(
|
||||
REVOKE_FOR_USER_SOURCE,
|
||||
/\[security\] User-wide remember-login revocation FAILED/,
|
||||
"both delete failures must log a loud [security] warning"
|
||||
);
|
||||
assert.match(
|
||||
REVOKE_FOR_USER_SOURCE,
|
||||
/return revoked;/,
|
||||
"the count contract (destroyBrowserSessionsForUser's rememberLoginsRevoked) must survive"
|
||||
);
|
||||
});
|
||||
|
||||
// adpanel:remember-revoke-durable — the stall half of the contract: node-redis
|
||||
// has no command timeout, so the awaited Redis steps must be explicitly
|
||||
// bounded or a stalled Redis wedges logout/teardown past any limit (the repo
|
||||
// documents exactly this for the sid tombstone write and bounds it at 1s).
|
||||
test("the revocation Redis steps are time-bounded: timeout degrades to the false signal, genuine errors still throw", () => {
|
||||
assert.match(
|
||||
indexSource,
|
||||
/const REMEMBER_REVOKE_WRITE_TIMEOUT_MS = Math\.max\(/,
|
||||
"the remember revoke bound must be a named constant (own env knob, same 1s discipline as the tombstone write)"
|
||||
);
|
||||
assert.match(
|
||||
DELETER_SOURCE,
|
||||
/await withTimeout\(\s*\n\s*multi\.exec\(\),\s*\n\s*REMEMBER_REVOKE_WRITE_TIMEOUT_MS,/,
|
||||
"the shared delete helper must bound its MULTI exec — an unbounded await hangs the caller for as long as the stall lasts"
|
||||
);
|
||||
assert.match(
|
||||
DELETER_SOURCE,
|
||||
/if \(err\?\.message !== REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL\) throw err;\s*\n\s*return false;/,
|
||||
"on timeout the delete must return false (the established Redis-unavailable signal); non-timeout errors must keep propagating to the caller's catch"
|
||||
);
|
||||
assert.match(
|
||||
REVOKE_FOR_USER_SOURCE,
|
||||
/await withTimeout\(\s*\n\s*redisClient\.hGetAll\(REMEMBER_LOGIN_REGISTRY_REDIS_KEY\),\s*\n\s*REMEMBER_REVOKE_WRITE_TIMEOUT_MS,/,
|
||||
"the cross-worker sweep's hash read must share the same bound — its timeout rejection flows into the existing sweepErrored handling"
|
||||
);
|
||||
});
|
||||
|
||||
test("every revocation call site awaits the helpers; logout/teardown callers never reject", () => {
|
||||
const count = (str) => indexSource.split(str).length - 1;
|
||||
// Conscious count update (adpanel:remember-logout-lineage, WAVE-3): the
|
||||
// logout and bulk-eviction upgrades are joined by the four SESSION-BOUND
|
||||
// single-id sites — remember middleware restore-failure hygiene,
|
||||
// stale-account teardown, the suspension middleware branch, and the
|
||||
// status-page pre-sweep revoke — each of which can present a
|
||||
// pre-rotation identifier while a rotation commits (suspension of a
|
||||
// compromised account is exactly where that milliseconds rotate-race
|
||||
// window is least acceptable). All six opportunistic sites now go through
|
||||
// the lineage-scoped revoke (pinned in
|
||||
// tests/remember-logout-lineage.test.js), which degrades to exactly the
|
||||
// single-id reach when no live entry/lineage stamp names a chain — never
|
||||
// worse than the twin it replaced. The awaited never-rejects contract is
|
||||
// the helper's own, so every caller keeps its await/guard posture; the
|
||||
// protected invariant "every revocation call site awaits the helpers" is
|
||||
// preserved (strengthened: the six sites now also close the rotate race).
|
||||
assert.strictEqual(
|
||||
count("await revokeRememberLoginRegistryEntry("),
|
||||
0,
|
||||
"no opportunistic call site may keep the exact single-id revoke — every session-bound site is lineage-scoped"
|
||||
);
|
||||
assert.strictEqual(
|
||||
count("await revokeRememberLoginLineage("),
|
||||
6,
|
||||
"logout, bulk eviction and the four session-bound sites must await the lineage-scoped revoke"
|
||||
);
|
||||
assert.strictEqual(
|
||||
count("await revokeRememberLoginsForUser("),
|
||||
7,
|
||||
"all seven user-wide call sites must await the (now async) revoke"
|
||||
);
|
||||
// Conscious regex update (adpanel:remember-logout-lineage): same
|
||||
// existed-based counting contract, now through the lineage helper. Second
|
||||
// conscious update (same topic): the call now passes the cache record's
|
||||
// lineage stamp as lineageHint so a MID-CHAIN rotated-away id still names
|
||||
// its chain's set — the existed-based counting contract is unchanged.
|
||||
assert.match(
|
||||
indexSource,
|
||||
/if \(rememberLoginId && \(await revokeRememberLoginLineage\(rememberLoginId, \{ emailHint: String\(entry\?\.email \|\| ""\), lineageHint: String\(entry\?\.lineage \|\| ""\)\s*\}\)\)\) \{\s*\n\s*result\.rememberLoginsRevoked \+= 1;/,
|
||||
"the admin eviction call site must keep its existed-based counting contract"
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Functional pins: the extracted functions run against stubbed Redis plumbing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Same race the index.js helper implements (copied verbatim): the extracted
|
||||
// regions call withTimeout, so the sandbox must provide the REAL semantics,
|
||||
// not a passthrough, or the stall pins below would prove nothing.
|
||||
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 makeSandbox({ redisClient, deleteImpl, registry, withTimeout = sandboxWithTimeout, 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,
|
||||
// adpanel:remember-revoke-dead-letter — the extracted failure paths now
|
||||
// also enqueue the failed ids for the freshness poller's retry; the
|
||||
// sandbox records the calls so the contract pins below keep proving the
|
||||
// warn/return behavior (full dead-letter behavior is pinned in
|
||||
// remember-revoke-dead-letter.test.js).
|
||||
enqueueRememberRevocationDeadLetter: (ids) => {
|
||||
for (const id of Array.isArray(ids) ? ids : [ids]) sandbox.__deadLettered.push(String(id));
|
||||
},
|
||||
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,
|
||||
REMEMBER_REVOKE_WRITE_TIMEOUT_MS: timeoutMs,
|
||||
REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL: "remember-revoke-write-timeout",
|
||||
// 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: [],
|
||||
__deadLettered: [],
|
||||
};
|
||||
vm.createContext(sandbox);
|
||||
return { sandbox, warnings };
|
||||
}
|
||||
|
||||
test("on success the entry is removed from the snapshot, the delete is awaited and existed is returned", async () => {
|
||||
const registry = { "abc123": { uid: "u1", email: "a@x" } };
|
||||
const deletes = [];
|
||||
const { sandbox } = makeSandbox({
|
||||
registry,
|
||||
// Copy ids into a host-realm array: arguments arriving from the vm sandbox
|
||||
// carry that realm's Array prototype, which breaks deepStrictEqual.
|
||||
deleteImpl: async (ids) => {
|
||||
deletes.push(Array.from(ids));
|
||||
return true;
|
||||
},
|
||||
});
|
||||
vm.runInContext(REVOKE_ENTRY_SOURCE, sandbox, { filename: "revoke-entry-sandbox.js" });
|
||||
|
||||
const result = await sandbox.revokeRememberLoginRegistryEntry("abc123");
|
||||
assert.strictEqual(result, true, "existed must still be returned for the eviction call site's counting");
|
||||
assert.deepStrictEqual(deletes, [["abc123"]], "the targeted HDEL must be awaited with exactly the revoked id");
|
||||
assert.ok(!("abc123" in registry), "the local snapshot entry must be deleted synchronously");
|
||||
});
|
||||
|
||||
test("on Redis failure the loud [security] log fires and the promise still resolves (callers never reject)", async () => {
|
||||
// Failure mode 1: the delete helper reports false (Redis unready).
|
||||
const registry1 = { "abc123": { uid: "u1", email: "a@x" } };
|
||||
const s1 = makeSandbox({ 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 must have applied regardless of Redis");
|
||||
assert.strictEqual(
|
||||
s1.warnings.filter((w) => w.includes("[security] Remember-login revocation FAILED") && w.includes("saved:abc123")).length,
|
||||
1,
|
||||
"exactly one loud [security] warning naming the display id"
|
||||
);
|
||||
|
||||
// Failure mode 2: the delete helper throws (Redis error).
|
||||
const registry2 = { "abc123": { uid: "u1", email: "a@x" } };
|
||||
const s2 = makeSandbox({
|
||||
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.ok(s2.warnings.some((w) => w.includes("[security] Remember-login revocation FAILED") && w.includes("ECONNRESET")), "the thrown error's message must surface in the loud warning");
|
||||
|
||||
// File-store mode: no Redis client — the local delete IS the durable
|
||||
// revocation, so no [security] alarm and no Redis call.
|
||||
const registry3 = { "abc123": { uid: "u1", email: "a@x" } };
|
||||
const s3 = makeSandbox({
|
||||
registry: registry3,
|
||||
redisClient: null,
|
||||
deleteImpl: async () => {
|
||||
throw new Error("delete must not be called in file-store mode");
|
||||
},
|
||||
});
|
||||
vm.runInContext(REVOKE_ENTRY_SOURCE, s3.sandbox, { filename: "revoke-entry-sandbox.js" });
|
||||
const r3 = await s3.sandbox.revokeRememberLoginRegistryEntry("abc123");
|
||||
assert.strictEqual(r3, true);
|
||||
assert.ok(!("abc123" in registry3));
|
||||
assert.strictEqual(s3.warnings.filter((w) => w.includes("[security]")).length, 0, "file-store mode must not raise false [security] alarms");
|
||||
|
||||
// The targeted HDEL is issued even when this worker's snapshot does not
|
||||
// contain the entry (cluster topology: Redis is authoritative for existence).
|
||||
const deletes4 = [];
|
||||
const s4 = makeSandbox({ registry: {}, deleteImpl: async (ids) => (deletes4.push(Array.from(ids)), true) });
|
||||
vm.runInContext(REVOKE_ENTRY_SOURCE, s4.sandbox, { filename: "revoke-entry-sandbox.js" });
|
||||
const r4 = await s4.sandbox.revokeRememberLoginRegistryEntry("remote-only");
|
||||
assert.strictEqual(r4, false, "existed must be false when the entry was not in local memory");
|
||||
assert.deepStrictEqual(deletes4, [["remote-only"]], "the HDEL must still target the field — the entry can exist in Redis while local memory is stale");
|
||||
});
|
||||
|
||||
test("user-wide revoke: awaited batch delete plus cross-worker sweep; failures warn loudly and still resolve", async () => {
|
||||
const registry = {
|
||||
"id-a": { uid: "u1", email: "a@x" },
|
||||
"id-b": { uid: "u1", email: "A@X" },
|
||||
"id-other": { uid: "u2", email: "b@x" },
|
||||
"id-replacement": { uid: "u3", email: "a@x" },
|
||||
};
|
||||
const deletes = [];
|
||||
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" }),
|
||||
"id-remote-replacement": JSON.stringify({ uid: "u3", email: "a@x" }),
|
||||
}),
|
||||
};
|
||||
const { sandbox, warnings } = makeSandbox({
|
||||
registry,
|
||||
redisClient,
|
||||
deleteImpl: async (ids) => {
|
||||
deletes.push(Array.from(ids));
|
||||
return true;
|
||||
},
|
||||
});
|
||||
vm.runInContext(REVOKE_FOR_USER_SOURCE, sandbox, { filename: "revoke-user-sandbox.js" });
|
||||
|
||||
const revoked = await sandbox.revokeRememberLoginsForUser({ id: "u1", email: "a@x" });
|
||||
assert.strictEqual(revoked, 2, "the locally-known count contract must survive");
|
||||
assert.strictEqual(deletes.length, 2, "exactly two awaited delete calls: the known-id batch and the sweep");
|
||||
assert.deepStrictEqual(deletes[0], ["id-a", "id-b"], "the known-id batch must be deleted in one awaited call");
|
||||
assert.deepStrictEqual(Object.keys(registry).sort(), ["id-other", "id-replacement"], "a replacement account's local entries must survive email reuse");
|
||||
assert.deepStrictEqual(deletes[1], ["id-a", "id-remote"], "the awaited sweep must delete cross-worker entries invisible to local memory");
|
||||
assert.deepStrictEqual(sandbox.__legacyCutoffs, ["u1"], "the legacy cutoff must still be recorded");
|
||||
assert.strictEqual(warnings.filter((w) => w.includes("[security]")).length, 0, "success must not warn");
|
||||
|
||||
// Failure: every Redis step failing must warn loudly and still resolve.
|
||||
const failingClient = { isOpen: false, hGetAll: async () => { throw new Error("blip"); } };
|
||||
const registry2 = { "id-a": { uid: "u1", email: "a@x" } };
|
||||
const s2 = makeSandbox({
|
||||
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, "the count must be returned even when Redis fails");
|
||||
assert.ok(!("id-a" in registry2), "the local deletes still applied");
|
||||
// Common prefix covers both the "revocation FAILED" and "revocation sweep
|
||||
// FAILED" message variants.
|
||||
const securityWarns = s2.warnings.filter((w) => w.includes("[security] User-wide remember-login revocation"));
|
||||
assert.ok(securityWarns.length >= 2, "both the known-id delete and the sweep must log their failure loudly");
|
||||
assert.ok(s2.warnings.some((w) => w.includes("a@x")), "the warning names the revoked account");
|
||||
});
|
||||
|
||||
test("post-create saved-login cleanup removes only unbound entries from memory and Redis", async () => {
|
||||
const registry = { legacy: { email: "a@x" }, fresh: { uid: "u2", email: "a@x" } };
|
||||
const remote = { ...registry, remoteLegacy: { email: "A@X" } };
|
||||
const deletes = [];
|
||||
const { sandbox } = makeSandbox({
|
||||
registry,
|
||||
redisClient: { isOpen: true, hGetAll: async () => Object.fromEntries(Object.entries(remote).map(([id, entry]) => [id, JSON.stringify(entry)])) },
|
||||
deleteImpl: async (ids) => (deletes.push(Array.from(ids)), true),
|
||||
});
|
||||
vm.runInContext(REVOKE_FOR_USER_SOURCE, sandbox, { filename: "revoke-user-sandbox.js" });
|
||||
|
||||
assert.equal(await sandbox.revokeRememberLoginsForUser({ email: "a@x" }, { unboundOnly: true }), 1);
|
||||
assert.deepEqual(Object.keys(registry), ["fresh"]);
|
||||
assert.deepEqual(deletes, [["legacy"], ["legacy", "remoteLegacy"]]);
|
||||
});
|
||||
|
||||
// Functional pin for the stall half: the shared delete helper runs against a
|
||||
// never-settling MULTI exec (the exact shape of a stalled Redis, which
|
||||
// buffers commands instead of erroring) and must resolve false within the
|
||||
// bound instead of hanging the caller.
|
||||
function makeDeleterSandbox({ execImpl, redisReady = true, timeoutMs = 40 }) {
|
||||
const warnings = [];
|
||||
const hDels = [];
|
||||
let multiStub;
|
||||
multiStub = {
|
||||
set: () => multiStub,
|
||||
hDel: (key, id) => {
|
||||
hDels.push([String(key), String(id)]);
|
||||
return multiStub;
|
||||
},
|
||||
incr: () => multiStub,
|
||||
exec: execImpl,
|
||||
};
|
||||
const sandbox = {
|
||||
console: {
|
||||
warn: (...args) => warnings.push(args.map(String).join(" ")),
|
||||
log: () => {},
|
||||
},
|
||||
redisClient: { multi: () => multiStub },
|
||||
getRevokedRememberLoginRedisKey,
|
||||
REVOKED_REMEMBER_LOGIN_TTL_SECONDS,
|
||||
ensureRememberLoginRedisReady: async () => redisReady,
|
||||
withTimeout: sandboxWithTimeout,
|
||||
REMEMBER_REVOKE_WRITE_TIMEOUT_MS: timeoutMs,
|
||||
REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL: "remember-revoke-write-timeout",
|
||||
REMEMBER_LOGIN_REGISTRY_REDIS_KEY: "adpanel:remember-logins",
|
||||
REMEMBER_LOGIN_REGISTRY_VERSION_REDIS_KEY: "adpanel:remember-logins-version",
|
||||
};
|
||||
vm.createContext(sandbox);
|
||||
return { sandbox, warnings, hDels };
|
||||
}
|
||||
|
||||
test("deleteRememberLoginRegistryFields: a stalled Redis times out into the false signal within the bound", async () => {
|
||||
const { sandbox, hDels } = makeDeleterSandbox({
|
||||
execImpl: () => new Promise(() => {}), // stalled Redis: the exec never settles
|
||||
});
|
||||
vm.runInContext(DELETER_SOURCE, sandbox, { filename: "remember-deleter-sandbox.js" });
|
||||
|
||||
const started = Date.now();
|
||||
const result = await sandbox.deleteRememberLoginRegistryFields(["id-1", "id-2"]);
|
||||
const elapsed = Date.now() - started;
|
||||
assert.strictEqual(result, false, "the timeout must convert to the established Redis-unavailable false signal");
|
||||
assert.ok(elapsed < 2000, `the await must resolve within the bound (took ${elapsed}ms) — logout must not wedge`);
|
||||
assert.strictEqual(hDels.length, 2, "both targeted HDELs were queued before the stall");
|
||||
|
||||
// Genuine (non-timeout) Redis errors keep their existing semantics: they
|
||||
// propagate to the caller's catch instead of masquerading as "unavailable".
|
||||
const failing = makeDeleterSandbox({
|
||||
execImpl: () => Promise.reject(new Error("ECONNRESET")),
|
||||
});
|
||||
vm.runInContext(DELETER_SOURCE, failing.sandbox, { filename: "remember-deleter-sandbox.js" });
|
||||
await assert.rejects(
|
||||
failing.sandbox.deleteRememberLoginRegistryFields(["id-1"]),
|
||||
/ECONNRESET/,
|
||||
"non-timeout errors must still throw (callers distinguish errored vs unavailable)"
|
||||
);
|
||||
|
||||
// Success path unchanged: an exec that settles within the bound returns true.
|
||||
const ok = makeDeleterSandbox({ execImpl: () => Promise.resolve([1, 1]) });
|
||||
vm.runInContext(DELETER_SOURCE, ok.sandbox, { filename: "remember-deleter-sandbox.js" });
|
||||
assert.strictEqual(await ok.sandbox.deleteRememberLoginRegistryFields(["id-1"]), true);
|
||||
});
|
||||
|
||||
test("user-wide revoke: a stalled sweep read times out into the existing sweepErrored path and still resolves", async () => {
|
||||
const registry = { "id-a": { uid: "u1", email: "a@x" } };
|
||||
const deletes = [];
|
||||
const stalledClient = {
|
||||
isOpen: true,
|
||||
hGetAll: () => new Promise(() => {}), // stalled Redis: the sweep read never settles
|
||||
};
|
||||
const { sandbox, warnings } = makeSandbox({
|
||||
registry,
|
||||
redisClient: stalledClient,
|
||||
deleteImpl: async (ids) => {
|
||||
deletes.push(Array.from(ids));
|
||||
return true;
|
||||
},
|
||||
});
|
||||
vm.runInContext(REVOKE_FOR_USER_SOURCE, sandbox, { filename: "revoke-user-sandbox.js" });
|
||||
|
||||
const started = Date.now();
|
||||
const revoked = await sandbox.revokeRememberLoginsForUser({ id: "u1", email: "a@x" });
|
||||
const elapsed = Date.now() - started;
|
||||
assert.strictEqual(revoked, 1, "the count contract survives the sweep stall");
|
||||
assert.strictEqual(deletes.length, 1, "the known-id batch delete still ran before the sweep stalled");
|
||||
assert.ok(elapsed < 2000, `the user-wide revoke must not wedge past the sweep bound (took ${elapsed}ms)`);
|
||||
assert.strictEqual(
|
||||
warnings.filter((w) => w.includes("[security] User-wide remember-login revocation sweep FAILED")).length,
|
||||
1,
|
||||
"exactly one loud sweep-failure warn: the timeout routes into the existing sweepErrored path"
|
||||
);
|
||||
assert.ok(warnings.some((w) => w.includes("remember-revoke-sweep-timeout")), "the timeout label surfaces in the warn");
|
||||
assert.ok(!warnings.some((w) => w.includes("Redis unavailable")), "the sweepErrored branch must suppress the redundant unavailable warn");
|
||||
assert.deepStrictEqual(sandbox.__legacyCutoffs, ["u1"], "teardown still completes: the legacy cutoff is recorded after the stall");
|
||||
});
|
||||
Reference in new issue
Block a user