Files
Homelab-manager/server/test/login.test.ts
T
bobbanandClaude Sonnet 5.5 2dac273b1d Harden the login flow: new session at sign-in, signed ID tokens, same-origin requests, headers
From an audit of the Authentik login, run against a fake OIDC provider:

- Session fixation: the session id wasn't changed at sign-in, so one planted beforehand
  (from another page on the domain) became signed in as the victim. It is regenerated now.
- Requests from another origin: SameSite=Lax doesn't stop another app on the same parent
  domain, and a body-less POST (stop a guest, rotate a token) needs no preflight. Every
  POST/PUT/PATCH/DELETE, and GET /auth/logout, is refused when Sec-Fetch-Site (or, for older
  browsers, Origin) says it came from elsewhere. The agent endpoint is exempt: it uses a token.
- ID token signature: openid-client checks a token's claims but, as OIDC allows for a token
  from the token endpoint, not its signature, so the login rested on HTTPS to Authentik
  alone. The signature is now verified against the provider's published keys (jose, now a
  declared dependency).
- SESSION_SECRET: production refuses to start without one (the fallback is in the source
  code) and warns when it is the .env.example placeholder or short.
- Response headers: frame-ancestors 'none', X-Frame-Options, nosniff, Referrer-Policy; the
  framework name is no longer sent.
- A failed sign-in shows a plain page and is audited (session / login_failed, with address
  and reason, no tokens); sign-in is limited to 20 attempts a minute per address so the
  audit log and session store can't be flooded.
- A failed OIDC discovery (provider down at the first sign-in) was remembered until restart;
  it is retried now.

Tests run the real app against the fake provider; switching each fix off in turn makes
the matching tests fail.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-06 23:35:34 +02:00

429 lines
23 KiB
TypeScript

