🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix: sidestep 500 on NextAuth HTML routes when callback URL is invalid (#16461)
Valery Meleshkin8f5fff8d3da6
diff --git a/web/src/__tests__/server/unit/next-auth-route-malformed-input.servertest.ts b/web/src/__tests__/server/unit/next-auth-route-malformed-input.servertest.tsindex 694493d5ef..b8cb226b57 100644--- a/web/src/__tests__/server/unit/next-auth-route-malformed-input.servertest.ts+++ b/web/src/__tests__/server/unit/next-auth-route-malformed-input.servertest.ts@@ -104,6 +104,49 @@ function createRequest({return { req, res };}+const callbackUrlCookieName = "next-auth.callback-url";+const htmlActions = ["signin", "signout", "error", "verify-request"] as const;+const expectedHtmlActionStatus = {+ signin: 302,+ signout: 200,+ error: 302,+ "verify-request": 200,+} as const;+const duplicateCallbackUrl = ["/home", "https://evil.com"];++const getHeaderText = (res: NextApiResponse, name: string) => {+ const value = res.getHeader(name);+ return Array.isArray(value) ? value.join("\n") : String(value ?? "");+};++const callAuthWithoutInvalidCallbackUrlError = async (+ req: NextApiRequest,+ res: NextApiResponse,+) => {+ const consoleError = vi+ .spyOn(console, "error")+ .mockImplementation(() => undefined);++ try {+ await auth(req, res);+ expect(+ consoleError.mock.calls.some((args) =>+ args.some((argument) =>+ String(argument).includes("INVALID_CALLBACK_URL_ERROR"),+ ),+ ),+ ).toBe(false);+ } finally {+ consoleError.mockRestore();+ }+};++const expectSafeCallbackUrlResponse = (res: NextApiResponse) => {+ expect(res.statusCode).toBeLessThan(500);+ expect(getHeaderText(res, "Location")).not.toContain("evil.com");+ expect(getHeaderText(res, "Set-Cookie")).not.toContain("evil.com");+};+describe("NextAuth error route malformed input handling", () => {beforeEach(() => {vi.clearAllMocks();@@ -150,6 +193,32 @@ describe("NextAuth error route malformed input handling", () => {);});+ for (const action of htmlActions) {+ it(`sanitizes duplicated callbackUrl query parameters for GET ${action} (/home first)`, async () => {+ const { req, res } = createRequest({+ nextauth: [action],+ query: { callbackUrl: duplicateCallbackUrl },+ });++ await callAuthWithoutInvalidCallbackUrlError(req, res);++ expect(res.statusCode).toBe(expectedHtmlActionStatus[action]);+ expectSafeCallbackUrlResponse(res);+ });+ }++ it("sanitizes an invalid callback-url cookie for GET signin", async () => {+ const { req, res } = createRequest({+ nextauth: ["signin"],+ cookies: { [callbackUrlCookieName]: "https://evil.com%0d%0a" },+ });++ await callAuthWithoutInvalidCallbackUrlError(req, res);++ expect(res.statusCode).toBe(expectedHtmlActionStatus.signin);+ expectSafeCallbackUrlResponse(res);+ });+it("uses a generic error for an ambiguous array-valued error", async () => {const { req, res } = createRequest({nextauth: ["error"],diff --git a/web/src/__tests__/server/unit/nextauth-invalid-callback-url.servertest.ts b/web/src/__tests__/server/unit/nextauth-invalid-callback-url.servertest.tsindex b9657137d4..d22fa09eda 100644--- a/web/src/__tests__/server/unit/nextauth-invalid-callback-url.servertest.ts+++ b/web/src/__tests__/server/unit/nextauth-invalid-callback-url.servertest.ts@@ -1,10 +1,38 @@import type { NextApiRequest, NextApiResponse } from "next";import { createMocks } from "node-mocks-http";-const { mockNextAuth, mockGetAuthOptions } = vi.hoisted(() => ({- mockNextAuth: vi.fn(async (_req: unknown, res: any) => res.status(200).end()),- mockGetAuthOptions: vi.fn(async () => ({})),-}));+type NextAuthRequestSnapshot = Pick<NextApiRequest, "query" | "cookies">;++const {+ mockNextAuth,+ mockGetAuthOptions,+ mockLoggerWarn,+ mockNextAuthRequestSnapshot,+} = vi.hoisted(() => {+ const mockNextAuthRequestSnapshot =+ vi.fn<(snapshot: NextAuthRequestSnapshot) => void>();+ const mockNextAuth = vi.fn(+ async (req: NextApiRequest, res: NextApiResponse) => {+ mockNextAuthRequestSnapshot({+ query: Object.fromEntries(+ Object.entries(req.query).map(([key, value]) => [+ key,+ Array.isArray(value) ? [...value] : value,+ ]),+ ),+ cookies: { ...req.cookies },+ });+ res.status(200).end();+ },+ );++ return {+ mockNextAuth,+ mockGetAuthOptions: vi.fn(async () => ({})),+ mockLoggerWarn: vi.fn(),+ mockNextAuthRequestSnapshot,+ };+});vi.mock("next-auth", () => ({ default: mockNextAuth }));@@ -17,7 +45,7 @@ vi.mock("@langfuse/shared/src/server", () => ({logger: {debug: vi.fn(),info: vi.fn(),- warn: vi.fn(),+ warn: mockLoggerWarn,error: vi.fn(),},ClickHouseClientManager: {@@ -39,6 +67,13 @@ vi.mock("@/src/env.mjs", () => ({import handler from "@/src/pages/api/auth/[...nextauth]";+const callbackUrlCookieName = "next-auth.callback-url";++const getNextAuthRequest = (): NextAuthRequestSnapshot => {+ expect(mockNextAuthRequestSnapshot).toHaveBeenCalledTimes(1);+ return mockNextAuthRequestSnapshot.mock.calls[0]![0];+};+const callHandler = async (options: Parameters<typeof createMocks>[0] = {}) => {const { req, res } = createMocks<NextApiRequest, NextApiResponse>({method: "GET",@@ -46,7 +81,7 @@ const callHandler = async (options: Parameters<typeof createMocks>[0] = {}) => {...options,});await handler(req, res);- return { req, res };+ return { res };};describe("[...nextauth] invalid callbackUrl handling", () => {@@ -122,6 +157,9 @@ describe("[...nextauth] invalid callbackUrl handling", () => {expect(res._getStatusCode()).toBe(200);expect(mockNextAuth).toHaveBeenCalledTimes(1);+ expect(getNextAuthRequest().query.callbackUrl).toBe(+ "https://cloud.langfuse.com/project/abc",+ );});it("passes through a relative callbackUrl", async () => {@@ -134,6 +172,7 @@ describe("[...nextauth] invalid callbackUrl handling", () => {expect(res._getStatusCode()).toBe(200);expect(mockNextAuth).toHaveBeenCalledTimes(1);+ expect(getNextAuthRequest().query.callbackUrl).toBe("/project/abc");});it("passes through a valid callback-url cookie", async () => {@@ -143,6 +182,9 @@ describe("[...nextauth] invalid callbackUrl handling", () => {expect(res._getStatusCode()).toBe(200);expect(mockNextAuth).toHaveBeenCalledTimes(1);+ expect(getNextAuthRequest().cookies[callbackUrlCookieName]).toBe(+ "https://cloud.langfuse.com",+ );});it("passes through when no callbackUrl is present", async () => {@@ -150,6 +192,8 @@ describe("[...nextauth] invalid callbackUrl handling", () => {expect(res._getStatusCode()).toBe(200);expect(mockNextAuth).toHaveBeenCalledTimes(1);+ expect(getNextAuthRequest().query.callbackUrl).toBeUndefined();+ expect(getNextAuthRequest().cookies[callbackUrlCookieName]).toBeUndefined();});it("passes through an empty callbackUrl query param (next-auth treats it as absent)", async () => {@@ -159,6 +203,7 @@ describe("[...nextauth] invalid callbackUrl handling", () => {expect(res._getStatusCode()).toBe(200);expect(mockNextAuth).toHaveBeenCalledTimes(1);+ expect(getNextAuthRequest().query.callbackUrl).toBe("");});it("passes through an empty callback-url cookie (next-auth treats it as absent)", async () => {@@ -168,15 +213,58 @@ describe("[...nextauth] invalid callbackUrl handling", () => {expect(res._getStatusCode()).toBe(200);expect(mockNextAuth).toHaveBeenCalledTimes(1);+ expect(getNextAuthRequest().cookies[callbackUrlCookieName]).toBe("");});- it("passes an invalid callbackUrl through on GET signin (next-auth redirects to its error page instead of 500ing)", async () => {+ it("removes an invalid callbackUrl before passing GET signin to next-auth", async () => {const { res } = await callHandler({query: { nextauth: ["signin"], callbackUrl: "www.example.com/foo" },});expect(res._getStatusCode()).toBe(200);expect(mockNextAuth).toHaveBeenCalledTimes(1);+ expect(getNextAuthRequest().query.callbackUrl).toBeUndefined();+ });++ it("removes invalid callbackUrl query and cookie independently before GET signin", async () => {+ const { res } = await callHandler({+ query: {+ nextauth: ["signin"],+ callbackUrl: ["https://evil.com", "/home"],+ },+ cookies: { [callbackUrlCookieName]: "https://evil.com%0d%0a" },+ });++ expect(res._getStatusCode()).toBe(200);+ const nextAuthRequest = getNextAuthRequest();+ expect(nextAuthRequest.query.callbackUrl).toBeUndefined();+ expect(nextAuthRequest.cookies[callbackUrlCookieName]).toBeUndefined();+ expect(mockLoggerWarn).toHaveBeenCalledTimes(2);++ const warningMetadata = mockLoggerWarn.mock.calls.map(+ ([message, metadata]) => {+ expect(message).toBe("[NEXT_AUTH] Invalid callback URL");+ expect(Object.keys(metadata).sort()).toEqual(+ ["action", "path", "inputSource", "valueType"].sort(),+ );+ expect(JSON.stringify(metadata)).not.toContain("evil.com");+ return metadata;+ },+ );+ expect(warningMetadata).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ action: "signin",+ inputSource: "query",+ valueType: "array",+ }),+ expect.objectContaining({+ action: "signin",+ inputSource: "cookie",+ valueType: "string",+ }),+ ]),+ );});it("rejects an invalid callbackUrl on POST signin with 400 (no HTML error-page carve-out for POST)", async () => {diff --git a/web/src/pages/api/auth/[...nextauth].ts b/web/src/pages/api/auth/[...nextauth].tsindex cc6b8c16e7..cd1501105f 100644--- a/web/src/pages/api/auth/[...nextauth].ts+++ b/web/src/pages/api/auth/[...nextauth].ts@@ -11,6 +11,10 @@ const maxAuthErrorLength = 1_000;const authErrorFallback = "Configuration";type AuthErrorSource = "query" | "path";+type CallbackUrlInputSource = "query" | "cookie";++const getCallbackUrlValueType = (value: unknown) =>+ Array.isArray(value) ? "array" : typeof value;// Single parse of the [...nextauth] catch-all: [action, provider], e.g.// /api/auth/callback/credentials -> ["callback", "credentials"].@@ -82,31 +86,55 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {// next-auth rejects malformed callbackUrl values (query param or cookie)// with a hardcoded 500, so vulnerability scanners probing auth routes page- // our server-error monitors. Malformed client input is a 4xx; reject it- // before next-auth sees it. Two carve-outs keep parity with next-auth:- // falsy values are treated as absent (assertConfig checks truthiness), and- // GET requests to next-auth's HTML page actions are exempt — those never- // 500; next-auth redirects them to the configured error page.+ // our server-error monitors. Falsy values are treated as absent because+ // next-auth's assertConfig checks truthiness. For GET requests to next-auth's+ // HTML page actions, remove malformed inputs and let next-auth render its+ // normal flow; other actions retain the 400 boundary.const rendersHtmlErrorPage =req.method === "GET" &&["signin", "signout", "error", "verify-request"].includes(nextAuthAction ?? "",);+ const callbackUrlCookieName = getCookieName("next-auth.callback-url");const callbackUrlParam = req.query.callbackUrl;- const callbackUrlCookie =- req.cookies[getCookieName("next-auth.callback-url")];- const invalidCallbackUrl =- !rendersHtmlErrorPage &&- ((Boolean(callbackUrlParam) && !isValidCallbackUrl(callbackUrlParam)) ||- (Boolean(callbackUrlCookie) && !isValidCallbackUrl(callbackUrlCookie)));- if (invalidCallbackUrl) {- logger.warn("[NEXT_AUTH] Rejected invalid callback URL", {- callbackUrlParamType: Array.isArray(callbackUrlParam)- ? "array"- : typeof callbackUrlParam,- callbackUrlCookiePresent: Boolean(callbackUrlCookie),+ const callbackUrlCookie = req.cookies[callbackUrlCookieName];+ const invalidCallbackUrlParam =+ Boolean(callbackUrlParam) && !isValidCallbackUrl(callbackUrlParam);+ const invalidCallbackUrlCookie =+ Boolean(callbackUrlCookie) && !isValidCallbackUrl(callbackUrlCookie);++ const logInvalidCallbackUrl = (+ inputSource: CallbackUrlInputSource,+ value: unknown,+ ) => {+ logger.warn("[NEXT_AUTH] Invalid callback URL", {+ action: nextAuthAction,path: req.url?.split("?")[0]?.slice(0, 200),+ inputSource,+ valueType: getCallbackUrlValueType(value),});+ };++ if (invalidCallbackUrlParam) {+ logInvalidCallbackUrl("query", callbackUrlParam);+ }+ if (invalidCallbackUrlCookie) {+ logInvalidCallbackUrl("cookie", callbackUrlCookie);+ }++ if (rendersHtmlErrorPage) {+ if (invalidCallbackUrlParam) {+ const { callbackUrl: _invalidCallbackUrl, ...sanitizedQuery } = req.query;+ req.query = sanitizedQuery;+ }+ if (invalidCallbackUrlCookie) {+ const {+ [callbackUrlCookieName]: _invalidCallbackUrl,+ ...sanitizedCookies+ } = req.cookies;+ req.cookies = sanitizedCookies;+ }+ } else if (invalidCallbackUrlParam || invalidCallbackUrlCookie) {return res.status(400).json({ message: "Invalid callback URL" });}