🪢 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): reject non-POST credentials callback requests with 405 (#15989)
Niklas Semmler15d3ab10d410
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 b52c057383..b9657137d4 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@@ -192,3 +192,54 @@ describe("[...nextauth] invalid callbackUrl handling", () => {expect(mockNextAuth).not.toHaveBeenCalled();});});++describe("[...nextauth] credentials callback method guard", () => {+ afterEach(() => {+ vi.clearAllMocks();+ });++ it("rejects a GET to the credentials callback with 405 and an Allow: POST header", async () => {+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({+ method: "GET",+ query: { nextauth: ["callback", "credentials"] },+ });+ await handler(req, res);++ expect(res._getStatusCode()).toBe(405);+ expect(res.getHeader("Allow")).toBe("POST");+ expect(mockNextAuth).not.toHaveBeenCalled();+ });++ it("rejects a PUT to the credentials callback with 405", async () => {+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({+ method: "PUT",+ query: { nextauth: ["callback", "credentials"] },+ });+ await handler(req, res);++ expect(res._getStatusCode()).toBe(405);+ expect(mockNextAuth).not.toHaveBeenCalled();+ });++ it("passes a POST to the credentials callback through to next-auth", async () => {+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({+ method: "POST",+ query: { nextauth: ["callback", "credentials"] },+ });+ await handler(req, res);++ expect(res._getStatusCode()).toBe(200);+ expect(mockNextAuth).toHaveBeenCalledTimes(1);+ });++ it("still returns 200 for a HEAD to the credentials callback", async () => {+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({+ method: "HEAD",+ query: { nextauth: ["callback", "credentials"] },+ });+ await handler(req, res);++ expect(res._getStatusCode()).toBe(200);+ expect(mockNextAuth).not.toHaveBeenCalled();+ });+});diff --git a/web/src/pages/api/auth/[...nextauth].ts b/web/src/pages/api/auth/[...nextauth].tsindex 2b25e9a414..028fa0f2f7 100644--- a/web/src/pages/api/auth/[...nextauth].ts+++ b/web/src/pages/api/auth/[...nextauth].ts@@ -12,9 +12,15 @@ const authErrorFallback = "Configuration";type AuthErrorSource = "query" | "path";-const getAuthAction = (req: NextApiRequest) => {+// Single parse of the [...nextauth] catch-all: [action, provider], e.g.+// /api/auth/callback/credentials -> ["callback", "credentials"].+const getNextAuthSegments = (+ req: NextApiRequest,+): [string | undefined, string | undefined] => {const nextauth = req.query.nextauth;- return Array.isArray(nextauth) ? nextauth[0] : nextauth;+ return Array.isArray(nextauth)+ ? [nextauth[0], nextauth[1]]+ : [nextauth, undefined];};const logAuthErrorFallback = (@@ -53,12 +59,27 @@ const encodeAuthError = (error: unknown, source: AuthErrorSource) => {};export default async function auth(req: NextApiRequest, res: NextApiResponse) {+ const [nextAuthAction, nextAuthProvider] = getNextAuthSegments(req);+// Workaround for corporate email link checkers (e.g., Outlook SafeLink)// https://next-auth.js.org/tutorials/avoid-corporate-link-checking-email-providerif (req.method === "HEAD") {return res.status(200).end();}+ // next-auth answers non-POST requests to the credentials callback with a+ // bare, unlogged 500, so scanners probing this URL page our error-rate+ // monitors. Reject them with a 405 before next-auth sees them.+ const isCredentialsCallback =+ nextAuthAction === "callback" && nextAuthProvider === "credentials";+ if (isCredentialsCallback && req.method !== "POST") {+ logger.warn(+ `[NEXT_AUTH] Rejected ${req.method} to credentials callback with 405`,+ );+ res.setHeader("Allow", "POST");+ return res.status(405).json({ message: "Method Not Allowed" });+ }+// 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@@ -66,9 +87,6 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {// 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(@@ -96,10 +114,7 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {// This happens before NextAuth processes the callback, allowing us to preserve// the IdP's error_description which NextAuth would otherwise strip// Only intercept if this is an OAuth callback request (path starts with 'callback')- const isCallbackRequest =- Array.isArray(req.query.nextauth) &&- req.query.nextauth.length > 0 &&- req.query.nextauth[0] === "callback";+ const isCallbackRequest = nextAuthAction === "callback";if (isCallbackRequest &&@@ -138,10 +153,8 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {// 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 (nextAuthAction === "error") {+ const error = req.query.error ?? nextAuthProvider;if (error !== undefined) {const source = req.query.error !== undefined ? "query" : "path";req.query.error = encodeAuthError(error, source);