Initial upload to Gitea

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

No files matched your search

+384
View File
@@ -0,0 +1,384 @@
"use strict";
// adpanel:credential-session-rebind — behavior pins for the ONE shared
// post-credential-change session rebind (utils/credential-session-rebind.js).
//
// The constraint under test: after an interactive credential change NO copy
// of any pre-change session may survive — including the caller's OWN sid —
// and the owner ends up re-bound onto a freshly regenerated session with a
// forceFreshId remember re-issue, while a failure after the remember mint
// must not leave a live 365-day credential behind (the login binder's
// post-mint hygiene, mirrored here).
//
// Unlike the login binder (pinned by tests/login-session-bind-module.test.js
// against its index.js wiring), this module is exercised directly through
// its factory with fake req/res/session objects and fake deps, so every step
// of the sequence and its ordering is observable without booting index.js.
const test = require("node:test");
const assert = require("node:assert");
const { createCredentialSessionRebinder } = require("./credential-session-rebind.js");
// ---------------------------------------------------------------------------
// Fakes
// ---------------------------------------------------------------------------
// Faithful express-session model: regenerate() destroys the old store record,
// mints a new sid and WIPES the session data (the behavior the rebinder's
// identity re-bind must survive); save() persists under the current sid.
function makeReqRes({ sid = "old-sid", sessionUser = "user@example.test", saveError = null, regenerateNeverSettles = false, calls } = {}) {
const events = [];
const log = calls || events; // share one ordering log with the fake deps when asked
const store = new Map([[sid, { user: sessionUser }]]);
const req = {
sessionID: sid,
headers: { "user-agent": "test-agent" },
session: {
user: sessionUser,
accountId: 7,
accountEpoch: 3,
rememberLoginId: "revoked-old-id",
regenerate(cb) {
log.push(["regenerate", req.sessionID]);
if (regenerateNeverSettles) return; // hung store callback — never reports
store.delete(req.sessionID);
req.sessionID = `new-${req.sessionID}`;
for (const key of Object.keys(req.session)) {
if (key !== "regenerate" && key !== "save") delete req.session[key];
}
store.set(req.sessionID, {});
cb(null);
},
save(cb) {
log.push(["save", req.sessionID]);
if (saveError) return cb(saveError);
cb(null);
},
},
};
const res = { cookies: [], cleared: [] };
res.cookie = (name, value, opts) => res.cookies.push({ name, value, opts });
res.clearCookie = (name, opts) => res.cleared.push({ name, opts });
return { req, res, events, store };
}
// Fake deps recording every call with an ordering log. `mintedId` is written
// onto the session by setRememberLoginCookie exactly like the real chain
// (ensureRememberLoginSessionId inside issueRememberLoginToken).
function makeDeps(overrides = {}) {
const calls = [];
const deps = {
// Real semantics, but the module's 5s constants are not shortened here —
// timeout behavior is tested with an injected bounded withTimeout below.
withTimeout: (promise) => Promise.resolve(promise).then((v) => v),
destroyBrowserSessionsForUser: async (user) => {
calls.push(["destroy", user && user.email, user && user.id]);
return { destroyed: 2, rememberLoginsRevoked: 1, errors: [] };
},
writeRevokedSidTombstone: async (sid) => {
calls.push(["tombstone", sid]);
return true;
},
getSessionDisplayId: (sid) => `display(${sid})`,
// Real semantics: ensure WRITES the ensured id into the session when it
// is absent (a freshly regenerated session is always absent) and returns
// it — the audit rebuild consumes exactly this id.
ensureRememberLoginSessionId: (req) => {
calls.push(["remember-id"]);
if (!req.session.rememberLoginId) req.session.rememberLoginId = "ensured-1";
return req.session.rememberLoginId;
},
buildBrowserSessionAuditFromRequest: (req, email, rememberLoginId) => {
calls.push(["audit", email, rememberLoginId]);
return { email, rememberLoginId, userAgent: req.headers["user-agent"] };
},
setRememberLoginCookie: (req, res, user, options) => {
calls.push(["mint", user && user.email, user && user.password, options]);
req.session.rememberLoginId = "minted-1";
return 4102444800000;
},
markRememberLoginSessionFresh: (req, expiresAt) => {
calls.push(["fresh", expiresAt]);
},
upsertActiveBrowserSessionCacheEntry: (sid) => {
calls.push(["upsert", sid]);
},
clearRememberLoginCookie: (req, res) => {
calls.push(["clearCookie"]);
},
revokeRememberLoginRegistryEntry: async (id) => {
calls.push(["revoke", id]);
return true;
},
logger: { warn: (msg) => calls.push(["warn", msg]) },
...overrides,
};
return { deps, calls };
}
const USER = { id: 42, email: "user@example.test", password: "hashed-new", secret: "S3CRET", session_epoch: 3 };
// Bounded withTimeout used for the timeout tests: same race shape as the
// real helper, but a short overridden window so the test stays fast while
// the labeled rejection still propagates.
function testWithTimeout(msOverride) {
return (promise, _ms, label) =>
Promise.race([
Promise.resolve(promise),
new Promise((_, reject) => setTimeout(() => reject(new Error(label)), msOverride)),
]);
}
// ---------------------------------------------------------------------------
// Construction
// ---------------------------------------------------------------------------
test("construction fails closed on every missing dep", () => {
const required = [
"withTimeout",
"destroyBrowserSessionsForUser",
"writeRevokedSidTombstone",
"getSessionDisplayId",
"ensureRememberLoginSessionId",
"buildBrowserSessionAuditFromRequest",
"setRememberLoginCookie",
"markRememberLoginSessionFresh",
"upsertActiveBrowserSessionCacheEntry",
"clearRememberLoginCookie",
"revokeRememberLoginRegistryEntry",
];
for (const missing of required) {
const { deps } = makeDeps();
delete deps[missing];
assert.throws(
() => createCredentialSessionRebinder(deps),
(err) => err.message.includes(missing) && err.message.includes("createCredentialSessionRebinder"),
`missing ${missing} must fail construction loudly`
);
}
// The complete set constructs and returns the named-method object contract.
const { deps } = makeDeps();
const rebinder = createCredentialSessionRebinder(deps);
assert.equal(typeof rebinder.rebindOwnerSession, "function", "the factory returns an object carrying rebindOwnerSession");
});
// ---------------------------------------------------------------------------
// Happy path
// ---------------------------------------------------------------------------
test("happy path: destroy without exclusion, pre-sid tombstone, regenerate, identity re-bind, audit rebuild, forceFreshId mint, fresh mark, cache upsert, bounded save — in order", async () => {
const { deps, calls } = makeDeps();
const rebinder = createCredentialSessionRebinder(deps);
const { req, res, store } = makeReqRes({ calls });
const result = await rebinder.rebindOwnerSession(req, res, { user: USER });
// The user-wide destroy ran with NO options object at all — no
// excludeSessionId may ever reach it (the whole point of the rebinder).
assert.deepEqual(calls.find((c) => c[0] === "destroy"), ["destroy", "user@example.test", 42]);
const destroyCall = calls.filter((c) => c[0] === "destroy");
assert.equal(destroyCall.length, 1);
// The caller's own pre-regeneration sid was tombstoned explicitly (the
// destroyer's cache-based scan can miss it).
assert.ok(calls.some((c) => c[0] === "tombstone" && c[1] === "old-sid"), "the pre-regeneration sid must be tombstoned");
// The session was regenerated (new sid in the store, old one gone) and the
// identity re-bound onto the fresh session object.
assert.equal(req.sessionID, "new-old-sid");
assert.equal(store.has("old-sid"), false, "the old store record must be destroyed by the regenerate");
assert.equal(req.session.user, "user@example.test");
assert.equal(req.session.accountId, 42);
assert.equal(req.session.accountEpoch, 3);
// The audit rebuild mirrors the login binder: the remember id is ensured
// first and the audit object is rebuilt FROM it onto the regenerated
// session (which the regenerate wiped).
assert.ok(calls.some((c) => c[0] === "remember-id"), "the remember id is ensured before the mint");
assert.deepEqual(
calls.find((c) => c[0] === "audit"),
["audit", "user@example.test", "ensured-1"],
"the audit is built from the request and the ensured remember id"
);
assert.deepEqual(
req.session.browserSessionAudit,
{ email: "user@example.test", rememberLoginId: "ensured-1", userAgent: "test-agent" },
"the regenerated session carries the rebuilt audit object"
);
// The remember re-issue carries forceFreshId and the post-change material.
assert.deepEqual(
calls.find((c) => c[0] === "mint"),
["mint", "user@example.test", "hashed-new", { forceFreshId: true }]
);
assert.deepEqual(calls.find((c) => c[0] === "fresh"), ["fresh", 4102444800000], "the freshness mark consumes the mint's expiry");
// Cache upsert + save target the REGENERATED sid.
assert.deepEqual(calls.find((c) => c[0] === "upsert"), ["upsert", "new-old-sid"]);
assert.ok(calls.some((c) => c[0] === "save" && c[1] === "new-old-sid"));
// Step ordering: destroy -> tombstone -> regenerate -> ensure/audit -> mint -> upsert -> save.
const order = calls.map((c) => c[0]);
const idx = (step) => order.indexOf(step);
assert.ok(idx("destroy") < idx("tombstone"), "destroy runs before the explicit tombstone");
assert.ok(idx("tombstone") < idx("regenerate"), "the tombstone lands before the regenerate");
assert.ok(idx("regenerate") < idx("remember-id"), "the audit rebuild happens only after the regenerate (the wipe is why it exists)");
assert.ok(idx("remember-id") < idx("audit"), "the audit consumes the ensured remember id");
assert.ok(idx("audit") < idx("mint"), "the audit rebuild lands before the mint (the forceFreshId audit re-sync consumes it)");
assert.ok(idx("regenerate") < idx("mint"), "the mint happens only after the regenerate");
assert.ok(idx("mint") < idx("upsert"), "cache upsert after the mint");
assert.ok(idx("upsert") < order.lastIndexOf("save"), "save last");
// The destroy result is returned so routes keep their response fields.
assert.deepEqual(result.sessionInvalidation, { destroyed: 2, rememberLoginsRevoked: 1, errors: [] });
// No hygiene on success: nothing cleared, nothing revoked.
assert.equal(calls.filter((c) => c[0] === "clearCookie").length, 0);
assert.equal(calls.filter((c) => c[0] === "revoke").length, 0);
});
test("destroyAs overrides only the destroy identity (email change: destroy old, rebind new)", async () => {
const { deps, calls } = makeDeps();
const rebinder = createCredentialSessionRebinder(deps);
const { req, res } = makeReqRes();
const NEW_USER = { ...USER, email: "new@example.test" };
const OLD_IDENTITY = { ...USER, email: "old@example.test" };
await rebinder.rebindOwnerSession(req, res, { user: NEW_USER, destroyAs: OLD_IDENTITY });
assert.deepEqual(calls.find((c) => c[0] === "destroy"), ["destroy", "old@example.test", 42], "the sweep must match the OLD email identity");
assert.equal(req.session.user, "new@example.test", "the session re-binds to the NEW email");
assert.deepEqual(
calls.find((c) => c[0] === "mint"),
["mint", "new@example.test", "hashed-new", { forceFreshId: true }],
"the remember re-issue mints against the NEW identity"
);
});
test("a refused mint (no expiry) leaves nothing to clean up and still completes the rebind", async () => {
const { deps, calls } = makeDeps({
setRememberLoginCookie: (req, res, user, options) => {
calls.push(["mint", options]);
// Real bail-out shape (remote-proxy-trust gate): no session write, no expiry.
return undefined;
},
});
const rebinder = createCredentialSessionRebinder(deps);
const { req, res } = makeReqRes({ calls });
const result = await rebinder.rebindOwnerSession(req, res, { user: USER });
assert.ok(calls.some((c) => c[0] === "save"), "the rebind still completes");
assert.equal(calls.filter((c) => c[0] === "revoke").length, 0, "no minted id, nothing to revoke");
assert.equal(calls.filter((c) => c[0] === "clearCookie").length, 0);
assert.deepEqual(result.sessionInvalidation.destroyed, 2);
// Conscious pin update (the audit rebuild): the ensure now runs BEFORE the
// mint, so the ensured lineage id legitimately stays on the session even
// when the mint is refused — it is bookkeeping, not a credential: no
// cookie, no registry entry, nothing revocable, and never the revoked id
// (the regenerate wiped the session, so the ensure can only mint fresh).
// The invariant is unchanged: a refused mint leaves no LIVE remember
// credential riding the rebind.
assert.notEqual(req.session.rememberLoginId, "revoked-old-id", "a refused mint must never resurrect the revoked id");
assert.equal(req.session.rememberLoginId, "ensured-1", "only the inert ensured lineage id remains (no minted id, nothing to revoke)");
});
// ---------------------------------------------------------------------------
// Post-mint failure hygiene
// ---------------------------------------------------------------------------
test("save failure: minted cookie cleared, minted registry id revoked, regenerated sid tombstoned, ORIGINAL error rethrown", async () => {
const originalError = new Error("store blew up");
const { deps, calls } = makeDeps();
const rebinder = createCredentialSessionRebinder(deps);
const { req, res } = makeReqRes({ saveError: originalError });
await assert.rejects(
rebinder.rebindOwnerSession(req, res, { user: USER }),
(err) => err === originalError,
"the original error must propagate for the route's existing 500 handling"
);
assert.ok(calls.some((c) => c[0] === "clearCookie"), "the just-minted remember cookie must be cleared");
assert.deepEqual(calls.find((c) => c[0] === "revoke"), ["revoke", "minted-1"], "the just-minted registry id must be revoked");
assert.ok(calls.some((c) => c[0] === "tombstone" && c[1] === "new-old-sid"), "the REGENERATED sid must be tombstoned (late store write protection)");
});
test("a skipped store write (tombstone guard signal) is converted into the labeled failure with full hygiene", async () => {
const skipSymbol = Symbol.for("adpanel:storeWriteSkipped");
const { deps, calls } = makeDeps();
const rebinder = createCredentialSessionRebinder(deps);
const { req, res } = makeReqRes();
// The save "succeeds" but marks the session the way the store's tombstone
// guard reports a refused write.
req.session.save = (cb) => {
req.session[skipSymbol] = "tombstone read error";
cb(null);
};
await assert.rejects(
rebinder.rebindOwnerSession(req, res, { user: USER }),
(err) => err.message.includes("session store write skipped")
);
assert.ok(calls.some((c) => c[0] === "clearCookie"), "hygiene runs on the false-success path too");
assert.ok(calls.some((c) => c[0] === "revoke" && c[1] === "minted-1"));
assert.ok(calls.some((c) => c[0] === "tombstone" && c[1] === "new-old-sid"));
});
test("regenerate timeout fails closed: no mint, no save, labeled error propagates", async () => {
const { deps, calls } = makeDeps({ withTimeout: testWithTimeout(20) });
const rebinder = createCredentialSessionRebinder(deps);
const { req, res } = makeReqRes({ regenerateNeverSettles: true });
await assert.rejects(
rebinder.rebindOwnerSession(req, res, { user: USER }),
(err) => err.message === "session-regenerate-timeout",
"a hung store regenerate must fail the rebind closed with the binder's label"
);
assert.equal(calls.filter((c) => c[0] === "mint").length, 0, "nothing minted on a regenerate failure");
assert.equal(calls.filter((c) => c[0] === "save").length, 0, "no save attempted");
assert.equal(calls.filter((c) => c[0] === "revoke").length, 0, "nothing to revoke");
assert.equal(calls.filter((c) => c[0] === "clearCookie").length, 0);
// The pre-regeneration tombstone DID happen (before the regenerate).
assert.ok(calls.some((c) => c[0] === "tombstone" && c[1] === "old-sid"));
});
test("save timeout fails closed with full post-mint hygiene", async () => {
const { deps, calls } = makeDeps({ withTimeout: testWithTimeout(20) });
const rebinder = createCredentialSessionRebinder(deps);
const { req, res } = makeReqRes();
req.session.save = () => {}; // hung store save — never reports
await assert.rejects(
rebinder.rebindOwnerSession(req, res, { user: USER }),
(err) => err.message === "session-save-timeout"
);
assert.ok(calls.some((c) => c[0] === "clearCookie"), "minted cookie cleared on the timeout path");
assert.ok(calls.some((c) => c[0] === "revoke" && c[1] === "minted-1"), "minted registry id revoked");
assert.ok(calls.some((c) => c[0] === "tombstone" && c[1] === "new-old-sid"), "regenerated sid tombstoned");
});
test("a pre-regeneration tombstone that is not durable warns and still rebinds (destroy already swept the cache-visible copies)", async () => {
const { deps, calls } = makeDeps({
writeRevokedSidTombstone: async (sid) => {
calls.push(["tombstone", sid]);
return sid !== "old-sid"; // the pre-regeneration tombstone fails
},
});
const rebinder = createCredentialSessionRebinder(deps);
const { req, res } = makeReqRes({ calls });
const result = await rebinder.rebindOwnerSession(req, res, { user: USER });
assert.ok(calls.some((c) => c[0] === "warn" && c[1].includes("display(old-sid)")), "the display-id helper renders the warning (never a raw sid)");
assert.ok(calls.some((c) => c[0] === "save"), "the rebind still completes");
assert.deepEqual(result.sessionInvalidation.destroyed, 2);
});