From 2dac273b1de96c8720d3f8d285a3f64e0a2a05e6 Mon Sep 17 00:00:00 2001 From: Bobban Rydh Date: Tue, 6 Oct 2026 23:35:34 +0200 Subject: [PATCH] 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 --- .env.example | 2 + README.md | 12 + package-lock.json | 1 + server/package.json | 1 + server/src/auth/idToken.ts | 37 +++ server/src/auth/oidc.ts | 4 + server/src/auth/router.ts | 92 ++++-- server/src/env.ts | 25 ++ server/src/utils/rateLimit.ts | 32 +++ server/src/utils/sameOriginGuard.ts | 44 +++ server/src/utils/securityHeaders.ts | 21 ++ server/test/login.test.ts | 428 ++++++++++++++++++++++++++++ 12 files changed, 681 insertions(+), 18 deletions(-) create mode 100644 server/src/auth/idToken.ts create mode 100644 server/src/utils/rateLimit.ts create mode 100644 server/src/utils/sameOriginGuard.ts create mode 100644 server/src/utils/securityHeaders.ts create mode 100644 server/test/login.test.ts diff --git a/.env.example b/.env.example index 3dbcb6e..ddb0e03 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,8 @@ APP_BASE_URL=https://homelab.example.lan # Random long string used to sign session cookies. Generate with: # node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" +# Required in production: without it the app refuses to start (the alternative is a value that is +# in the source code). Changing it signs everyone out. SESSION_SECRET=change-me-to-a-random-64-char-hex-string # 32-byte (64 hex char) key used to encrypt stored integration API tokens, and the diff --git a/README.md b/README.md index 62a9ece..7db7446 100644 --- a/README.md +++ b/README.md @@ -232,6 +232,18 @@ relatives), and connect to the address they checked rather than looking the name checks and scans; a WHOIS server must be public. IDs in a request (a device, a node, a DNS record) are checked against what a real ID looks like before they go into a call to a connected system. `npm test --workspace server` covers all of this. +**Signing in** — through Authentik (OpenID Connect) with PKCE and a random `state`. The ID token's signature is checked against Authentik's +published keys, not just its contents, so the login doesn't rest on the connection to Authentik alone. A new session id is issued at sign-in. A +request that changes something is refused when it comes from another origin: the session cookie is SameSite=Lax, which doesn't stop another app on +the same parent domain, so the server also checks where each such request came from. A failed sign-in shows a plain message and is written to the +audit log (as `session` / `login_failed`, with the address and a short reason), and sign-in is limited to 20 attempts a minute per address. +Every response carries `frame-ancestors 'none'`, `X-Frame-Options`, `nosniff` and a no-referrer-to-other-sites policy. In production the app +refuses to start without a `SESSION_SECRET`, and warns if it is still the placeholder from `.env.example`. +Things to know: the first account to sign in becomes admin, so sign in yourself first on a new install. A session lasts up to 7 days after last use, +and disabling someone in Authentik does not end it — delete them on the Users page (or revoke the session on the Sessions page) and it ends at once. +If Authentik uses a certificate from an internal CA, point Node at the CA with `NODE_EXTRA_CA_CERTS=/path/to/ca.pem` rather than turning verification +off with `NODE_TLS_REJECT_UNAUTHORIZED=0`. + **Privacy** — a page every signed-in user can open that says what this installation stores (accounts, sign-in sessions with their IP and browser, the audit and diagnostic logs, server reports, the secrets tracker, credentials), where data diff --git a/package-lock.json b/package-lock.json index 527ba2d..080ff6a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5002,6 +5002,7 @@ "drizzle-orm": "^0.45.2", "express": "^4.21.2", "express-session": "^1.18.1", + "jose": "^6.2.12", "mysql2": "^3.24.5", "node-schedule": "^2.1.1", "nodemailer": "^6.9.14", diff --git a/server/package.json b/server/package.json index 209d1f9..929c276 100644 --- a/server/package.json +++ b/server/package.json @@ -17,6 +17,7 @@ "drizzle-orm": "^0.45.2", "express": "^4.21.2", "express-session": "^1.18.1", + "jose": "^6.2.12", "mysql2": "^3.24.5", "node-schedule": "^2.1.1", "nodemailer": "^6.9.14", diff --git a/server/src/auth/idToken.ts b/server/src/auth/idToken.ts new file mode 100644 index 0000000..aa8d5c6 --- /dev/null +++ b/server/src/auth/idToken.ts @@ -0,0 +1,37 @@ +import * as client from "openid-client"; +import { createRemoteJWKSet, jwtVerify } from "jose"; +import { env } from "../env.js"; + +const keySets = new WeakMap>(); + +/** + * Checks the ID token's signature against the keys the identity provider publishes. + * + * openid-client already checks the token's claims (issuer, audience, expiry, subject) but, as OpenID Connect allows for a token + * received straight from the token endpoint, not its signature: it takes the HTTPS connection to the provider as proof of where + * the token came from. That makes the whole login only as strong as that connection — if certificate checking toward the + * provider is ever switched off (the usual way to cope with an internal CA is NODE_TLS_REJECT_UNAUTHORIZED=0), anyone on the + * network path could hand the app a token naming any user, the admin included. Verifying the signature as well means a weakened + * connection no longer lets a forged login through. + * + * Throws if the signature is wrong or the provider publishes no keys. + */ +export async function verifyIdTokenSignature(config: client.Configuration, idToken: string): Promise { + const metadata = config.serverMetadata(); + if (!metadata.jwks_uri) throw new Error("The identity provider publishes no signing keys (no jwks_uri)."); + + let keys = keySets.get(config); + if (!keys) { + // Fetched on demand and cached; an unknown key id (the provider rotated its key) triggers a re-fetch. + keys = createRemoteJWKSet(new URL(metadata.jwks_uri)); + keySets.set(config, keys); + } + + await jwtVerify(idToken, keys, { + issuer: metadata.issuer, + audience: env.authentik.clientId, + // The one algorithm openid-client itself accepts unless told otherwise, so this can't turn away a token the library would take. + algorithms: [config.clientMetadata().id_token_signed_response_alg ?? "RS256"], + clockTolerance: 60, + }); +} diff --git a/server/src/auth/oidc.ts b/server/src/auth/oidc.ts index f827213..6fd5757 100644 --- a/server/src/auth/oidc.ts +++ b/server/src/auth/oidc.ts @@ -10,6 +10,10 @@ export function getOidcConfig(): Promise { env.authentik.clientId, env.authentik.clientSecret, ); + // If the provider was unreachable this time, try again on the next sign-in — not never, until the app is restarted. + configPromise.catch(() => { + configPromise = null; + }); } return configPromise; } diff --git a/server/src/auth/router.ts b/server/src/auth/router.ts index 82bfae4..c3351fe 100644 --- a/server/src/auth/router.ts +++ b/server/src/auth/router.ts @@ -1,4 +1,4 @@ -import { Router } from "express"; +import { Router, type Request, type Response } from "express"; import * as client from "openid-client"; import { eq } from "drizzle-orm"; import { getOidcConfig } from "./oidc.js"; @@ -7,12 +7,54 @@ import { env } from "../env.js"; import { db } from "../db/client.js"; import { users } from "../db/schema.js"; import { recordAudit } from "../services/audit.js"; +import { verifyIdTokenSignature } from "./idToken.js"; +import { rateLimit } from "../utils/rateLimit.js"; export const authRouter = Router(); -authRouter.get("/login", async (req, res, next) => { +// Anyone can reach these two without an account. Each visit to /login starts a session and each failed callback is written to the +// audit log, so without a limit one script could fill the disk and the log. +const signInLimiter = rateLimit({ windowMs: 60_000, max: 20, message: "Too many sign-in attempts. Wait a minute and try again." }); + +const SIGN_IN_FAILED_PAGE = ` +Sign-in failed + +

