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

+425
View File
@@ -0,0 +1,425 @@
"use strict";
// adpanel:ssh-gate-owner-binding / adpanel:ssh-gate-tombstone — source pins +
// behavior pins for sshTerminalCredentialActive.
//
// The SSH terminal token is a pivot into internal networks, so the websocket
// upgrade gate and the 60s live-recheck sweep re-derive liveness from the
// token's sid/uid on every use. A READABLE session record alone is not proof
// of liveness: the record must also (1) belong to the token's own uid, (2)
// still belong to the CURRENT account row via the ONE shared predicate
// sessionAccountBindingMismatch (utils/session-account-binding.js — the same
// id/epoch shape the HTTP session middleware and the Socket.IO handshake
// reject on), and (3) clear the revoked-sid tombstone consult (logout and
// suspension tombstone the sid BEFORE destroying the record, so a
// stale-but-readable record behind a tombstone must fail closed).
//
// Fail-open/fail-closed contract under test:
// - destroyed/missing record (sessionStore.get → null) → false (fail closed);
// - a PRESENT tombstone (local cache or Redis hit) → false (fail closed);
// - a Redis ERROR during the tombstone consult → the check fails OPEN (the
// read-path convention of isSessionSidRevoked, { failClosed: false }): an
// errored consult never CONFIRMS a revocation, and rejecting on it would
// mass-kill every legitimate live tunnel during a Redis blip — the same
// posture the HTTP revoked-sid gate and the Socket.IO handshake use;
// - store errors/expiry (the 5s bounded get), unknown users, DB errors,
// suspended accounts and accounts without entitlement stay fail closed.
//
// Pins held here:
// 1. Source: the extracted body references isSessionSidRevoked with the
// explicit { failClosed: false } read-path flag and
// sessionAccountBindingMismatch (the shared helpers are actually wired,
// not re-implemented); the 5s bounded store get stays; both call sites
// (upgrade gate + live-recheck sweep) await the ONE function, so they
// inherit every check by construction; the Socket.IO handshake keeps its
// own binding + tombstone pair (the sibling copy must not drift).
// 2. Behavior (vm-extracted sshTerminalCredentialActive AND the real
// isSessionSidRevoked, real utils/session-account-binding.js predicate):
// the matrix above, with fake sessionStore/redis/findUserByEmail.
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):
// skips // and /* */ comments so the adpanel: comment convention cannot
// desync the brace tracker.
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);
}
const GATE_SOURCE = extractBlock(indexSource, "async function sshTerminalCredentialActive(payload) {");
const REVOKE_SOURCE = extractBlock(indexSource, "async function isSessionSidRevoked(sid, { failClosed = true } = {}) {");
// ---------------------------------------------------------------------------
// Source pins — the shared helpers are wired, the posture is explicit
// ---------------------------------------------------------------------------
test("the gate body references the shared tombstone helper with the explicit read-path flag", () => {
assert.match(
GATE_SOURCE,
/isSessionSidRevoked\(sid,\s*\{\s*failClosed:\s*false\s*\}\)/,
"the tombstone consult must use the documented READ-path convention: a Redis ERROR must not mass-kill live tunnels, a PRESENT tombstone still fails closed"
);
assert.match(
GATE_SOURCE,
/if \(await isSessionSidRevoked\(/,
"the consult must gate the result (fail closed on a present tombstone)"
);
});
test("the gate body uses the ONE shared account-binding predicate, never a second comparison", () => {
assert.match(
GATE_SOURCE,
/sessionAccountBindingMismatch\(session,\s*user\)/,
"the id/epoch binding must come from utils/session-account-binding.js (the same shape the HTTP middleware and the Socket.IO handshake reject on)"
);
// No drifting parallel comparison: the body must not hand-roll its own
// accountId/accountEpoch arithmetic alongside the shared predicate.
assert.doesNotMatch(
GATE_SOURCE,
/session\.accountId|session\.accountEpoch/,
"the body must not read accountId/accountEpoch directly — that is the shared predicate's job"
);
assert.match(
indexSource,
/const \{[^{}]*\bsessionAccountBindingMismatch\b[^{}]*\} = require\("\.\/utils\/session-account-binding"\);/,
"index.js must import the shared predicate (no local re-definition)"
);
assert.doesNotMatch(
indexSource,
/function sessionAccountBindingMismatch\(/,
"no second, local definition of the predicate may exist"
);
});
test("the owner check precedes the tombstone consult, which precedes the user lookup + binding check", () => {
const ownerIdx = GATE_SOURCE.indexOf('session?.user');
const tombstoneIdx = GATE_SOURCE.indexOf("isSessionSidRevoked(sid");
const userLookupIdx = GATE_SOURCE.indexOf("findUserByEmail(uid)");
const bindingIdx = GATE_SOURCE.indexOf("sessionAccountBindingMismatch(session, user)");
assert.ok(ownerIdx >= 0 && tombstoneIdx > ownerIdx,
"a foreign record must be rejected before any Redis tombstone consult");
assert.ok(userLookupIdx > tombstoneIdx,
"the DB lookup must not run for a tombstoned sid");
assert.ok(bindingIdx > userLookupIdx,
"the binding predicate needs the resolved user row, so it follows the lookup");
});
test("the 5s bounded store get stays (fail closed on errors/expiry/timeouts)", () => {
assert.match(
GATE_SOURCE,
/await withTimeout\(new Promise\(\(resolve\) => \{/,
"the sessionStore.get must run inside the bounded promise"
);
assert.match(
GATE_SOURCE,
/try \{\s*\n\s*sessionStore\.get\(sid,/,
"the bounded read must wrap the store callback"
);
assert.match(GATE_SOURCE, /5000, "ssh-terminal-session-recheck-timeout"/,
"the 5s bound with its own label must stay (a wedged store must not hang the upgrade handshake or the sweep)");
assert.match(GATE_SOURCE, /\.catch\(\(\) => null\);\s*\n\s*if \(!session\) return false;/,
"a store error/timeout resolves to null and fails closed");
assert.match(GATE_SOURCE, /findUserByEmail\(uid\)\.catch\(\(\) => null\)/,
"DB lookup errors stay fail closed");
});
test("both call sites await the ONE gate function and inherit every check", () => {
const callSites = [...indexSource.matchAll(/await sshTerminalCredentialActive\(/g)].map((m) => m.index);
assert.strictEqual(callSites.length, 2,
"exactly the two known call sites: the websocket upgrade gate and the live-recheck sweep");
// Upgrade gate: rejects the upgrade on a false verdict.
const gateSite = indexSource.indexOf("if (!(await sshTerminalCredentialActive(payload))) {");
assert.ok(gateSite >= 0, "the upgrade gate call site must exist");
// Live-recheck sweep: destroys the tunnel when the verdict flips false.
const sweepSite = indexSource.indexOf("const active = await sshTerminalCredentialActive({ sid: payload.sid, uid: payload.uid });");
assert.ok(sweepSite >= 0, "the live-recheck sweep call site must exist");
});
test("the Socket.IO handshake keeps its own binding + tombstone pair (sibling copy must not drift)", () => {
// The handshake is the OTHER Socket.IO auth surface: it must reject on the
// same binding shape AND consult the tombstone with the same read-path
// flag. No fix was needed there (both checks already existed) — this pin
// keeps it that way.
const handshakeTag = indexSource.indexOf("// adpanel:session-account-binding — the handshake enforces the same");
assert.ok(handshakeTag >= 0, "the handshake's binding comment must exist");
const window = indexSource.slice(handshakeTag, handshakeTag + 2000);
assert.match(window, /sessionAccountBindingMismatch\(socket\.request\.session,\s*user\)/,
"the handshake must reject on the shared binding shape");
assert.match(window, /isSessionSidRevoked\(String\(socket\.request\.sessionID \|\| ""\),\s*\{\s*failClosed:\s*false\s*\}\)/,
"the handshake's tombstone consult must keep the read-path fail-open flag");
});
// ---------------------------------------------------------------------------
// Behavior pins — the real extracted functions against fakes
// ---------------------------------------------------------------------------
// Real race semantics (verbatim discipline from tests/remember-rotation-bounded.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));
}
// A withTimeout that RECORDS the requested bound but races at a capped
// latency, so the never-settling-store pin proves "timeout → false" without
// actually waiting 5s; the literal 5000 bound is pinned by the source test
// above.
function makeRecordingWithTimeout(captured) {
return (promise, ms, label) => {
captured.push({ ms, label });
return sandboxWithTimeout(promise, Math.min(ms, 120), label);
};
}
const ADMIN_EMAIL = "admin@panel.test";
const ADMIN_ROW = { id: 7, email: ADMIN_EMAIL, suspended: false, admin: true, agent_access: 0, session_epoch: 3 };
function buildHarness({
sessionRecord = null,
sessionGetError = null,
sessionGetSettles = true,
userRow = ADMIN_ROW,
redisGetImpl = async () => null,
redisClient = undefined,
localTombstones = new Set(),
withTimeout = sandboxWithTimeout,
} = {}) {
const storeGets = [];
const sessionStore = {
get(sid, cb) {
storeGets.push(sid);
if (!sessionGetSettles) return; // wedged store: the callback never fires
if (sessionGetError) return cb(sessionGetError, null);
cb(null, sessionRecord);
},
};
const userLookups = [];
const findUserByEmail = async (email) => {
userLookups.push(email);
if (userRow === null) return null;
return userRow;
};
const redisGets = [];
const resolvedRedis = redisClient === undefined
? {
get(key) {
redisGets.push(key);
return redisGetImpl(key);
},
}
: redisClient;
const tombstoneLocal = localTombstones;
const calls = { revocations: [] };
const isSessionSidRevoked = undefined; // resolved in the vm from REVOKE_SOURCE
const sandbox = {
console: { log: () => {}, warn: (...a) => { calls.warnings = calls.warnings || []; calls.warnings.push(a.map(String).join(" ")); } },
sessionStore,
findUserByEmail,
sessionAccountBindingMismatch: require("../utils/session-account-binding").sessionAccountBindingMismatch,
withTimeout,
// Real isSessionSidRevoked's closure dependencies (fakes with the same
// shape the index.js bindings have):
isRevokedSidTombstoneCachedLocally: (id) => tombstoneLocal.has(String(id)),
rememberRevokedSidTombstoneLocally: (id) => tombstoneLocal.add(String(id)),
getRevokedSidTombstoneRedisKey: (id) => `adpanel:revoked-sid-tombstone:${id}`,
getSessionDisplayId: (id) => String(id),
redisClient: resolvedRedis,
};
vm.createContext(sandbox);
const revokeFn = vm.runInContext(`(${REVOKE_SOURCE})`, sandbox, { filename: "revoke-sandbox.js" });
sandbox.isSessionSidRevoked = revokeFn;
const gateFn = vm.runInContext(`(${GATE_SOURCE})`, sandbox, { filename: "gate-sandbox.js" });
return {
gate: (payload) => gateFn(payload),
storeGets,
userLookups,
redisGets,
sandbox,
calls,
};
}
function liveSession(overrides = {}) {
return {
user: ADMIN_EMAIL,
accountId: 7,
accountEpoch: 3,
cookie: { httpOnly: true },
...overrides,
};
}
test("a readable-but-tombstoned session fails closed", async () => {
const h = buildHarness({ sessionRecord: liveSession(), redisGetImpl: async () => "1" });
assert.strictEqual(await h.gate({ sid: "sess-tombstoned", uid: ADMIN_EMAIL }), false,
"a PRESENT tombstone must fail closed even though the record is still readable");
assert.strictEqual(h.redisGets.length, 1, "the tombstone layer must actually be consulted");
assert.ok(h.redisGets[0].endsWith(":sess-tombstoned"), "the consult must use the sid's tombstone key");
});
test("a destroyed record (store get → null) fails closed before any tombstone consult", async () => {
const h = buildHarness({ sessionRecord: null, redisGetImpl: async () => { throw new Error("should not be consulted"); } });
assert.strictEqual(await h.gate({ sid: "sess-destroyed", uid: ADMIN_EMAIL }), false,
"the destroyed record fails the null check — the fail-closed base layer");
assert.strictEqual(h.redisGets.length, 0,
"no Redis consult may run for a record that is already gone");
});
test("a session record belonging to a different user fails closed", async () => {
const h = buildHarness({ sessionRecord: liveSession({ user: "someone-else@panel.test" }) });
assert.strictEqual(await h.gate({ sid: "sess-foreign", uid: ADMIN_EMAIL }), false,
"a foreign/stale record must not lend this token SSH authority");
assert.strictEqual(h.userLookups.length, 0,
"the owner gate precedes the DB lookup — no user row is resolved for a foreign record");
});
test("the owner comparison is case-insensitive (session.user and payload uid are emails)", async () => {
const h = buildHarness({ sessionRecord: liveSession({ user: ADMIN_EMAIL.toUpperCase() }) });
assert.strictEqual(await h.gate({ sid: "sess-live", uid: ADMIN_EMAIL }), true,
"the same email in different case is the same owner — the gate must pass on the happy path");
});
test("an accountId binding mismatch (stale record under a recreated account) fails closed", async () => {
const h = buildHarness({ sessionRecord: liveSession({ accountId: 8 }) });
assert.strictEqual(await h.gate({ sid: "sess-stale-id", uid: ADMIN_EMAIL }), false,
"the shared predicate must reject a session bound to another account row");
assert.strictEqual(h.userLookups.length, 1, "the binding check runs after the row resolves");
});
test("an accountEpoch binding mismatch (session minted before the current epoch) fails closed", async () => {
const h = buildHarness({ sessionRecord: liveSession({ accountEpoch: 2 }) });
assert.strictEqual(await h.gate({ sid: "sess-stale-epoch", uid: ADMIN_EMAIL }), false,
"the shared predicate must reject a stale epoch");
});
test("sessions minted before accountId/accountEpoch existed pass (covered by the revocation sweep)", async () => {
const h = buildHarness({ sessionRecord: liveSession({ accountId: undefined, accountEpoch: undefined }) });
assert.strictEqual(await h.gate({ sid: "sess-legacy", uid: ADMIN_EMAIL }), true,
"the shared predicate's documented legacy-session pass-through is inherited, not re-decided here");
});
test("an unknown user, a suspended account and a revoked entitlement all fail closed", async () => {
const unknown = buildHarness({ sessionRecord: liveSession(), userRow: null });
assert.strictEqual(await unknown.gate({ sid: "sess-u1", uid: ADMIN_EMAIL }), false, "unknown user → false");
const suspended = buildHarness({ sessionRecord: liveSession(), userRow: { ...ADMIN_ROW, suspended: true } });
assert.strictEqual(await suspended.gate({ sid: "sess-u2", uid: ADMIN_EMAIL }), false, "suspended → false");
const demoted = buildHarness({ sessionRecord: liveSession(), userRow: { ...ADMIN_ROW, admin: false } });
assert.strictEqual(await demoted.gate({ sid: "sess-u3", uid: ADMIN_EMAIL }), false,
"no admin and no agent_access → the entitlement predicate fails closed");
});
test("a Redis ERROR during the tombstone consult fails OPEN (read-path convention): the live tunnel survives", async () => {
const h = buildHarness({
sessionRecord: liveSession(),
redisGetImpl: async () => { throw new Error("redis down"); },
});
assert.strictEqual(await h.gate({ sid: "sess-live", uid: ADMIN_EMAIL }), true,
"an errored consult never CONFIRMS a revocation — it must not mass-kill live tunnels");
assert.strictEqual(h.redisGets.length, 1, "the consult ran and errored");
assert.ok((h.calls.warnings || []).some((w) => w.includes("failing open")),
"the real helper warns with its documented failing-open wording");
});
test("a tombstone hit in the worker-local cache fails closed without touching Redis", async () => {
const h = buildHarness({
sessionRecord: liveSession(),
localTombstones: new Set(["sess-cached"]),
});
assert.strictEqual(await h.gate({ sid: "sess-cached", uid: ADMIN_EMAIL }), false,
"the local fast path is authoritative for a PRESENT tombstone");
assert.strictEqual(h.redisGets.length, 0, "no Redis round-trip needed for a local tombstone hit");
});
test("the tombstone consult is wired with the read-path flag end-to-end", async () => {
// With the REAL extracted isSessionSidRevoked, a rejecting Redis + default
// failClosed would return false here. The gate passing proves the call
// site really passes { failClosed: false } (the source pin holds it in
// place; this proves it executes).
const h = buildHarness({
sessionRecord: liveSession(),
redisGetImpl: async () => { throw new Error("redis down"); },
});
assert.strictEqual(await h.gate({ sid: "sess-live", uid: ADMIN_EMAIL }), true);
});
test("a wedged store times out inside the bound and fails closed (5s bound preserved)", async () => {
const captured = [];
const h = buildHarness({
sessionGetSettles: false,
withTimeout: makeRecordingWithTimeout(captured),
});
const started = Date.now();
assert.strictEqual(await h.gate({ sid: "sess-wedged", uid: ADMIN_EMAIL }), false,
"a store that never settles must fail closed, not hang the handshake or the sweep");
assert.ok(Date.now() - started < 2000, `the bound must actually fire (elapsed ${Date.now() - started}ms)`);
assert.deepStrictEqual(captured, [{ ms: 5000, label: "ssh-terminal-session-recheck-timeout" }],
"the gate must keep requesting its own 5s bound under the documented label");
});
test("degenerate payloads fail closed without touching the store", async () => {
const h = buildHarness({ sessionRecord: liveSession() });
assert.strictEqual(await h.gate({ sid: "", uid: ADMIN_EMAIL }), false, "empty sid → false");
assert.strictEqual(await h.gate({ sid: "sess-x", uid: "" }), false, "empty uid → false");
assert.strictEqual(await h.gate(null), false, "no payload → false");
assert.strictEqual(h.storeGets.length, 0, "no store read for degenerate payloads");
const noStore = buildHarness({ sessionRecord: liveSession() });
noStore.sandbox.sessionStore = undefined;
// Re-extract a fresh gate against the mutated sandbox: the gate reads the
// sandbox global directly, so a second run proves the unavailable-store
// guard without a second extraction of the source.
const gateFn2 = vm.runInContext(`(${GATE_SOURCE})`, noStore.sandbox, { filename: "gate-sandbox2.js" });
assert.strictEqual(await gateFn2({ sid: "sess-y", uid: ADMIN_EMAIL }), false,
"an unavailable session store must fail closed");
});