Files
pipelines/web/test/sessionId.test.mjs
T
alan 1ad85de1f1 Keep step-up elevation for the signed-in session and stop gating terminals
The proxy forwards an HMAC-derived session id (X-Pipelines-Session) on
/connect and POST /files; the server trusts it only on token-authenticated
requests and keys elevation by it, so reconnects stay elevated up to a 24 h
cap. Terminals rely on their su -l login. The app no longer forgets the
elevation on disconnect and asks again only on a fresh refusal.
2026-11-10 03:00:45 +00:00

185 lines
8.7 KiB
JavaScript

// The proxy tells the Pipelines server which web session a /connect upgrade or
// an upload belongs to (X-Pipelines-Session), so step-up elevation lasts for
// the sign-in instead of one connection. The id is derived, never the cookie.
import test from "node:test";
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdtemp, rename, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import net from "node:net";
import { once } from "node:events";
import { AuthStore, hashPassword } from "../src/authStore.js";
import { SESSION_HEADER, withServerToken } from "../src/serverToken.js";
const here = fileURLToPath(new URL("..", import.meta.url));
const PASSWORD = "tulip orbit canyon ember";
const CHEAP = { N: 1024, r: 8, p: 1, keyLength: 32 };
const SERVER_TOKEN = "t".repeat(48);
async function scratch(t) {
const dir = await mkdtemp(join(tmpdir(), "pipelines-session-id-"));
t.after(() => rm(dir, { recursive: true, force: true }));
return dir;
}
const replace = async (file, data) => {
await writeFile(`${file}.next`, JSON.stringify(data), { mode: 0o600 });
await rename(`${file}.next`, file);
};
test("sessionId is stable per token and changes with logout, revoke-all and a password change", async (t) => {
const file = join(await scratch(t), "web-auth.json");
const data = { password_hash: hashPassword(PASSWORD, CHEAP), secret: "s".repeat(40), generation: 2 };
await writeFile(file, JSON.stringify(data), { mode: 0o600 });
let now = 1_800_000_000_000;
const store = new AuthStore(file, { now: () => now, log: () => {} });
const a = store.issue(3600).token;
const b = store.issue(3600).token;
const id = store.sessionId(a);
assert.match(id, /^[A-Za-z0-9_-]{43}$/);
assert.equal(store.sessionId(a), id);
assert.notEqual(store.sessionId(b), id);
assert.ok(!id.includes(a.split(".")[4]), "the id does not reveal the token id");
assert.equal(store.sessionId("forged"), "");
// Logout: the token stops naming a session, a new sign-in is a new id.
store.revoke(a);
assert.equal(store.sessionId(a), "");
// Revoke-all: every older token is gone.
now += 1000;
store.revokeAll();
assert.equal(store.sessionId(b), "");
now += 1000;
const c = store.issue(3600).token;
const before = store.sessionId(c);
assert.ok(before && before !== id);
// A password change (new generation and secret) ends c too.
await replace(file, { ...data, secret: "n".repeat(40), generation: 3 });
assert.equal(store.sessionId(c), "");
assert.notEqual(store.sessionId(store.issue(3600).token), before);
});
test("withServerToken drops a client-supplied session id and sets the proxy's own", () => {
const forged = { "X-Pipelines-Session": "forged", cookie: "pipelines_session=v2.x" };
assert.deepEqual(withServerToken(forged, SERVER_TOKEN), { cookie: "pipelines_session=v2.x", "x-pipelines-token": SERVER_TOKEN });
assert.equal(withServerToken(forged, SERVER_TOKEN, "derived")[SESSION_HEADER], "derived");
assert.equal(withServerToken(forged, "", "derived")[SESSION_HEADER], undefined);
});
async function freePort() {
const server = net.createServer().listen(0, "127.0.0.1");
await once(server, "listening");
const { port } = server.address();
await new Promise((done) => server.close(done));
return port;
}
/** A stand-in server that records each request's head and answers it. */
async function recordingUpstream(t) {
const heads = [];
const held = new Set();
const server = net.createServer((socket) => {
held.add(socket);
socket.on("error", () => {});
socket.on("close", () => held.delete(socket));
let buffered = "";
socket.on("data", (chunk) => {
if (buffered.includes("\r\n\r\n")) return;
buffered += chunk.toString("latin1");
const end = buffered.indexOf("\r\n\r\n");
if (end < 0) return;
const [line, ...rest] = buffered.slice(0, end).split("\r\n");
const headers = Object.fromEntries(rest.map((h) => [h.slice(0, h.indexOf(":")).toLowerCase(), h.slice(h.indexOf(":") + 1).trim()]));
heads.push({ line, headers });
if (/^upgrade$/i.test(headers.connection ?? "") || headers.upgrade)
socket.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n");
else socket.end("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok");
});
}).listen(0, "127.0.0.1");
await once(server, "listening");
t.after(() => { for (const socket of held) socket.destroy(); return new Promise((done) => server.close(done)); });
return { port: server.address().port, heads };
}
async function startProxy(t, authData) {
const dir = await scratch(t);
const auth = join(dir, "web-auth.json");
await writeFile(auth, JSON.stringify(authData), { mode: 0o600 });
const tokenFile = join(dir, "server-token");
await writeFile(tokenFile, SERVER_TOKEN, { mode: 0o600 });
const upstream = await recordingUpstream(t);
const port = await freePort();
const child = spawn(process.execPath, ["serve.mjs", "--port", String(port), "--root", join(dir, "absent"),
"--pipelines", `127.0.0.1:${upstream.port}`], {
cwd: here,
env: { ...process.env, PIPELINES_WEB_AUTH: "", PIPELINES_WEB_AUTH_FILE: auth, PIPELINES_SERVER_TOKEN_FILE: tokenFile, PIPELINES_WEB_SWEEP_MS: "200" },
stdio: ["ignore", "pipe", "pipe"],
});
t.after(async () => { const exited = once(child, "exit"); child.kill(); await exited; });
await once(child.stdout, "data");
return { auth, port, base: `http://127.0.0.1:${port}`, host: `127.0.0.1:${port}`, heads: upstream.heads };
}
const login = (proxy, password = PASSWORD) =>
fetch(proxy.base + "/login", { method: "POST", body: new URLSearchParams({ password, next: "/" }), redirect: "manual" });
const cookieOf = (response) => response.headers.get("set-cookie").split(";")[0];
/** The session id the upstream saw on one /connect through the proxy. */
async function connectId(proxy, cookie) {
const socket = net.connect(proxy.port, "127.0.0.1");
await once(socket, "connect");
socket.on("error", () => {});
socket.write(`GET /connect HTTP/1.1\r\nHost: ${proxy.host}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
`Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n` +
`X-Pipelines-Session: forged-by-the-client-0123456789\r\nCookie: ${cookie}\r\n\r\n`);
const [chunk] = await once(socket, "data");
assert.match(chunk.toString(), /^HTTP\/1.1 101/);
socket.destroy();
const head = proxy.heads.at(-1);
assert.match(head.line, /^GET \/connect /);
return head.headers[SESSION_HEADER];
}
async function uploadHead(proxy, cookie, method = "POST") {
const response = await fetch(proxy.base + "/files?path=~/x", {
method,
body: method === "POST" ? "x" : undefined,
headers: { Cookie: cookie, "X-Pipelines-Session": "forged-by-the-client-0123456789" },
});
await response.text();
return proxy.heads.at(-1);
}
test("the proxy forwards a derived session id on /connect and uploads, never the cookie", async (t) => {
const data = { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40), generation: 0 };
const proxy = await startProxy(t, data);
const cookie = cookieOf(await login(proxy));
const token = cookie.slice(cookie.indexOf("=") + 1);
const id = await connectId(proxy, cookie);
assert.match(id, /^[A-Za-z0-9_-]{43}$/);
assert.notEqual(id, "forged-by-the-client-0123456789");
assert.ok(!id.includes(token) && !token.includes(id));
// Every reconnect of this sign-in names the same session.
assert.equal(await connectId(proxy, cookie), id);
const upload = await uploadHead(proxy, cookie);
assert.match(upload.line, /^POST \/files/);
assert.equal(upload.headers[SESSION_HEADER], id);
// Only uploads carry it; a download does not.
assert.equal((await uploadHead(proxy, cookie, "GET")).headers[SESSION_HEADER], undefined);
// Another sign-in is another session.
const other = cookieOf(await login(proxy));
assert.notEqual(await connectId(proxy, other), id);
// Logout ends the old id; the next sign-in has a new one.
await fetch(proxy.base + "/logout", { method: "POST", headers: { Cookie: cookie, Origin: proxy.base }, redirect: "manual" });
const again = cookieOf(await login(proxy));
const afterLogout = await connectId(proxy, again);
assert.notEqual(afterLogout, id);
// A password change: the old cookie is refused, a new sign-in is a new id.
await replace(proxy.auth, { ...data, password_hash: hashPassword("ember canyon orbit tulip"), secret: "n".repeat(40), generation: 1 });
await new Promise((done) => setTimeout(done, 300));
const changed = cookieOf(await login(proxy, "ember canyon orbit tulip"));
const afterChange = await connectId(proxy, changed);
assert.ok(![id, afterLogout].includes(afterChange));
});