fix(auth): harden the OIDC token path and state-cookie lifecycle

Token verification: jwtVerify now carries a closed asymmetric algorithm
allowlist (RS256/PS256/ES256/EdDSA — an HMAC alg would let anyone with
the client secret forge identities) and a 60 s clock tolerance for the
usual self-host drift between IdP and app box. The JWKS fetch — jose's
own, outside safeFetch by design — is disciplined instead by pinning
the jwks_uri host to the configured issuer's host byte-exact and
passing the same 15 s timeout safeFetch defaults to. requirePublicHost
stays deliberately unused on this surface: LAN/Tailscale-only IdPs are
a legitimate topology and the issuer is operator config, not user
input.

Discovery: the issuer comparison now tolerates exactly one trailing
slash on either side (a recurring IdP/operator mismatch); token
verification still matches the provider-sent issuer byte-exact.

State cookie: the cookie is set under Path=/api/auth/oidc but was
deleted without a path — RFC 6265 keys cookies by (name, domain,
path), so the deletion never matched and the single-use blob survived
its whole TTL. Every delete now repeats the exact path, via a shared
constant.

Also: the IdP error code recorded in the wide event is whitelisted
against the closed OAuth error-code set (unknown values collapse to
"other"); the status route drops an unreachable try/catch and a
duplicated annotate; the passkey conditional-UI autofill stays unarmed
under OIDC_ONLY (passkey login is a server-enforced dead end there);
env-manifest gains the three optional OIDC_* tuning vars; the env
example notes why the issuer should be HTTPS.
This commit is contained in:
Marc-André Bombeck committed 2026-07-14 11:53:53 +02:00
1 parent 9b8b31c864
commit 7592c73947
10 files changed
+252 -32

No files matched your search