/**
* Regression tests for the login flow, run against a fake OpenID Connect provider (a small HTTPS server that signs real tokens —
* and, when asked, broken ones) and the real application from createApp().
*
* - the ID token's signature is checked, not just its claims
* - a new session id is issued at sign-in (no session fixation)
* - a request that changes something, made from another origin, is refused
* - a failed sign-in gets a plain explanation and an audit entry, and sign-in is rate-limited
* - every response carries the anti-framing headers
* - the session secret is checked at startup
*
* Needs `openssl` (for the fake provider's throwaway certificate); skipped without it.
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawnSync } from "node:child_process";
import https from "node:https";
import http from "node:http";
import crypto from "node:crypto";
const haveOpenssl = spawnSync("openssl", ["version"]).status === 0;
const dir = mkdtempSync(join(tmpdir(), "hm-login-test-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; // the fake provider's certificate is self-signed and thrown away
const CLIENT_ID = "hm-client";
const CLIENT_SECRET = "client-secret";
let issuerBase = "";
let failDiscovery = true; // the very first sign-in must find the provider down, to prove that isn't remembered forever
// ─── the fake provider ──────────────────────────────────────────────────────
type Provider = { server: https.Server; close: () => void };
let provider: Provider | null = null;
const codes = new Map<string, { scenario: string; challenge: string; sub: string }>();
async function startProvider(): Promise<Provider> {
const jose = await import("jose");
const cert = spawnSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", join(dir, "k.pem"), "-out", join(dir, "c.pem"), "-days", "1", "-subj", "//CN=localhost"], {
encoding: "utf8",
env: { ...process.env, MSYS_NO_PATHCONV: "1" },
});
if (cert.status !== 0) throw new Error(`openssl failed: ${cert.stderr}`);
const good = await jose.generateKeyPair("RS256");
const other = await jose.generateKeyPair("RS256");
const jwk = { ...(await jose.exportJWK(good.publicKey)), kid: "k1", alg: "RS256", use: "sig" };
async function idToken(scenario: string, sub: string) {
const now = Math.floor(Date.now() / 1000);
const claims = { iss: issuerBase, aud: CLIENT_ID, exp: now + 600 };
let key = good.privateKey;
if (scenario === "badsig") key = other.privateKey;
if (scenario === "wrongiss") claims.iss = "https://evil.example/";
if (scenario === "wrongaud") claims.aud = "someone-elses-client";
if (scenario === "expired") claims.exp = now - 3600;
if (scenario === "none") {
// an unsigned token, the classic forgery
const b64 = (o: object) => Buffer.from(JSON.stringify(o)).toString("base64url");
return `${b64({ alg: "none", typ: "JWT" })}.${b64({ ...claims, sub, iat: now - 10 })}.`;
}
if (scenario === "hs256") {
// signed with the client secret instead of the provider's key — not what the provider does, and not what the app expects
return new jose.SignJWT({}).setProtectedHeader({ alg: "HS256" }).setIssuer(claims.iss).setAudience(claims.aud).setSubject(sub).setIssuedAt(now - 10).setExpirationTime(claims.exp).sign(new TextEncoder().encode(CLIENT_SECRET));
}
let jwt = new jose.SignJWT({ email: `${sub}@example.test`, name: sub }).setProtectedHeader({ alg: "RS256", kid: "k1" }).setIssuer(claims.iss).setAudience(claims.aud).setIssuedAt(now - 10).setExpirationTime(claims.exp);
if (scenario !== "nosub") jwt = jwt.setSubject(sub);
return jwt.sign(key);
}
const server = https.createServer({ key: readFileSync(join(dir, "k.pem")), cert: readFileSync(join(dir, "c.pem")) }, async (req, res) => {
const url = new URL(req.url!, issuerBase);
const json = (o: unknown) => {
res.setHeader("content-type", "application/json");
res.end(JSON.stringify(o));
};
if (url.pathname.endsWith("/.well-known/openid-configuration")) {
if (failDiscovery) {
res.statusCode = 503;
return res.end("down");
}
return json({
issuer: issuerBase, authorization_endpoint: issuerBase + "authorize", token_endpoint: issuerBase + "token", jwks_uri: issuerBase + "jwks",
userinfo_endpoint: issuerBase + "userinfo", end_session_endpoint: issuerBase + "end-session",
response_types_supported: ["code"], subject_types_supported: ["public"], id_token_signing_alg_values_supported: ["RS256"],
code_challenge_methods_supported: ["S256"], token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"],
});
}
if (url.pathname.endsWith("/jwks")) return json({ keys: [jwk] });
if (url.pathname.endsWith("/authorize")) {
const [scenario, sub] = (url.searchParams.get("login_hint") ?? "good|nobody").split("|");
const code = `${scenario}.${crypto.randomBytes(6).toString("hex")}`;
codes.set(code, { scenario, challenge: url.searchParams.get("code_challenge")!, sub });
const back = new URL(url.searchParams.get("redirect_uri")!);
back.searchParams.set("code", code);
back.searchParams.set("state", url.searchParams.get("state")!);
back.searchParams.set("iss", issuerBase);
res.statusCode = 302;
res.setHeader("location", back.href);
return res.end();
}
if (url.pathname.endsWith("/token") && req.method === "POST") {
let body = "";
for await (const c of req) body += c;
const form = new URLSearchParams(body);
const entry = codes.get(form.get("code") ?? "");
if (!entry) {
res.statusCode = 400;
return json({ error: "invalid_grant" });
}
if (crypto.createHash("sha256").update(form.get("code_verifier") ?? "").digest("base64url") !== entry.challenge) {
res.statusCode = 400;
return json({ error: "invalid_grant", error_description: "PKCE verification failed" });
}
codes.delete(form.get("code")!);
return json({ token_type: "Bearer", access_token: "at-" + entry.sub, expires_in: 300, id_token: await idToken(entry.scenario, entry.sub) });
}
if (url.pathname.endsWith("/userinfo")) {
const sub = (req.headers.authorization ?? "").replace(/^Bearer at-/, "");
return json({ sub, email: "from-userinfo@example.test", name: "From Userinfo" });
}
res.statusCode = 404;
res.end("nope");
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
issuerBase = `https://127.0.0.1:${(server.address() as { port: number }).port}/application/o/hm/`;
return { server, close: () => server.close() };
}
// The app reads its configuration when its modules are first loaded, so the provider has to be up — and its address known —
// before anything from ../src is imported.
if (haveOpenssl) {
provider = await startProvider();
Object.assign(process.env, {
AUTHENTIK_ISSUER_URL: issuerBase,
AUTHENTIK_CLIENT_ID: CLIENT_ID,
AUTHENTIK_CLIENT_SECRET: CLIENT_SECRET,
APP_BASE_URL: "http://app.test",
SESSION_SECRET: "test-session-secret-that-is-long-enough",
});
}
const { SESSION_SECRET_PLACEHOLDER, checkSessionSecret } = await import("../src/env.js");
// ─── the app ────────────────────────────────────────────────────────────────
let app: http.Server;
let appPort = 0;
let db: typeof import("../src/db/client.js")["db"];
let tables: typeof import("../src/db/schema.js");
type Res = { status: number; headers: http.IncomingHttpHeaders; text: string };
let ipCounter = 0;
const freshIp = () => `10.1.${Math.floor(++ipCounter / 250)}.${ipCounter % 250}`;
function call(method: string, path: string, opts: { cookie?: string; headers?: Record<string, string>; ip?: string } = {}): Promise<Res> {
return new Promise((resolve, reject) => {
const headers: Record<string, string> = { "x-forwarded-for": opts.ip ?? freshIp(), ...opts.headers };
if (opts.cookie) headers.cookie = opts.cookie;
const req = http.request({ host: "127.0.0.1", port: appPort, method, path, headers }, (res) => {
let text = "";
res.on("data", (c) => (text += c));
res.on("end", () => resolve({ status: res.statusCode ?? 0, headers: res.headers, text }));
});
req.on("error", reject);
req.end();
});
}
const sidOf = (setCookie?: string[]) => setCookie?.find((c) => c.startsWith("connect.sid="))?.split(";")[0];
const hopToProvider = (u: string) =>
new Promise<Res>((resolve, reject) =>
https.get(u, { rejectUnauthorized: false }, (res) => {
let text = "";
res.on("data", (c) => (text += c));
res.on("end", () => resolve({ status: res.statusCode ?? 0, headers: res.headers, text }));
}).on("error", reject),
);
/** The browser's part of the sign-in, done by hand, as one client address. */
async function signIn(scenario: string, sub: string, opts: { cookie?: string; tamperState?: boolean; ip?: string } = {}) {
const ip = opts.ip ?? freshIp();
const start = await call("GET", "/auth/login", { cookie: opts.cookie, ip });
const cookie = sidOf(start.headers["set-cookie"]) ?? opts.cookie!;
const authUrl = new URL(start.headers.location!);
authUrl.searchParams.set("login_hint", `${scenario}|${sub}`);
const back = new URL((await hopToProvider(authUrl.href)).headers.location!);
if (opts.tamperState) back.searchParams.set("state", "not-the-state");
// The provider sends the browser back from another site, so the callback arrives marked cross-site — and must still work.
const callback = await call("GET", back.pathname + back.search, { cookie, ip, headers: { "sec-fetch-site": "cross-site" } });
return { cookie, callback, newCookie: sidOf(callback.headers["set-cookie"]), authUrl, loginResponse: start };
}
const me = async (cookie: string) => (await call("GET", "/api/me", { cookie })).status;
before(async () => {
if (!haveOpenssl) return;
const { runMigrations } = await import("../src/db/migrate.js");
({ db } = await import("../src/db/client.js"));
tables = await import("../src/db/schema.js");
const { createApp } = await import("../src/app.js");
await runMigrations();
app = createApp().listen(0);
appPort = (app.address() as { port: number }).port;
});
after(() => {
app?.close();
provider?.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the SQLite file locked until the process exits.
}
});
const auditEntries = async (action: string) => (await db.select().from(tables.auditLog)).filter((e) => e.action === action);
// ─── tests ──────────────────────────────────────────────────────────────────
describe("sign-in", { skip: !haveOpenssl }, () => {
test("an unreachable provider is a plain message — and isn't remembered once it's back", async () => {
const down = await call("GET", "/auth/login");
assert.equal(down.status, 400, down.text);
assert.match(down.text, /Sign-in failed/);
assert.doesNotMatch(down.text, /503|ECONN|discovery|127\.0\.0\.1/i, "the page must not say why");
failDiscovery = false;
const up = await call("GET", "/auth/login");
assert.equal(up.status, 302, "the first failure was cached and the provider is never asked again");
const entries = await auditEntries("login_failed");
assert.ok(entries.some((e) => JSON.parse(e.detail!).reason === "provider_unreachable"));
});
test("the authorization request uses PKCE, a random state, and a cookie scripts can't read", async () => {
const r = await call("GET", "/auth/login");
const u = new URL(r.headers.location!);
assert.equal(u.searchParams.get("code_challenge_method"), "S256");
assert.ok((u.searchParams.get("state") ?? "").length >= 32);
assert.equal(u.searchParams.get("scope"), "openid email profile");
const cookie = (r.headers["set-cookie"] ?? []).join(";");
assert.match(cookie, /HttpOnly/);
assert.match(cookie, /SameSite=Lax/);
});
test("a good sign-in works: the first account is admin, the next is a viewer, and the name comes from userinfo", async () => {
const first = await signIn("good", "alice");
assert.equal(first.callback.status, 302);
assert.equal(first.callback.headers.location, "/");
assert.equal(await me(first.newCookie!), 200);
const second = await signIn("good", "bob");
assert.equal(await me(second.newCookie!), 200);
const roles = Object.fromEntries((await db.select().from(tables.users)).map((u) => [u.oidcSub, u.role]));
assert.deepEqual(roles, { alice: "admin", bob: "viewer" });
assert.equal((await db.select().from(tables.users))[0].name, "From Userinfo");
});
test("tokens that must never be believed leave nobody signed in, and the person gets a plain page", async () => {
for (const scenario of ["badsig", "wrongiss", "wrongaud", "expired", "nosub", "none", "hs256"]) {
const r = await signIn(scenario, "mallory");
assert.equal(r.callback.status, 400, `${scenario}: ${r.callback.text.slice(0, 100)}`);
assert.match(r.callback.text, /Sign-in failed/, scenario);
assert.doesNotMatch(r.callback.text, /JWT|signature|claim|openid|stack/i, `${scenario}: the page explains too much`);
assert.notEqual(await me(r.newCookie ?? r.cookie), 200, `${scenario}: signed in anyway`);
}
assert.equal((await db.select().from(tables.users)).some((u) => u.oidcSub === "mallory"), false, "an account was created for a forged identity");
});
test("a token signed with the wrong key is refused — which the OIDC library alone would not have done", async () => {
const r = await signIn("badsig", "mallory");
assert.equal(r.callback.status, 400);
const entry = (await auditEntries("login_failed")).map((e) => JSON.parse(e.detail!)).find((d) => /signature/i.test(d.error ?? ""));
assert.ok(entry, "the audit entry should say the signature didn't verify");
});
test("a wrong state is refused", async () => {
const r = await signIn("good", "mallory", { tamperState: true });
assert.equal(r.callback.status, 400);
assert.notEqual(await me(r.cookie), 200);
});
test("a failed sign-in is in the audit log, with where it came from and no secrets", async () => {
const before = (await auditEntries("login_failed")).length;
await signIn("wrongaud", "mallory", { ip: "203.0.113.7" });
const entries = await auditEntries("login_failed");
assert.equal(entries.length, before + 1);
const latest = entries.at(-1)!;
assert.equal(latest.category, "session");
const detail = JSON.parse(latest.detail!);
assert.equal(detail.ip, "203.0.113.7");
assert.equal(detail.reason, "provider_rejected");
assert.doesNotMatch(latest.detail!, /eyJ|secret|code=/i, "a token or code ended up in the audit log");
});
test("a stale callback page is explained, but isn't written to the audit log", async () => {
const before = (await auditEntries("login_failed")).length;
const r = await call("GET", "/auth/callback?code=x&state=y");
assert.equal(r.status, 400);
assert.match(r.text, /Sign-in failed/);
assert.equal((await auditEntries("login_failed")).length, before);
});
test("the session id changes at sign-in, so a planted one is worthless", async () => {
const planted = sidOf((await call("GET", "/auth/login")).headers["set-cookie"])!;
const victim = await signIn("good", "victim", { cookie: planted });
assert.ok(victim.newCookie, "no new session cookie was issued at sign-in");
assert.notEqual(victim.newCookie, planted);
assert.equal(await me(victim.newCookie!), 200);
assert.notEqual(await me(planted), 200, "the planted session id was signed in as the victim");
});
test("a callback can't be replayed", async () => {
const r = await signIn("good", "bob");
const again = await call("GET", r.callback.headers.location === "/" ? new URL(r.authUrl.searchParams.get("redirect_uri")!).pathname + "?code=x&state=y" : "/", { cookie: r.newCookie });
assert.equal(again.status, 400);
});
test("sign-in is rate limited per address, and one address doesn't affect another", async () => {
const noisy = "198.51.100.9";
const statuses: number[] = [];
for (let i = 0; i < 25; i++) statuses.push((await call("GET", "/auth/login", { ip: noisy })).status);
assert.ok(statuses.includes(429), `no 429 in ${statuses.join(",")}`);
assert.equal(statuses[0], 302);
const limited = await call("GET", "/auth/login", { ip: noisy });
assert.equal(limited.status, 429);
assert.ok(Number(limited.headers["retry-after"]) > 0);
assert.equal((await call("GET", "/auth/login", { ip: "198.51.100.10" })).status, 302);
});
});
describe("requests from another origin", { skip: !haveOpenssl }, () => {
let adminCookie = "";
let serverId = 0;
const rotate = (headers: Record<string, string>) => call("POST", `/api/servers/${serverId}/rotate-token`, { cookie: adminCookie, headers });
const tokenHash = async () => (await db.select().from(tables.servers))[0].apiTokenHash;
before(async () => {
adminCookie = (await signIn("good", "alice")).newCookie!; // alice is the admin created above
const { generateApiToken } = await import("../src/services/tokens.js");
const { prefix, hash } = generateApiToken();
serverId = (await db.insert(tables.servers).values({ name: "victim-host", apiTokenHash: hash, apiTokenPrefix: prefix }).returning())[0].id;
});
test("a body-less POST from a sibling site is refused and does nothing", async () => {
const before = await tokenHash();
for (const site of ["same-site", "cross-site"]) {
const r = await rotate({ origin: "http://other-app.homelab.lan", "sec-fetch-site": site, "sec-fetch-mode": "no-cors" });
assert.equal(r.status, 403, `${site}: ${r.text}`);
assert.match(r.text, /cross_origin_request/);
}
assert.equal(await tokenHash(), before, "the token was rotated by a request from another origin");
});
test("the app's own pages still work (same-origin, or typed into the address bar)", async () => {
assert.equal((await rotate({ "sec-fetch-site": "same-origin", origin: "http://127.0.0.1:" + appPort })).status, 200);
assert.equal((await rotate({ "sec-fetch-site": "none" })).status, 200);
});
test("without Sec-Fetch-Site the Origin decides; no Origin at all means a script, not a browser", async () => {
assert.equal((await rotate({ origin: "http://evil.example" })).status, 403);
assert.equal((await rotate({ origin: "null" })).status, 403, "an opaque origin (a sandboxed frame) isn't this app");
assert.equal((await rotate({ origin: "http://127.0.0.1:" + appPort })).status, 200, "the host the browser reached");
assert.equal((await rotate({ origin: "http://app.test" })).status, 200, "the configured APP_BASE_URL");
assert.equal((await rotate({})).status, 200, "curl, no browser headers");
});
test("reading is never blocked", async () => {
const r = await call("GET", "/api/me", { cookie: adminCookie, headers: { "sec-fetch-site": "cross-site" } });
assert.equal(r.status, 200);
});
test("signing out from another page is refused, from the app itself it works", async () => {
const victim = (await signIn("good", "bob")).newCookie!;
const evil = await call("GET", "/auth/logout", { cookie: victim, headers: { "sec-fetch-site": "cross-site", "sec-fetch-dest": "image" } });
assert.equal(evil.status, 403);
assert.equal(await me(victim), 200, "a cross-site request signed the user out");
const own = await call("GET", "/auth/logout", { cookie: victim, headers: { "sec-fetch-site": "same-origin" } });
assert.equal(own.status, 302);
assert.notEqual(await me(victim), 200);
});
test("the agent endpoint, which uses a token and not a cookie, is not affected", async () => {
// Its own server and token: the rotate-token tests above change the shared one.
const { generateApiToken } = await import("../src/services/tokens.js");
const { token: agentToken, prefix, hash } = generateApiToken();
await db.insert(tables.servers).values({ name: "agent-host", apiTokenHash: hash, apiTokenPrefix: prefix });
const r = await new Promise<number>((resolve, reject) => {
const body = JSON.stringify({ hostname: "victim-host", tasks: [] });
const req = http.request(
{ host: "127.0.0.1", port: appPort, method: "POST", path: "/api/agent/report", headers: { authorization: `Bearer ${agentToken}`, "content-type": "application/json", "content-length": String(Buffer.byteLength(body)), "sec-fetch-site": "cross-site" } },
(res) => {
res.resume();
res.on("end", () => resolve(res.statusCode ?? 0));
},
);
req.on("error", reject);
req.end(body);
});
assert.equal(r, 202);
});
});
describe("headers", { skip: !haveOpenssl }, () => {
test("every response says it can't be framed or sniffed, and doesn't name the framework", async () => {
for (const path of ["/health", "/api/me", "/auth/login", "/no-such-page"]) {
const r = await call("GET", path);
assert.equal(r.headers["content-security-policy"], "frame-ancestors 'none'", path);
assert.equal(r.headers["x-frame-options"], "DENY", path);
assert.equal(r.headers["x-content-type-options"], "nosniff", path);
assert.equal(r.headers["referrer-policy"], "same-origin", path);
assert.equal(r.headers["x-powered-by"], undefined, path);
}
});
});
describe("session secret", () => {
test("production refuses to run without one, and warns about a weak one", () => {
assert.ok(checkSessionSecret(undefined, "production").fatal);
assert.ok(checkSessionSecret("", "production").fatal);
assert.ok(checkSessionSecret(SESSION_SECRET_PLACEHOLDER, "production").warning);
assert.equal(checkSessionSecret(SESSION_SECRET_PLACEHOLDER, "production").fatal, undefined, "an existing install must not be locked out by an upgrade");
assert.ok(checkSessionSecret("short", "production").warning);
assert.deepEqual(checkSessionSecret("a".repeat(64), "production"), {});
assert.deepEqual(checkSessionSecret(undefined, "development"), {}, "development may use the built-in default");
});
});