🪢 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: prevent NextAuth callback URLs from causing server errors (#15760)
Valery Meleshkinb62153aae718
diff --git a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.tsindex 0f6e9d5235..b067e3728c 100644--- a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts@@ -24,8 +24,7 @@ import { beforeEach, vi } from "vitest";import { z } from "zod";const authMocks = vi.hoisted(() => ({- getServerSession: vi.fn(),- getAuthOptions: vi.fn().mockResolvedValue({}),+ getServerAuthSessionForRequest: vi.fn(),}));const entitlementMocks = vi.hoisted(() => ({@@ -51,12 +50,8 @@ const langfuseClientMocks = vi.hoisted(() => ({getLangfuseClient: vi.fn(() => ({})),}));-vi.mock("next-auth", () => ({- getServerSession: authMocks.getServerSession,-}));-vi.mock("@/src/server/auth", () => ({- getAuthOptions: authMocks.getAuthOptions,+ getServerAuthSessionForRequest: authMocks.getServerAuthSessionForRequest,}));vi.mock("@/src/features/entitlements/server/hasEntitlement", () => ({@@ -196,7 +191,7 @@ describe("in-app agent public API route auth", () => {});it("adds the authenticated user to the request span", async () => {- authMocks.getServerSession.mockResolvedValue(+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(createInAppAgentSession({ orgId: "org-1", projectId: "project-1" }),);@@ -251,7 +246,7 @@ describe("in-app agent public API route auth", () => {name: "In-app Agent User",},});- authMocks.getServerSession.mockResolvedValue(+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(createInAppAgentSession({orgId: org.id,projectId: project.id,@@ -391,7 +386,7 @@ describe("in-app agent public API route auth", () => {await withInAppAgentCloudEnv(async () => {const { conversationId, org, project, userId } =await setupWatchConversation();- authMocks.getServerSession.mockResolvedValue(+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(createInAppAgentSession({orgId: org.id,projectId: project.id,@@ -415,7 +410,7 @@ describe("in-app agent public API route auth", () => {it("rejects an unauthenticated watch", async () => {await withInAppAgentCloudEnv(async () => {const { conversationId, project } = await setupWatchConversation();- authMocks.getServerSession.mockResolvedValue(null);+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(null);const response = await callWatchRoute({projectId: project.id,@@ -430,7 +425,7 @@ describe("in-app agent public API route auth", () => {await withInAppAgentCloudEnv(async () => {const { conversationId, org, project, userId } =await setupWatchConversation();- authMocks.getServerSession.mockResolvedValue(+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(createInAppAgentSession({orgId: org.id,projectId: project.id,@@ -452,7 +447,7 @@ describe("in-app agent public API route auth", () => {await withInAppAgentCloudEnv(async () => {const { conversationId, org, project, userId } =await setupWatchConversation();- authMocks.getServerSession.mockResolvedValue(+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(createInAppAgentSession({orgId: org.id,projectId: project.id,@@ -474,7 +469,7 @@ describe("in-app agent public API route auth", () => {await withInAppAgentCloudEnv(async () => {const { conversationId, org, project, userId } =await setupWatchConversation();- authMocks.getServerSession.mockResolvedValue(+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(createInAppAgentSession({orgId: org.id,projectId: project.id,@@ -505,7 +500,7 @@ describe("in-app agent public API route auth", () => {email: `${otherUserId}@example.com`,},});- authMocks.getServerSession.mockResolvedValue(+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(createInAppAgentSession({orgId: org.id,projectId: project.id,@@ -530,7 +525,7 @@ describe("in-app agent public API route auth", () => {where: { id: other.org.id },data: { aiFeaturesEnabled: true },});- authMocks.getServerSession.mockResolvedValue(+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(createInAppAgentSession({orgId: other.org.id,projectId: other.project.id,@@ -1026,7 +1021,7 @@ describe("in-app agent public API route auth", () => {if (!sessionUser) {throw new Error("Expected an authenticated session user");}- authMocks.getServerSession.mockResolvedValue(session);+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(session);rateLimitMocks.rateLimitRequest.mockResolvedValue({isRateLimited: () => true,res: {@@ -1126,7 +1121,7 @@ describe("in-app agent public API route auth", () => {admin: true,includeProjectMembership: false,});- authMocks.getServerSession.mockResolvedValue(session);+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(session);rateLimitMocks.rateLimitRequest.mockResolvedValue({isRateLimited: () => true,res: {@@ -1207,7 +1202,7 @@ describe("in-app agent public API route auth", () => {where: { id: org.id },data: { aiFeaturesEnabled: true },});- authMocks.getServerSession.mockResolvedValue(+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(await createPersistedInAppAgentSession({orgId: org.id,projectId: project.id,@@ -1326,7 +1321,7 @@ describe("in-app agent public API route auth", () => {where: { id: org.id },data: { aiFeaturesEnabled: true },});- authMocks.getServerSession.mockResolvedValue(+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(await createPersistedInAppAgentSession({orgId: org.id,projectId: project.id,@@ -1462,7 +1457,7 @@ describe("in-app agent public API route auth", () => {where: { id: org.id },data: { aiFeaturesEnabled: true },});- authMocks.getServerSession.mockResolvedValue(+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(await createPersistedInAppAgentSession({orgId: org.id,projectId: project.id,@@ -1547,7 +1542,7 @@ describe("in-app agent public API route auth", () => {where: { id: org.id },data: { aiFeaturesEnabled: true },});- authMocks.getServerSession.mockResolvedValue(+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(await createPersistedInAppAgentSession({orgId: org.id,projectId: project.id,@@ -1705,7 +1700,7 @@ async function setupInAppAgentProjectSession() {name: "In-app Agent User",},});- authMocks.getServerSession.mockResolvedValue(+ authMocks.getServerAuthSessionForRequest.mockResolvedValue(createInAppAgentSession({ orgId: org.id, projectId: project.id, userId }),);diff --git a/web/src/__tests__/server/unit/getServerAuthSession-invalid-callback-url.servertest.ts b/web/src/__tests__/server/unit/getServerAuthSession-invalid-callback-url.servertest.tsnew file mode 100644index 0000000000..4bd338df1f--- /dev/null+++ b/web/src/__tests__/server/unit/getServerAuthSession-invalid-callback-url.servertest.ts@@ -0,0 +1,114 @@+import type { NextApiRequest, NextApiResponse } from "next";+import { NextRequest } from "next/server";+import type * as NextAuth from "next-auth";+import { createMocks } from "node-mocks-http";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { getCookieName } from "@/src/server/utils/cookies";++const { mockGetServerSession } = vi.hoisted(() => ({+ mockGetServerSession: vi.fn(),+}));++vi.mock("next-auth", () => ({+ getServerSession: mockGetServerSession,+}));++vi.mock("@/src/ee/features/multi-tenant-sso/utils", () => ({+ findMultiTenantSsoConfig: vi.fn(),+ getSsoAuthProviderIdForDomain: vi.fn(),+ loadSsoProviders: vi.fn().mockResolvedValue([]),+}));++import {+ getAuthOptions,+ getServerAuthSession,+ getServerAuthSessionForRequest,+} from "@/src/server/auth";++const callbackUrlCookieName = getCookieName("next-auth.callback-url");+const originalNextAuthSecret = process.env.NEXTAUTH_SECRET;++const assertSanitizedRequest = (request: {+ cookies?: Partial<Record<string, string>>;+}) => {+ expect(request.cookies?.[callbackUrlCookieName]).toBeUndefined();+ expect(request.cookies?.["next-auth.session-token"]).toBe("valid-token");+};++describe("getServerAuthSession invalid callback URL handling", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetServerSession.mockImplementation(async (request) => {+ assertSanitizedRequest(request);+ return null;+ });+ });++ afterEach(() => {+ if (originalNextAuthSecret === undefined) {+ delete process.env.NEXTAUTH_SECRET;+ } else {+ process.env.NEXTAUTH_SECRET = originalNextAuthSecret;+ }+ });++ it("removes an invalid callback-url cookie before calling next-auth", async () => {+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({+ method: "GET",+ });+ req.cookies = {+ [callbackUrlCookieName]: "nslookup -q=cname scanner.example",+ "next-auth.session-token": "valid-token",+ };++ await expect(getServerAuthSession({ req, res })).resolves.toBeNull();++ expect(mockGetServerSession).toHaveBeenCalledTimes(1);+ });++ it("removes an invalid callback-url cookie from an App Router request", async () => {+ const { getServerSession: realGetServerSession } =+ await vi.importActual<typeof NextAuth>("next-auth");+ process.env.NEXTAUTH_SECRET = "test-secret";+ mockGetServerSession.mockImplementation((request, response, options) => {+ assertSanitizedRequest(request);+ return realGetServerSession(request, response, options);+ });++ const request = new NextRequest("http://localhost/api/in-app-agent", {+ headers: {+ cookie: `${callbackUrlCookieName}=nslookup -q=cname scanner.example; next-auth.session-token=valid-token`,+ },+ });++ await expect(getServerAuthSessionForRequest(request)).resolves.toBeNull();++ expect(mockGetServerSession).toHaveBeenCalledTimes(1);+ });++ it("sanitizes an invalid callback-url cookie from a raw cookie header", async () => {+ const request = new Request("http://localhost/api/in-app-agent", {+ headers: {+ cookie: `${callbackUrlCookieName}=nslookup -q=cname scanner.example; next-auth.session-token=valid-token`,+ },+ });++ await expect(getServerAuthSessionForRequest(request)).resolves.toBeNull();++ expect(mockGetServerSession).toHaveBeenCalledTimes(1);+ });++ it("falls back to the base URL for a malformed redirect callback URL", async () => {+ const authOptions = await getAuthOptions();+ const redirect = authOptions.callbacks?.redirect;+ if (!redirect) throw new Error("Expected a redirect callback");++ expect(+ redirect({+ url: "/project/test\r\nscanner-payload",+ baseUrl: "http://localhost:3000",+ }),+ ).toBe("http://localhost:3000");+ });+});diff --git a/web/src/features/in-app-agent/server/handler.ts b/web/src/features/in-app-agent/server/handler.tsindex 122a8a3041..1545498dc9 100644--- a/web/src/features/in-app-agent/server/handler.ts+++ b/web/src/features/in-app-agent/server/handler.ts@@ -1,6 +1,5 @@import { EventType } from "@ag-ui/core";import { type Session } from "next-auth";-import { getServerSession } from "next-auth";import { env } from "@/src/env.mjs";import {@@ -60,7 +59,7 @@ import {getDefaultInAppAgentSandboxProviderType,} from "@langfuse/shared/in-app-agent/server/sandbox/config";import { getLangfuseClient } from "@/src/features/natural-language-filters/server/utils";-import { getAuthOptions } from "@/src/server/auth";+import { getServerAuthSessionForRequest } from "@/src/server/auth";import { assertInAppAgentAvailable } from "@/src/features/in-app-agent/server/availability";import { createHttpHeaderFromRateLimit } from "@/src/features/public-api/server/RateLimitService";import type { RateLimitService } from "@/src/features/public-api/server/RateLimitService";@@ -104,8 +103,7 @@ const SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE =export default async function handler(request: Request) {try {- const authOptions = await getAuthOptions();- const session = await getServerSession(authOptions);+ const session = await getServerAuthSessionForRequest(request);if (!session?.user) {throw new UnauthorizedError("Unauthenticated");diff --git a/web/src/features/in-app-agent/server/watchHandler.ts b/web/src/features/in-app-agent/server/watchHandler.tsindex 7a0da1cc2e..290466a3a8 100644--- a/web/src/features/in-app-agent/server/watchHandler.ts+++ b/web/src/features/in-app-agent/server/watchHandler.ts@@ -1,5 +1,3 @@-import { getServerSession } from "next-auth";-import { BaseError, ForbiddenError, UnauthorizedError } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";import { addUserToSpan, logger } from "@langfuse/shared/src/server";@@ -9,7 +7,7 @@ import { watchConversationFrames } from "@langfuse/shared/in-app-agent/server/waimport { z } from "zod";import { assertInAppAgentAvailable } from "@/src/features/in-app-agent/server/availability";-import { getAuthOptions } from "@/src/server/auth";+import { getServerAuthSessionForRequest } from "@/src/server/auth";import { isProjectMemberOrAdmin } from "@/src/server/utils/checkProjectMembershipOrAdmin";const WatchQuerySchema = z.object({@@ -20,8 +18,7 @@ const WatchQuerySchema = z.object({export default async function watchHandler(request: Request) {try {- const authOptions = await getAuthOptions();- const session = await getServerSession(authOptions);+ const session = await getServerAuthSessionForRequest(request);if (!session?.user) {throw new UnauthorizedError("Unauthenticated");diff --git a/web/src/features/playground/server/authorizeRequest.ts b/web/src/features/playground/server/authorizeRequest.tsindex e6020881f3..4616ce848c 100644--- a/web/src/features/playground/server/authorizeRequest.ts+++ b/web/src/features/playground/server/authorizeRequest.ts@@ -1,6 +1,4 @@-import { getServerSession } from "next-auth";--import { getAuthOptions } from "@/src/server/auth";+import { getServerAuthSessionForRequest } from "@/src/server/auth";import { isProjectMemberOrAdmin } from "@/src/server/utils/checkProjectMembershipOrAdmin";import { ForbiddenError, UnauthorizedError } from "@langfuse/shared";import { hasProjectAccess } from "../../rbac/utils/checkProjectAccess";@@ -11,9 +9,9 @@ export type AuthorizeRequestResult = {export const authorizeRequestOrThrow = async (projectId: string,+ request: Request,): Promise<AuthorizeRequestResult> => {- const authOptions = await getAuthOptions();- const session = await getServerSession(authOptions);+ const session = await getServerAuthSessionForRequest(request);if (!session?.user) throw new UnauthorizedError("Unauthenticated");if (!isProjectMemberOrAdmin(session.user, projectId))diff --git a/web/src/features/playground/server/chatCompletionHandler.ts b/web/src/features/playground/server/chatCompletionHandler.tsindex e5258faf9c..fcb251baff 100644--- a/web/src/features/playground/server/chatCompletionHandler.ts+++ b/web/src/features/playground/server/chatCompletionHandler.ts@@ -29,7 +29,7 @@ import * as opentelemetry from "@opentelemetry/api";export default async function chatCompletionHandler(req: NextRequest) {try {const body = validateChatCompletionBody(await req.json());- const { userId } = await authorizeRequestOrThrow(body.projectId);+ const { userId } = await authorizeRequestOrThrow(body.projectId, req);const blockedUsers = env.LANGFUSE_BLOCKED_USERIDS_CHATCOMPLETION;if (blockedUsers.has(userId)) {diff --git a/web/src/pages/api/auth/[...nextauth].ts b/web/src/pages/api/auth/[...nextauth].tsindex 2e524a7104..2b25e9a414 100644--- a/web/src/pages/api/auth/[...nextauth].ts+++ b/web/src/pages/api/auth/[...nextauth].ts@@ -1,8 +1,7 @@-import { validateHeaderValue } from "node:http";-import { getAuthOptions } from "@/src/server/auth";import { getGclidFromRequest } from "@/src/features/auth/lib/signupAttribution";import { getCookieName } from "@/src/server/utils/cookies";+import { isValidCallbackUrl } from "@/src/server/utils/nextAuthCallbackUrl";import { env } from "@/src/env.mjs";import { logger } from "@langfuse/shared/src/server";import type { NextApiRequest, NextApiResponse } from "next";@@ -53,23 +52,6 @@ const encodeAuthError = (error: unknown, source: AuthErrorSource) => {}};-// 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 {- validateHeaderValue("Location", url);- 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@@ -101,9 +83,11 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {(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),+ callbackUrlParamType: Array.isArray(callbackUrlParam)+ ? "array"+ : typeof callbackUrlParam,+ callbackUrlCookiePresent: Boolean(callbackUrlCookie),+ path: req.url?.split("?")[0]?.slice(0, 200),});return res.status(400).json({ message: "Invalid callback URL" });}diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex d54e07c287..714a754bfa 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -38,6 +38,10 @@ import WordPressProvider from "next-auth/providers/wordpress";import { type Provider } from "next-auth/providers/index";import { getCookieName, getCookieOptions } from "./utils/cookies";import { nextAuthLogger } from "./utils/nextAuthLogger";+import {+ getRequestCookies,+ isValidCallbackUrl,+} from "./utils/nextAuthCallbackUrl";import {findMultiTenantSsoConfig,getSsoAuthProviderIdForDomain,@@ -773,6 +777,8 @@ export async function getAuthOptions(signupAttribution?: {// keeps the default same-origin semantics while turning malformed input// into a safe redirect to baseUrl instead of a 500.redirect({ url, baseUrl }) {+ if (!isValidCallbackUrl(url)) return baseUrl;+try {// Relative callback URLs are always safe to resolve against baseUrl.if (url.startsWith("/")) return `${baseUrl}${url}`;@@ -1172,5 +1178,66 @@ export const getServerAuthSession = async (ctx: {ctx.res.setHeader("Pragma", "no-cache");ctx.res.setHeader("Expires", "0");+ sanitizeServerSessionCallbackUrl(+ ctx.req,+ ctx.req.url?.split("?")[0]?.slice(0, 200),+ );+return getServerSession(ctx.req, ctx.res, authOptions);};++/**+ * App Router equivalent of getServerAuthSession. Passing the request and+ * response explicitly lets us sanitize the parsed cookies before next-auth's+ * config assertion runs.+ */+export const getServerAuthSessionForRequest = async (request: Request) => {+ const authOptions = await getAuthOptions();+ const cookies = getRequestCookies(request);+ const req = {+ headers: Object.fromEntries(request.headers.entries()),+ cookies,+ } as GetServerSidePropsContext["req"];++ sanitizeServerSessionCallbackUrl(+ req,+ new URL(request.url).pathname.slice(0, 200),+ );++ const res = {+ getHeader: () => undefined,+ setCookie: () => undefined,+ setHeader: () => undefined,+ } as unknown as GetServerSidePropsContext["res"];++ const session = await getServerSession(req, res, authOptions);++ // Match getServerSession's App Router behavior. The explicit request/response+ // form above selects its Pages Router branch, which otherwise keeps expires.+ if (!session) return session;++ const { expires: _expires, ...sessionWithoutExpires } = session;++ return sessionWithoutExpires as Session;+};++const sanitizeServerSessionCallbackUrl = (+ req: { cookies?: Partial<Record<string, string>> },+ path: string | undefined,+) => {+ const callbackUrlCookieName = getCookieName("next-auth.callback-url");+ const callbackUrlCookie = req.cookies?.[callbackUrlCookieName];++ if (!callbackUrlCookie || isValidCallbackUrl(callbackUrlCookie)) return;++ const { [callbackUrlCookieName]: _invalidCallbackUrl, ...sanitizedCookies } =+ req.cookies ?? {};+ req.cookies = sanitizedCookies;++ logger.warn(+ "[NEXT_AUTH] Ignored invalid callback URL for server-side session",+ {+ path,+ },+ );+};diff --git a/web/src/server/utils/nextAuthCallbackUrl.ts b/web/src/server/utils/nextAuthCallbackUrl.tsnew file mode 100644index 0000000000..a0801b0227--- /dev/null+++ b/web/src/server/utils/nextAuthCallbackUrl.ts@@ -0,0 +1,57 @@+import { validateHeaderValue } from "node:http";++type RequestWithCookieStore = Request & {+ cookies?: {+ getAll: () => Array<{ name: string; value: string }>;+ };+};++// Matches next-auth's URL/scheme check and also rejects values Node cannot+// safely place in a Location header. Relative URLs must start with `/`;+// absolute URLs must parse with an http(s) scheme.+export 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,+ );+ } catch {+ return false;+ }+};++const parseCookieHeader = (cookieHeader: string | null) => {+ const cookies: Record<string, string> = {};++ for (const part of cookieHeader?.split(";") ?? []) {+ const separatorIndex = part.indexOf("=");+ if (separatorIndex === -1) continue;++ const name = part.slice(0, separatorIndex).trim();+ if (!name) continue;++ const value = part.slice(separatorIndex + 1).trim();+ try {+ cookies[name] = decodeURIComponent(value);+ } catch {+ cookies[name] = value;+ }+ }++ return cookies;+};++export const getRequestCookies = (request: Request) => {+ const requestWithCookieStore = request as RequestWithCookieStore;+ if (requestWithCookieStore.cookies) {+ return Object.fromEntries(+ requestWithCookieStore.cookies+ .getAll()+ .map(({ name, value }) => [name, value]),+ );+ }++ return parseCookieHeader(request.headers.get("cookie"));+};