@@ -459,4 +459,25 @@ describe("GET /api/auth/oidc/callback", () => {
const res = await GET(validRequest());
expect(res.headers.get("location")).toContain("error=oidc_failed");
});
it("deletes the state cookie with the exact path it was set under", async () => {
// RFC 6265 keys cookies by (name, domain, path) — a deletion without
// `Path=/api/auth/oidc` would target a `/`-scoped cookie that does not
// exist and leave the real single-use blob alive.
const errorRes = await GET(makeRequest({ query: "?error=access_denied" }));
const errorCookie = errorRes.headers
.getSetCookie()
.find((c) => c.startsWith("oidc_auth_state="))!;
expect(errorCookie.toLowerCase()).toContain("path=/api/auth/oidc");
mockIdentity();
mockUserLookups({
byIdentity: userRow({ oidcIssuer: METADATA.issuer, oidcSub: "sub-1" }),
});
const successRes = await GET(validRequest());
const successCookie = successRes.headers
.getSetCookie()
.find((c) => c.startsWith("oidc_auth_state="))!;
expect(successCookie.toLowerCase()).toContain("path=/api/auth/oidc");
});
});
+47 -4
View File
@@ -22,6 +22,7 @@ import {
OIDC_MFA_COOKIE_PATH,
OIDC_MFA_TTL_MS,
OIDC_STATE_COOKIE,
OIDC_STATE_COOKIE_PATH,
} from "@/lib/auth/oidc-cookie";
import { createMfaChallenge } from "@/lib/auth/mfa/challenge";
import { syncMfaEnrollCookie } from "@/lib/auth/mfa-enrollment";
@@ -34,10 +35,47 @@ function errorRedirect(req: NextRequest, reason: string): NextResponse {
const response = NextResponse.redirect(
new URL(`${LOGIN_ERROR_URL}?error=${reason}`, req.url),
);
response.cookies.delete(OIDC_STATE_COOKIE);
deleteStateCookie(response);
return response;
}
/**
* The state cookie is set with `path: "/api/auth/oidc"`; the delete must
* repeat that path (RFC 6265 keys cookies by name+domain+path — a bare
* delete would target `/` and never match, leaving the single-use blob
* alive for the rest of its TTL).
*/
function deleteStateCookie(response: NextResponse): void {
response.cookies.delete({
name: OIDC_STATE_COOKIE,
path: OIDC_STATE_COOKIE_PATH,
});
}
/**
* Closed set of RFC 6749 §4.1.2.1 / OIDC Core §3.1.2.6 authorization error
* codes. The wide-event meta only ever carries a member of this set (or
* "other") — never the raw, attacker-influenceable query value.
*/
const KNOWN_IDP_ERROR_CODES = new Set([
"access_denied",
"invalid_request",
"unauthorized_client",
"unsupported_response_type",
"invalid_scope",
"server_error",
"temporarily_unavailable",
"interaction_required",
"login_required",
"account_selection_required",
"consent_required",
"invalid_request_uri",
"invalid_request_object",
"request_not_supported",
"request_uri_not_supported",
"registration_not_supported",
]);
interface StoredOidcState {
state: string;
nonce: string;
@@ -82,7 +120,12 @@ export const GET = apiHandler(async (req: NextRequest) => {
const { searchParams } = req.nextUrl;
const idpError = searchParams.get("error");
if (idpError) {
annotate({ meta: { reason: "idp_denied", idpError } });
annotate({
meta: {
reason: "idp_denied",
idpError: KNOWN_IDP_ERROR_CODES.has(idpError) ? idpError : "other",
},
});
return errorRedirect(req, "oidc_denied");
}
@@ -299,7 +342,7 @@ export const GET = apiHandler(async (req: NextRequest) => {
loginUrl.searchParams.set("next", stored.next);
}
const response = NextResponse.redirect(loginUrl);
response.cookies.delete(OIDC_STATE_COOKIE);
deleteStateCookie(response);
response.cookies.set(
OIDC_MFA_COOKIE,
JSON.stringify({ ticket: challenge.ticket, methods }),
@@ -341,7 +384,7 @@ export const GET = apiHandler(async (req: NextRequest) => {
await auditLog("auth.oidc.login", { userId: user.id, ipAddress: ip });
const response = NextResponse.redirect(new URL(stored.next, req.url));
response.cookies.delete(OIDC_STATE_COOKIE);
deleteStateCookie(response);
return response;
} catch (err) {
getEvent()?.setError(err);
+8 -2
View File
@@ -13,7 +13,11 @@ import {
getOidcRedirectUri,
sanitizeOidcNextPath,
} from "@/lib/auth/oidc";
import { OIDC_STATE_COOKIE, OIDC_STATE_TTL_MS } from "@/lib/auth/oidc-cookie";
import {
OIDC_STATE_COOKIE,
OIDC_STATE_COOKIE_PATH,
OIDC_STATE_TTL_MS,
} from "@/lib/auth/oidc-cookie";
/**
* Redirects the browser to the configured OIDC provider's authorization
@@ -84,7 +88,9 @@ export const GET = apiHandler(async (req: NextRequest) => {
// the session cookie and the Withings OAuth state cookie.
sameSite: "lax",
maxAge: Math.floor(OIDC_STATE_TTL_MS / 1000),
path: "/api/auth/oidc",
// Shared constant — the callback's delete must repeat this exact path
// (RFC 6265 keys cookies by name+domain+path).
path: OIDC_STATE_COOKIE_PATH,
});
return response;
+9 -14
View File
@@ -6,19 +6,14 @@ import { getOidcConfig, isOidcOnly } from "@/lib/auth/oidc";
export const dynamic = "force-dynamic";
/** Public — the login page reads this pre-session to decide whether to
* render the SSO button and whether to hide password/passkey login. */
* render the SSO button and whether to hide password/passkey login. Pure
* env reads; nothing here can throw. */
export const GET = apiHandler(async () => {
try {
const config = getOidcConfig();
annotate({ action: { name: "auth.oidc.status" } });
return apiSuccess({
enabled: config !== null,
buttonLabel: config?.buttonLabel ?? null,
only: isOidcOnly(),
});
} catch {
// Fail closed, matching registration-status.
annotate({ action: { name: "auth.oidc.status" } });
return apiSuccess({ enabled: false, buttonLabel: null, only: false });
}
annotate({ action: { name: "auth.oidc.status" } });
const config = getOidcConfig();
return apiSuccess({
enabled: config !== null,
buttonLabel: config?.buttonLabel ?? null,
only: isOidcOnly(),
});
});