🪢 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(web): skip uninterpolated route patterns on post-login redirect (#17226)
cursor[bot]c0d1491c90c9
diff --git a/web/src/__tests__/redirect.clienttest.ts b/web/src/__tests__/redirect.clienttest.tsindex 1a58c0746a..86df2e6ae1 100644--- a/web/src/__tests__/redirect.clienttest.ts+++ b/web/src/__tests__/redirect.clienttest.ts@@ -278,6 +278,34 @@ describe("getSafeRedirectPath", () => {);});+ it("rejects Next.js route patterns that would fail href interpolation", () => {+ // Pre-hydration asPath on a statically-optimized dynamic route is the+ // raw pattern. router.replace(that) throws href-interpolation-failed.+ expect(+ getSafeRedirectPath("/project/[projectId]/datasets/[datasetId]/items"),+ ).toBe("/");+ expect(+ getSafeRedirectPath("/project/[projectId]/prompts/[[...folder]]"),+ ).toBe("/");+ expect(getSafeRedirectPath("/project/[projectId]/traces")).toBe("/");+ expect(+ getSafeRedirectPath(+ "/project/[projectId]/datasets/[datasetId]/items?page=1",+ ),+ ).toBe("/");+ });++ it("still allows interpolated paths and bracketed query values", () => {+ expect(getSafeRedirectPath("/project/abc123/datasets/ds1/items")).toBe(+ "/project/abc123/datasets/ds1/items",+ );+ // Brackets in the query string are not route params. The WHATWG+ // serializer may percent-encode the value; the path must not fall back.+ expect(getSafeRedirectPath("/project/abc123/traces?filter=[x]")).toMatch(+ /^\/project\/abc123\/traces\?filter=/,+ );+ });+it("should handle non-string input gracefully", () => {// @ts-expect-error Testing runtime behavior with invalid inputexpect(getSafeRedirectPath(123)).toBe("/");@@ -406,16 +434,25 @@ describe("stripBasePath", () => {expect(stripBasePath("/apps\n\r\u0000/dashboard")).toBe("/dashboard");});- it("does NOT strip Unicode bidi-formatting characters outside the C0 range", () => {- // U+202E (RTL-override) is intentionally out of scope for this fix;- // it lives at 0x202E, beyond the 0x00-0x1F / 0x7F regex scope. The- // result still has a leading "/" so it survives the path-vs-leading-- // slash guard; downstream code decides whether to display it.- expect(stripBasePath("/apps\u202E/dashboard")).toBe("/\u202E/dashboard");+ it("does NOT strip when a Unicode bidi character breaks the segment boundary", () => {+ // U+202E (RTL-override) is outside the C0 control strip. It also+ // sits between `/apps` and `/`, so the path is not a basePath+ // segment and must be left alone.+ expect(stripBasePath("/apps\u202E/dashboard")).toBe(+ "/apps\u202E/dashboard",+ );});it("leaves paths without basePath untouched", () => {expect(stripBasePath("/no-base")).toBe("/no-base");});++ it("does not strip a longer path that only shares a string prefix", () => {+ // `/apps` must not eat the front of `/appslication`.+ expect(stripBasePath("/appslication")).toBe("/appslication");+ expect(stripBasePath("/appslication/dashboard")).toBe(+ "/appslication/dashboard",+ );+ });});});diff --git a/web/src/components/layouts/app-layout/hooks/useAuthGuard.clienttest.tsx b/web/src/components/layouts/app-layout/hooks/useAuthGuard.clienttest.tsxnew file mode 100644index 0000000000..82cbdd2bac--- /dev/null+++ b/web/src/components/layouts/app-layout/hooks/useAuthGuard.clienttest.tsx@@ -0,0 +1,153 @@+import { renderHook } from "@testing-library/react";+import type { Mock } from "vitest";+import type { Session } from "next-auth";+import type { SessionContextValue } from "next-auth/react";+import { useRouter } from "next/router";++import { useAuthGuard } from "@/src/components/layouts/app-layout/hooks/useAuthGuard";++vi.mock("next/router", () => ({+ useRouter: vi.fn(),+}));++const DATASET_ITEMS_PATTERN = "/project/[projectId]/datasets/[datasetId]/items";++function mockRouter(+ overrides: {+ pathname?: string;+ asPath?: string;+ query?: Record<string, string | undefined>;+ isReady?: boolean;+ } = {},+) {+ (useRouter as Mock).mockReturnValue({+ pathname: overrides.pathname ?? "/",+ asPath: overrides.asPath ?? overrides.pathname ?? "/",+ query: overrides.query ?? {},+ isReady: overrides.isReady ?? true,+ });+}++function unauthenticated(): SessionContextValue {+ return {+ status: "unauthenticated",+ data: null,+ update: vi.fn(),+ };+}++function authenticated(): SessionContextValue {+ return {+ status: "authenticated",+ data: { user: { id: "u1", email: "[email protected]" } } as Session,+ update: vi.fn(),+ };+}++describe("useAuthGuard", () => {+ test("waits for router hydration before storing asPath on a protected route", () => {+ // First client render of a statically-optimized dynamic page: asPath is+ // still the route pattern. Capturing it as targetPath makes the post-login+ // router.replace throw href-interpolation-failed.+ mockRouter({+ pathname: DATASET_ITEMS_PATTERN,+ asPath: DATASET_ITEMS_PATTERN,+ isReady: false,+ });++ const { result } = renderHook(() => useAuthGuard(unauthenticated(), false));++ expect(result.current).toEqual({ action: "loading", message: "Loading" });+ });++ test("stores the hydrated asPath once the router is ready", () => {+ mockRouter({+ pathname: DATASET_ITEMS_PATTERN,+ asPath: "/project/p1/datasets/ds1/items",+ isReady: true,+ });++ const { result } = renderHook(() => useAuthGuard(unauthenticated(), false));++ expect(result.current).toEqual({+ action: "redirect",+ url: `/auth/sign-in?targetPath=${encodeURIComponent("/project/p1/datasets/ds1/items")}`,+ message: "Redirecting",+ });+ });++ test("does not store an uninterpolated asPath even when isReady", () => {+ mockRouter({+ pathname: DATASET_ITEMS_PATTERN,+ asPath: DATASET_ITEMS_PATTERN,+ isReady: true,+ });++ const { result } = renderHook(() => useAuthGuard(unauthenticated(), false));++ expect(result.current).toEqual({+ action: "redirect",+ url: "/auth/sign-in",+ message: "Redirecting",+ });+ });++ test("recomputes when isReady flips on the same router object", () => {+ const router = {+ pathname: DATASET_ITEMS_PATTERN,+ asPath: DATASET_ITEMS_PATTERN,+ query: {},+ isReady: false,+ };+ (useRouter as Mock).mockReturnValue(router);++ const session = unauthenticated();+ const { result, rerender } = renderHook(() => useAuthGuard(session, false));++ expect(result.current.action).toBe("loading");++ router.isReady = true;+ router.asPath = "/project/p1/datasets/ds1/items";+ rerender();++ expect(result.current).toEqual({+ action: "redirect",+ url: `/auth/sign-in?targetPath=${encodeURIComponent("/project/p1/datasets/ds1/items")}`,+ message: "Redirecting",+ });+ });++ test("does not redirect an authenticated user to an uninterpolated route pattern", () => {+ mockRouter({+ pathname: "/auth/sign-in",+ asPath: `/auth/sign-in?targetPath=${encodeURIComponent(DATASET_ITEMS_PATTERN)}`,+ query: { targetPath: DATASET_ITEMS_PATTERN },+ isReady: true,+ });++ const { result } = renderHook(() => useAuthGuard(authenticated(), false));++ expect(result.current).toEqual({+ action: "redirect",+ url: "/",+ message: "Redirecting",+ });+ });++ test("redirects an authenticated user on sign-in to a hydrated targetPath", () => {+ mockRouter({+ pathname: "/auth/sign-in",+ asPath: `/auth/sign-in?targetPath=${encodeURIComponent("/project/p1/datasets/ds1/items")}`,+ query: { targetPath: "/project/p1/datasets/ds1/items" },+ isReady: true,+ });++ const { result } = renderHook(() => useAuthGuard(authenticated(), false));++ expect(result.current).toEqual({+ action: "redirect",+ url: "/project/p1/datasets/ds1/items",+ message: "Redirecting",+ });+ });+});diff --git a/web/src/components/layouts/app-layout/hooks/useAuthGuard.ts b/web/src/components/layouts/app-layout/hooks/useAuthGuard.tsindex 11883cf7ef..d90cbf2de9 100644--- a/web/src/components/layouts/app-layout/hooks/useAuthGuard.ts+++ b/web/src/components/layouts/app-layout/hooks/useAuthGuard.ts@@ -4,7 +4,6 @@*/import { useRouter } from "next/router";-import { useMemo } from "react";import { PATH_CONSTANTS } from "../utils/pathClassification";import { getSafeRedirectPath, stripBasePath } from "@/src/utils/redirect";import type { SessionContextValue } from "next-auth/react";@@ -32,89 +31,95 @@ export function useAuthGuard(_hideNavigation: boolean,): AuthGuardResult {const router = useRouter();+ const { pathname, query, asPath, isReady } = router;- return useMemo(() => {- const { pathname, query, asPath } = router;+ // Loading state+ if (session.status === "loading") {+ return { action: "loading", message: "Loading" };+ }- // Loading state- if (session.status === "loading") {- return { action: "loading", message: "Loading" };- }+ const isUnauthPath = PATH_CONSTANTS.unauthenticated.some((p) =>+ pathname.startsWith(p),+ );+ const isPublicPath = pathname.startsWith("/public/");- const isUnauthPath = PATH_CONSTANTS.unauthenticated.some((p) =>- pathname.startsWith(p),- );- const isPublicPath = pathname.startsWith("/public/");+ // Check if path is publishable (can be accessed without authentication)+ const isPublishable = PATH_CONSTANTS.publishable.some((path) => {+ // Case 1: Exact match (e.g., pathname === "/auth/reset-password")+ if (pathname === path) return true;- // Check if path is publishable (can be accessed without authentication)- const isPublishable = PATH_CONSTANTS.publishable.some((path) => {- // Case 1: Exact match (e.g., pathname === "/auth/reset-password")- if (pathname === path) return true;+ // Case 2: Prefix match for dynamic routes+ // Example: path = "/project/[projectId]/traces/[traceId]"+ // -> pathPrefix = "/project/[^/]+/traces" (last segment removed, params converted to regex)+ // -> matches pathname like "/project/abc123/traces/xyz789"+ // This allows shared trace/session links to be accessed without authentication+ const pathPrefix = path+ .split("/")+ .slice(0, -1)+ .join("/")+ .replace(/\[([^\]]+)\]/g, "[^/]+");+ const prefixRegex = new RegExp(`^${pathPrefix}/`);+ return prefixRegex.test(pathname);+ });- // Case 2: Prefix match for dynamic routes- // Example: path = "/project/[projectId]/traces/[traceId]"- // -> pathPrefix = "/project/[^/]+/traces" (last segment removed, params converted to regex)- // -> matches pathname like "/project/abc123/traces/xyz789"- // This allows shared trace/session links to be accessed without authentication- const pathPrefix = path- .split("/")- .slice(0, -1)- .join("/")- .replace(/\[([^\]]+)\]/g, "[^/]+");- const prefixRegex = new RegExp(`^${pathPrefix}/`);- return prefixRegex.test(pathname);- });+ // Invalid user - has session but no DB user+ // This can happen if user was deleted from DB but still has valid JWT+ if (+ session.data &&+ session.data.user === null &&+ !isUnauthPath &&+ !isPublishable &&+ !isPublicPath+ ) {+ return { action: "sign-out", message: "Redirecting" };+ }- // Invalid user - has session but no DB user- // This can happen if user was deleted from DB but still has valid JWT- if (- session.data &&- session.data.user === null &&- !isUnauthPath &&- !isPublishable &&- !isPublicPath- ) {- return { action: "sign-out", message: "Redirecting" };+ // Unauthenticated user trying to access protected route+ if (+ session.status === "unauthenticated" &&+ !isUnauthPath &&+ !isPublishable &&+ !isPublicPath+ ) {+ // Before hydration, asPath is still the route pattern+ // (`/project/[projectId]/...`). Storing that as targetPath makes the+ // post-login router.replace throw href-interpolation-failed.+ if (!isReady) {+ return { action: "loading", message: "Loading" };}- // Unauthenticated user trying to access protected route- if (- session.status === "unauthenticated" &&- !isUnauthPath &&- !isPublishable &&- !isPublicPath- ) {- // asPath already includes the base path when accessed via browser- // Strip the base path if present to avoid double-prepending- const rawPath = asPath || pathname || "/";- const pathToStore = stripBasePath(rawPath);+ // asPath already includes the base path when accessed via browser.+ // Sanitize first (rejects open redirects and leftover route+ // patterns), then strip the base path so router.replace does not+ // double-prepend it.+ const rawPath = asPath || pathname || "/";+ const pathToStore = stripBasePath(getSafeRedirectPath(rawPath));- // Only include targetPath if it's not the root- const targetPathQuery =- pathToStore !== "/"- ? `?targetPath=${encodeURIComponent(pathToStore)}`- : "";+ // Only include targetPath if it's not the root+ const targetPathQuery =+ pathToStore !== "/"+ ? `?targetPath=${encodeURIComponent(pathToStore)}`+ : "";- return {- action: "redirect",- url: `/auth/sign-in${targetPathQuery}`,- message: "Redirecting",- };- }+ return {+ action: "redirect",+ url: `/auth/sign-in${targetPathQuery}`,+ message: "Redirecting",+ };+ }- // Authenticated user on authentication page - redirect to target or home- if (session.status === "authenticated" && isUnauthPath) {- const queryTargetPath = query.targetPath as string | undefined;- const redirectUrl = getSafeRedirectPath(queryTargetPath);- const routerRedirectUrl = stripBasePath(redirectUrl);- return {- action: "redirect",- url: routerRedirectUrl,- message: "Redirecting",- };- }+ // Authenticated user on authentication page - redirect to target or home+ if (session.status === "authenticated" && isUnauthPath) {+ const queryTargetPath = query.targetPath as string | undefined;+ const redirectUrl = getSafeRedirectPath(queryTargetPath);+ const routerRedirectUrl = stripBasePath(redirectUrl);+ return {+ action: "redirect",+ url: routerRedirectUrl,+ message: "Redirecting",+ };+ }- // All checks passed - allow access- return { action: "allow" };- }, [session.status, session.data, router]);+ // All checks passed - allow access+ return { action: "allow" };}diff --git a/web/src/components/layouts/app-layout/index.tsx b/web/src/components/layouts/app-layout/index.tsxindex 4b26b995e1..bbec673aaa 100644--- a/web/src/components/layouts/app-layout/index.tsx+++ b/web/src/components/layouts/app-layout/index.tsx@@ -68,10 +68,14 @@ export function AppLayout(props: PropsWithChildren) {)?.title;const metadata = useLayoutMetadata(activePathName, navigation.navigation);- // Handle auth guard actions (redirect or sign-out)+ // Handle auth guard actions (redirect or sign-out). Depend on the action+ // and URL primitives so a new result object every render does not re-fire+ // router.replace.+ const redirectUrl =+ authGuard.action === "redirect" ? authGuard.url : undefined;useEffect(() => {- if (authGuard.action === "redirect") {- router.replace(authGuard.url);+ if (authGuard.action === "redirect" && redirectUrl !== undefined) {+ router.replace(redirectUrl);} else if (authGuard.action === "sign-out") {// Invalid JWT user: stay on this page (redirect: false) but still drop// the pageload v4 cache so a later hard load is not tagged as the@@ -79,7 +83,7 @@ export function AppLayout(props: PropsWithChildren) {clearV4BetaEnabledSentryTag();signOut({ redirect: false });}- }, [authGuard, router]);+ }, [authGuard.action, redirectUrl, router]);// Loading or redirecting state. Loading only applies to a cold load: once a// shell has rendered, a re-check keeps it instead of unmounting it.diff --git a/web/src/utils/redirect.ts b/web/src/utils/redirect.tsindex aa705284bd..377f997b95 100644--- a/web/src/utils/redirect.ts+++ b/web/src/utils/redirect.ts@@ -6,6 +6,18 @@ import { env } from "@/src/env.mjs";*/const REDIRECT_ORIGIN = "https://langfuse.invalid";+/**+ * A path segment that is still a Next.js pages-router dynamic param+ * (`[id]`, `[...slug]`, `[[...slug]]`). Passing that string to+ * `router.push`/`replace` throws href-interpolation-failed.+ */+const UNINTERPOLATED_ROUTE_SEGMENT =+ /(?:^|\/)(?:\[(?:\.\.\.)?[A-Za-z_][\w]*\]|\[\[(?:\.\.\.)?[A-Za-z_][\w]*\]\])(?=\/|$)/;++function pathnameHasUninterpolatedRouteParam(pathname: string): boolean {+ return UNINTERPOLATED_ROUTE_SEGMENT.test(pathname);+}+/*** Validates and sanitizes a redirect path to prevent open redirect attacks.*@@ -14,6 +26,8 @@ const REDIRECT_ORIGIN = "https://langfuse.invalid";* - Parses with the WHATWG URL constructor and rejects off-origin results* (protocol-relative, backslash-normalized, absolute http(s), other schemes)* - Rejects serialized output that starts with "//" after dot-segment resolution+ * - Rejects pathnames that still contain Next.js dynamic segments+ * (`[param]`, `[[...param]]`) — those are unhydrated route patterns, not URLs* - Automatically prepends NEXT_PUBLIC_BASE_PATH if configured** Returned paths are URL-serialized: spaces and control characters are@@ -64,6 +78,12 @@ export function getSafeRedirectPath(return safeDefault;}+ // Pre-hydration asPath on a statically-optimized dynamic route is the raw+ // pattern. router.replace(that) throws instead of navigating.+ if (pathnameHasUninterpolatedRouteParam(url.pathname)) {+ return safeDefault;+ }+const includesBasePath =basePath &&(url.pathname === basePath || url.pathname.startsWith(`${basePath}/`));@@ -85,14 +105,24 @@ export function stripBasePath(path: string): string {return "/";}- if (!path.startsWith(basePath)) {- return path;- }-// Strip ASCII control characters (0x00-0x1F, 0x7F) so a newline or// null byte cannot split the basePath prefix from the remainder.const cleaned = path.replace(/[\x00-\x1F\x7F]/g, "");+ if (cleaned === basePath) {+ return "/";+ }++ // Require a path-segment boundary so `/my-app` does not strip the+ // prefix of `/my-application`.+ if (+ !cleaned.startsWith(`${basePath}/`) &&+ !cleaned.startsWith(`${basePath}?`) &&+ !cleaned.startsWith(`${basePath}#`)+ ) {+ return cleaned || "/";+ }+const stripped = cleaned.slice(basePath.length) || "/";return stripped.startsWith("/") ? stripped : `/${stripped}`;}