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>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-06 23:35:34 +02:00
1 parent 73b86d88de
commit 2dac273b1d
12 files changed
+681 -18

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
import * as client from "openid-client";
import { createRemoteJWKSet, jwtVerify } from "jose";
import { env } from "../env.js";
const keySets = new WeakMap<client.Configuration, ReturnType<typeof createRemoteJWKSet>>();
/**
* 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<void> {
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,
});
}
+4
View File
@@ -10,6 +10,10 @@ export function getOidcConfig(): Promise<client.Configuration> {
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;
}
+74 -18
View File
@@ -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 = `<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Sign-in failed</title></head>
<body style="font-family: system-ui, sans-serif; max-width: 32rem; margin: 4rem auto; padding: 0 1rem; line-height: 1.5">
<h1>Sign-in failed</h1>
<p>Something went wrong while signing you in. <a href="/auth/login">Try again</a>.</p>
<p>If it keeps failing, ask an administrator to look at the audit log.</p>
</body></html>`;
/**
* 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);
+25
View File
@@ -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(
+32
View File
@@ -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<string, { count: number; resetAt: number }>();
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();
};
}
+44
View File
@@ -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." });
}
+21
View File
@@ -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();
}