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,617 @@
|
||||
"use strict";
|
||||
|
||||
// adpanel:session-inventory-error-propagation — Finding 2 (P1): session
|
||||
// inventory failures silently undermined credential-change revocation.
|
||||
//
|
||||
// THE CHAIN (pre-fix): scanActiveBrowserSessionsByIds swallowed per-id store
|
||||
// get errors (catch → null → filtered out); normalizeSessionStoreSession
|
||||
// swallowed JSON parse errors; getCachedActiveBrowserSessions served the STALE
|
||||
// cache when a forced scan failed and the cache was non-empty. Consequence:
|
||||
// destroyBrowserSessionsForUser proceeded on an incomplete or stale inventory
|
||||
// with result.errors === [] while a session of the user stayed alive.
|
||||
//
|
||||
// THE FIX:
|
||||
// (a) scan incompleteness is COUNTED and surfaced — per-id get failures and
|
||||
// unparsable records land in the scan's errors (additive
|
||||
// activeBrowserSessionCache.lastScanIncomplete/.lastScanErrors); the
|
||||
// public array return of getCachedActiveBrowserSessions is unchanged;
|
||||
// (b) destroyBrowserSessionsForUser surfaces incompleteness: descriptive
|
||||
// entries in result.errors, a loud [security] warn, and the additive
|
||||
// result.scanIncomplete flag — while revokeRememberLoginsForUser stays
|
||||
// UNCONDITIONAL and first, and its own Redis failures now thread into
|
||||
// result.errors too;
|
||||
// (c) a FAILED forced scan must NOT silently resolve with stale entries:
|
||||
// force:true REJECTS (destroy's catch records the `scan:` error); the
|
||||
// stale-cache fallback remains for the non-forced READ-ONLY consumer
|
||||
// (the admin browser-login inventory), whose own catch preserves its UX;
|
||||
// (d) one bounded re-scan round when the pre-scan was degraded (the same
|
||||
// bounded-retry pattern as the post-destroy verification loop): a
|
||||
// transient store error must not downgrade the eviction when a single
|
||||
// retry can complete the inventory.
|
||||
//
|
||||
// Pins held here: source pins on the propagation chain + behavior pins on the
|
||||
// vm-extracted REAL scan/scan-cache/destroy chain against scripted session
|
||||
// stores.
|
||||
|
||||
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");
|
||||
|
||||
// Brace-balanced extraction (same shape as tests/remember-rotation-bounded.test.js).
|
||||
function extractBlock(source, startMarker) {
|
||||
const start = source.indexOf(startMarker);
|
||||
assert.ok(start >= 0, `marker not found: ${startMarker}`);
|
||||
let i = start + startMarker.length;
|
||||
let depth;
|
||||
if (startMarker.endsWith("{")) {
|
||||
depth = 1;
|
||||
} else {
|
||||
while (i < source.length && /\s/.test(source[i])) i += 1;
|
||||
assert.ok(i < source.length && source[i] === "{", `no opening brace after: ${startMarker}`);
|
||||
depth = 1;
|
||||
}
|
||||
let inString = null;
|
||||
while (i < source.length && depth > 0) {
|
||||
i += 1;
|
||||
const ch = source[i];
|
||||
if (inString) {
|
||||
if (ch === "\\") { i += 1; continue; }
|
||||
if (ch === inString) inString = null;
|
||||
continue;
|
||||
}
|
||||
if (ch === "/" && source[i + 1] === "/") {
|
||||
while (i < source.length && source[i] !== "\n") i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "/" && source[i + 1] === "*") {
|
||||
i += 2;
|
||||
while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i += 1;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"' || ch === "'" || ch === "`") inString = ch;
|
||||
else if (ch === "{") depth += 1;
|
||||
else if (ch === "}") depth -= 1;
|
||||
}
|
||||
assert.ok(depth === 0, `unbalanced braces after: ${startMarker}`);
|
||||
return source.slice(start, i + 1);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source pins
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("per-id scan failures and corrupt records are counted, not swallowed", () => {
|
||||
const byIds = extractBlock(indexSource, "async function scanActiveBrowserSessionsByIds(sessionIds) {");
|
||||
assert.match(byIds, /const scanErrors = \[\];/, "the scan owns an error sink");
|
||||
assert.match(
|
||||
byIds,
|
||||
/catch \(err\) \{\s*\n\s*scanErrors\.push\(`\$\{getSessionDisplayId\(sid\)\}:\$\{err\?\.message \|\| err\}`\);/,
|
||||
"a per-id get failure must be recorded (display-id scoped), not swallowed"
|
||||
);
|
||||
assert.match(
|
||||
byIds,
|
||||
/return \{ records: sessions\.filter\(Boolean\), errors: scanErrors \};/,
|
||||
"the scan must return its incompleteness alongside the records"
|
||||
);
|
||||
|
||||
const normalize = extractBlock(indexSource, "function normalizeSessionStoreSession(rawSession, onError) {");
|
||||
assert.match(
|
||||
normalize,
|
||||
/if \(typeof onError === "function"\) onError\(err\);/,
|
||||
"a corrupt JSON record must be REPORTED through the error sink"
|
||||
);
|
||||
assert.match(
|
||||
normalize,
|
||||
/if \(rawSession === null \|\| rawSession === undefined\) return null;/,
|
||||
"a null/undefined store record stays a benign skip (the ids-then-get expiry race)"
|
||||
);
|
||||
const entries = extractBlock(indexSource, "function normalizeSessionStoreEntries(rawSessions, scanErrors) {");
|
||||
assert.match(entries, /normalizeSessionStoreSession\(rawSession, \(err\) =>/, "the entry pusher threads the sink with the record's sid");
|
||||
});
|
||||
|
||||
test("the shared scan promise is stored RAW and each caller dispatches the stale fallback on its OWN force flag", () => {
|
||||
// Conscious pin update (adpanel:session-inventory-error-propagation,
|
||||
// WAVE-3 joiner dispatch): the pre-fix shape attached the creator's stale
|
||||
// fallback to the SHARED promise, so a forced caller joining an in-flight
|
||||
// scan started by a non-forced creator inherited the creator's !force
|
||||
// closure and received the stale array instead of a rejection. The
|
||||
// protected invariants are preserved and strengthened: a FAILED forced
|
||||
// scan still REJECTS (stronger — even when the scan was started by someone
|
||||
// else), the stale fallback is still non-forced-only, the completed-scan
|
||||
// incompleteness still lands on the cache record, and the public array
|
||||
// return shape is unchanged.
|
||||
const cached = extractBlock(indexSource, "async function getCachedActiveBrowserSessions({ force = false } = {}) {");
|
||||
assert.match(cached, /const scan = await scanActiveBrowserSessionsFromStore\(\);/, "the shared scan body is preserved");
|
||||
// The completed-scan incompleteness is recorded on the cache record
|
||||
// (additive fields; the public array return is unchanged).
|
||||
assert.match(
|
||||
cached,
|
||||
/activeBrowserSessionCache\.lastScanIncomplete = scan\.errors\.length > 0;/,
|
||||
"the cache record must carry the scan's incompleteness"
|
||||
);
|
||||
assert.match(cached, /activeBrowserSessionCache\.lastScanErrors = scan\.errors;/, "the cache record must carry the scan's error entries");
|
||||
assert.match(cached, /return scan\.records;/, "the public array return shape is unchanged");
|
||||
|
||||
// Joiner dispatch: joiners reuse the in-flight promise; the creator stores
|
||||
// it RAW on the cache — the IIFE settles straight into the exactly-once
|
||||
// clearing .finally with NO caller's catch attached to what joiners
|
||||
// inherit.
|
||||
assert.match(
|
||||
cached,
|
||||
/const sharedScan = activeBrowserSessionCache\.promise \|\|\s*\(activeBrowserSessionCache\.promise = \(async \(\) => \{/,
|
||||
"joiners must reuse the in-flight promise; the creator stores it RAW on the cache"
|
||||
);
|
||||
assert.match(
|
||||
cached,
|
||||
/\}\)\(\)\.finally\(\(\) => \{\s*\n\s*activeBrowserSessionCache\.promise = null;\s*\n\s*\}\)\);/,
|
||||
"the stored promise carries NO catch — the IIFE settles straight into the exactly-once clearing finally"
|
||||
);
|
||||
// The per-caller fallback dispatches on THIS caller's flag.
|
||||
assert.match(
|
||||
cached,
|
||||
/return force \? sharedScan : sharedScan\.catch\(\(err\) => \{/,
|
||||
"the stale fallback must be dispatched on the CALLER's force flag, not the creator's"
|
||||
);
|
||||
const catchIdx = cached.indexOf("sharedScan.catch((err) => {");
|
||||
assert.ok(catchIdx >= 0, "the per-caller fallback keeps its catch");
|
||||
const catchBody = cached.slice(catchIdx, catchIdx + 400);
|
||||
assert.match(
|
||||
catchBody,
|
||||
/activeBrowserSessionCache\.lastScanIncomplete = true;/,
|
||||
"a degraded attempt served stale must be marked on the cache record (Wave-2's alternative, adopted)"
|
||||
);
|
||||
assert.match(catchBody, /if \(activeBrowserSessionCache\.sessions\.size > 0\) \{/, "the stale fallback still requires a non-empty cache");
|
||||
assert.match(
|
||||
catchBody,
|
||||
/throw err;/,
|
||||
"an empty-cache fallback still rejects (forced callers never reach this fallback at all — they get the raw rejection)"
|
||||
);
|
||||
});
|
||||
|
||||
test("destroyBrowserSessionsForUser surfaces incompleteness and keeps the user-wide sweep first", () => {
|
||||
const destroyFn = extractBlock(indexSource, "async function destroyBrowserSessionsForUser(user, options = {}) {");
|
||||
const sweepIdx = destroyFn.indexOf("result.rememberLoginsRevoked = await revokeRememberLoginsForUser(user, {");
|
||||
assert.ok(sweepIdx >= 0, "the user-wide remember sweep is still awaited");
|
||||
assert.ok(sweepIdx < destroyFn.indexOf("getCachedActiveBrowserSessions({ force: true })"),
|
||||
"the user-wide remember sweep stays UNCONDITIONAL and FIRST (before the scan)");
|
||||
assert.match(
|
||||
destroyFn,
|
||||
/onError: \(message\) => result\.errors\.push\(`remember-revoke:\$\{message\}`\)/,
|
||||
"the sweep's own Redis failures thread into result.errors"
|
||||
);
|
||||
assert.match(destroyFn, /scanIncomplete: false,/, "the additive degradation flag exists on the result literal");
|
||||
assert.match(
|
||||
destroyFn,
|
||||
/console\.warn\(`\[security\] Browser-session inventory scan DEGRADED for \$\{stripLogControlChars\(email\)\}/,
|
||||
"a degraded scan warns loudly on the [security] channel"
|
||||
);
|
||||
// (d) one bounded re-scan round before declaring the result.
|
||||
assert.match(destroyFn, /if \(scanDegraded\) \{[\s\S]*?await getCachedActiveBrowserSessions\(\{ force: true \}\);/, "one bounded re-scan round runs when the pre-scan was degraded");
|
||||
assert.match(
|
||||
destroyFn,
|
||||
/if \(rememberLoginId && \(await revokeRememberLoginLineage\(rememberLoginId, \{ emailHint: String\(entry\?\.email \|\| ""\), lineageHint: String\(entry\?\.lineage \|\| ""\)\s*\}\)\)\) \{/,
|
||||
"the per-target remember revocation keeps its existed-based counting (lineage-scoped, with the record's lineage stamp as the hint)"
|
||||
);
|
||||
// The result contract stays additive: the four original fields keep their
|
||||
// shapes.
|
||||
const resultLiteral = destroyFn.slice(destroyFn.indexOf("const result = {"), destroyFn.indexOf("};", destroyFn.indexOf("const result = {")));
|
||||
for (const field of ["destroyed: 0,", "skipped: 0,", "rememberLoginsRevoked: 0,", "errors: [],"]) {
|
||||
assert.ok(resultLiteral.includes(field), `the result literal keeps ${field}`);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Behavior pins — the REAL scan chain against scripted session stores
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Real race semantics (verbatim discipline from tests/remember-revoke-durable.test.js).
|
||||
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 sessionRecord(email, opts = {}) {
|
||||
return {
|
||||
user: email,
|
||||
browserSessionAudit: { email, createdAt: Date.now() - 1000, lastSeenAt: Date.now() - 1000, rememberLoginId: opts.rememberLoginId || "" },
|
||||
__lastAccess: Date.now() - 1000,
|
||||
cookie: { expires: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString() },
|
||||
...(opts.extra || {}),
|
||||
};
|
||||
}
|
||||
|
||||
function buildHarness({ store, sweepImpl, lineageImpl, tombstoneImpl }) {
|
||||
const warnings = [];
|
||||
const destroyCalls = { sweep: [], lineage: [], destroyed: [], order: [] };
|
||||
const activeBrowserSessionCache = { scannedAt: 0, sessions: new Map(), promise: null };
|
||||
|
||||
const sandbox = {
|
||||
console: { log: () => {}, warn: (...a) => warnings.push(a.map(String).join(" ")), error: (...a) => warnings.push(a.map(String).join(" ")) },
|
||||
sessionStore: store,
|
||||
activeBrowserSessionCache,
|
||||
matchesAccountForRevocation: require("../utils/session-account-binding").matchesAccountForRevocation,
|
||||
ACTIVE_BROWSER_SESSION_SCAN_TTL_MS: 15 * 1000,
|
||||
ACTIVE_BROWSER_SESSION_SCAN_CONCURRENCY: 25,
|
||||
// The user-wide sweep stays unconditional and first; a failure threads
|
||||
// through the optional onError sink (the same contract the real helper
|
||||
// exposes — verified against the real helper's signature in the source
|
||||
// pins above).
|
||||
revokeRememberLoginsForUser: async (user, options = {}) => {
|
||||
destroyCalls.order.push("sweep");
|
||||
destroyCalls.sweep.push(options);
|
||||
return sweepImpl ? sweepImpl(user, options) : 2;
|
||||
},
|
||||
revokeRememberLoginLineage: async (rememberId, hints) => {
|
||||
destroyCalls.order.push(`lineage:${rememberId}`);
|
||||
destroyCalls.lineage.push({ rememberId, hints });
|
||||
return lineageImpl ? lineageImpl(rememberId, hints) : false;
|
||||
},
|
||||
writeRevokedSidTombstone: async (sid) => {
|
||||
destroyCalls.order.push(`tombstone:${sid}`);
|
||||
return tombstoneImpl ? tombstoneImpl(sid) : true;
|
||||
},
|
||||
callSessionStore: undefined, // extracted below
|
||||
mapWithConcurrency: undefined,
|
||||
getFileStoreSessionIdFromFilename: undefined,
|
||||
normalizeSessionStoreSession: undefined,
|
||||
normalizeSessionStoreEntries: undefined,
|
||||
buildActiveBrowserSessionRecord: undefined,
|
||||
normalizeBrowserSessionAudit: (raw, fallback = {}) => {
|
||||
const audit = raw && typeof raw === "object" ? raw : {};
|
||||
const lastSeenAt = Number(audit.lastSeenAt || fallback.lastSeenAt || 0) || 0;
|
||||
return {
|
||||
email: String(audit.email || fallback.email || "").trim().toLowerCase(),
|
||||
createdAt: Number(audit.createdAt || fallback.createdAt || 0) || lastSeenAt,
|
||||
lastSeenAt,
|
||||
userAgent: String(audit.userAgent || fallback.userAgent || "").trim().slice(0, 255),
|
||||
firstIp: String(audit.firstIp || fallback.firstIp || "").trim().slice(0, 64),
|
||||
lastIp: String(audit.lastIp || fallback.lastIp || "").trim().slice(0, 64),
|
||||
rememberLoginId: String(audit.rememberLoginId || fallback.rememberLoginId || "").trim(),
|
||||
};
|
||||
},
|
||||
scanActiveBrowserSessionsByIds: undefined,
|
||||
scanActiveBrowserSessionsFromStore: undefined,
|
||||
getCachedActiveBrowserSessions: undefined,
|
||||
removeActiveBrowserSessionCacheEntry: undefined,
|
||||
invalidateActiveBrowserSessionCache: undefined,
|
||||
destroyBrowserSessionsForUser: undefined,
|
||||
getSessionDisplayId: (sid) => `disp:${String(sid || "").slice(0, 6)}`,
|
||||
stripLogControlChars: (value) => String(value || "").replace(/[\x00-\x1f\x7f]/g, ""),
|
||||
};
|
||||
|
||||
vm.createContext(sandbox);
|
||||
const EXTRACTS = [
|
||||
["callSessionStore", "function callSessionStore(methodName, ...args) {"],
|
||||
["mapWithConcurrency", "async function mapWithConcurrency(items, limit, worker) {"],
|
||||
["getFileStoreSessionIdFromFilename", "function getFileStoreSessionIdFromFilename(fileName) {"],
|
||||
["normalizeSessionStoreSession", "function normalizeSessionStoreSession(rawSession, onError) {"],
|
||||
["normalizeSessionStoreEntries", "function normalizeSessionStoreEntries(rawSessions, scanErrors) {"],
|
||||
["buildActiveBrowserSessionRecord", "function buildActiveBrowserSessionRecord(sessionId, sess) {"],
|
||||
["scanActiveBrowserSessionsByIds", "async function scanActiveBrowserSessionsByIds(sessionIds) {"],
|
||||
["scanActiveBrowserSessionsFromStore", "async function scanActiveBrowserSessionsFromStore() {"],
|
||||
["getCachedActiveBrowserSessions", "async function getCachedActiveBrowserSessions({ force = false } = {}) {"],
|
||||
["removeActiveBrowserSessionCacheEntry", "function removeActiveBrowserSessionCacheEntry(sessionId) {"],
|
||||
["invalidateActiveBrowserSessionCache", "function invalidateActiveBrowserSessionCache() {"],
|
||||
["destroyBrowserSessionsForUser", "async function destroyBrowserSessionsForUser(user, options = {}) {"],
|
||||
];
|
||||
for (const [name, marker] of EXTRACTS) {
|
||||
sandbox[name] = vm.runInContext(`(${extractBlock(indexSource, marker)})`, sandbox, { filename: `${name}-sandbox.js` });
|
||||
}
|
||||
return { sandbox, warnings, destroyCalls, activeBrowserSessionCache };
|
||||
}
|
||||
|
||||
const EMAIL = "target@example.test";
|
||||
const USER = { id: 7, email: EMAIL };
|
||||
|
||||
test("browser eviction and post-create legacy cleanup spare a replacement account reusing the same email", async () => {
|
||||
const destroyed = [];
|
||||
const store = {
|
||||
all(callback) {
|
||||
callback(null, {
|
||||
original: sessionRecord(EMAIL, { extra: { accountId: USER.id } }),
|
||||
replacement: sessionRecord(EMAIL, { extra: { accountId: USER.id + 1 } }),
|
||||
legacy: sessionRecord(EMAIL),
|
||||
});
|
||||
},
|
||||
destroy(sessionId, callback) {
|
||||
destroyed.push(sessionId);
|
||||
callback(null);
|
||||
},
|
||||
};
|
||||
|
||||
const { sandbox, destroyCalls } = buildHarness({ store });
|
||||
const result = await sandbox.destroyBrowserSessionsForUser(USER);
|
||||
assert.equal(result.errors.length, 0);
|
||||
assert.equal(result.destroyed, 2);
|
||||
assert.deepEqual(destroyed.sort(), ["legacy", "original"]);
|
||||
|
||||
destroyed.length = 0;
|
||||
const orphanSweep = await sandbox.destroyBrowserSessionsForUser({ email: EMAIL }, { unboundOnly: true });
|
||||
assert.equal(orphanSweep.errors.length, 0);
|
||||
assert.deepEqual(destroyed, ["legacy"]);
|
||||
assert.equal(destroyCalls.sweep[1].unboundOnly, true);
|
||||
});
|
||||
|
||||
test("account-specific socket eviction spares a replacement account reusing the same email", () => {
|
||||
const disconnected = [];
|
||||
const sockets = [USER.id, USER.id + 1, undefined].map((accountId) => ({
|
||||
request: { session: { accountId } },
|
||||
emit() {},
|
||||
disconnect() { disconnected.push(accountId); },
|
||||
}));
|
||||
const activeSocketsByEmail = new Map([[EMAIL, new Set(sockets)]]);
|
||||
const disconnectSource = extractBlock(indexSource, 'function disconnectSocketsForUser(email, reason = "account-suspended", options = {}) {');
|
||||
const disconnect = vm.runInNewContext(`(${disconnectSource})`, {
|
||||
activeSocketsByEmail,
|
||||
matchesAccountForRevocation: require("../utils/session-account-binding").matchesAccountForRevocation,
|
||||
});
|
||||
|
||||
assert.equal(disconnect(EMAIL, "account-deleted", { accountId: USER.id }), 2);
|
||||
assert.deepEqual(disconnected, [USER.id, undefined]);
|
||||
assert.deepEqual(Array.from(activeSocketsByEmail.get(EMAIL)), [sockets[1]]);
|
||||
});
|
||||
|
||||
test("socket access refresh verifies each binding before applying the current account's access", async () => {
|
||||
const current = { ...USER, session_epoch: 11 };
|
||||
const calls = [];
|
||||
const socketFor = (accountId, accountEpoch) => ({
|
||||
request: { session: { accountId, accountEpoch } },
|
||||
disconnect() { calls.push(["disconnect", accountId, accountEpoch]); },
|
||||
async _updateAccessSet(access, admin) { calls.push(["update", accountId, accountEpoch, Array.from(access), admin]); },
|
||||
});
|
||||
const sockets = new Set([
|
||||
socketFor(current.id - 1, current.session_epoch),
|
||||
socketFor(current.id, current.session_epoch - 1),
|
||||
socketFor(current.id, current.session_epoch),
|
||||
]);
|
||||
const activeSocketsByEmail = new Map([[EMAIL, sockets]]);
|
||||
const refreshSource = extractBlock(indexSource, "async function syncSocketAccessForEmail(email) {");
|
||||
const refresh = vm.runInNewContext(`(${refreshSource})`, {
|
||||
activeSocketsByEmail,
|
||||
findUserByEmail: async () => current,
|
||||
getAccessListForEmail: async (email, id) => {
|
||||
assert.equal(email, current.email);
|
||||
assert.equal(id, current.id);
|
||||
sockets.add(socketFor(current.id + 1, current.session_epoch));
|
||||
return ["Example"];
|
||||
},
|
||||
sessionAccountBindingMismatch: require("../utils/session-account-binding").sessionAccountBindingMismatch,
|
||||
});
|
||||
|
||||
await refresh(EMAIL);
|
||||
assert.deepEqual(calls, [
|
||||
["disconnect", current.id - 1, current.session_epoch],
|
||||
["disconnect", current.id, current.session_epoch - 1],
|
||||
["update", current.id, current.session_epoch, ["Example", "example"], false],
|
||||
]);
|
||||
});
|
||||
|
||||
function threeSessionStore({ failingSid, corruptSid, failGetAlways = true }) {
|
||||
const failOnceDone = {};
|
||||
const sessions = {
|
||||
"sid-a": sessionRecord(EMAIL, { rememberLoginId: "remember-a" }),
|
||||
"sid-b": sessionRecord(EMAIL, { rememberLoginId: "remember-b" }),
|
||||
"sid-c": sessionRecord(EMAIL, { rememberLoginId: "remember-c" }),
|
||||
};
|
||||
return {
|
||||
ids: async () => Object.keys(sessions),
|
||||
get: async (sid) => {
|
||||
if (sid === failingSid) {
|
||||
if (failGetAlways) throw new Error("store get failed (transient)");
|
||||
// fail exactly once, then behave (the re-scan recovery scenario) —
|
||||
// a synchronous flip: both scan rounds run inside one destroy call,
|
||||
// before any setImmediate callback could fire
|
||||
if (!failOnceDone[sid]) {
|
||||
failOnceDone[sid] = true;
|
||||
throw new Error("store get failed (transient)");
|
||||
}
|
||||
}
|
||||
// Real stores parse their records on get; only a corrupt/truncated
|
||||
// record surfaces as a raw (unparsable) string.
|
||||
if (sid === corruptSid) return '{"user": "target@example.test", CORRUPT';
|
||||
return sessions[sid] ? sessions[sid] : null;
|
||||
},
|
||||
destroy: async (sid) => {
|
||||
if (!sessions[sid]) throw new Error("ENOENT: no such session");
|
||||
delete sessions[sid];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("a per-id get failure surfaces: result.errors names it, the flag is set, the readable targets are destroyed, the sweep ran first", async () => {
|
||||
const harness = buildHarness({ store: threeSessionStore({ failingSid: "sid-c" }) });
|
||||
const result = await harness.sandbox.destroyBrowserSessionsForUser(USER, {});
|
||||
assert.deepStrictEqual(harness.destroyCalls.order[0], "sweep", "the user-wide remember sweep ran FIRST");
|
||||
assert.strictEqual(result.rememberLoginsRevoked, 2, "the sweep's count contract is preserved");
|
||||
assert.strictEqual(result.destroyed, 2, "only the successfully-read targets are destroyed");
|
||||
assert.strictEqual(result.skipped, 0);
|
||||
assert.strictEqual(result.scanIncomplete, true, "the degraded scan must be surfaced to the caller");
|
||||
assert.ok(
|
||||
result.errors.some((e) => e.startsWith("scan:") && e.includes("disp:sid-c") && e.includes("store get failed")),
|
||||
`result.errors must name the failing store read; got ${JSON.stringify(result.errors)}`
|
||||
);
|
||||
assert.ok(
|
||||
harness.warnings.some((w) => w.includes("[security] Browser-session inventory scan DEGRADED") && w.includes(EMAIL)),
|
||||
"the degraded eviction warns loudly"
|
||||
);
|
||||
// One bounded re-scan round ran (same failure), and the per-target destroy
|
||||
// still ran for the readable targets.
|
||||
assert.deepStrictEqual(
|
||||
harness.destroyCalls.order.filter((e) => e.startsWith("tombstone:")),
|
||||
["tombstone:sid-a", "tombstone:sid-b"],
|
||||
"the readable targets are tombstoned and destroyed"
|
||||
);
|
||||
});
|
||||
|
||||
test("a corrupt JSON record is an inventory failure too (parse errors were silently swallowed)", async () => {
|
||||
const harness = buildHarness({ store: threeSessionStore({ failingSid: "", corruptSid: "sid-b" }) });
|
||||
const result = await harness.sandbox.destroyBrowserSessionsForUser(USER, {});
|
||||
assert.strictEqual(result.scanIncomplete, true, "a corrupt record degrades the scan");
|
||||
assert.ok(
|
||||
result.errors.some((e) => e.startsWith("scan:") && e.includes("disp:sid-b")),
|
||||
`the corrupt record must be named in result.errors; got ${JSON.stringify(result.errors)}`
|
||||
);
|
||||
assert.strictEqual(result.destroyed, 2, "the two parsable targets are still destroyed");
|
||||
});
|
||||
|
||||
test("the one bounded re-scan round recovers a transient failure: the eviction is NOT declared degraded", async () => {
|
||||
const harness = buildHarness({ store: threeSessionStore({ failingSid: "sid-c", failGetAlways: false }) });
|
||||
const result = await harness.sandbox.destroyBrowserSessionsForUser(USER, {});
|
||||
assert.strictEqual(result.scanIncomplete, false, "the retry completed the inventory — no degradation");
|
||||
assert.deepStrictEqual([...result.errors], [], "the first round's transient error entries are cleared (the acted-on inventory is complete)");
|
||||
assert.strictEqual(result.destroyed, 3, "all three targets destroyed");
|
||||
assert.strictEqual(
|
||||
harness.warnings.filter((w) => w.includes("[security] Browser-session inventory scan DEGRADED")).length,
|
||||
0,
|
||||
"no degradation warn on a recovered scan"
|
||||
);
|
||||
});
|
||||
|
||||
test("a full-scan failure with a non-empty stale cache REJECTS on force:true instead of silently serving stale", async () => {
|
||||
const staleRecords = [
|
||||
{ sessionId: "old-1", email: EMAIL, rememberLoginId: "remember-old" },
|
||||
{ sessionId: "old-2", email: "other@example.test", rememberLoginId: "" },
|
||||
];
|
||||
const harness = buildHarness({
|
||||
store: {
|
||||
ids: async () => { throw new Error("ids went away"); },
|
||||
destroy: async () => {},
|
||||
},
|
||||
});
|
||||
// Pre-seed the stale cache (a previous good scan).
|
||||
harness.activeBrowserSessionCache.sessions = new Map(staleRecords.map((r) => [r.sessionId, r]));
|
||||
harness.activeBrowserSessionCache.scannedAt = Date.now();
|
||||
|
||||
// (c) forced readers must get the rejection, not the stale list.
|
||||
await assert.rejects(
|
||||
harness.sandbox.getCachedActiveBrowserSessions({ force: true }),
|
||||
/ids went away/,
|
||||
"a failed forced scan must reject"
|
||||
);
|
||||
// ...and destroy's existing catch records the scan: error (never silent).
|
||||
const result = await harness.sandbox.destroyBrowserSessionsForUser(USER, {});
|
||||
assert.ok(result.errors.some((e) => e.startsWith("scan:") && e.includes("ids went away")), `destroy must record the scan failure; got ${JSON.stringify(result.errors)}`);
|
||||
assert.strictEqual(result.scanIncomplete, true);
|
||||
assert.strictEqual(result.destroyed, 1, "the stale cache still names one target — eviction proceeds best-effort, DEGRADED");
|
||||
assert.ok(harness.warnings.some((w) => w.includes("[security] Browser-session inventory scan DEGRADED")), "the loud degraded warn fired");
|
||||
});
|
||||
|
||||
test("non-forced readers keep their stale-tolerant UX (the admin inventory's read-only fallback)", async () => {
|
||||
const harness = buildHarness({
|
||||
store: { ids: async () => { throw new Error("ids went away"); } },
|
||||
});
|
||||
harness.activeBrowserSessionCache.sessions = new Map([["old-1", { sessionId: "old-1", email: EMAIL }]]);
|
||||
harness.activeBrowserSessionCache.scannedAt = Date.now();
|
||||
const stale = await harness.sandbox.getCachedActiveBrowserSessions({ force: false });
|
||||
assert.deepStrictEqual(
|
||||
[...stale].map((r) => r.sessionId),
|
||||
["old-1"],
|
||||
"a non-forced reader resolves with the stale cache on a failed scan (read-only UX preserved)"
|
||||
);
|
||||
// A forced reader against the SAME failed store still rejects.
|
||||
await assert.rejects(harness.sandbox.getCachedActiveBrowserSessions({ force: true }));
|
||||
});
|
||||
|
||||
test("WAVE-3 joiner dispatch: a forced caller joining a NON-FORCED creator's in-flight failing scan REJECTS (the creator's stale fallback is not inherited)", async () => {
|
||||
// The Wave-2 probe scenario, end to end: expired TTL + a non-forced reader
|
||||
// starting a failing scan + a forced (destructive) caller joining the SAME
|
||||
// in-flight promise. Pre-fix, the joiner inherited the CREATOR's stale
|
||||
// fallback (the catch's !force was closed over the creator's argument) and
|
||||
// destroyBrowserSessionsForUser would proceed on a stale inventory with no
|
||||
// `scan:` error, scanIncomplete:false and no bounded re-scan — eviction
|
||||
// reported complete on stale data. The shared promise is now stored raw
|
||||
// and each caller dispatches on its own flag.
|
||||
let releaseIds;
|
||||
const idsGate = new Promise((resolve) => { releaseIds = resolve; });
|
||||
let idsCalls = 0;
|
||||
const harness = buildHarness({
|
||||
store: {
|
||||
ids: async () => { idsCalls += 1; await idsGate; throw new Error("ids went away"); },
|
||||
destroy: async () => {},
|
||||
},
|
||||
});
|
||||
harness.activeBrowserSessionCache.sessions = new Map([["old-1", { sessionId: "old-1", email: EMAIL, rememberLoginId: "remember-old" }]]);
|
||||
harness.activeBrowserSessionCache.scannedAt = Date.now() - 60 * 1000; // expired TTL
|
||||
|
||||
// The non-forced creator passes the expired-TTL gate and starts the
|
||||
// failing scan (gated in flight).
|
||||
const creatorPromise = harness.sandbox.getCachedActiveBrowserSessions({ force: false });
|
||||
// The forced joiner arrives while the scan is in flight: it must JOIN the
|
||||
// single-flight scan and inherit the REJECTION, never the creator's stale
|
||||
// array.
|
||||
const joinerPromise = harness.sandbox.getCachedActiveBrowserSessions({ force: true });
|
||||
assert.strictEqual(idsCalls, 1, "the forced caller JOINED the in-flight scan (single-flight preserved — no second scan started)");
|
||||
releaseIds(); // let the shared scan fail now
|
||||
|
||||
await assert.rejects(
|
||||
joinerPromise,
|
||||
/ids went away/,
|
||||
"the forced joiner must reject instead of receiving the creator's stale fallback array"
|
||||
);
|
||||
// The creator keeps its own stale-tolerant fallback (dispatched on its own
|
||||
// flag) — the read-only UX is preserved for the caller that asked for it.
|
||||
const stale = await creatorPromise;
|
||||
assert.deepStrictEqual(
|
||||
[...stale].map((r) => r.sessionId),
|
||||
["old-1"],
|
||||
"the non-forced creator still resolves with the stale cache on its own failed scan"
|
||||
);
|
||||
// The degraded attempt is marked on the cache record (Wave-2's
|
||||
// alternative, adopted), and the shared promise cleared exactly once.
|
||||
assert.strictEqual(harness.activeBrowserSessionCache.lastScanIncomplete, true, "the failed attempt is marked on the cache record");
|
||||
assert.strictEqual(harness.activeBrowserSessionCache.promise, null, "the shared promise cleared exactly once after settling");
|
||||
});
|
||||
|
||||
test("the user-wide sweep's own failure threads into result.errors (it used to be warn/DLQ-only)", async () => {
|
||||
const harness = buildHarness({
|
||||
store: threeSessionStore({ failingSid: "" }),
|
||||
sweepImpl: async (user, options) => {
|
||||
if (typeof options?.onError === "function") {
|
||||
options.onError("user-wide remember revocation failed: Redis unavailable");
|
||||
options.onError("cross-worker remember revocation sweep failed: Redis unavailable");
|
||||
}
|
||||
return 2;
|
||||
},
|
||||
});
|
||||
const result = await harness.sandbox.destroyBrowserSessionsForUser(USER, {});
|
||||
assert.strictEqual(result.rememberLoginsRevoked, 2, "the count contract is preserved");
|
||||
assert.ok(
|
||||
result.errors.some((e) => e === "remember-revoke:user-wide remember revocation failed: Redis unavailable") &&
|
||||
result.errors.some((e) => e === "remember-revoke:cross-worker remember revocation sweep failed: Redis unavailable"),
|
||||
`the sweep failures must land in result.errors; got ${JSON.stringify(result.errors)}`
|
||||
);
|
||||
// The sweep failure entries reach the caller even when the scan is complete.
|
||||
assert.strictEqual(result.scanIncomplete, false, "the scan itself was complete");
|
||||
});
|
||||
|
||||
test("per-target eviction revokes the target's lineage (lineage-scoped revoke) and still fails closed on undurable tombstones", async () => {
|
||||
const harness = buildHarness({
|
||||
store: threeSessionStore({ failingSid: "" }),
|
||||
lineageImpl: (rememberId) => (rememberId === "remember-b" ? false : true),
|
||||
tombstoneImpl: (sid) => sid !== "sid-b",
|
||||
});
|
||||
const result = await harness.sandbox.destroyBrowserSessionsForUser(USER, {});
|
||||
const lineageTargets = harness.destroyCalls.lineage.map((c) => c.rememberId).sort();
|
||||
assert.deepStrictEqual(lineageTargets, ["remember-a", "remember-b", "remember-c"], "every target's remember credential goes through the lineage-scoped revoke");
|
||||
assert.ok(harness.destroyCalls.lineage.every((c) => c.hints && typeof c.hints.emailHint === "string" && c.hints.emailHint.includes(EMAIL)),
|
||||
"the lineage revoke receives the target's email hint");
|
||||
assert.strictEqual(result.destroyed, 3, "the destroy still completes (tombstone false does not abort)");
|
||||
assert.ok(
|
||||
result.errors.some((e) => e.includes("disp:sid-b") && e.includes("revoked-sid tombstone not durable")),
|
||||
"an undurable tombstone still surfaces as an eviction error (fail closed for callers)"
|
||||
);
|
||||
assert.strictEqual(result.rememberLoginsRevoked, 4, "the sweep count (2) stays; the per-target existed-count adds only the true revocations (remember-a + remember-c)");
|
||||
});
|
||||
Reference in new issue
Block a user