fix(oidc): sign-in no longer fails on a duplicated service-worker callback

A browser SSO sign-in landed on /auth/login?error=oidc_failed even though it
had succeeded. Two layers conspired:

- The service worker enables navigation preload, but its fetch handler returned
  early for /api/ paths without calling event.respondWith(). For the OIDC
  login/callback navigations that left the preload unconsumed, so the browser
  also ran its own default fetch and the callback was requested twice. The
  first request redeemed the single-use authorization code and set the session;
  the second tried to redeem the now-consumed code, failed at the IdP token
  endpoint, and that 307 to the error page is what the user saw.

- Even with the double request gone, a legitimate retry (proxy, double
  navigation) hit the same wall on the server.

Fix both layers:

- The worker settles /api/auth/* navigations itself, consuming the preload
  response (or fetching once when there is none), so exactly one request
  reaches the server. These responses are never cached.

- The callback is idempotent. When the single-use state cookie is already
  consumed but the request carries a database-validated, unexpired session, the
  callback treats it as a duplicate of a completed login and redirects into the
  app instead of surfacing an error. The authorization code is never exchanged
  on this branch, and a consumed/forged/expired state from a caller with no
  valid session still fails closed with the unchanged oidc_state error.

Refs #600
This commit is contained in:
Marc-André Bombeck committed 2026-07-23 15:08:31 +02:00
1 parent e39161ad14
commit 60d5416cf8
5 files changed
+232 -4

No files matched your search

@@ -38,7 +38,11 @@ vi.mock("@/lib/db", () => ({
}));
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
vi.mock("@/lib/auth/session", () => ({ createSession: vi.fn() }));
vi.mock("@/lib/auth/session", () => ({
createSession: vi.fn(),
validateSessionFromCookieValue: vi.fn(),
SESSION_COOKIE_NAME: "healthlog_session",
}));
vi.mock("@/lib/auth/login-alert", () => ({ recordSignInDevice: vi.fn() }));
vi.mock("@/lib/auth/mfa/challenge", () => ({
createMfaChallenge: vi.fn(async () => ({
@@ -84,7 +88,10 @@ import { GET } from "../route";
import { checkAuthSurfaceRateLimit } from "@/lib/rate-limit";
import { prisma } from "@/lib/db";
import { auditLog } from "@/lib/auth/audit";
import { createSession } from "@/lib/auth/session";
import {
createSession,
validateSessionFromCookieValue,
} from "@/lib/auth/session";
import { createMfaChallenge } from "@/lib/auth/mfa/challenge";
import {
getOidcConfig,
@@ -591,6 +598,52 @@ describe("GET /api/auth/oidc/callback", () => {
});
});
describe("GET /api/auth/oidc/callback — duplicate-callback idempotency", () => {
// A duplicated callback for the SAME sign-in: the first callback already
// redeemed the single-use code, set the session cookie, and deleted the
// single-use state cookie — so the duplicate arrives with a live `code` +
// `state` in the query but NO state cookie. Whether it also fails closed
// turns entirely on whether a VALIDATED session is present.
function duplicateRequest(withSession: boolean): NextRequest {
const req = new NextRequest(
"http://localhost/api/auth/oidc/callback?code=abc&state=STATE",
);
if (withSession) req.cookies.set("healthlog_session", "hls_valid_secret");
return req;
}
it("redirects a duplicate into the app when a valid session is present, WITHOUT re-redeeming the code", async () => {
vi.mocked(validateSessionFromCookieValue).mockResolvedValue({
session: { id: "sess-1", expiresAt: new Date(Date.now() + 1_000_000) },
user: userRow() as never,
} as never);
const res = await GET(duplicateRequest(true));
const location = res.headers.get("location")!;
// Lands in the app, not on the error page.
expect(location).not.toContain("error=");
expect(new URL(location).pathname).toBe("/");
// The now-consumed authorization code is NEVER exchanged again, and no
// second session is minted — the redirect is inert.
expect(exchangeCodeForTokens).not.toHaveBeenCalled();
expect(createSession).not.toHaveBeenCalled();
});
it("still fails closed (oidc_state) for a consumed/forged state with NO valid session", async () => {
// The security assertion: a caller who presents a real-looking callback
// but holds no valid session gets the unchanged error and the code is
// never redeemed. This must stay red if the fail-closed path is weakened.
vi.mocked(validateSessionFromCookieValue).mockResolvedValue(null);
const res = await GET(duplicateRequest(false));
expect(res.headers.get("location")).toContain("error=oidc_state");
expect(exchangeCodeForTokens).not.toHaveBeenCalled();
expect(createSession).not.toHaveBeenCalled();
});
});
describe("GET /api/auth/oidc/callback — native branch", () => {
beforeEach(() => {
vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({
+38 -2
View File
@@ -6,7 +6,11 @@ import { checkAuthSurfaceRateLimit } from "@/lib/rate-limit";
import { decrypt } from "@/lib/crypto";
import { prisma } from "@/lib/db";
import { auditLog } from "@/lib/auth/audit";
import { createSession } from "@/lib/auth/session";
import {
createSession,
validateSessionFromCookieValue,
SESSION_COOKIE_NAME,
} from "@/lib/auth/session";
import { recordSignInDevice } from "@/lib/auth/login-alert";
import {
deriveUniqueUsername,
@@ -195,7 +199,39 @@ export const GET = apiHandler(async (req: NextRequest) => {
// and there is nothing safe to hand the app (spec §1 web-fallback).
if (!code || !state) return errorRedirect("oidc_state");
if (!stored) return errorRedirect("oidc_state");
if (!stored) {
// Defence-in-depth idempotency for a duplicated callback. The single-use
// state cookie is set with `path: "/api/auth/oidc"` and DELETED by the
// first callback the moment it succeeds. A second callback for the same
// sign-in (a client/proxy retry, a double navigation, or the
// service-worker double-request this release also fixes) therefore arrives
// with the state cookie already gone — `stored` is null — and, because the
// first callback set the session, it carries a live session cookie.
// Redeeming the now-consumed authorization code again fails at the IdP and
// surfaces `?error=oidc_failed` on a sign-in that actually succeeded. So
// when a VALIDATED session is present, treat this as a duplicate of a
// completed login and send the user into the app instead of erroring.
//
// Fail-closed is preserved for the real attack case: the code is NEVER
// exchanged on this branch, and the session is resolved against the
// database + its expiry (not merely "a cookie is present"). A forged,
// replayed, or expired state from a caller with no valid session gets the
// unchanged `oidc_state` error; a caller who already holds their own valid
// session gains nothing here but a redirect to a page they could already
// reach — no code redemption, no session mint, no identity change.
const existingSession = await validateSessionFromCookieValue(
req.cookies.get(SESSION_COOKIE_NAME)?.value,
);
if (existingSession) {
annotate({ meta: { reason: "duplicate_callback_authenticated" } });
const response = NextResponse.redirect(oidcAppUrl("/"));
// The state cookie is already consumed; delete defensively so a stray
// blob can never outlive this response.
deleteStateCookie(response);
return response;
}
return errorRedirect("oidc_state");
}
// CSRF check — timing-safe, byte-for-byte, mirroring the Withings callback.
if (