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,556 @@
|
||||
"use strict";
|
||||
|
||||
// Regression tests for three fixes, pinned with source assertions (index.js
|
||||
// boots servers on require, so route/module behavior is locked by reading the
|
||||
// source as text — same technique as the other audit tests).
|
||||
//
|
||||
// Issue 4 (LOW): on the session revoke route, a session-type target whose
|
||||
// live session record vanished after listing (stale cache) fell into the
|
||||
// dead-session → saved-login fallback with an EMPTY target email hint, so it
|
||||
// classified "self" and a grace grant could ride the fallback into
|
||||
// revokeRememberedTarget against a peer admin's saved login. The fix derives
|
||||
// the hint from the remember-login registry (the surviving owner record)
|
||||
// BEFORE the tri-state classification, and adds a defensive second layer: the
|
||||
// fallback re-derives the remembered target's owner classification and aborts
|
||||
// fail-closed when a peer-admin (or unknown) target would ride a grace grant.
|
||||
//
|
||||
// Issue 5 (LOW): the remember-me hard expiry was effectively infinite for
|
||||
// active users — failing the 6h validation half alone re-issued the token
|
||||
// with a fresh 365-day expiry and the SAME jti. The fix (a) anchors the
|
||||
// 365-day hard expiry to ORIGINAL issuance (registry field absoluteExpiresAt;
|
||||
// silent re-issues are capped at the anchor's remaining lifetime, the
|
||||
// re-issued cookie's maxAge dies with the token, an expired anchor refuses
|
||||
// the silent re-issue, and pre-anchor entries backfill from their own exp)
|
||||
// and (b) rotates the identifier on every silent re-issue with a
|
||||
// compare-and-swap registry swap (HSET new + HDEL old + version bump in one
|
||||
// Lua script, gated on the presented entry still existing with the same
|
||||
// owner), so two tabs converging on one cookie jar end up with EXACTLY ONE
|
||||
// valid identifier and the drift loser fails closed to full password re-auth.
|
||||
//
|
||||
// Issue 6 (LOW): the one-time revoke token was resurrectable — consumption
|
||||
// deleted the in-memory session entry, but persistence rode the
|
||||
// end-of-request save, so an in-flight request holding the pre-consumption
|
||||
// snapshot re-saved the consumed token. The fix records consumption durably
|
||||
// OUTSIDE the session snapshot (Redis SET NX EX with a TTL exceeding the
|
||||
// token's own TTL, keyed per admin session like the mint map) with the
|
||||
// check-and-mark being one atomic operation; an already-marked or unmarkable
|
||||
// token is treated as consumed (fail closed), while the in-memory delete is
|
||||
// kept.
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const INDEX_JS = path.join(ROOT, "index.js");
|
||||
|
||||
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
||||
|
||||
function countOccurrences(haystack, needle) {
|
||||
return haystack.split(needle).length - 1;
|
||||
}
|
||||
|
||||
function sliceBetween(source, startMarker, endMarker) {
|
||||
const start = source.indexOf(startMarker);
|
||||
assert.ok(start >= 0, `start marker not found: ${startMarker}`);
|
||||
const end = source.indexOf(endMarker, start + startMarker.length);
|
||||
assert.ok(end > start, `end marker not found after start: ${endMarker}`);
|
||||
return source.slice(start, end);
|
||||
}
|
||||
|
||||
const REVOKE_ROUTE = sliceBetween(
|
||||
indexSource,
|
||||
'app.post("/api/settings/sessions/revoke"',
|
||||
"const PANEL_INFO_FILE"
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Issue 4 — dead-session → remembered fallback classifies the peer admin
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("dead-session targets derive the peer-admin hint from the remember registry before classification", () => {
|
||||
const hintBlock = sliceBetween(
|
||||
REVOKE_ROUTE,
|
||||
'let targetEmailHint = "";',
|
||||
"// Peer-admin protection:"
|
||||
);
|
||||
|
||||
const liveHintIdx = hintBlock.indexOf("} else if (targetSession && targetSession.user) {");
|
||||
const fallbackHintIdx = hintBlock.indexOf("} else if (rememberLoginId) {");
|
||||
assert.ok(liveHintIdx >= 0, "the live-session hint branch must remain");
|
||||
assert.ok(fallbackHintIdx > liveHintIdx, "the dead-session fallback hint branch must follow the live one");
|
||||
assert.ok(
|
||||
hintBlock.includes("getRememberLoginRegistryEntry(rememberLoginId)"),
|
||||
"the fallback hint must come from the remember-login registry entry bound to the token"
|
||||
);
|
||||
assert.ok(
|
||||
hintBlock.includes("findRememberLoginIdBySessionId(sessionId)"),
|
||||
"the fallback hint must also resolve the saved login by the dead session's id"
|
||||
);
|
||||
assert.ok(
|
||||
hintBlock.indexOf("targetEmailHint = String(fallbackHintEntry.email") > fallbackHintIdx,
|
||||
"the fallback branch must set the target email hint from the registry owner"
|
||||
);
|
||||
|
||||
// The enriched hint must exist BEFORE the tri-state classification so the
|
||||
// existing fail-closed discipline covers dead-session targets.
|
||||
const classificationIdx = REVOKE_ROUTE.indexOf('let targetClassification = "self";');
|
||||
const hintIdx = REVOKE_ROUTE.indexOf('let targetEmailHint = "";');
|
||||
assert.ok(classificationIdx > hintIdx, "hint derivation must precede the tri-state classification");
|
||||
});
|
||||
|
||||
test("the fallback re-classifies the remembered target and never rides a grace grant for a peer admin", () => {
|
||||
const guard = sliceBetween(
|
||||
REVOKE_ROUTE,
|
||||
"const graceState = targetIsOtherAdmin",
|
||||
"const revokeRememberedTarget = async"
|
||||
);
|
||||
|
||||
assert.ok(
|
||||
guard.includes("const ensureRememberedTargetNotRidingGrace = async (targetRememberLoginId) => {"),
|
||||
"the defensive fallback guard must exist"
|
||||
);
|
||||
assert.ok(
|
||||
guard.includes("if (!graceState) return { ok: true };"),
|
||||
"the guard only arbitrates requests that are actually riding a grace grant"
|
||||
);
|
||||
assert.ok(
|
||||
guard.includes('ownerClassification = "unknown";'),
|
||||
"the fallback re-classification must be a tri-state that starts unknown for differing owners"
|
||||
);
|
||||
assert.ok(
|
||||
guard.includes('ownerClassification = ownerUser && ownerUser.admin ? "admin" : "user";'),
|
||||
"only a successful owner lookup may classify admin/user"
|
||||
);
|
||||
assert.ok(
|
||||
guard.includes('const ownerIsOtherAdmin = ownerClassification === "admin" || ownerClassification === "unknown";'),
|
||||
"an unknown owner must be handled exactly like a peer admin"
|
||||
);
|
||||
const catchBody = sliceBetween(guard, "catch (lookupErr) {", "}");
|
||||
assert.ok(
|
||||
!catchBody.includes("ownerClassification"),
|
||||
"the lookup catch must not weaken the owner classification"
|
||||
);
|
||||
assert.ok(
|
||||
guard.includes('code: "peer-admin-revoke-forbidden"'),
|
||||
"a peer-admin fallback under grace must abort with a clear error"
|
||||
);
|
||||
|
||||
// Both fallback dispatch sites (direct remembered target and the
|
||||
// dead-session → remembered fallback) must consult the guard first.
|
||||
const revokeCall = "return revokeRememberedTarget(rememberLoginId, sessionId);";
|
||||
assert.equal(countOccurrences(REVOKE_ROUTE, revokeCall), 2, "both fallback branches must be preserved");
|
||||
|
||||
const guardDefIdx = REVOKE_ROUTE.indexOf("const ensureRememberedTargetNotRidingGrace = async");
|
||||
const guard1Idx = REVOKE_ROUTE.indexOf("const rememberedGuard = await ensureRememberedTargetNotRidingGrace(rememberLoginId);");
|
||||
const call1Idx = REVOKE_ROUTE.indexOf(revokeCall);
|
||||
const guard2Idx = REVOKE_ROUTE.indexOf("const fallbackGuard = await ensureRememberedTargetNotRidingGrace(rememberLoginId);");
|
||||
const call2Idx = REVOKE_ROUTE.indexOf(revokeCall, call1Idx + revokeCall.length);
|
||||
assert.ok(guardDefIdx >= 0 && guard1Idx > guardDefIdx && call1Idx > guard1Idx, "the remembered branch must guard before revoking");
|
||||
assert.ok(guard2Idx > call1Idx && call2Idx > guard2Idx, "the dead-session fallback must guard before revoking");
|
||||
assert.ok(
|
||||
REVOKE_ROUTE.includes("if (!rememberedGuard.ok) return rememberedGuard.response;") &&
|
||||
REVOKE_ROUTE.includes("if (!fallbackGuard.ok) return fallbackGuard.response;"),
|
||||
"a failed guard must abort the revoke with the guard's fail-closed response"
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Issue 5 — anchored absolute expiry + identifier rotation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("the registry entry carries an absoluteExpiresAt anchor from issuance", () => {
|
||||
const normalizer = sliceBetween(
|
||||
indexSource,
|
||||
"function normalizeRememberLoginRegistry(raw) {",
|
||||
"function normalizeRememberLoginLegacyCutoffs(raw) {"
|
||||
);
|
||||
assert.ok(
|
||||
normalizer.includes("absoluteExpiresAt: Number(entry.absoluteExpiresAt || 0) || 0,"),
|
||||
"normalization must preserve the anchor field (and backfill legacy entries as 0)"
|
||||
);
|
||||
|
||||
const upsert = sliceBetween(
|
||||
indexSource,
|
||||
"function upsertRememberLoginRegistryEntry(req, user, expiresAt, issuedAt = Date.now()) {",
|
||||
"function revokeRememberLoginRegistryEntry(rememberId) {"
|
||||
);
|
||||
assert.ok(
|
||||
upsert.includes("absoluteExpiresAt: Number(expiresAt) || (Date.now() + REMEMBER_LOGIN_MAX_AGE_MS),"),
|
||||
"interactive issuance must anchor the hard expiry at its own expiry"
|
||||
);
|
||||
|
||||
const anchorResolver = sliceBetween(
|
||||
indexSource,
|
||||
"function resolveRememberLoginAnchorMs(oldEntry) {",
|
||||
"// CAS identifier rotation:"
|
||||
);
|
||||
assert.ok(
|
||||
anchorResolver.includes("Number(oldEntry?.absoluteExpiresAt || oldEntry?.expiresAt || 0)"),
|
||||
"rotations inherit the anchor; pre-anchor entries backfill from their own exp"
|
||||
);
|
||||
});
|
||||
|
||||
test("silent re-issues cap the expiry at the anchor and die with the cookie", () => {
|
||||
const rotate = sliceBetween(
|
||||
indexSource,
|
||||
"async function rotateRememberLoginCookie(req, res, user, parsedToken) {",
|
||||
"function rememberLoginNeedsRefresh(tokenPayload) {"
|
||||
);
|
||||
assert.ok(
|
||||
rotate.includes("const expiresAt = Math.min(now + REMEMBER_LOGIN_MAX_AGE_MS, anchor);"),
|
||||
"the re-issued token exp must be capped at the anchored hard expiry"
|
||||
);
|
||||
assert.ok(
|
||||
rotate.includes("if (expiresAt <= now) return 0;"),
|
||||
"an anchor already in the past must refuse the silent re-issue"
|
||||
);
|
||||
assert.ok(
|
||||
rotate.includes("{ ...getRememberLoginCookieOptions(req), maxAge: Math.max(0, expiresAt - now) }"),
|
||||
"the re-issued cookie's maxAge must be aligned with the token's remaining lifetime"
|
||||
);
|
||||
assert.ok(
|
||||
rotate.includes("absoluteExpiresAt: anchor,"),
|
||||
"the rotated entry must carry the inherited anchor forward"
|
||||
);
|
||||
});
|
||||
|
||||
test("every silent re-issue rotates to a NEW jti via a compare-and-swap registry swap", () => {
|
||||
const rotate = sliceBetween(
|
||||
indexSource,
|
||||
"async function rotateRememberLoginCookie(req, res, user, parsedToken) {",
|
||||
"function rememberLoginNeedsRefresh(tokenPayload) {"
|
||||
);
|
||||
assert.ok(
|
||||
rotate.includes("const rememberId = crypto.randomBytes(18).toString(\"hex\");"),
|
||||
"rotation must mint a fresh identifier, not reuse the presented one"
|
||||
);
|
||||
assert.ok(
|
||||
rotate.includes("delete rememberLoginRegistry[oldId];") &&
|
||||
rotate.indexOf("rememberLoginRegistry[rememberId] = entry;") < rotate.indexOf("delete rememberLoginRegistry[oldId];"),
|
||||
"the new entry must be registered and the OLD entry deleted"
|
||||
);
|
||||
assert.ok(
|
||||
rotate.includes("req.session.rememberLoginId = rememberId;"),
|
||||
"the session must be re-bound to the new id so logout/revoke removes the current entry"
|
||||
);
|
||||
assert.ok(
|
||||
rotate.includes("rememberLoginRegistryFreshCheckedAt = 0;"),
|
||||
"a successful rotation must force a registry version re-check (the version bump was ours)"
|
||||
);
|
||||
|
||||
const lua = sliceBetween(
|
||||
indexSource,
|
||||
"const REMEMBER_LOGIN_ROTATE_LUA = [",
|
||||
'].join("\\n");'
|
||||
);
|
||||
const hsetIdx = lua.indexOf("redis.call('HSET'");
|
||||
const hdelIdx = lua.indexOf("redis.call('HDEL'");
|
||||
const incrIdx = lua.indexOf("redis.call('INCR'");
|
||||
assert.ok(lua.includes("if not old then return -1 end"), "rotation must refuse when the presented entry no longer exists (drift)");
|
||||
assert.ok(
|
||||
lua.includes("tostring(oldEntry.uid) ~= ARGV[2]"),
|
||||
"rotation must verify the presented entry still belongs to the presented cookie's owner"
|
||||
);
|
||||
assert.ok(hsetIdx >= 0 && hdelIdx > hsetIdx && incrIdx > hdelIdx, "HSET new, HDEL old and the version bump must run in one atomic script");
|
||||
|
||||
// Drift and Redis failures both fail closed (return 0 → the caller clears
|
||||
// the remember state and the next login is a full password login).
|
||||
const driftIdx = rotate.indexOf("if (!rotated) {");
|
||||
const commitIdx = rotate.indexOf("commitRotation();", driftIdx);
|
||||
const failClosedIdx = rotate.indexOf("return 0;", driftIdx);
|
||||
assert.ok(driftIdx >= 0 && failClosedIdx > driftIdx && failClosedIdx < commitIdx, "a lost CAS must fail closed before any state is committed");
|
||||
const catchIdx = rotate.indexOf("} catch (err) {");
|
||||
assert.ok(catchIdx >= 0 && rotate.indexOf("return 0;", catchIdx) > catchIdx, "a Redis failure during rotation must fail closed");
|
||||
});
|
||||
|
||||
test("the remember middleware and the restore path rotate instead of re-issuing a fresh 365d credential", () => {
|
||||
const ensure = sliceBetween(
|
||||
indexSource,
|
||||
"async function ensureRememberLoginCookie(req, res, user = null) {",
|
||||
"async function restoreRememberedLogin(req, res) {"
|
||||
);
|
||||
const restore = sliceBetween(
|
||||
indexSource,
|
||||
"async function restoreRememberedLogin(req, res) {",
|
||||
"const sessionMiddleware = session({"
|
||||
);
|
||||
|
||||
assert.ok(!ensure.includes("setRememberLoginCookie("), "the silent middleware path must never call the fresh-365d issuance");
|
||||
assert.ok(!restore.includes("setRememberLoginCookie("), "the restore path must never call the fresh-365d issuance");
|
||||
assert.ok(ensure.includes("await rotateRememberLoginCookie(req, res, resolvedUser, parsed);"), "the middleware silent re-issue must rotate");
|
||||
assert.ok(restore.includes("await rotateRememberLoginCookie(req, res, user, parsed);"), "restore must rotate the presented identifier");
|
||||
|
||||
// The 6h validation interval still gates rotation: inside the anchor's
|
||||
// refresh window a fresh validation skips WITHOUT rotating (otherwise every
|
||||
// request would mint a new identifier).
|
||||
// Conscious text update (adpanel:remember-rotation-cadence): the 6h half is
|
||||
// anchored to the presented token's own iat (credential age) instead of the
|
||||
// last-activity stamp — an active browser must keep reaching the rotation
|
||||
// boundary. The storm-guard POSITION (before rotation) is unchanged.
|
||||
assert.ok(
|
||||
ensure.includes("rememberLoginValidationIntervalFresh(parsed.iat)"),
|
||||
"the refresh-window storm guard (6h half on its own) must exist in the middleware path"
|
||||
);
|
||||
assert.ok(
|
||||
ensure.indexOf("rememberLoginValidationIntervalFresh(parsed.iat)") < ensure.indexOf("await rotateRememberLoginCookie"),
|
||||
"the storm guard must run before rotation"
|
||||
);
|
||||
|
||||
// Adoption must not require a fresh token: a drift loser inside the refresh
|
||||
// window has to ADOPT the winner's identifier (and then skip via the 6h
|
||||
// guard) instead of rotating on every request.
|
||||
const adoptionBlock = sliceBetween(ensure, "// Identifier adoption:", "// Silent re-issue:");
|
||||
assert.ok(
|
||||
adoptionBlock.includes("isManagedRememberLoginToken(parsed, resolvedUser)") &&
|
||||
!adoptionBlock.includes("rememberLoginNeedsRefresh"),
|
||||
"adoption must converge two tabs on one identifier regardless of the remaining window"
|
||||
);
|
||||
|
||||
// Restore fails closed: a refused rotation aborts the restore (full password
|
||||
// re-auth) BEFORE the regenerated session is authenticated.
|
||||
// Conscious marker update (adpanel:credential-generation): the restore's
|
||||
// bind line now sources the fresh re-read row — the markers track it. Same
|
||||
// assertions: rotation precedes authentication and its refusal aborts.
|
||||
const rotateIdx = restore.indexOf("await rotateRememberLoginCookie(req, res, user, parsed);");
|
||||
const refuseIdx = restore.indexOf("if (!expiresAt) {", rotateIdx);
|
||||
const authIdx = restore.indexOf("req.session.user = freshRestoreRow.email;", rotateIdx);
|
||||
assert.ok(refuseIdx > rotateIdx && authIdx > refuseIdx, "rotation must happen before authentication and its refusal must abort the restore");
|
||||
const refuseBody = sliceBetween(restore, "if (!expiresAt) {", "req.session.user = freshRestoreRow.email;");
|
||||
assert.ok(refuseBody.includes("clearRememberLoginCookie(req, res);") && refuseBody.includes("return false;"), "a refused restore clears the remember cookie and fails");
|
||||
|
||||
// The anchored expiry flows into the session so the skip predicate's
|
||||
// refresh-window check measures the real remaining lifetime.
|
||||
assert.ok(
|
||||
ensure.includes("markRememberLoginSessionFresh(req, expiresAt);") &&
|
||||
restore.includes("markRememberLoginSessionFresh(req, expiresAt);"),
|
||||
"both silent paths must store the anchored expiry via markRememberLoginSessionFresh"
|
||||
);
|
||||
});
|
||||
|
||||
test("canSkipRememberLoginValidation keeps the 6h interval and reads the anchored expiry for its refresh window", () => {
|
||||
// Conscious marker/text update (adpanel:remember-rotation-cadence): the 6h
|
||||
// half's signature gained the credential-age input (the presented token's
|
||||
// iat); the anchored-expiry refresh-window clause and the shared
|
||||
// REMEMBER_LOGIN_VALIDATE_INTERVAL_MS constant are unchanged.
|
||||
const canSkip = sliceBetween(
|
||||
indexSource,
|
||||
"function canSkipRememberLoginValidation(req, credentialIssuedAt) {",
|
||||
"function signRememberLoginPayload(encodedPayload) {"
|
||||
);
|
||||
assert.ok(canSkip.includes("REMEMBER_LOGIN_REFRESH_WINDOW_MS"), "the >30d-remaining clause must remain");
|
||||
assert.ok(canSkip.includes("rememberLoginValidationIntervalFresh(credentialIssuedAt)"), "the 6h validation half must remain");
|
||||
assert.ok(
|
||||
canSkip.includes("rememberLoginExpiresAt"),
|
||||
"the window check must read the anchored expiry stored by markRememberLoginSessionFresh"
|
||||
);
|
||||
assert.ok(
|
||||
indexSource.includes("function rememberLoginValidationIntervalFresh(credentialIssuedAt) {") &&
|
||||
indexSource.includes("REMEMBER_LOGIN_VALIDATE_INTERVAL_MS"),
|
||||
"the extracted 6h half must use the same validation interval constant"
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Issue 6 — one-shot revoke tokens survive stale session saves
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("consumption is durably marked outside the session snapshot with an atomic check-and-mark", () => {
|
||||
assert.ok(
|
||||
indexSource.includes('const CONSUMED_ACTION_TOKEN_REDIS_PREFIX = "adpanel:consumed-action-token:";'),
|
||||
"consumed tokens need a dedicated Redis key prefix"
|
||||
);
|
||||
assert.ok(
|
||||
indexSource.includes("Math.ceil((SESSION_REVOKE_TARGET_TOKEN_TTL_MS + 5 * 60 * 1000) / 1000)"),
|
||||
"the marker TTL must reuse the action token TTL constant plus slack"
|
||||
);
|
||||
|
||||
const claim = sliceBetween(
|
||||
indexSource,
|
||||
"async function claimSessionRevokeTargetToken(req, token) {",
|
||||
"// Single-use consumption."
|
||||
);
|
||||
assert.ok(
|
||||
claim.includes('String(req?.sessionID || "")'),
|
||||
"the marker must be scoped per admin session id, mirroring the per-session mint map"
|
||||
);
|
||||
assert.ok(claim.includes("{ NX: true, EX: CONSUMED_ACTION_TOKEN_TTL_SECONDS }"), "the check-and-mark must be one atomic SET NX EX");
|
||||
assert.ok(claim.includes('return reply === "OK";'), "only the first consumption may claim the token");
|
||||
const claimCatchIdx = claim.indexOf("} catch (err) {");
|
||||
assert.ok(
|
||||
claimCatchIdx >= 0 && claim.slice(claimCatchIdx).includes("return false;"),
|
||||
"a Redis failure must fail closed (token unusable for that request)"
|
||||
);
|
||||
assert.ok(claim.includes("isConsumedActionTokenCachedLocally"), "file-store mode must keep a process-local marker outside the session snapshot");
|
||||
});
|
||||
|
||||
test("the consume path claims durably first, keeps the in-memory delete, and is awaited at the verify site", () => {
|
||||
const consume = sliceBetween(
|
||||
indexSource,
|
||||
"async function consumeSessionRevokeTargetToken(req, token) {",
|
||||
"const STEALTH_MODE"
|
||||
);
|
||||
assert.ok(consume.includes("delete targets["), "single-use consumption must still delete the in-memory session entry");
|
||||
const claimIdx = consume.indexOf("if (!(await claimSessionRevokeTargetToken(req, raw))) return null;");
|
||||
const deleteIdx = consume.indexOf("delete targets[");
|
||||
assert.ok(claimIdx >= 0 && claimIdx < deleteIdx, "the durable claim must gate the in-memory delete (an already-marked token resolves to nothing)");
|
||||
assert.ok(
|
||||
consume.includes("if (!entry) return null;") && consume.indexOf("if (!entry) return null;") < claimIdx,
|
||||
"a token missing from the session snapshot still resolves to nothing"
|
||||
);
|
||||
|
||||
// adpanel:async-handler-containment — the consumption await is guarded (a
|
||||
// Redis rejection must answer a bounded 500, not hang the client); the
|
||||
// binding is hoisted above the guard try so the body below reads a defined
|
||||
// binding (the sweep's hoisted-binding convention).
|
||||
assert.ok(
|
||||
indexSource.includes("resolvedTarget = await consumeSessionRevokeTargetToken(req, revokeToken);"),
|
||||
"the revoke route must await the now-async consumption on first verification"
|
||||
);
|
||||
assert.equal(
|
||||
countOccurrences(indexSource, "consumeSessionRevokeTargetToken(req, revokeToken)"),
|
||||
1,
|
||||
"consumption must happen exactly once, before any step-up or grace use"
|
||||
);
|
||||
});
|
||||
|
||||
// ---- Review-fix pins: confirmed revocation + rotation-race sweep + drift-preserve ----
|
||||
|
||||
test("single-login revocations are confirmed against Redis, not fire-and-forget", () => {
|
||||
const helper = sliceBetween(
|
||||
indexSource,
|
||||
"async function revokeRememberLoginRegistryEntryConfirmed(rememberId, ownerHint = null) {",
|
||||
"function findRememberLoginIdBySessionId"
|
||||
);
|
||||
assert.ok(helper.length > 0, "the confirmed revocation helper must exist");
|
||||
assert.match(helper, /await deleteRememberLoginRegistryFields\(\[id\]\)/, "the delete must be awaited, not queued fire-and-forget");
|
||||
assert.match(helper, /revoke-unverified/, "success requires verifying the field is actually gone from Redis");
|
||||
assert.match(helper, /REMEMBER_LOGIN_REVOKE_RACE_SWEEP_WINDOW_MS/, "same-owner entries minted inside the rotation race window must be swept");
|
||||
assert.match(indexSource, /const REMEMBER_LOGIN_REVOKE_RACE_SWEEP_MAX_ROUNDS = 3;/, "the sweep must be bounded");
|
||||
assert.match(
|
||||
helper,
|
||||
/const localEntry = rememberLoginRegistry\[id\];[\s\S]*?targetUid = String\(localEntry\.uid \|\| ""\)\.trim\(\);/,
|
||||
"when the presented row is already gone (cross-worker rotation during processing, or a retry after a failed sweep), the sweep owner must fall back to this worker's registry view — otherwise the sweep silently skips and a rotated identifier survives a 'successful' revoke"
|
||||
);
|
||||
assert.match(helper, /!remote\[mintedId\]|reason: "redis-error"/, "Redis failures must fail closed");
|
||||
assert.doesNotMatch(helper, /queueRememberLoginRedisPersist/, "the confirmed path must bypass the error-swallowing write queue");
|
||||
|
||||
// Both revoke-route call sites must use the confirmed helper — passing the
|
||||
// owner they already know (uid from the registry view, target email) so the
|
||||
// race sweep still runs when the presented row was already rotated away —
|
||||
// and abort with a retryable 503 when the revocation cannot be confirmed.
|
||||
assert.match(
|
||||
indexSource,
|
||||
/const revokeConfirmed = await revokeRememberLoginRegistryEntryConfirmed\(savedLoginId, \{ uid: String\(registryEntry\.uid \|\| ""\), email: targetEmail \}\);/,
|
||||
"the remembered-target path must await the confirmed revocation with its known owner"
|
||||
);
|
||||
assert.match(
|
||||
indexSource,
|
||||
/const targetRevokeConfirmed = await revokeRememberLoginRegistryEntryConfirmed\(targetRememberLoginId, \{ email: targetEmail \}\);/,
|
||||
"the session-target saved-login path must await the confirmed revocation with its known owner"
|
||||
);
|
||||
assert.match(
|
||||
helper,
|
||||
/const sweepMatchesOwner = \(parsed\) => \{/,
|
||||
"the sweep must match same-owner entries by uid OR the caller-supplied email"
|
||||
);
|
||||
assert.match(
|
||||
helper,
|
||||
/ownerHint\?\.email/,
|
||||
"the sweep owner must accept the caller's email hint (covers rows rotated away before the revoke)"
|
||||
);
|
||||
assert.equal(
|
||||
countOccurrences(indexSource, 'code: "remember-revoke-unconfirmed"'),
|
||||
2,
|
||||
"both call sites must fail closed with a retryable revocation-unconfirmed response"
|
||||
);
|
||||
// The fire-and-forget variant now has NO call site. Conscious count update
|
||||
// (adpanel:remember-logout-lineage, WAVE-3): logout and
|
||||
// destroyBrowserSessionsForUser's per-target eviction were upgraded to the
|
||||
// lineage-scoped revoke in the previous wave; the four remaining
|
||||
// session-bound single-id paths (the stale-account-binding teardowns on
|
||||
// session restore, the suspension middleware branch, and the status-page
|
||||
// pre-sweep single revoke) joined them — a presented identifier can
|
||||
// already have been rotated away when the revoke runs, and only lineage
|
||||
// revocation reaches the replacement (suspension of a compromised account
|
||||
// is exactly where that rotate-race window is least acceptable). The
|
||||
// lineage helper degrades to exactly the single-id reach when no live
|
||||
// entry/lineage stamp names a chain — never worse than the twin it
|
||||
// replaced. The confirmed variant is still awaited at exactly the two
|
||||
// revoke-route sites (protected invariant unchanged: the revoke route must
|
||||
// not use the queued variant).
|
||||
assert.equal(
|
||||
countOccurrences(indexSource, "revokeRememberLoginRegistryEntry(") - countOccurrences(indexSource, "function revokeRememberLoginRegistryEntry("),
|
||||
0,
|
||||
"no opportunistic path keeps the queued variant — every session-bound site uses the lineage-scoped helper; the revoke route must not use the queued variant either"
|
||||
);
|
||||
assert.equal(
|
||||
countOccurrences(indexSource, "await revokeRememberLoginRegistryEntryConfirmed("),
|
||||
2,
|
||||
"the confirmed revocation must be used exactly at the two revoke-route call sites"
|
||||
);
|
||||
});
|
||||
|
||||
test("the registry sync preserves locally minted never-synced entries on version drift", () => {
|
||||
const sync = sliceBetween(
|
||||
indexSource,
|
||||
"async function syncRememberLoginRegistryToRedis() {",
|
||||
"async function initializeRememberLoginStores()"
|
||||
);
|
||||
assert.match(sync, /const locallyMintedRememberLoginIds = new Set\(\);|locallyMintedRememberLoginIds/, "the mint-provenance set must exist");
|
||||
assert.match(
|
||||
sync,
|
||||
/locallyMintedRememberLoginIds\.has\(mintedId\) && !remote\[mintedId\]/,
|
||||
"drift adoption must preserve only locally minted entries that are absent remotely (nothing remote could have revoked a field that never existed)"
|
||||
);
|
||||
assert.match(
|
||||
sync,
|
||||
/if \(Object\.keys\(preservedMintedEntries\)\.length === 0\) return true;/,
|
||||
"a drift with nothing to preserve still adopts the remote view wholesale"
|
||||
);
|
||||
assert.match(
|
||||
sync,
|
||||
/locallyMintedRememberLoginIds\.delete\(id\);\n \}\n\n for \(const id of Object\.keys\(remote\)\)/,
|
||||
"a successful guarded write must clear the mint mark (the id now exists in Redis)"
|
||||
);
|
||||
|
||||
const upsert = sliceBetween(
|
||||
indexSource,
|
||||
"function upsertRememberLoginRegistryEntry(req, user, expiresAt, issuedAt = Date.now()) {",
|
||||
"function revokeRememberLoginRegistryEntry(rememberId) {"
|
||||
);
|
||||
assert.match(upsert, /const isNewRememberLoginMint = !rememberLoginRegistry\[rememberId\];/, "only fresh mints may be marked (updates to a known id stay remote-authoritative)");
|
||||
assert.match(upsert, /if \(isNewRememberLoginMint\) locallyMintedRememberLoginIds\.add\(rememberId\);/, "fresh mints must be recorded in the provenance set");
|
||||
});
|
||||
|
||||
test("a lost-ACK guarded write clears the mint mark so drift-preserve cannot resurrect", () => {
|
||||
// If the EVAL executed server-side but the client observed an error, the row
|
||||
// now exists in Redis while the mint mark is still set. A remote revocation
|
||||
// of that row followed by a drift-adopt must NOT preserve and re-insert it —
|
||||
// so both guarded-write catch blocks must clear the mark (fail-safe: a mark
|
||||
// whose row never landed simply dies with the cookie).
|
||||
const sync = sliceBetween(
|
||||
indexSource,
|
||||
"async function syncRememberLoginRegistryToRedis() {",
|
||||
"async function initializeRememberLoginStores()"
|
||||
);
|
||||
const syncCatch = sync.slice(sync.indexOf("written = await guardedRememberLoginRegistryFieldWrite(expectedVersion, id, entry);"));
|
||||
const catchEnd = syncCatch.indexOf("return false;");
|
||||
assert.ok(
|
||||
syncCatch.slice(0, catchEnd).includes("locallyMintedRememberLoginIds.delete(id);"),
|
||||
"the registry sync's guarded-write catch must clear the mint mark (lost-ACK fail-safe)"
|
||||
);
|
||||
|
||||
const audit = sliceBetween(
|
||||
indexSource,
|
||||
"function syncRememberLoginRegistryAudit(rememberId, audit, email = \"\")",
|
||||
"function isManagedRememberLoginToken("
|
||||
);
|
||||
const auditCatch = audit.slice(audit.indexOf("written = await guardedRememberLoginRegistryFieldWrite(rememberLoginRegistryVersion, id, freshEntry);"));
|
||||
const auditCatchEnd = auditCatch.indexOf("return false;");
|
||||
assert.ok(
|
||||
auditCatch.slice(0, auditCatchEnd).includes("locallyMintedRememberLoginIds.delete(id);"),
|
||||
"the audit sync's guarded-write catch must clear the mint mark (lost-ACK fail-safe)"
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user