🪢 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(auth): return 400 instead of 500 for invalid callbackUrl (#15171)
Niklas Semmler7f601a620361
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.tsnew file mode 100644index 0000000000..c87eae3975--- /dev/null+++ b/web/src/__tests__/server/unit/nextauth-invalid-callback-url.servertest.ts@@ -0,0 +1,182 @@+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 () => ({})),+}));++vi.mock("next-auth", () => ({ default: mockNextAuth }));++vi.mock("@/src/server/auth", () => ({+ getAuthOptions: mockGetAuthOptions,+}));++vi.mock("@langfuse/shared/src/server", () => ({+ redis: null,+ logger: {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ },+ ClickHouseClientManager: {+ getInstance: () => ({+ closeAllConnections: vi.fn(async () => undefined),+ }),+ },+}));++vi.mock("@/src/env.mjs", () => ({+ env: {+ NEXTAUTH_URL: "http://localhost:3000",+ NEXT_PUBLIC_BASE_PATH: undefined,+ NEXTAUTH_COOKIE_DOMAIN: undefined,+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: undefined,+ NEXTAUTH_COOKIE_NAME_SUFFIX: undefined,+ },+}));++import handler from "@/src/pages/api/auth/[...nextauth]";++const callHandler = async (options: Parameters<typeof createMocks>[0] = {}) => {+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({+ method: "GET",+ query: { nextauth: ["callback", "email"] },+ ...options,+ });+ await handler(req, res);+ return { req, res };+};++describe("[...nextauth] invalid callbackUrl handling", () => {+ afterEach(() => {+ vi.clearAllMocks();+ });++ it("rejects a SQL-injection callbackUrl query param with 400", async () => {+ const { res } = await callHandler({+ query: {+ nextauth: ["callback", "email"],+ callbackUrl:+ "'+convert(int, cast(0x5f21403264696c656d6d61 as varchar(8000)))+'",+ },+ });++ expect(res._getStatusCode()).toBe(400);+ expect(mockNextAuth).not.toHaveBeenCalled();+ });++ it("rejects a non-http(s) scheme callbackUrl with 400", async () => {+ const { res } = await callHandler({+ query: {+ nextauth: ["callback", "email"],+ callbackUrl: "javascript:alert(1)",+ },+ });++ expect(res._getStatusCode()).toBe(400);+ expect(mockNextAuth).not.toHaveBeenCalled();+ });++ it("rejects a repeated (array) callbackUrl query param with 400", async () => {+ const { res } = await callHandler({+ query: {+ nextauth: ["callback", "email"],+ callbackUrl: ["https://a.example.com", "https://b.example.com"],+ },+ });++ expect(res._getStatusCode()).toBe(400);+ expect(mockNextAuth).not.toHaveBeenCalled();+ });++ it("rejects an invalid callback-url cookie with 400", async () => {+ const { res } = await callHandler({+ cookies: { "next-auth.callback-url": "z`z'z\"${{%{{\\" },+ });++ expect(res._getStatusCode()).toBe(400);+ expect(mockNextAuth).not.toHaveBeenCalled();+ });++ it("passes through a valid absolute callbackUrl", async () => {+ const { res } = await callHandler({+ query: {+ nextauth: ["callback", "email"],+ callbackUrl: "https://cloud.langfuse.com/project/abc",+ },+ });++ expect(res._getStatusCode()).toBe(200);+ expect(mockNextAuth).toHaveBeenCalledTimes(1);+ });++ it("passes through a relative callbackUrl", async () => {+ const { res } = await callHandler({+ query: {+ nextauth: ["callback", "email"],+ callbackUrl: "/project/abc",+ },+ });++ expect(res._getStatusCode()).toBe(200);+ expect(mockNextAuth).toHaveBeenCalledTimes(1);+ });++ it("passes through a valid callback-url cookie", async () => {+ const { res } = await callHandler({+ cookies: { "next-auth.callback-url": "https://cloud.langfuse.com" },+ });++ expect(res._getStatusCode()).toBe(200);+ expect(mockNextAuth).toHaveBeenCalledTimes(1);+ });++ it("passes through when no callbackUrl is present", async () => {+ const { res } = await callHandler();++ expect(res._getStatusCode()).toBe(200);+ expect(mockNextAuth).toHaveBeenCalledTimes(1);+ });++ it("passes through an empty callbackUrl query param (next-auth treats it as absent)", async () => {+ const { res } = await callHandler({+ query: { nextauth: ["callback", "email"], callbackUrl: "" },+ });++ expect(res._getStatusCode()).toBe(200);+ expect(mockNextAuth).toHaveBeenCalledTimes(1);+ });++ it("passes through an empty callback-url cookie (next-auth treats it as absent)", async () => {+ const { res } = await callHandler({+ cookies: { "next-auth.callback-url": "" },+ });++ expect(res._getStatusCode()).toBe(200);+ expect(mockNextAuth).toHaveBeenCalledTimes(1);+ });++ it("passes an invalid callbackUrl through on GET signin (next-auth redirects to its error page instead of 500ing)", async () => {+ const { res } = await callHandler({+ query: { nextauth: ["signin"], callbackUrl: "www.example.com/foo" },+ });++ expect(res._getStatusCode()).toBe(200);+ expect(mockNextAuth).toHaveBeenCalledTimes(1);+ });++ it("rejects an invalid callbackUrl on POST signin with 400 (no HTML error-page carve-out for POST)", async () => {+ const { res } = await callHandler({+ method: "POST",+ query: {+ nextauth: ["signin", "email"],+ callbackUrl: "www.example.com/foo",+ },+ });++ expect(res._getStatusCode()).toBe(400);+ expect(mockNextAuth).not.toHaveBeenCalled();+ });+});diff --git a/web/src/pages/api/auth/[...nextauth].ts b/web/src/pages/api/auth/[...nextauth].tsindex d78f3c17b1..caf5853b87 100644--- a/web/src/pages/api/auth/[...nextauth].ts+++ b/web/src/pages/api/auth/[...nextauth].ts@@ -1,8 +1,26 @@import { getAuthOptions } from "@/src/server/auth";+import { getCookieName } from "@/src/server/utils/cookies";import { env } from "@/src/env.mjs";+import { logger } from "@langfuse/shared/src/server";import type { NextApiRequest, NextApiResponse } from "next";import NextAuth from "next-auth";+// Mirrors next-auth's assertConfig check (core/lib/assert.ts). Must never be+// stricter than next-auth: relative URLs always pass (next-auth resolves them+// against the deployment origin), absolute URLs must parse with an http(s)+// scheme.+const isValidCallbackUrl = (url: unknown): boolean => {+ if (typeof url !== "string") return false;+ try {+ return /^https?:/.test(+ new URL(url, url.startsWith("/") ? "http://localhost" : undefined)+ .protocol,+ );+ } catch {+ return false;+ }+};+export default async function auth(req: NextApiRequest, res: NextApiResponse) {// Workaround for corporate email link checkers (e.g., Outlook SafeLink)// https://next-auth.js.org/tutorials/avoid-corporate-link-checking-email-provider@@ -10,6 +28,37 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {return res.status(200).end();}+ // 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.+ const nextAuthAction = Array.isArray(req.query.nextauth)+ ? req.query.nextauth[0]+ : req.query.nextauth;+ const rendersHtmlErrorPage =+ req.method === "GET" &&+ ["signin", "signout", "error", "verify-request"].includes(+ nextAuthAction ?? "",+ );+ 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", {+ callbackUrlParam: String(callbackUrlParam).slice(0, 200),+ callbackUrlCookie: String(callbackUrlCookie).slice(0, 200),+ path: req.url?.slice(0, 200),+ });+ return res.status(400).json({ message: "Invalid callback URL" });+ }+// Intercept OAuth callback errors to preserve error_description from IdP// This happens before NextAuth processes the callback, allowing us to preserve// the IdP's error_description which NextAuth would otherwise strip