Files
pipelines/web/test/authStore.test.mjs
T
alan e43f9fa50c 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.
2026-11-10 01:21:28 +00:00

196 lines
9.9 KiB
JavaScript

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);
});