Files
pipelines/web/test/authProxy.test.mjs
T
alan d55e1e7162 Let installed apps sign in over https again
The __Host- session cookie name now goes to browsers only. Native clients
(no Origin or fetch metadata), including app builds from before the change,
get the plain cookie name, still Secure over https, so they find their
session after signing in.
2026-11-10 02:19:36 +00:00

190 lines
10 KiB
JavaScript

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'/);
// A browser over https (Tailscale serve): __Host- prefix, Secure, HSTS.
const https = await login(proxy, { "X-Forwarded-Proto": "https", Origin: proxy.base, "Sec-Fetch-Site": "same-origin" });
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);
// Over https a native client keeps the plain name (installed apps from before
// the __Host- cookie read only that), still Secure, and it signs in.
const native = await login(proxy, { "X-Forwarded-Proto": "https" });
assert.match(native.headers.get("set-cookie"), /^pipelines_session=v2\./);
assert.match(native.headers.get("set-cookie"), /; Secure/);
assert.equal(await signedIn(proxy, cookieOf(native)), true);
});
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);
});