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.
This commit is contained in:
2026-11-10 03:00:45 +00:00
parent 60b4c495f1
commit 1ad85de1f1
19 changed files with 876 additions and 165 deletions
+19 -2
View File
@@ -149,6 +149,19 @@ function session(req) {
}
}
/**
* The derived id the server keys step-up elevation by (AuthStore.sessionId),
* or "" without a live session. Forwarded on /connect and POST /files only.
*/
function elevationSession(req) {
if (!auth) return "";
try {
return store.sessionId(sessionValue(req));
} catch {
return "";
}
}
function isAuthed(req) {
return !auth || session(req) !== null;
}
@@ -444,8 +457,10 @@ async function serveIndex(res) {
*/
function proxyArtifact(req, res) {
let headers;
// An upload is gated by the session's elevation on the server.
const upload = req.method === "POST" && (req.url ?? "").split("?")[0] === "/files";
try {
headers = withServerToken(req.headers);
headers = withServerToken(req.headers, undefined, upload ? elevationSession(req) : "");
} catch {
res.writeHead(503, { "Content-Type": "text/plain; charset=utf-8" }).end("Server token unavailable");
return;
@@ -667,7 +682,9 @@ const targetHost = pipelinesTarget.slice(0, pipelinesTarget.lastIndexOf(":")) ||
function proxyUpgrade(req, clientSocket, clientHead) {
let headers;
try {
headers = withServerToken(req.headers);
// The server keys step-up elevation by this session, so a reconnect of
// the same sign-in stays elevated.
headers = withServerToken(req.headers, undefined, elevationSession(req));
} catch {
clientSocket.end("HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n");
return;
+15
View File
@@ -214,6 +214,21 @@ export class AuthStore {
return { id, expires: Number(expires), issued: Number(issued) };
}
/**
* The opaque id the Pipelines server keys step-up elevation by, for a valid
* token, else "". It is an HMAC (under the cookie secret) of the token's
* generation and id, never the cookie: a new sign-in, a password change or
* a revoke-all yields a new id, so the old elevation is never named again.
*/
sessionId(token) {
const session = this.check(token);
if (!session) return "";
const { generation } = this.load();
return createHmac("sha256", this.load().secret)
.update(`pipelines-elevation-session.v1.${generation}.${this.notBefore}.${session.id}`)
.digest("base64url");
}
/** Signs one token out (server-side logout). */
revoke(token) {
const session = this.check(token);
+12 -5
View File
@@ -8,6 +8,8 @@ import { homedir } from "node:os";
import { join } from "node:path";
export const SERVER_TOKEN_HEADER = "x-pipelines-token";
// The proxy's opaque id of the signed-in web session (protocol.SessionHeader).
export const SESSION_HEADER = "x-pipelines-session";
export function serverTokenPath(env = process.env) {
if (env.PIPELINES_SERVER_TOKEN_FILE) return env.PIPELINES_SERVER_TOKEN_FILE;
@@ -37,12 +39,17 @@ export function serverToken(path = serverTokenPath()) {
return cached.token;
}
// Headers for the local upstream: any client-supplied token is dropped and the
// proxy's own is set, so the browser never chooses what the server sees.
export function withServerToken(headers, token = serverToken()) {
// Headers for the local upstream: any client-supplied token or session id is
// dropped and the proxy's own token is set, so the browser never chooses what
// the server sees. session, when given, is the proxy's derived session id
// (AuthStore.sessionId), set only where the server keys elevation by it.
export function withServerToken(headers, token = serverToken(), session = "") {
const result = { ...headers };
for (const name of Object.keys(result))
if (name.toLowerCase() === SERVER_TOKEN_HEADER) delete result[name];
for (const name of Object.keys(result)) {
const lower = name.toLowerCase();
if (lower === SERVER_TOKEN_HEADER || lower === SESSION_HEADER) delete result[name];
}
if (token) result[SERVER_TOKEN_HEADER] = token;
if (token && session) result[SESSION_HEADER] = session;
return result;
}
+184
View File
@@ -0,0 +1,184 @@
// 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));
});