377 lines
18 KiB
JavaScript
377 lines
18 KiB
JavaScript
"use strict";
|
|
|
|
// adpanel:tombstone-skip-signal — Finding (Low, caller-contract incoherence):
|
|
// the tombstone store wrapper's write-path read uses the FAIL-CLOSED default,
|
|
// so during a Redis read blip every set()/touch() is treated as "revoked" →
|
|
// skipped → finish(null) (SUCCESS). For a login binder save that means the
|
|
// client is told login succeeded while NOTHING was persisted, and the
|
|
// save-failure hygiene (remember-credential revoke + regenerated-sid
|
|
// tombstone) never fires. The audit confirmed this is fail-SAFE (nothing
|
|
// authenticated is gained; express-session 1.19.0 fails store.get at load
|
|
// with next(err) too — node_modules/express-session/index.js:500-506 — so
|
|
// the write-skip window is the narrow load→save gap), and the defect is the
|
|
// false SUCCESS contract, not data exposure.
|
|
//
|
|
// The repair is a signal channel, not a blanket finish(err): a blanket error
|
|
// would 500 EVERY session's endHandler save AND touch during a blip
|
|
// (express-session 1.19.0 forwards BOTH error classes to next(err) —
|
|
// index.js:350-356 and 362-369 — an availability regression for all
|
|
// generic traffic). Instead the wrapper, on the SET path only, marks the
|
|
// live session object with a non-enumerable registry symbol
|
|
// (Symbol.for("adpanel:storeWriteSkipped")) when the skip reason is READ-
|
|
// ERROR, and keeps finish(null). Only the login binder reads the marker,
|
|
// after its awaited save, and converts it into the labeled failure whose
|
|
// existing catch runs the hygiene and rethrows → 500. Confirmed-revocation
|
|
// skips set NOTHING (dropping a dead sid's write is intentional and must
|
|
// not fail a login), touch skips keep finish(null) (rolling-expiry loss
|
|
// during a blip is benign and pre-existing), and every other consumer of
|
|
// the wrapped store (express-session endHandler saves for all sessions,
|
|
// remember-restore, the captcha pending saves) keeps today's behavior
|
|
// because they never read the marker.
|
|
//
|
|
// This file pins the wrapper half with the REAL machinery (extracted
|
|
// index.js regions run in a vm sandbox — the sid-tombstone-dead-letter
|
|
// style): the real local cache, the real isSessionSidRevoked, the real
|
|
// wrapper, over a fake store whose tombstone read errors. The binder half
|
|
// (post-save check → hygiene → labeled rethrow) is pinned functionally in
|
|
// tests/login-session-bind-module.test.js; the two halves compose through
|
|
// the shared registry key, pinned here by keyFor and in both sources by
|
|
// single-occurrence counts.
|
|
|
|
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 BINDER_JS = path.join(ROOT, "utils", "login-session-bind.js");
|
|
|
|
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
|
const binderSource = fs.readFileSync(BINDER_JS, "utf8");
|
|
const guardSource = fs.readFileSync(path.join(ROOT, "utils", "session-store-guard.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);
|
|
}
|
|
|
|
function countOccurrences(haystack, needle) {
|
|
let count = 0;
|
|
let pos = 0;
|
|
for (;;) {
|
|
const idx = haystack.indexOf(needle, pos);
|
|
if (idx < 0) return count;
|
|
count += 1;
|
|
pos = idx + needle.length;
|
|
}
|
|
}
|
|
|
|
// The REAL tombstone machinery (constants, per-worker cache helpers, the
|
|
// durable write + its dead-letter queue) — same extraction the
|
|
// sid-tombstone-dead-letter test uses.
|
|
const MACHINERY_SOURCE = extractRegion(
|
|
indexSource,
|
|
"// ---- Revoked-sid tombstones (anti-resurrection) ----",
|
|
"// Consult BOTH layers before trusting a sid:"
|
|
);
|
|
|
|
// The REAL revocation check (fail-closed default, fail-open opt-out).
|
|
const CHECKER_SOURCE = extractRegion(
|
|
indexSource,
|
|
"// Consult BOTH layers before trusting a sid:",
|
|
"const wrapSessionStoreWithTombstoneGuard"
|
|
);
|
|
|
|
// The REAL wrapper including the signal constants (constants live between
|
|
// the checker and the wrapper by design: the checker region above ends
|
|
// exactly at them).
|
|
const WRAPPER_SOURCE = extractRegion(
|
|
indexSource,
|
|
"const wrapSessionStoreWithTombstoneGuard",
|
|
"wrapSessionStoreWithTombstoneGuard(sessionStore);"
|
|
);
|
|
|
|
// Real withTimeout semantics (the machinery calls it; a passthrough would
|
|
// not exercise the bounded-write path the same way the dead-letter test does).
|
|
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));
|
|
}
|
|
|
|
const SYMBOL = Symbol.for("adpanel:storeWriteSkipped");
|
|
|
|
// Builds a sandbox with the REAL machinery + checker + wrapper wrapped around
|
|
// a recording fake store. redisGet drives the three verdict shapes:
|
|
// - async () => { throw } → tombstone READ ERROR (fail-closed skip)
|
|
// - async () => "1" → CONFIRMED revocation (Redis hit)
|
|
// - async () => null → clean verdict (write proceeds)
|
|
function makeSignalSandbox({ redisGet } = {}) {
|
|
const events = [];
|
|
const warnings = [];
|
|
const store = {
|
|
set(sid, sess, cb) { events.push(`set:${sid}`); process.nextTick(() => cb(null)); },
|
|
touch(sid, sess, cb) { events.push(`touch:${sid}`); process.nextTick(() => cb(null)); },
|
|
destroy(sid, cb) { events.push(`destroy:${sid}`); if (typeof cb === "function") process.nextTick(() => cb(null)); },
|
|
};
|
|
const sandbox = {
|
|
console: {
|
|
warn: (...args) => warnings.push(args.map(String).join(" ")),
|
|
log: () => {},
|
|
error: () => {},
|
|
},
|
|
process: { env: {} },
|
|
scaleForMemory: (base) => base,
|
|
redisClient: { isOpen: true, get: redisGet },
|
|
withTimeout: sandboxWithTimeout,
|
|
getSessionDisplayId: (id) => `sess:${id}`,
|
|
sessionStore: store,
|
|
require: (id) => {
|
|
assert.strictEqual(id, "./utils/session-store-guard");
|
|
return require("../utils/session-store-guard");
|
|
},
|
|
};
|
|
vm.createContext(sandbox);
|
|
vm.runInContext(
|
|
MACHINERY_SOURCE + "\n" + CHECKER_SOURCE + "\n" + WRAPPER_SOURCE + "\nwrapSessionStoreWithTombstoneGuard(sessionStore);",
|
|
sandbox,
|
|
{ filename: "tombstone-skip-signal-sandbox.js" }
|
|
);
|
|
return { sandbox, events, warnings, store };
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Behavioral pins: the REAL wrapper over a fake store whose tombstone read
|
|
// errors (the Redis read blip)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("read-error skip on set: the live session object carries the non-enumerable signal, caller still sees success", async () => {
|
|
const box = makeSignalSandbox({
|
|
redisGet: async () => { throw new Error("ECONNRESET-blip"); },
|
|
});
|
|
const sess = { user: "someone@example.com", cookie: {} };
|
|
let cbCount = 0;
|
|
const outcome = await new Promise((resolve) => {
|
|
box.store.set("sid-read-error", sess, (err, result) => {
|
|
cbCount += 1;
|
|
resolve({ err, result });
|
|
});
|
|
});
|
|
|
|
// The caller contract is unchanged: the skip still reports SUCCESS (the
|
|
// signal channel, not a finish(err), is the repair — a blanket error would
|
|
// 500 every session's endHandler save during a blip).
|
|
assert.strictEqual(outcome.err, null, "the skipped write must keep reporting success to the store caller");
|
|
assert.strictEqual(outcome.result, undefined);
|
|
assert.strictEqual(cbCount, 1, "the callback must settle exactly once");
|
|
|
|
// THE signal: the session object carries the registry symbol with the
|
|
// read-error reason.
|
|
assert.strictEqual(sess[SYMBOL], "tombstone-read-error", "a read-error skip must mark the live session object");
|
|
assert.strictEqual(
|
|
Symbol.keyFor(Object.getOwnPropertySymbols(sess)[0]),
|
|
"adpanel:storeWriteSkipped",
|
|
"the marker must be the exact registry symbol the login binder reads"
|
|
);
|
|
const descriptor = Object.getOwnPropertyDescriptor(sess, SYMBOL);
|
|
assert.strictEqual(descriptor.enumerable, false, "the marker must be non-enumerable");
|
|
assert.strictEqual(descriptor.configurable, false, "defineProperty defaults hold (a second skip re-defines inside the try/catch)");
|
|
|
|
// The signal never persists: JSON.stringify is what the express-session
|
|
// hash and the connect-redis record are built from.
|
|
assert.ok(
|
|
!JSON.stringify(sess).includes("tombstone-read-error"),
|
|
"the marker must stay out of the serialized record and the session hash"
|
|
);
|
|
assert.deepStrictEqual(
|
|
Object.keys(sess),
|
|
["user", "cookie"],
|
|
"the marker must not appear among the session's data keys"
|
|
);
|
|
|
|
// The skip still re-destroys and never calls the underlying set.
|
|
assert.ok(box.events.includes("destroy:sid-read-error"), "a skipped write still re-destroys the sid");
|
|
assert.ok(!box.events.includes("set:sid-read-error"), "the underlying store set must not run for a skipped write");
|
|
|
|
// The fail-closed warn (the checker's own wording) still fired.
|
|
assert.ok(
|
|
box.warnings.some((w) => w.includes("Revoked-sid tombstone check failed") && w.includes("failing closed") && w.includes("sess:sid-read-error")),
|
|
"the read blip keeps its loud [security] warn"
|
|
);
|
|
});
|
|
|
|
test("confirmed-revocation skip on set: NO signal, caller still sees success (dropping a dead sid's write is intentional)", async () => {
|
|
const box = makeSignalSandbox({ redisGet: async () => "1" });
|
|
const sess = { user: "victim@example.com", cookie: {} };
|
|
let cbCount = 0;
|
|
const outcome = await new Promise((resolve) => {
|
|
box.store.set("sid-confirmed", sess, (err) => {
|
|
cbCount += 1;
|
|
resolve({ err });
|
|
});
|
|
});
|
|
|
|
assert.strictEqual(outcome.err, null, "the confirmed-revocation skip keeps its success contract");
|
|
assert.strictEqual(cbCount, 1);
|
|
assert.strictEqual(sess[SYMBOL], undefined, "a CONFIRMED revocation must NOT mark the session object");
|
|
assert.deepStrictEqual(Object.getOwnPropertySymbols(sess), [], "no symbol of any kind may leak onto the session object");
|
|
assert.ok(box.events.includes("destroy:sid-confirmed"), "the re-destroy still runs for a tombstoned sid");
|
|
assert.ok(!box.events.includes("set:sid-confirmed"), "the underlying store set must not run");
|
|
assert.ok(
|
|
box.warnings.every((w) => !w.includes("failing closed")),
|
|
"a confirmed verdict comes from a successful Redis read — no failure warn"
|
|
);
|
|
});
|
|
|
|
test("clean verdict on set: the write proceeds, no signal, no destroy", async () => {
|
|
const box = makeSignalSandbox({ redisGet: async () => null });
|
|
const sess = { user: "healthy@example.com", cookie: {} };
|
|
const outcome = await new Promise((resolve) => {
|
|
box.store.set("sid-ok", sess, (err) => resolve({ err }));
|
|
});
|
|
|
|
assert.strictEqual(outcome.err, null);
|
|
assert.strictEqual(sess[SYMBOL], undefined, "a clean write must never be marked");
|
|
assert.deepStrictEqual(Object.getOwnPropertySymbols(sess), []);
|
|
assert.ok(box.events.includes("set:sid-ok"), "the underlying store set must run for an unrevoked sid");
|
|
assert.ok(!box.events.includes("destroy:sid-ok"), "no re-destroy for an unrevoked sid");
|
|
});
|
|
|
|
test("an unreadable durable file marker cannot authorize a restored session", async () => {
|
|
const box = makeSignalSandbox({ redisGet: async () => null });
|
|
box.sandbox.redisClient = null;
|
|
box.sandbox.fileSessionRevocations = { has: () => { throw new Error("marker-unreadable"); } };
|
|
assert.strictEqual(await box.sandbox.isSessionSidRevoked("test-file-sid", { failClosed: false }), true);
|
|
});
|
|
|
|
test("touch read-error skip: finish(null) and NO signal (the touch path is unchanged)", async () => {
|
|
const box = makeSignalSandbox({
|
|
redisGet: async () => { throw new Error("ECONNRESET-blip"); },
|
|
});
|
|
const sess = { cookie: {} };
|
|
const outcome = await new Promise((resolve) => {
|
|
box.store.touch("sid-touch", sess, (err) => resolve({ err }));
|
|
});
|
|
|
|
assert.strictEqual(outcome.err, null, "touch skips keep the success contract");
|
|
assert.strictEqual(sess[SYMBOL], undefined, "touch skips must not mark the session object — no consumer signals through touch");
|
|
assert.deepStrictEqual(Object.getOwnPropertySymbols(sess), []);
|
|
assert.ok(box.events.includes("destroy:sid-touch"), "the fail-closed skip still re-destroys");
|
|
assert.ok(!box.events.includes("touch:sid-touch"), "the underlying store touch must not run for a skipped write");
|
|
});
|
|
|
|
test("a frozen session object cannot crash the skip path (the signal channel is simply unavailable)", async () => {
|
|
const box = makeSignalSandbox({
|
|
redisGet: async () => { throw new Error("ECONNRESET-blip"); },
|
|
});
|
|
const sess = Object.freeze({ user: "frozen@example.com" });
|
|
const outcome = await new Promise((resolve) => {
|
|
box.store.set("sid-frozen", sess, (err) => resolve({ err }));
|
|
});
|
|
|
|
assert.strictEqual(outcome.err, null, "the defineProperty failure must be absorbed, never surfaced as a store error");
|
|
assert.deepStrictEqual(Object.getOwnPropertySymbols(sess), [], "no marker landed on the frozen object");
|
|
assert.ok(box.events.includes("destroy:sid-frozen"), "the skip path completed (re-destroy ran)");
|
|
assert.ok(!box.events.includes("set:sid-frozen"), "the underlying store set must not run");
|
|
});
|
|
|
|
test("the fail-closed read-error verdict still re-destroys when the destroy itself errors, and still reports success", async () => {
|
|
const box = makeSignalSandbox({
|
|
redisGet: async () => { throw new Error("ECONNRESET-blip"); },
|
|
});
|
|
box.store.destroy = (sid, cb) => {
|
|
box.events.push(`destroy:${sid}`);
|
|
process.nextTick(() => cb(new Error("destroy-also-blipped")));
|
|
};
|
|
const sess = { user: "someone@example.com" };
|
|
const outcome = await new Promise((resolve) => {
|
|
box.store.set("sid-destroy-err", sess, (err) => resolve({ err }));
|
|
});
|
|
|
|
assert.strictEqual(outcome.err, null, "even a failing re-destroy keeps the skip's success contract");
|
|
assert.strictEqual(sess[SYMBOL], "tombstone-read-error", "the signal is set before/independently of the destroy outcome");
|
|
assert.ok(
|
|
box.warnings.some((w) => w.includes("re-destroy errored")),
|
|
"the re-destroy failure keeps its existing warn"
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Structural pins: the distinguisher and its invariant
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("the wrapper distinguishes read-error from confirmed via the per-worker cache, on the set path only", () => {
|
|
const wrapper = guardSource;
|
|
assert.match(
|
|
wrapper,
|
|
/methodName === "set" &&\s*!isRevokedSidTombstoneCachedLocally\(sid\)/,
|
|
"the skip-reason distinguisher is revoked-without-local-cache (set path only)"
|
|
);
|
|
assert.match(
|
|
wrapper,
|
|
/try \{\s*Object\.defineProperty\(args\[1\], SESSION_STORE_WRITE_SKIPPED_SYMBOL, \{\s*value: SESSION_STORE_WRITE_SKIPPED_READ_ERROR,\s*enumerable: false,\s*\}\);/,
|
|
"the marker is installed through the non-enumerable defineProperty, inside a try/catch"
|
|
);
|
|
assert.match(wrapper, /adpanel:tombstone-skip-signal - a READ-ERROR skip must be/, "the constraint comment must document the distinguisher");
|
|
|
|
// The confirm-vs-error invariant the distinguisher depends on: the REAL
|
|
// checker populates the per-worker cache on EVERY confirmed verdict before
|
|
// returning true, and the fail-closed catch never caches.
|
|
const checker = extractRegion(
|
|
indexSource,
|
|
"async function isSessionSidRevoked(",
|
|
"const wrapSessionStoreWithTombstoneGuard"
|
|
);
|
|
assert.match(
|
|
checker,
|
|
/if \(hit\) \{\s*rememberRevokedSidTombstoneLocally\(id\);\s*return true;\s*\}/,
|
|
"every Redis-confirmed verdict must populate the local cache BEFORE returning true (the distinguisher's invariant)"
|
|
);
|
|
const catchStart = checker.indexOf("} catch (err) {");
|
|
assert.ok(catchStart >= 0, "the checker's catch block must exist");
|
|
const catchBody = checker.slice(catchStart);
|
|
assert.match(catchBody, /return redisClient \? failClosed : true;/, "the catch keeps the fail-closed default");
|
|
assert.ok(
|
|
!catchBody.slice(0, catchBody.indexOf("}")) .includes("rememberRevokedSidTombstoneLocally"),
|
|
"the read-error verdict must NOT populate the local cache (that is what makes revoked-without-cache mean read-error)"
|
|
);
|
|
});
|
|
|
|
test("the registry key is declared exactly once per file and the binder reads the same symbol", () => {
|
|
assert.strictEqual(
|
|
countOccurrences(guardSource, 'Symbol.for("adpanel:storeWriteSkipped")'),
|
|
1,
|
|
"exactly one Symbol.for site in the shared guard — never forked"
|
|
);
|
|
assert.strictEqual(
|
|
countOccurrences(binderSource, 'Symbol.for("adpanel:storeWriteSkipped")'),
|
|
1,
|
|
"exactly one Symbol.for site in the binder (the post-save check)"
|
|
);
|
|
assert.ok(
|
|
binderSource.includes('req.session?.[Symbol.for("adpanel:storeWriteSkipped")]'),
|
|
"the binder must read the marker off the live session object"
|
|
);
|
|
assert.match(
|
|
binderSource,
|
|
/session store write skipped \(\$\{storeWriteSkipReason\}\)/,
|
|
"the rethrown failure must carry the labeled skip reason"
|
|
);
|
|
// The check sits INSIDE the existing hygiene try: after the awaited save,
|
|
// before the catch — so the remember revoke + tombstone hygiene runs.
|
|
const saveAwaitIdx = binderSource.indexOf("req.session.save(cb)");
|
|
const checkIdx = binderSource.indexOf('Symbol.for("adpanel:storeWriteSkipped")');
|
|
const catchIdx = binderSource.indexOf("} catch (err) {");
|
|
assert.ok(saveAwaitIdx >= 0 && catchIdx > saveAwaitIdx, "the binder harness pins must keep their anchors");
|
|
assert.ok(checkIdx > saveAwaitIdx && checkIdx < catchIdx, "the post-save check must sit after the awaited save and before the hygiene catch");
|
|
});
|