Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(security): resolve client-side URL redirect vulnerability (CodeQL alert) (#10621)

Michael Fröhlich2e2826b87352
diff --git a/web/src/__tests__/redirect.clienttest.ts b/web/src/__tests__/redirect.clienttest.ts
new file mode 100644
index 0000000000..4f183a72f8
--- /dev/null
+++ b/web/src/__tests__/redirect.clienttest.ts
@@ -0,0 +1,214 @@
+import { getSafeRedirectPath } from "@/src/utils/redirect";
+import { env } from "@/src/env.mjs";
+
+describe("getSafeRedirectPath", () => {
+ const originalBasePath = env.NEXT_PUBLIC_BASE_PATH;
+
+ afterAll(() => {
+ // Restore original value after all tests
+ (env as any).NEXT_PUBLIC_BASE_PATH = originalBasePath;
+ });
+
+ describe("without basePath configured", () => {
+ beforeEach(() => {
+ // Ensure basePath is undefined for these tests
+ (env as any).NEXT_PUBLIC_BASE_PATH = undefined;
+ });
+
+ it("should return '/' for null input", () => {
+ expect(getSafeRedirectPath(null)).toBe("/");
+ });
+
+ it("should return '/' for undefined input", () => {
+ expect(getSafeRedirectPath(undefined)).toBe("/");
+ });
+
+ it("should return '/' for empty string", () => {
+ expect(getSafeRedirectPath("")).toBe("/");
+ });
+
+ it("should return '/' for whitespace-only string", () => {
+ expect(getSafeRedirectPath(" ")).toBe("/");
+ });
+
+ it("should allow valid relative paths", () => {
+ expect(getSafeRedirectPath("/dashboard")).toBe("/dashboard");
+ expect(getSafeRedirectPath("/project/123")).toBe("/project/123");
+ expect(getSafeRedirectPath("/settings")).toBe("/settings");
+ expect(getSafeRedirectPath("/")).toBe("/");
+ });
+
+ it("should allow paths with query parameters", () => {
+ expect(getSafeRedirectPath("/dashboard?tab=overview")).toBe(
+ "/dashboard?tab=overview",
+ );
+ expect(getSafeRedirectPath("/project/123?view=traces")).toBe(
+ "/project/123?view=traces",
+ );
+ });
+
+ it("should allow paths with hash fragments", () => {
+ expect(getSafeRedirectPath("/dashboard#section")).toBe(
+ "/dashboard#section",
+ );
+ expect(getSafeRedirectPath("/settings#profile")).toBe(
+ "/settings#profile",
+ );
+ });
+
+ it("should trim whitespace from paths", () => {
+ expect(getSafeRedirectPath(" /dashboard ")).toBe("/dashboard");
+ expect(getSafeRedirectPath("\t/project/123\n")).toBe("/project/123");
+ });
+
+ describe("open redirect attack prevention", () => {
+ it("should block protocol-relative URLs", () => {
+ expect(getSafeRedirectPath("//evil.com")).toBe("/");
+ expect(getSafeRedirectPath("//evil.com/path")).toBe("/");
+ expect(getSafeRedirectPath("///evil.com")).toBe("/");
+ });
+
+ it("should block absolute HTTP URLs", () => {
+ expect(getSafeRedirectPath("http://evil.com")).toBe("/");
+ expect(getSafeRedirectPath("http://evil.com/path")).toBe("/");
+ });
+
+ it("should block absolute HTTPS URLs", () => {
+ expect(getSafeRedirectPath("https://evil.com")).toBe("/");
+ expect(getSafeRedirectPath("https://evil.com/path")).toBe("/");
+ });
+
+ it("should block javascript: URIs", () => {
+ expect(getSafeRedirectPath("javascript:alert(1)")).toBe("/");
+ expect(getSafeRedirectPath("javascript:void(0)")).toBe("/");
+ });
+
+ it("should block data: URIs", () => {
+ expect(
+ getSafeRedirectPath("data:text/html,<script>alert(1)</script>"),
+ ).toBe("/");
+ expect(getSafeRedirectPath("data:text/plain,test")).toBe("/");
+ });
+
+ it("should block file: URIs", () => {
+ expect(getSafeRedirectPath("file:///etc/passwd")).toBe("/");
+ expect(getSafeRedirectPath("file://server/share")).toBe("/");
+ });
+
+ it("should block ftp: URIs", () => {
+ expect(getSafeRedirectPath("ftp://evil.com")).toBe("/");
+ });
+
+ it("should block other protocol schemes", () => {
+ expect(getSafeRedirectPath("mailto:[email protected]")).toBe("/");
+ expect(getSafeRedirectPath("tel:+1234567890")).toBe("/");
+ expect(getSafeRedirectPath("vbscript:alert(1)")).toBe("/");
+ });
+
+ it("should block paths that don't start with /", () => {
+ expect(getSafeRedirectPath("dashboard")).toBe("/");
+ expect(getSafeRedirectPath("./dashboard")).toBe("/");
+ expect(getSafeRedirectPath("../dashboard")).toBe("/");
+ expect(getSafeRedirectPath("evil.com")).toBe("/");
+ });
+
+ it("should handle URL-encoded attack attempts", () => {
+ // %2F%2F = //
+ expect(getSafeRedirectPath(decodeURIComponent("%2F%2Fevil.com"))).toBe(
+ "/",
+ );
+ // Note: The function receives already-decoded input in real usage
+ // since router.query.targetPath is already decoded by Next.js
+ });
+ });
+ });
+
+ describe("with basePath configured", () => {
+ beforeEach(() => {
+ // Set basePath for these tests
+ (env as any).NEXT_PUBLIC_BASE_PATH = "/my-app";
+ });
+
+ afterEach(() => {
+ // Reset basePath after tests
+ (env as any).NEXT_PUBLIC_BASE_PATH = undefined;
+ });
+
+ it("should return basePath for null input", () => {
+ expect(getSafeRedirectPath(null)).toBe("/my-app/");
+ });
+
+ it("should return basePath for undefined input", () => {
+ expect(getSafeRedirectPath(undefined)).toBe("/my-app/");
+ });
+
+ it("should return basePath for empty string", () => {
+ expect(getSafeRedirectPath("")).toBe("/my-app/");
+ });
+
+ it("should prepend basePath to valid relative paths", () => {
+ expect(getSafeRedirectPath("/dashboard")).toBe("/my-app/dashboard");
+ expect(getSafeRedirectPath("/project/123")).toBe("/my-app/project/123");
+ expect(getSafeRedirectPath("/")).toBe("/my-app/");
+ });
+
+ it("should prepend basePath to paths with query parameters", () => {
+ expect(getSafeRedirectPath("/dashboard?tab=overview")).toBe(
+ "/my-app/dashboard?tab=overview",
+ );
+ });
+
+ it("should prepend basePath to paths with hash fragments", () => {
+ expect(getSafeRedirectPath("/dashboard#section")).toBe(
+ "/my-app/dashboard#section",
+ );
+ });
+
+ it("should return basePath for blocked URLs", () => {
+ expect(getSafeRedirectPath("//evil.com")).toBe("/my-app/");
+ expect(getSafeRedirectPath("http://evil.com")).toBe("/my-app/");
+ expect(getSafeRedirectPath("javascript:alert(1)")).toBe("/my-app/");
+ });
+ });
+
+ describe("edge cases", () => {
+ beforeEach(() => {
+ (env as any).NEXT_PUBLIC_BASE_PATH = undefined;
+ });
+
+ it("should handle very long paths", () => {
+ const longPath = "/project/" + "a".repeat(1000);
+ expect(getSafeRedirectPath(longPath)).toBe(longPath);
+ });
+
+ it("should handle paths with special characters", () => {
+ expect(getSafeRedirectPath("/path/with spaces")).toBe(
+ "/path/with spaces",
+ );
+ expect(getSafeRedirectPath("/path/with-dashes")).toBe(
+ "/path/with-dashes",
+ );
+ expect(getSafeRedirectPath("/path/with_underscores")).toBe(
+ "/path/with_underscores",
+ );
+ });
+
+ it("should handle paths with encoded characters", () => {
+ expect(getSafeRedirectPath("/path%20with%20spaces")).toBe(
+ "/path%20with%20spaces",
+ );
+ expect(getSafeRedirectPath("/path%2Fwith%2Fencoded")).toBe(
+ "/path%2Fwith%2Fencoded",
+ );
+ });
+
+ it("should handle non-string input gracefully", () => {
+ // @ts-expect-error Testing runtime behavior with invalid input
+ expect(getSafeRedirectPath(123)).toBe("/");
+ // @ts-expect-error Testing runtime behavior with invalid input
+ expect(getSafeRedirectPath({})).toBe("/");
+ // @ts-expect-error Testing runtime behavior with invalid input
+ expect(getSafeRedirectPath([])).toBe("/");
+ });
+ });
+});
diff --git a/web/src/components/layouts/layout.tsx b/web/src/components/layouts/layout.tsx
index cc9142776a..6dc914a1c6 100644
--- a/web/src/components/layouts/layout.tsx
+++ b/web/src/components/layouts/layout.tsx
@@ -13,8 +13,8 @@ import { env } from "@/src/env.mjs";
import { Spinner } from "@/src/components/layouts/spinner";
import { hasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { Toaster } from "@/src/components/ui/sonner";
-import DOMPurify from "dompurify";
import { ThemeToggle } from "@/src/features/theming/ThemeToggle";
+import { getSafeRedirectPath } from "@/src/utils/redirect";
import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";
import { useEntitlements } from "@/src/features/entitlements/hooks";
import { useUiCustomization } from "@/src/ee/features/ui-customization/useUiCustomization";
@@ -303,17 +303,7 @@ export default function Layout(props: PropsWithChildren) {
unauthenticatedPaths.includes(router.pathname)
) {
const queryTargetPath = router.query.targetPath as string | undefined;
-
- const sanitizedTargetPath = queryTargetPath
- ? DOMPurify.sanitize(queryTargetPath)
- : undefined;
-
- // only allow relative links
- const targetPath =
- sanitizedTargetPath?.startsWith("/") &&
- !sanitizedTargetPath.startsWith("//")
- ? sanitizedTargetPath
- : "/";
+ const targetPath = getSafeRedirectPath(queryTargetPath);
void router.replace(targetPath);
return <Spinner message="Redirecting" />;
diff --git a/web/src/pages/auth/sign-in.tsx b/web/src/pages/auth/sign-in.tsx
index 2e2b09e3fe..26cd089c8d 100644
--- a/web/src/pages/auth/sign-in.tsx
+++ b/web/src/pages/auth/sign-in.tsx
@@ -44,7 +44,7 @@ import useLocalStorage from "@/src/components/useLocalStorage";
import { AuthProviderButton } from "@/src/features/auth/components/AuthProviderButton";
import { cn } from "@/src/utils/tailwind";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
-import DOMPurify from "dompurify";
+import { getSafeRedirectPath } from "@/src/utils/redirect";
const credentialAuthForm = z.object({
email: z.string().email(),
@@ -569,17 +569,10 @@ export default function SignIn({
const emailParam = router.query.email as string | undefined;
// Validate targetPath to prevent open redirect attacks
- const sanitizedTargetPath = queryTargetPath
- ? DOMPurify.sanitize(queryTargetPath)
+ const targetPath = queryTargetPath
+ ? getSafeRedirectPath(queryTargetPath)
: undefined;
- // Only allow relative links (must start with '/' but not '//')
- const targetPath =
- sanitizedTargetPath?.startsWith("/") &&
- !sanitizedTargetPath.startsWith("//")
- ? sanitizedTargetPath
- : undefined;
-
// Credentials
const credentialsForm = useForm({
resolver: zodResolver(credentialAuthForm),
diff --git a/web/src/pages/auth/sign-up.tsx b/web/src/pages/auth/sign-up.tsx
index 15558d4df6..2543c8f82b 100644
--- a/web/src/pages/auth/sign-up.tsx
+++ b/web/src/pages/auth/sign-up.tsx
@@ -30,7 +30,7 @@ import { Divider } from "@tremor/react";
import { Turnstile } from "@marsidev/react-turnstile";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
import { useRouter } from "next/router";
-import DOMPurify from "dompurify";
+import { getSafeRedirectPath } from "@/src/utils/redirect";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import useLocalStorage from "@/src/components/useLocalStorage";
@@ -53,17 +53,10 @@ export default function SignIn({
const emailParam = router.query.email as string | undefined;
// Validate targetPath to prevent open redirect attacks
- const sanitizedTargetPath = queryTargetPath
- ? DOMPurify.sanitize(queryTargetPath)
+ const targetPath = queryTargetPath
+ ? getSafeRedirectPath(queryTargetPath)
: undefined;
- // Only allow relative links (must start with '/' but not '//')
- const targetPath =
- sanitizedTargetPath?.startsWith("/") &&
- !sanitizedTargetPath.startsWith("//")
- ? sanitizedTargetPath
- : undefined;
-
const [turnstileToken, setTurnstileToken] = useState<string>();
// Used to refresh turnstile as the token can only be used once
const [turnstileCData, setTurnstileCData] = useState<string>(
diff --git a/web/src/utils/redirect.ts b/web/src/utils/redirect.ts
new file mode 100644
index 0000000000..1bc2aa4f4d
--- /dev/null
+++ b/web/src/utils/redirect.ts
@@ -0,0 +1,58 @@
+import { env } from "@/src/env.mjs";
+
+/**
+ * Validates and sanitizes a redirect path to prevent open redirect attacks.
+ *
+ * Security Requirements:
+ * - Only allows relative paths starting with "/" (e.g., "/dashboard", "/project/123")
+ * - Blocks protocol-relative URLs (e.g., "//evil.com")
+ * - Blocks absolute URLs (e.g., "http://evil.com", "https://evil.com")
+ * - Blocks javascript: and data: URIs
+ * - Automatically prepends NEXT_PUBLIC_BASE_PATH if configured
+ *
+ * @param targetPath - The path to validate (typically from query params or user input)
+ * @returns A safe redirect path with basePath prepended, or "/" (with basePath) if invalid
+ *
+ * @example
+ * // With NEXT_PUBLIC_BASE_PATH="/my-app"
+ * getSafeRedirectPath("/dashboard") // Returns "/my-app/dashboard"
+ * getSafeRedirectPath("//evil.com") // Returns "/my-app/" (safe default)
+ * getSafeRedirectPath("http://evil.com") // Returns "/my-app/" (safe default)
+ *
+ * @example
+ * // Without NEXT_PUBLIC_BASE_PATH
+ * getSafeRedirectPath("/dashboard") // Returns "/dashboard"
+ * getSafeRedirectPath("//evil.com") // Returns "/" (safe default)
+ */
+export function getSafeRedirectPath(
+ targetPath: string | undefined | null,
+): string {
+ const basePath = env.NEXT_PUBLIC_BASE_PATH ?? "";
+ const safeDefault = basePath ? `${basePath}/` : "/";
+
+ // Handle empty/null/undefined
+ if (!targetPath || typeof targetPath !== "string") {
+ return safeDefault;
+ }
+
+ // Trim whitespace
+ const trimmed = targetPath.trim();
+
+ if (!trimmed) {
+ return safeDefault;
+ }
+
+ // Only allow paths starting with "/" but not "//" (protocol-relative URLs)
+ // This blocks:
+ // - Protocol-relative: "//evil.com"
+ // - Absolute URLs: "http://evil.com", "https://evil.com"
+ // - JavaScript URIs: "javascript:alert(1)"
+ // - Data URIs: "data:text/html,..."
+ // - Other schemes: "file://", "ftp://", etc.
+ if (!trimmed.startsWith("/") || trimmed.startsWith("//")) {
+ return safeDefault;
+ }
+
+ // Prepend basePath if configured
+ return basePath + trimmed;
+}