Files
Kelx/tests/ssh-terminal-window-per-tab.test.js
2026-11-30 16:32:37 +00:00

341 lines
17 KiB
JavaScript

"use strict";
// Tests for the SSH terminal window per-tab state split and the per-user
// concurrency caps (client storage + panel upgrade gate + sshterm service).
//
// Bug (client): closeTerminal() used to write { open: false, sessionId: "" }
// into the single shared adpanel:ssh-terminal-window:v1 localStorage record,
// so closing the terminal in one tab broke auto-restore in every other tab:
// after the next navigation their still-live terminals vanished (no restore)
// and their stored session id was gone, so even a manual click started a
// brand-new session instead of re-attaching to the still-live one the server
// explicitly keeps alive for the remaining viewers. The fix splits the state:
// ownership fields (open/minimized/sessionId/live) live in per-tab
// sessionStorage; the shared localStorage record keeps geometry and a
// "last live session" hint (sessionId/live) so a tab that has never opened a
// terminal here can still attach to another tab's live session. A one-time
// migration adopts a legacy shared record into the tab store so in-flight
// terminals survive the deploy.
//
// Hardening (server): concurrent connects were unbounded per owner. The
// sshterm service now reserves one slot per owner before dialing SSH
// (SSH_TERM_MAX_SESSIONS_PER_USER, default 4) and the panel's upgrade gate
// reserves one slot per uid before its async credential recheck
// (SSH_TERMINAL_MAX_TUNNELS_PER_USER = 8), both released exactly once on the
// socket/session teardown path. The behavioral tests below exercise the
// extracted slot accounting and storage routing; the wiring (reserve before
// dial/await, release on the single close teardown point) is locked with
// source assertions, same technique as the other audit tests.
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 CLIENT_JS = path.join(ROOT, "public", "js", "ssh-terminal-window.js");
const CLIENT_MIN_JS = path.join(ROOT, "public", "js", "ssh-terminal-window.min.js");
const INDEX_JS = path.join(ROOT, "index.js");
const clientSource = fs.readFileSync(CLIENT_JS, "utf8");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
function sliceBetween(source, startMarker, endMarker, label) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `${label}: start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start);
assert.ok(end > start, `${label}: end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
// ---------------------------------------------------------------------------
// Browser storage emulation + evaluation of the client's storage layer
// ---------------------------------------------------------------------------
function makeStorageBackend() {
const map = new Map();
return {
getItem: (key) => (map.has(key) ? map.get(key) : null),
setItem: (key, value) => { map.set(key, String(value)); },
removeItem: (key) => { map.delete(key); },
clear: () => map.clear(),
map: map,
};
}
// The slice spans the storage constants, the module-level window handles and
// every storage helper up to viewport() — none of which touch the DOM at
// evaluation time (matchMedia is absent on the fake window by design).
const storageLayerSlice = sliceBetween(
clientSource,
'const STORAGE_KEY = "adpanel:ssh-terminal-window:v1";',
"function viewport()",
"client storage layer"
);
function makeClientStorage(opts = {}) {
const fakeWindow = { };
if (!opts.throwingSession) fakeWindow.sessionStorage = makeStorageBackend();
if (!opts.throwingLocal) fakeWindow.localStorage = makeStorageBackend();
const layer = new Function(
"window",
`"use strict";\n${storageLayerSlice}\nreturn { readTabState, writeTabState, readSharedState, writeSharedState, readState, writeState, migrateLegacySharedState, isValidSessionId };`
)(fakeWindow);
return { layer, session: fakeWindow.sessionStorage, local: fakeWindow.localStorage };
}
test("client storage: ownership fields route to sessionStorage, geometry to localStorage", () => {
const { layer, session, local } = makeClientStorage();
layer.writeState({
open: true,
minimized: true,
sessionId: "session-abc12345",
live: true,
x: 10,
y: 20,
w: 800,
h: 600,
});
const tab = JSON.parse(session.getItem("adpanel:ssh-terminal-window:tab:v1"));
assert.strictEqual(tab.open, true);
assert.strictEqual(tab.minimized, true);
assert.strictEqual(tab.sessionId, "session-abc12345");
assert.strictEqual(tab.live, true);
const shared = JSON.parse(local.getItem("adpanel:ssh-terminal-window:v1"));
assert.strictEqual(shared.x, 10);
assert.strictEqual(shared.w, 800);
// The ownership fields must NOT leak back into the shared record — that is
// exactly the global-flip bug this split removes.
assert.ok(!("open" in shared));
assert.ok(!("minimized" in shared));
assert.ok(!("sessionId" in shared));
assert.ok(!("live" in shared));
});
test("client storage: merged read lets the tab record win and the shared record fall back", () => {
const { layer } = makeClientStorage();
// Shared hint only (a tab that never opened here): merged read exposes it.
layer.writeSharedState({ sessionId: "session-live9999", live: true });
let merged = layer.readState();
assert.strictEqual(merged.sessionId, "session-live9999");
assert.strictEqual(merged.live, true);
assert.strictEqual(merged.open, undefined);
// Once the tab owns a record, its values override the hint — including an
// explicit empty sessionId left by closeTerminal.
layer.writeTabState({ open: true, sessionId: "", live: false });
merged = layer.readState();
assert.strictEqual(merged.sessionId, "");
assert.strictEqual(merged.live, false);
assert.strictEqual(merged.open, true);
});
test("client storage: migration adopts a legacy shared record once, then strips it", () => {
const { layer, session, local } = makeClientStorage();
layer.writeSharedState({
open: true,
minimized: true,
sessionId: "session-legacy123",
live: true,
x: 42,
});
layer.migrateLegacySharedState();
const tab = JSON.parse(session.getItem("adpanel:ssh-terminal-window:tab:v1"));
assert.strictEqual(tab.open, true);
assert.strictEqual(tab.minimized, true);
assert.strictEqual(tab.sessionId, "session-legacy123");
assert.strictEqual(tab.live, true);
const shared = JSON.parse(local.getItem("adpanel:ssh-terminal-window:v1"));
assert.ok(!("open" in shared) && !("minimized" in shared));
assert.strictEqual(shared.x, 42);
// The remaining sessionId/live pair is now purely the last-live hint.
assert.strictEqual(shared.sessionId, "session-legacy123");
// Second run is a no-op (no legacy fields left).
layer.writeTabState({ open: false, sessionId: "" });
layer.migrateLegacySharedState();
const tabAgain = JSON.parse(session.getItem("adpanel:ssh-terminal-window:tab:v1"));
assert.strictEqual(tabAgain.open, false);
});
test("client storage: migration never clobbers a tab that already owns its state", () => {
const { layer } = makeClientStorage();
layer.writeTabState({ open: false, minimized: false, sessionId: "", live: false });
layer.writeSharedState({ open: true, minimized: true, sessionId: "session-legacy123", live: true });
layer.migrateLegacySharedState();
const merged = layer.readState();
// The tab explicitly closed its window; a legacy open:true must not
// resurrect it here.
assert.strictEqual(merged.open, false);
assert.strictEqual(merged.sessionId, "");
});
test("client storage: migration keeps a closed legacy record from restoring", () => {
const { layer, session } = makeClientStorage();
layer.writeSharedState({ open: false, minimized: false, sessionId: "", live: false });
layer.migrateLegacySharedState();
assert.strictEqual(session.getItem("adpanel:ssh-terminal-window:tab:v1"), null, "a closed legacy record must not be adopted");
assert.strictEqual(layer.readState().open, undefined, "no adoption means no auto-restore");
assert.ok(!("open" in layer.readSharedState()), "legacy ownership fields must be stripped either way");
});
test("client storage: blocked or throwing storage degrades to an empty record", () => {
const throwing = makeClientStorage({ throwingSession: true, throwingLocal: true });
assert.doesNotThrow(() => throwing.layer.writeState({ open: true }));
assert.deepStrictEqual(throwing.layer.readState(), {});
assert.doesNotThrow(() => throwing.layer.migrateLegacySharedState());
});
test("client storage: isValidSessionId mirrors the server's normalization shape", () => {
const { layer } = makeClientStorage();
assert.strictEqual(layer.isValidSessionId("5f0c9a1e-2b7d-4e08-9c11-aa22bb33cc44"), true);
assert.strictEqual(layer.isValidSessionId("session-1a2b3c-xyz:9"), true);
assert.strictEqual(layer.isValidSessionId(""), false);
assert.strictEqual(layer.isValidSessionId("short"), false);
assert.strictEqual(layer.isValidSessionId("has space 12345"), false);
assert.strictEqual(layer.isValidSessionId("invalid$char-123"), false);
assert.strictEqual(layer.isValidSessionId(12345678901234), false);
});
// ---------------------------------------------------------------------------
// The two server-side slot accountings, evaluated from their live source
// ---------------------------------------------------------------------------
const tunnelSlotSlice = sliceBetween(
indexSource,
"const SSH_TERMINAL_MAX_TUNNELS_PER_USER = 8;",
"function evictSshTerminalTokenCacheForUser",
"panel tunnel slot layer"
);
const tunnelSlots = new Function(
`"use strict";\n${tunnelSlotSlice}\nreturn { reserveSshTerminalTunnelSlot, releaseSshTerminalTunnelSlot, SSH_TERMINAL_MAX_TUNNELS_PER_USER };`
)();
test("panel tunnel cap: reservations are capped per uid at SSH_TERMINAL_MAX_TUNNELS_PER_USER", () => {
assert.strictEqual(tunnelSlots.SSH_TERMINAL_MAX_TUNNELS_PER_USER, 8);
const uid = "cap-test@example.com";
for (let i = 0; i < 8; i += 1) {
assert.strictEqual(tunnelSlots.reserveSshTerminalTunnelSlot(uid), true, `reservation ${i + 1} must succeed`);
}
assert.strictEqual(tunnelSlots.reserveSshTerminalTunnelSlot(uid), false, "the 9th concurrent tunnel must be refused");
// Independent owners are unaffected.
assert.strictEqual(tunnelSlots.reserveSshTerminalTunnelSlot("other@example.com"), true);
tunnelSlots.releaseSshTerminalTunnelSlot("other@example.com");
for (let i = 0; i < 8; i += 1) tunnelSlots.releaseSshTerminalTunnelSlot(uid);
assert.strictEqual(tunnelSlots.reserveSshTerminalTunnelSlot(uid), true, "releases must free the slots again");
tunnelSlots.releaseSshTerminalTunnelSlot(uid);
});
test("panel tunnel cap: uid keys are normalized (trimmed, lowercased) and empty uids are refused", () => {
const uid = "case-test@example.com";
assert.strictEqual(tunnelSlots.reserveSshTerminalTunnelSlot(` ${uid.toUpperCase()} `), true);
// Same bucket after normalization: the cap is per real user, not per
// spelling of the email.
assert.strictEqual(tunnelSlots.reserveSshTerminalTunnelSlot(uid), true);
assert.strictEqual(tunnelSlots.reserveSshTerminalTunnelSlot(""), false);
assert.strictEqual(tunnelSlots.reserveSshTerminalTunnelSlot(" "), false);
assert.strictEqual(tunnelSlots.reserveSshTerminalTunnelSlot(null), false);
// Over-release floors at zero and never grants extra capacity.
tunnelSlots.releaseSshTerminalTunnelSlot(uid);
tunnelSlots.releaseSshTerminalTunnelSlot(uid);
tunnelSlots.releaseSshTerminalTunnelSlot(uid);
for (let i = 0; i < 8; i += 1) {
assert.strictEqual(tunnelSlots.reserveSshTerminalTunnelSlot(uid), true, "no extra slot may appear after over-release");
}
assert.strictEqual(tunnelSlots.reserveSshTerminalTunnelSlot(uid), false);
for (let i = 0; i < 8; i += 1) tunnelSlots.releaseSshTerminalTunnelSlot(uid);
});
// ---------------------------------------------------------------------------
// Wiring locked by source assertions
// ---------------------------------------------------------------------------
test("client wiring: closeTerminal clears only the per-tab record and marks the hint dead", () => {
const region = sliceBetween(clientSource, "function closeTerminal()", "function startDrag(", "closeTerminal");
assert.ok(
region.includes('writeState({ open: false, minimized: false, live: false, sessionId: "" })'),
"closeTerminal must clear the per-tab ownership record"
);
assert.ok(region.includes("writeSharedState({ live: false })"), "closeTerminal must mark the shared hint not-live");
assert.ok(
!region.includes('sessionId: "" })\n') || region.indexOf("writeState(") < region.indexOf("writeSharedState("),
"the per-tab clear must precede the hint update"
);
});
test("client wiring: openTerminal falls back to the live hint only for tabs that never opened here", () => {
const region = sliceBetween(clientSource, "async function openTerminal(", "function toggleMinimized(", "openTerminal");
assert.ok(
region.includes("let sessionId = isValidSessionId(tab.sessionId) ? tab.sessionId : \"\";"),
"the tab's own id must be read from the tab record explicitly — the merged read would leak the shared hint for a record-less tab"
);
assert.ok(
region.includes('if (!sessionId && !("sessionId" in tab)) {'),
"the hint must be consulted only when this tab has no own sessionId record"
);
assert.ok(
region.includes("shared.live !== false"),
"a hint reported dead (live === false) must not be attached to"
);
assert.ok(region.includes("minted = true"), "an unresolvable id must mint fresh and flag fresh=1");
});
test("client wiring: restore path migrates the legacy record before reading state", () => {
const region = sliceBetween(clientSource, "function attachLaunchers()", "function ensureLauncher()", "attachLaunchers");
const migrateAt = region.indexOf("migrateLegacySharedState();");
const readAt = region.indexOf("const state = readState();");
assert.ok(migrateAt >= 0 && readAt > migrateAt, "migration must run before the restore read");
});
test("client wiring: live reports mirror into the shared hint behind the frame-identity guard", () => {
const region = sliceBetween(clientSource, 'window.addEventListener("message"', "window.addEventListener(\"resize\"", "message listener");
assert.ok(
region.indexOf("event.source !== frame.contentWindow") >= 0 && region.indexOf("event.source !== frame.contentWindow") < region.indexOf("writeSharedState("),
"the hint mirror must stay behind the unforgeable frame-identity check"
);
assert.ok(
region.includes("if (isValidSessionId(sid)) writeSharedState({ sessionId: sid, live: true })"),
"live reports must publish the tab's own session id as the hint"
);
});
test("panel wiring: tunnel slot is reserved synchronously before the async credential recheck", () => {
const region = sliceBetween(indexSource, "function attachSshTerminalUpgradeProxy(", "const httpServer = httpMod.createServer(", "upgrade gate");
const reserveAt = region.indexOf("reserveSshTerminalTunnelSlot(payload.uid)");
const closeReleaseAt = region.indexOf('socket.once("close", () => releaseSshTerminalTunnelSlot(payload.uid));');
const asyncAt = region.indexOf("(async () => {");
const registerAt = region.indexOf("registerLiveSshTerminalSocket(payload.uid, socket)");
assert.ok(reserveAt >= 0, "the upgrade gate must reserve a tunnel slot");
assert.ok(closeReleaseAt > reserveAt, "the release must be bound to the socket's close right after reservation");
assert.ok(asyncAt > closeReleaseAt, "the reservation must be synchronous — before the async credential recheck");
assert.ok(registerAt > asyncAt, "registry registration stays inside the post-credential path");
const capReject = region.indexOf("rejectSshTerminalUpgrade(socket, 429)");
assert.ok(capReject > reserveAt - 200 && capReject < asyncAt, "a full slot set must answer 429 before the credential check");
});
test("panel wiring: cap rejections reuse the guarded idempotent reject helper", () => {
const region = sliceBetween(indexSource, "function rejectSshTerminalUpgrade(", "function scheduleOrphanUpgradeCleanup", "reject helper");
assert.ok(region.includes("socket.destroy()"), "rejection must still destroy the raw socket");
assert.ok(region.includes("Connection: close"), "rejection must close the HTTP connection");
});
// ---------------------------------------------------------------------------
// The minified mirror must stay byte-identical to the source (minus header)
// ---------------------------------------------------------------------------
test("client mirror: ssh-terminal-window.min.js is an exact copy of the source", () => {
const minSource = fs.readFileSync(CLIENT_MIN_JS, "utf8");
const header = "/* Mirror of ssh-terminal-window.js (no minifier in repo) — keep in sync. */\n";
assert.ok(minSource.startsWith(header), "the mirror header must be present");
assert.strictEqual(minSource.slice(header.length), clientSource, "the mirror body must equal the source byte-for-byte");
});