Sign-in failed

+

Something went wrong while signing you in. Try again.

+

If it keeps failing, ask an administrator to look at the audit log.

+`; + +/** + * A sign-in that didn't work: the person gets a plain explanation (never the reason — that tells an attacker what to adjust), + * and the reason goes to the server log and, unless it's just a stale page, the audit log. + */ +async function failSignIn(req: Request, res: Response, reason: string, err?: unknown, options: { audit?: boolean } = {}) { + const message = err instanceof Error ? err.message : err === undefined ? undefined : String(err); + console.error(`[auth] sign-in failed (${reason})${message ? `: ${message}` : ""}`); + if (options.audit !== false) { + try { + await recordAudit({ + category: "session", + action: "login_failed", + targetType: "auth", + detail: { reason, ...(message ? { error: message.slice(0, 200) } : {}), ip: req.ip }, + }); + } catch (auditErr) { + console.error("[auth] couldn't record the failed sign-in:", auditErr); + } + } + delete req.session.pendingAuth; // a failed attempt's state and verifier can't be tried again + res.status(400).type("html").send(SIGN_IN_FAILED_PAGE); +} + +authRouter.get("/login", signInLimiter, async (req, res, next) => { try { - const config = await getOidcConfig(); + let config; + try { + config = await getOidcConfig(); + } catch (err) { + return await failSignIn(req, res, "provider_unreachable", err); + } const codeVerifier = client.randomPKCECodeVerifier(); const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier); const state = client.randomState(); @@ -37,24 +79,33 @@ authRouter.get("/login", async (req, res, next) => { } }); -authRouter.get("/callback", async (req, res, next) => { +authRouter.get("/callback", signInLimiter, async (req, res, next) => { try { const pending = req.session.pendingAuth; if (!pending) { - return res.status(400).send("Login session expired. Please try signing in again."); + // A page left open, or the callback address visited by hand: not worth an audit entry. + return await failSignIn(req, res, "no_pending_login", undefined, { audit: false }); } - const config = await getOidcConfig(); - const currentUrl = new URL(req.originalUrl, env.appBaseUrl); - - const tokens = await client.authorizationCodeGrant(config, currentUrl, { - pkceCodeVerifier: pending.codeVerifier, - expectedState: pending.state, - }); + let config; + let tokens; + try { + config = await getOidcConfig(); + const currentUrl = new URL(req.originalUrl, env.appBaseUrl); + tokens = await client.authorizationCodeGrant(config, currentUrl, { + pkceCodeVerifier: pending.codeVerifier, + expectedState: pending.state, + }); + if (!tokens.id_token) throw new Error("The identity provider returned no ID token."); + // Not just the claims: the signature too, so the login doesn't rest on the connection to the provider alone. + await verifyIdTokenSignature(config, tokens.id_token); + } catch (err) { + return await failSignIn(req, res, "provider_rejected", err); + } const claims = tokens.claims(); if (!claims?.sub) { - return res.status(400).send("Identity provider did not return a valid identity."); + return await failSignIn(req, res, "no_identity"); } let email: string | undefined = typeof claims.email === "string" ? claims.email : undefined; @@ -90,8 +141,7 @@ authRouter.get("/callback", async (req, res, next) => { detail: { name: user.name ?? user.email ?? user.oidcSub, ip: req.ip }, }); - delete req.session.pendingAuth; - req.session.user = { + const signedIn = { sub: claims.sub, email, name, @@ -99,9 +149,15 @@ authRouter.get("/callback", async (req, res, next) => { ip: req.ip, userAgent: req.headers["user-agent"], }; - req.session.save((err) => { - if (err) return next(err); - res.redirect("/"); + // A new session id for the signed-in session. Reusing the one the browser arrived with would let anyone who had planted that + // id beforehand (from another page on the same domain, say) be signed in as whoever then completes the login. + req.session.regenerate((regenerateErr) => { + if (regenerateErr) return next(regenerateErr); + req.session.user = signedIn; + req.session.save((saveErr) => { + if (saveErr) return next(saveErr); + res.redirect("/"); + }); }); } catch (err) { next(err); diff --git a/server/src/env.ts b/server/src/env.ts index 36e263c..b326057 100644 --- a/server/src/env.ts +++ b/server/src/env.ts @@ -19,6 +19,31 @@ export const env = { }, }; +/** What .env.example ships with. Anyone who read the repository knows it. */ +export const SESSION_SECRET_PLACEHOLDER = "change-me-to-a-random-64-char-hex-string"; + +/** + * Whether the session secret is fit to run production with. Missing is fatal (the app would fall back to a value in its own + * source code); the placeholder from .env.example or something short is a warning, not a refusal, so an existing install + * that has been running with one isn't locked out by an upgrade. + */ +export function checkSessionSecret(value: string | undefined, nodeEnv: string): { fatal?: string; warning?: string } { + if (nodeEnv !== "production") return {}; + if (!value) { + return { + fatal: + "SESSION_SECRET is not set. Sessions would be signed with a value that is public (it is in the source code). " + + "Set it to a long random string, e.g. node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\" " + + "(everyone is signed out when it changes).", + }; + } + if (value === SESSION_SECRET_PLACEHOLDER) { + return { warning: "SESSION_SECRET is still the placeholder from .env.example, which is public. Replace it with a random value (everyone is signed out when it changes)." }; + } + if (value.length < 32) return { warning: "SESSION_SECRET is shorter than 32 characters. Use a long random value." }; + return {}; +} + export function warnIfAuthNotConfigured() { if (!env.authEnabled) { console.warn( diff --git a/server/src/utils/rateLimit.ts b/server/src/utils/rateLimit.ts new file mode 100644 index 0000000..c0d9a46 --- /dev/null +++ b/server/src/utils/rateLimit.ts @@ -0,0 +1,32 @@ +import type { NextFunction, Request, Response } from "express"; + +/** + * A small fixed-window limiter, per client address. It exists for the sign-in endpoints, which anyone can reach without an + * account: each visit to /auth/login starts a session, and each failed callback is written to the audit log, so without a + * limit one script could fill the disk and the log. Kept in memory — a restart clears it, which is fine for this. + */ +export function rateLimit(options: { windowMs: number; max: number; message: string }) { + const windows = new Map(); + + return (req: Request, res: Response, next: NextFunction) => { + const now = Date.now(); + const key = req.ip ?? "unknown"; + + if (windows.size > 10_000) { + for (const [k, w] of windows) if (w.resetAt <= now) windows.delete(k); + } + + let entry = windows.get(key); + if (!entry || entry.resetAt <= now) { + entry = { count: 0, resetAt: now + options.windowMs }; + windows.set(key, entry); + } + entry.count++; + + if (entry.count > options.max) { + res.setHeader("Retry-After", String(Math.ceil((entry.resetAt - now) / 1000))); + return res.status(429).type("text/plain").send(options.message); + } + next(); + }; +} diff --git a/server/src/utils/sameOriginGuard.ts b/server/src/utils/sameOriginGuard.ts new file mode 100644 index 0000000..df7e7cf --- /dev/null +++ b/server/src/utils/sameOriginGuard.ts @@ -0,0 +1,44 @@ +import type { NextFunction, Request, Response } from "express"; +import { env } from "../env.js"; + +/** + * Refuses a request that changes something when it was made by a page on another origin. + * + * The session cookie is SameSite=Lax, which stops *other sites* from sending it. It does not stop another app on the same + * parent domain (dockge.home.lan against hm.home.lan is "same site"), and a POST with no body — stop a guest, restart a + * container, rotate a token — needs no preflight and does exactly what it says. So the server asks the browser where the request + * came from. + * + * Modern browsers say so in Sec-Fetch-Site, and a page can't change it. For anything older, a browser always sends Origin + * with a cross-origin POST, so a request whose Origin isn't this app is refused. A request with neither header isn't from a + * browser (curl, a script) and has no ambient cookie to abuse, so it passes. + * + * Covered: every POST, PUT, PATCH and DELETE, and GET /auth/logout (signing someone out from another page is a + * nuisance, and it also ends their Authentik session). Not covered: the OIDC callback, which is a GET that + * legitimately arrives from the identity provider, and the agent endpoint, which uses a token and is mounted ahead of this. + */ +export function sameOriginGuard(req: Request, res: Response, next: NextFunction) { + const changesSomething = !["GET", "HEAD", "OPTIONS"].includes(req.method) || (req.method === "GET" && req.path === "/auth/logout"); + if (!changesSomething) return next(); + + const site = req.get("sec-fetch-site"); + if (site !== undefined) { + if (site === "same-origin" || site === "none") return next(); + return refuse(res); + } + + const origin = req.get("origin"); + if (origin === undefined) return next(); + try { + const host = new URL(origin).host; + const own = [req.get("host"), req.get("x-forwarded-host"), new URL(env.appBaseUrl).host]; + if (own.includes(host)) return next(); + } catch { + // an Origin that isn't a URL ("null", from a sandboxed frame) is not ours either + } + return refuse(res); +} + +function refuse(res: Response) { + return res.status(403).json({ error: "cross_origin_request", message: "This request came from a different origin than the app, so it was refused." }); +} diff --git a/server/src/utils/securityHeaders.ts b/server/src/utils/securityHeaders.ts new file mode 100644 index 0000000..f69e487 --- /dev/null +++ b/server/src/utils/securityHeaders.ts @@ -0,0 +1,21 @@ +import type { NextFunction, Request, Response } from "express"; + +/** + * Headers every response carries. Deliberately small: a full Content-Security-Policy would have to be tuned to the UI's own + * styles and scripts, and a wrong one breaks the app. + * + * - frame-ancestors 'none' / X-Frame-Options: nobody can put this app in a frame on another site and have someone click + * through it (the old header is for browsers that don't read the CSP one). + * - nosniff: a response is never reinterpreted as a different kind of file. + * - Referrer-Policy: the address of a page here isn't sent along when someone follows a link to another site — admin links + * and integration pages are exactly such links. + * + * No Strict-Transport-Security: whether the app is only ever reached over HTTPS is for the reverse proxy in front of it to say. + */ +export function securityHeaders(_req: Request, res: Response, next: NextFunction) { + res.setHeader("Content-Security-Policy", "frame-ancestors 'none'"); + res.setHeader("X-Frame-Options", "DENY"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.setHeader("Referrer-Policy", "same-origin"); + next(); +} diff --git a/server/test/login.test.ts b/server/test/login.test.ts new file mode 100644 index 0000000..b36f9a8 --- /dev/null +++ b/server/test/login.test.ts @@ -0,0 +1,428 @@ +/** + * 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(); + +async function startProvider(): Promise { + 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((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; ip?: string } = {}): Promise { + return new Promise((resolve, reject) => { + const headers: Record = { "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((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) => 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((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"); + }); +});