🪢 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: validate auth callbacks before passing them to nextauth (#15191)
Valery Meleshkin0e32ced9c29b
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.tsnew file mode 100644index 0000000000..694493d5ef--- /dev/null+++ b/web/src/__tests__/server/unit/next-auth-route-malformed-input.servertest.ts@@ -0,0 +1,213 @@+import { validateHeaderValue } from "node:http";++import type { NextApiRequest, NextApiResponse } from "next";+import type { NextAuthOptions } from "next-auth";+import { createMocks } from "node-mocks-http";+import { beforeEach, describe, expect, it, vi } from "vitest";++const { mockGetAuthOptions, mockLoggerWarn } = vi.hoisted(() => ({+ mockGetAuthOptions: vi.fn(),+ mockLoggerWarn: vi.fn(),+}));++vi.mock("@/src/server/auth", () => ({+ getAuthOptions: mockGetAuthOptions,+}));++vi.mock("@langfuse/shared/src/server", () => ({+ redis: null,+ logger: {+ debug: vi.fn(),+ info: vi.fn(),+ warn: mockLoggerWarn,+ 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: "",+ NEXTAUTH_COOKIE_DOMAIN: undefined,+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: undefined,+ NEXTAUTH_COOKIE_NAME_SUFFIX: undefined,+ },+}));++import auth from "@/src/pages/api/auth/[...nextauth]";++const authOptions: NextAuthOptions = {+ secret: "test-secret",+ providers: [],+ cookies: {+ callbackUrl: {+ name: "next-auth.callback-url",+ options: {+ httpOnly: true,+ sameSite: "lax",+ path: "/",+ secure: false,+ },+ },+ },+ pages: {+ error: "/auth/error",+ signIn: "/auth/sign-in",+ },+ callbacks: {+ redirect({ url, baseUrl }) {+ try {+ if (url.startsWith("/")) return `${baseUrl}${url}`;+ if (new URL(url).origin === baseUrl) return url;+ } catch {+ // Match the application callback that safely handles malformed POST+ // body callbackUrl values. Query and cookie validation happens before+ // NextAuth invokes this callback.+ }+ return baseUrl;+ },+ },+};++function createRequest({+ nextauth,+ query = {},+ cookies = {},+}: {+ nextauth: string[];+ query?: Record<string, string | string[]>;+ cookies?: Record<string, string>;+}) {+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({+ method: "GET",+ headers: { host: "localhost:3000" },+ query: { nextauth, ...query },+ });+ req.cookies = cookies;++ // node-mocks-http accepts control characters in headers while a real+ // ServerResponse rejects them. Keep the lightweight Next.js response mock,+ // but apply Node's production header validation to every setHeader call.+ const setHeader = res.setHeader.bind(res);+ vi.spyOn(res, "setHeader").mockImplementation((name, value) => {+ for (const item of Array.isArray(value) ? value : [value]) {+ validateHeaderValue(name, String(item));+ }+ return setHeader(name, value);+ });++ return { req, res };+}++describe("NextAuth error route malformed input handling", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetAuthOptions.mockResolvedValue(authOptions);+ });++ it("redirects a supported auth error without returning a 5xx", async () => {+ const { req, res } = createRequest({+ nextauth: ["error"],+ query: { error: "OAuthCallback" },+ });++ await auth(req, res);++ expect(res.statusCode).toBe(302);+ expect(res.getHeader("Location")).toBe(+ "http://localhost:3000/api/auth/signin?error=OAuthCallback",+ );+ expect(mockLoggerWarn).not.toHaveBeenCalled();+ });++ it("does not throw when an auth error contains invalid Location header characters", async () => {+ const { req, res } = createRequest({+ nextauth: ["error"],+ query: { error: "configuration\r\nscanner-payload" },+ });++ await expect(auth(req, res)).resolves.toBeUndefined();+ expect(res.statusCode).toBe(302);+ expect(res.getHeader("Location")).toBe(+ "/auth/error?error=configuration%0D%0Ascanner-payload",+ );+ });++ it("does not throw when the auth error path segment contains invalid Location header characters", async () => {+ const { req, res } = createRequest({+ nextauth: ["error", "configuration\r\nscanner-payload"],+ });++ await expect(auth(req, res)).resolves.toBeUndefined();+ expect(res.statusCode).toBe(302);+ expect(res.getHeader("Location")).toBe(+ "/auth/error?error=configuration%0D%0Ascanner-payload",+ );+ });++ it("uses a generic error for an ambiguous array-valued error", async () => {+ const { req, res } = createRequest({+ nextauth: ["error"],+ query: { error: ["OAuthCallback", "scanner-payload"] },+ });++ await auth(req, res);++ expect(res.statusCode).toBe(302);+ expect(res.getHeader("Location")).toBe("/auth/error?error=Configuration");+ expect(mockLoggerWarn).toHaveBeenCalledWith(+ "[NEXT_AUTH] Replaced malformed auth error with Configuration",+ {+ reason: "invalid_type",+ source: "query",+ errorType: "array",+ },+ );+ });++ it("logs when an oversized error uses the generic fallback", async () => {+ const error = "a".repeat(1_001);+ const { req, res } = createRequest({+ nextauth: ["error"],+ query: { error },+ });++ await auth(req, res);++ expect(res.statusCode).toBe(302);+ expect(res.getHeader("Location")).toBe("/auth/error?error=Configuration");+ expect(mockLoggerWarn).toHaveBeenCalledWith(+ "[NEXT_AUTH] Replaced malformed auth error with Configuration",+ {+ reason: "too_long",+ source: "query",+ errorLength: error.length,+ },+ );+ });++ it("logs the path source when an unencodable error uses the generic fallback", async () => {+ const error = "\uD800";+ const { req, res } = createRequest({+ nextauth: ["error", error],+ });++ await auth(req, res);++ expect(res.statusCode).toBe(302);+ expect(res.getHeader("Location")).toBe("/auth/error?error=Configuration");+ expect(mockLoggerWarn).toHaveBeenCalledWith(+ "[NEXT_AUTH] Replaced malformed auth error with Configuration",+ {+ reason: "encoding_failed",+ source: "path",+ errorLength: error.length,+ },+ );+ });+});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 c87eae3975..b52c057383 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@@ -91,6 +91,18 @@ describe("[...nextauth] invalid callbackUrl handling", () => {expect(mockNextAuth).not.toHaveBeenCalled();});+ it("rejects a callbackUrl containing decoded control characters", async () => {+ const { res } = await callHandler({+ query: {+ nextauth: ["callback", "email"],+ callbackUrl: "/project/test\r\nscanner-payload",+ },+ });++ 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\"${{%{{\\" },diff --git a/web/src/pages/api/auth/[...nextauth].ts b/web/src/pages/api/auth/[...nextauth].tsindex caf5853b87..80c9550f47 100644--- a/web/src/pages/api/auth/[...nextauth].ts+++ b/web/src/pages/api/auth/[...nextauth].ts@@ -1,3 +1,5 @@+import { validateHeaderValue } from "node:http";+import { getAuthOptions } from "@/src/server/auth";import { getCookieName } from "@/src/server/utils/cookies";import { env } from "@/src/env.mjs";@@ -5,6 +7,51 @@ import { logger } from "@langfuse/shared/src/server";import type { NextApiRequest, NextApiResponse } from "next";import NextAuth from "next-auth";+const maxAuthErrorLength = 1_000;+const authErrorFallback = "Configuration";++type AuthErrorSource = "query" | "path";++const getAuthAction = (req: NextApiRequest) => {+ const nextauth = req.query.nextauth;+ return Array.isArray(nextauth) ? nextauth[0] : nextauth;+};++const logAuthErrorFallback = (+ reason: "invalid_type" | "too_long" | "encoding_failed",+ source: AuthErrorSource,+ metadata: Record<string, unknown>,+) => {+ logger.warn("[NEXT_AUTH] Replaced malformed auth error with Configuration", {+ reason,+ source,+ ...metadata,+ });+ return authErrorFallback;+};++const encodeAuthError = (error: unknown, source: AuthErrorSource) => {+ if (typeof error !== "string") {+ return logAuthErrorFallback("invalid_type", source, {+ errorType: Array.isArray(error) ? "array" : typeof error,+ });+ }++ if (error.length > maxAuthErrorLength) {+ return logAuthErrorFallback("too_long", source, {+ errorLength: error.length,+ });+ }++ try {+ return encodeURIComponent(error);+ } catch {+ return logAuthErrorFallback("encoding_failed", source, {+ errorLength: error.length,+ });+ }+};+// 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)@@ -12,6 +59,7 @@ import NextAuth from "next-auth";const isValidCallbackUrl = (url: unknown): boolean => {if (typeof url !== "string") return false;try {+ validateHeaderValue("Location", url);return /^https?:/.test(new URL(url, url.startsWith("/") ? "http://localhost" : undefined).protocol,@@ -98,5 +146,18 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {res.setHeader("Pragma", "no-cache");res.setHeader("Expires", "0");+ // NextAuth interpolates unknown error values directly into a Location+ // header. Encode user-controlled text before it reaches that code path so+ // control characters cannot make Node throw ERR_INVALID_CHAR.+ if (getAuthAction(req) === "error") {+ const nextauth = req.query.nextauth;+ const error =+ req.query.error ?? (Array.isArray(nextauth) ? nextauth[1] : undefined);+ if (error !== undefined) {+ const source = req.query.error !== undefined ? "query" : "path";+ req.query.error = encodeAuthError(error, source);+ }+ }+return await NextAuth(req, res, authOptions);}