Hash the web password and revoke sessions server-side

Store a scrypt hash (migrating a plaintext password without changing it),
sign sessions with a generation that ./password and --revoke-all rotate,
make logout a same-origin POST that revokes the token, add sign out everywhere,
and close proxied websockets whose session ends. Enforce a strength rule for
new passwords, back off logins per client and server-wide, check Origin on
login, tighten next, add security headers and a __Host- cookie over https.
This commit is contained in:
2026-11-10 01:21:28 +00:00
parent f11ff8650d
commit e43f9fa50c
17 changed files with 1353 additions and 125 deletions
+183
View File
@@ -0,0 +1,183 @@
import test from "node:test";
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdtemp, readFile, 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 { hashPassword } from "../src/authStore.js";
const here = fileURLToPath(new URL("..", import.meta.url));
const PASSWORD = "tulip orbit canyon ember";
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 Pipelines server that accepts every websocket upgrade and holds it. */
async function fakeUpstream(t) {
const held = new Set();
const server = net.createServer((socket) => {
held.add(socket);
socket.once("data", () => socket.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n"));
socket.on("error", () => {});
socket.on("close", () => held.delete(socket));
}).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 server.address().port;
}
async function startProxy(t, authData) {
const dir = await mkdtemp(join(tmpdir(), "pipelines-auth-proxy-"));
t.after(() => rm(dir, { recursive: true, force: true }));
const auth = join(dir, "web-auth.json");
await writeFile(auth, JSON.stringify(authData), { mode: 0o600 });
const upstream = await fakeUpstream(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}`], {
cwd: here,
env: { ...process.env, PIPELINES_WEB_AUTH: "", PIPELINES_WEB_AUTH_FILE: auth, 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");
const base = `http://127.0.0.1:${port}`;
return { auth, port, base, host: `127.0.0.1:${port}` };
}
const login = (proxy, headers = {}, password = PASSWORD) =>
fetch(proxy.base + "/login", { method: "POST", body: new URLSearchParams({ password, next: "/runs/1" }), redirect: "manual", headers });
const cookieOf = (response) => response.headers.get("set-cookie").split(";")[0];
const signedIn = async (proxy, cookie) =>
(await fetch(proxy.base + "/login", { headers: { Cookie: cookie }, redirect: "manual" })).status === 302;
/** Opens /connect through the proxy and resolves when the 101 arrives. */
async function openSocket(proxy, cookie) {
const socket = net.connect(proxy.port, "127.0.0.1");
await once(socket, "connect");
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\nCookie: ${cookie}\r\n\r\n`);
const [chunk] = await once(socket, "data");
assert.match(chunk.toString(), /^HTTP\/1.1 101/);
const closed = once(socket, "close");
socket.on("error", () => {});
return { socket, closed };
}
const within = (promise, ms, what) =>
Promise.race([promise, new Promise((_, fail) => setTimeout(() => fail(new Error(`${what} not within ${ms} ms`)), ms))]);
test("login: Origin check, safe next, headers and the cookie prefix", async (t) => {
const proxy = await startProxy(t, { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40), generation: 0 });
const cross = await login(proxy, { Origin: "https://evil.example" });
assert.equal(cross.status, 403);
assert.equal(cross.headers.get("set-cookie"), null);
const page = await fetch(proxy.base + "/login?next=/%5Cevil.com");
const html = await page.text();
assert.match(html, /name="next" value="\/"/);
assert.match(page.headers.get("content-security-policy"), /frame-ancestors 'none'/);
assert.match(page.headers.get("content-security-policy"), /default-src 'none'/);
assert.equal(page.headers.get("x-frame-options"), "DENY");
assert.equal(page.headers.get("x-content-type-options"), "nosniff");
assert.equal(page.headers.get("referrer-policy"), "same-origin");
assert.equal(page.headers.get("strict-transport-security"), null);
const ok = await login(proxy, { Origin: proxy.base });
assert.equal(ok.status, 303);
assert.equal(ok.headers.get("location"), "/runs/1");
assert.match(ok.headers.get("set-cookie"), /^pipelines_session=v2\./);
assert.doesNotMatch(ok.headers.get("set-cookie"), /Secure/);
// An app response may be framed by the app itself only.
const app = await fetch(proxy.base + "/runs/1", { headers: { Cookie: cookieOf(ok) } });
assert.equal(app.headers.get("x-frame-options"), "SAMEORIGIN");
assert.match(app.headers.get("content-security-policy"), /frame-ancestors 'self'/);
// Over https (Tailscale serve): __Host- prefix, Secure, HSTS.
const https = await login(proxy, { "X-Forwarded-Proto": "https" });
const secure = https.headers.get("set-cookie");
assert.match(secure, /^__Host-pipelines_session=v2\./);
assert.match(secure, /; Path=\/;/);
assert.match(secure, /; Secure/);
assert.doesNotMatch(secure, /Domain=/i);
assert.match(https.headers.get("strict-transport-security"), /max-age=\d+/);
assert.equal(await signedIn(proxy, cookieOf(https)), true);
// A native client (no Origin) still signs in.
assert.equal((await login(proxy)).status, 303);
});
test("logout is a same-origin POST that revokes the token and closes its sockets", async (t) => {
const proxy = await startProxy(t, { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40) });
const a = cookieOf(await login(proxy));
const b = cookieOf(await login(proxy));
const ws = await openSocket(proxy, a);
const other = await openSocket(proxy, b);
// GET only shows a button; a cross-site POST is refused.
const page = await fetch(proxy.base + "/logout", { headers: { Cookie: a }, redirect: "manual" });
assert.equal(page.status, 200);
assert.match(await page.text(), /method="post" action="\/logout"/);
assert.equal((await fetch(proxy.base + "/logout", { method: "POST", headers: { Cookie: a, Origin: "https://evil.example" }, redirect: "manual" })).status, 403);
assert.equal(await signedIn(proxy, a), true);
const out = await fetch(proxy.base + "/logout", { method: "POST", headers: { Cookie: a, Origin: proxy.base }, redirect: "manual" });
assert.equal(out.status, 303);
assert.match(out.headers.get("set-cookie"), /pipelines_session=; .*Max-Age=0/);
// The copied cookie no longer works anywhere, and its socket is gone.
assert.equal(await signedIn(proxy, a), false);
await within(ws.closed, 2000, "the signed-out socket closing");
assert.equal(await signedIn(proxy, b), true);
assert.equal(other.socket.destroyed, false);
other.socket.destroy();
});
test("a password change revokes every session and closes open websockets", async (t) => {
const data = { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40), generation: 4 };
const proxy = await startProxy(t, data);
const cookie = cookieOf(await login(proxy));
const ws = await openSocket(proxy, cookie);
// What ./password writes: a new hash, secret and generation, atomically.
const next = { ...data, password_hash: hashPassword("ember canyon orbit tulip"), secret: "n".repeat(40), generation: 5 };
await writeFile(proxy.auth + ".next", JSON.stringify(next), { mode: 0o600 });
await rename(proxy.auth + ".next", proxy.auth);
await within(ws.closed, 3000, "the websocket closing after the password change");
assert.equal(await signedIn(proxy, cookie), false);
assert.equal((await login(proxy)).status, 401);
assert.equal((await login(proxy, {}, "ember canyon orbit tulip")).status, 303);
});
test("sign out everywhere from Settings, the session report and the weak-password warning", async (t) => {
const proxy = await startProxy(t, { password: "old-password", secret: "s".repeat(40) });
// The migration kept the old password working and stored only a hash.
const first = await login(proxy, {}, "old-password");
assert.equal(first.status, 303);
const stored = JSON.parse(await readFile(proxy.auth, "utf8"));
assert.equal(stored.password, undefined);
assert.match(stored.password_hash, /^scrypt\$/);
const a = cookieOf(first);
const b = cookieOf(await login(proxy, {}, "old-password"));
assert.equal((await fetch(proxy.base + "/api/session")).status, 401);
const report = await (await fetch(proxy.base + "/api/session", { headers: { Cookie: a } })).json();
assert.equal(report.weak_password, true);
assert.match(report.password_rule, /16 characters/);
const ws = await openSocket(proxy, b);
assert.equal((await fetch(proxy.base + "/api/sessions/revoke-all", { method: "POST", headers: { Cookie: a, Origin: "https://evil.example" } })).status, 403);
const revoke = await fetch(proxy.base + "/api/sessions/revoke-all", { method: "POST", headers: { Cookie: a, Origin: proxy.base } });
assert.equal(revoke.status, 200);
assert.deepEqual(await revoke.json(), { revoked: true });
await within(ws.closed, 2000, "every socket closing");
assert.equal(await signedIn(proxy, a), false);
assert.equal(await signedIn(proxy, b), false);
assert.equal(await signedIn(proxy, cookieOf(await login(proxy, {}, "old-password"))), true);
});
test("repeated wrong passwords are slowed down", async (t) => {
const proxy = await startProxy(t, { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40) });
for (let i = 0; i < 5; i++) assert.equal((await login(proxy, {}, "wrong")).status, 401);
const blocked = await login(proxy, {}, PASSWORD);
assert.equal(blocked.status, 429);
assert.ok(Number(blocked.headers.get("retry-after")) >= 1);
});
+6 -3
View File
@@ -27,11 +27,14 @@ test("atomic password updates take effect without restart and fail closed on inv
const cookie = first.headers.get("set-cookie").split(";")[0];
await writeFile(auth + ".next", JSON.stringify({ ...data, password:"new-password" })); await rename(auth + ".next",auth);
assert.equal((await login("old-password")).status,401);
assert.equal((await login("new-password")).status,303);
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie},redirect:"manual"})).status,302);
const second = await login("new-password"); assert.equal(second.status,303);
// A changed password signs the earlier session out; the new one is signed in.
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie},redirect:"manual"})).status,200);
const cookie2 = second.headers.get("set-cookie").split(";")[0];
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie2},redirect:"manual"})).status,302);
await writeFile(auth + ".next", "malformed"); await rename(auth + ".next",auth);
assert.equal((await login("new-password")).status,503);
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie},redirect:"manual"})).status,503);
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie2},redirect:"manual"})).status,503);
await writeFile(auth,JSON.stringify(data));
assert.equal((await login("old-password")).status,303);
});
+195
View File
@@ -0,0 +1,195 @@
import test from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, readFile, rm, stat, writeFile, rename } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { AuthStore, REVOKED_LIMIT, hashPassword, parseHash, verifyPassword } from "../src/authStore.js";
import { passwordProblem } from "../src/passwordPolicy.js";
import { LoginLimiter, clientKey } from "../src/loginLimiter.js";
import { safeNext, sameOriginRequest, isHttps, sessionCookieName } from "../src/webSecurity.js";
import { SessionSockets } from "../src/sessionSockets.js";
const CHEAP = { N: 1024, r: 8, p: 1, keyLength: 32 };
async function fixture(t, data) {
const dir = await mkdtemp(join(tmpdir(), "pipelines-auth-store-"));
t.after(() => rm(dir, { recursive: true, force: true }));
const file = join(dir, "web-auth.json");
await writeFile(file, JSON.stringify(data), { mode: 0o600 });
return file;
}
const replace = async (file, data) => {
await writeFile(`${file}.next`, JSON.stringify(data), { mode: 0o600 });
await rename(`${file}.next`, file);
};
test("hashes are scrypt with recorded parameters and verify in constant time", async () => {
const stored = hashPassword("tulip orbit canyon ember", CHEAP);
assert.match(stored, /^scrypt\$1024\$8\$1\$[A-Za-z0-9_-]+\$[A-Za-z0-9_-]+$/);
assert.ok(parseHash(stored));
assert.equal(await verifyPassword(stored, "tulip orbit canyon ember"), true);
assert.equal(await verifyPassword(stored, "tulip orbit canyon embers"), false);
assert.equal(await verifyPassword("scrypt$1000$8$1$AAAAAAAAAAA$BBBBBBBBBBBBBBBBBBBBBB", "x"), false);
assert.equal(parseHash("plain"), null);
});
test("a plaintext password migrates to a hash without changing it", async (t) => {
const file = await fixture(t, { password: "old-password", secret: "s".repeat(40), other: "kept" });
const logs = [];
const store = new AuthStore(file, { log: (line) => logs.push(line) });
const state = store.load();
const written = JSON.parse(await readFile(file, "utf8"));
assert.equal(written.password, undefined);
assert.equal(written.other, "kept");
assert.equal(written.password_weak, true);
assert.equal(written.secret, "s".repeat(40)); // first start: sessions stay valid
assert.equal(state.weak, true);
assert.equal(await verifyPassword(written.password_hash, "old-password"), true);
assert.equal((await stat(file)).mode & 0o777, 0o600);
assert.ok(!logs.join("\n").includes("old-password"));
// A strong plaintext is not flagged.
const strong = await fixture(t, { password: "tulip orbit canyon ember", secret: "s".repeat(40) });
assert.equal(new AuthStore(strong, { log() {} }).load().weak, false);
});
test("a plaintext password written over a running proxy signs every session out", async (t) => {
const file = await fixture(t, { password_hash: hashPassword("first passphrase here ok", CHEAP), secret: "s".repeat(40), generation: 3 });
const store = new AuthStore(file, { log() {} });
const { token } = store.issue(60);
await replace(file, { password: "new-password", secret: "s".repeat(40), generation: 3 });
assert.equal(store.check(token), null);
const written = JSON.parse(await readFile(file, "utf8"));
assert.equal(written.generation, 4);
assert.notEqual(written.secret, "s".repeat(40));
});
test("tokens: signature, expiry, generation, logout and sign out everywhere", async (t) => {
let now = 1_800_000_000_000;
const data = { password_hash: hashPassword("tulip orbit canyon ember", CHEAP), secret: "s".repeat(40), generation: 1 };
const file = await fixture(t, data);
const store = new AuthStore(file, { now: () => now, log() {} });
const a = store.issue(60).token;
const b = store.issue(3600).token;
assert.ok(store.check(a));
assert.equal(store.check(a.slice(0, -2) + (a.endsWith("A") ? "BB" : "AA")), null);
assert.equal(store.check(a.replace(/^v2\.1\./, "v2.2.")), null);
assert.equal(store.check("1800000000.abc.def"), null); // the old unversioned format
// Server-side logout of one token leaves the other.
assert.equal(store.revoke(a), true);
assert.equal(store.check(a), null);
assert.ok(store.check(b));
// The list survives a proxy restart.
assert.equal(new AuthStore(file, { now: () => now, log() {} }).check(a), null);
assert.equal(((await stat(`${file}.sessions.json`)).mode & 0o777), 0o600);
// Expiry.
now += 61_000;
const c = store.issue(60).token;
now += 1000;
assert.ok(store.check(c));
now += 60_000;
assert.equal(store.check(c), null);
// Sign out everywhere: every earlier token, but not a later sign-in.
const d = store.issue(3600).token;
now += 1;
store.revokeAll();
assert.equal(store.check(b), null);
assert.equal(store.check(d), null);
now += 1;
const e = store.issue(3600).token;
assert.ok(store.check(e));
assert.ok(new AuthStore(file, { now: () => now, log() {} }).check(e));
assert.equal(new AuthStore(file, { now: () => now, log() {} }).check(d), null);
// ./password (new secret and generation) ends every session.
await replace(file, { ...data, secret: "t".repeat(40), generation: 2 });
assert.equal(store.check(e), null);
const f = store.issue(3600).token;
assert.ok(store.check(f));
});
test("the signed-out list is bounded, dropping the soonest to expire", async (t) => {
const file = await fixture(t, { password_hash: hashPassword("tulip orbit canyon ember", CHEAP), secret: "s".repeat(40) });
const store = new AuthStore(file, { now: () => 1_000_000, log() {} });
store.load();
for (let i = 0; i < REVOKED_LIMIT + 5; i++) store.revoked.set(`token-id-${String(i).padStart(6, "0")}`, 10_000 + i);
store.saveSessions();
assert.equal(store.revoked.size, REVOKED_LIMIT);
assert.ok(!store.revoked.has("token-id-000000"));
assert.ok(store.revoked.has(`token-id-${String(REVOKED_LIMIT + 4).padStart(6, "0")}`));
});
test("the strength rule matches scripts/password.py", () => {
for (const strong of ["tulip orbit canyon ember", "correct horse battery staple", "k7#Rv9!qLm2@Xz4s", "cat dog sun red"])
assert.equal(passwordProblem(strong), null, strong);
for (const weak of ["short", "old password", "J8m!x2Lq0#vR9tZ", "password password password", "a".repeat(20),
"Password12345678!", "qwertyuiop1234567890", "password welcome admin letmein", "dog dog dog dog dog"])
assert.notEqual(passwordProblem(weak), null, weak);
});
test("limiter: per-client backoff, success reset, global cap and bounded eviction", () => {
let now = 0;
const limiter = new LoginLimiter({ now: () => now, freeFailures: 3, baseMs: 1000, maxKeys: 4, globalLimit: 10, globalWindowMs: 60_000 });
for (let i = 0; i < 2; i++) limiter.fail("a");
assert.equal(limiter.blocked("a"), 0);
limiter.fail("a");
assert.equal(limiter.blocked("a"), 1000);
limiter.fail("a");
assert.equal(limiter.blocked("a"), 2000); // doubles
assert.equal(limiter.blocked("b"), 0);
limiter.succeed("a");
assert.equal(limiter.blocked("a"), 0);
// Eviction keeps at most maxKeys clients, the least recent leaving first.
for (const key of ["k1", "k2", "k3", "k4", "k5"]) limiter.fail(key);
assert.equal(limiter.clients.size, 4);
assert.ok(!limiter.clients.has("k1"));
// The global window: ten failures from anyone block everyone.
now = 120_000;
for (let i = 0; i < 10; i++) limiter.fail(`spread-${i}`);
assert.ok(limiter.blocked("someone-new") > 0);
assert.ok(limiter.recent.length <= 10);
now += 60_000;
assert.equal(limiter.blocked("someone-new"), 0);
});
test("the limiter charges Tailscale users only behind a loopback Tailscale proxy", () => {
const req = (address, headers) => ({ socket: { remoteAddress: address }, headers });
assert.equal(clientKey(req("127.0.0.1", { "tailscale-user-login": "Alan@Example.com" })), "tailscale:alan@example.com");
assert.equal(clientKey(req("::1", { "tailscale-user-name": "x", "x-forwarded-for": "100.64.0.7, 1.1.1.1" })), "forwarded:100.64.0.7");
assert.equal(clientKey(req("127.0.0.1", { "x-forwarded-for": "100.64.0.7" })), "address:127.0.0.1");
assert.equal(clientKey(req("192.168.1.5", { "tailscale-user-login": "forged@example.com" })), "address:192.168.1.5");
});
test("next targets stay on this origin", () => {
for (const good of ["/", "/runs/12", "/chat?x=1#y", "/a/b//c"]) assert.equal(safeNext(good), good);
for (const bad of ["//evil.com", "/\\evil.com", "\\\\evil.com", "https://evil.com", "evil", "/ok\\path", "/a\nb", "", null])
assert.equal(safeNext(bad), "/", String(bad));
});
test("origin checks, https detection and cookie naming", () => {
const req = (headers, encrypted = false) => ({ headers: { host: "pipelines.example:8443", ...headers }, socket: { encrypted } });
assert.equal(sameOriginRequest(req({})), true);
assert.equal(sameOriginRequest(req({ origin: "https://pipelines.example:8443" })), true);
assert.equal(sameOriginRequest(req({ origin: "https://evil.example" })), false);
assert.equal(sameOriginRequest(req({ origin: "null" })), false);
assert.equal(sameOriginRequest(req({ "sec-fetch-site": "cross-site" })), false);
assert.equal(sameOriginRequest(req({ "sec-fetch-site": "same-site", origin: "https://pipelines.example:8443" })), false);
assert.equal(isHttps(req({ "x-forwarded-proto": "https" })), true);
assert.equal(isHttps(req({})), false);
assert.equal(sessionCookieName(req({ "x-forwarded-proto": "https" })), "__Host-pipelines_session");
assert.equal(sessionCookieName(req({})), "pipelines_session");
});
test("socket sweep destroys only sockets whose session is gone", async () => {
const { EventEmitter } = await import("node:events");
const sockets = new SessionSockets();
const make = () => Object.assign(new EventEmitter(), { destroyed: false, destroy() { this.destroyed = true; this.emit("close"); } });
const keep = make(), drop = make();
sockets.track(keep, "good");
sockets.track(drop, "bad");
assert.equal(sockets.sweep((token) => token === "good"), 1);
assert.equal(drop.destroyed, true);
assert.equal(keep.destroyed, false);
assert.equal(sockets.size, 1);
keep.emit("close");
assert.equal(sockets.size, 0);
});