Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(auth): validate next= redirect target to prevent open redirect (#1309)
Bohan Jiang2317533da4d2
diff --git a/apps/web/app/(auth)/login/page.test.tsx b/apps/web/app/(auth)/login/page.test.tsxindex 007659f6b3..15f9403c10 100644--- a/apps/web/app/(auth)/login/page.test.tsx+++ b/apps/web/app/(auth)/login/page.test.tsx@@ -24,8 +24,14 @@ vi.mock("next/navigation", () => ({}));// Mock auth store — shared LoginPage uses getState().sendCode/verifyCode,-// web wrapper uses useAuthStore((s) => s.user/isLoading)-vi.mock("@multica/core/auth", () => {+// web wrapper uses useAuthStore((s) => s.user/isLoading). Keep the real+// sanitizeNextUrl so the redirect-sanitization rules are exercised rather+// than silently drifting behind a mock reimplementation.+vi.mock("@multica/core/auth", async () => {+ const actual =+ await vi.importActual<typeof import("@multica/core/auth")>(+ "@multica/core/auth",+ );const authState = {sendCode: mockSendCode,verifyCode: mockVerifyCode,@@ -36,7 +42,7 @@ vi.mock("@multica/core/auth", () => {(selector: (s: typeof authState) => unknown) => selector(authState),{ getState: () => authState },);- return { useAuthStore };+ return { ...actual, useAuthStore };});// Mock auth-cookiediff --git a/apps/web/app/(auth)/login/page.tsx b/apps/web/app/(auth)/login/page.tsxindex 49a70a9dd8..fb227021fb 100644--- a/apps/web/app/(auth)/login/page.tsx+++ b/apps/web/app/(auth)/login/page.tsx@@ -3,7 +3,7 @@import { Suspense, useEffect } from "react";import { useSearchParams, useRouter } from "next/navigation";import { useQueryClient } from "@tanstack/react-query";-import { useAuthStore } from "@multica/core/auth";+import { sanitizeNextUrl, useAuthStore } from "@multica/core/auth";import { workspaceKeys } from "@multica/core/workspace/queries";import { paths } from "@multica/core/paths";import type { Workspace } from "@multica/core/types";@@ -25,8 +25,9 @@ function LoginPageContent() {// `next` carries a protected URL the user was originally headed to// (e.g. /invite/{id}). With URL-driven workspaces there is no legacy// "/issues" default — if `next` is absent we decide after login based on- // the user's workspace list.- const nextUrl = searchParams.get("next");+ // the user's workspace list. Sanitize first so a crafted `?next=https://evil`+ // cannot bounce the user off-origin after a successful login.+ const nextUrl = sanitizeNextUrl(searchParams.get("next"));// Already authenticated — honor ?next= or fall back to first workspace// (or /workspaces/new if the user has none). Skip this entire path whendiff --git a/apps/web/app/auth/callback/page.test.tsx b/apps/web/app/auth/callback/page.test.tsxnew file mode 100644index 0000000000..913c055832--- /dev/null+++ b/apps/web/app/auth/callback/page.test.tsx@@ -0,0 +1,86 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { render, waitFor } from "@testing-library/react";+import { paths } from "@multica/core/paths";++const { mockPush, mockSearchParams, mockLoginWithGoogle, mockListWorkspaces } =+ vi.hoisted(() => ({+ mockPush: vi.fn(),+ mockSearchParams: new URLSearchParams(),+ mockLoginWithGoogle: vi.fn(),+ mockListWorkspaces: vi.fn(),+ }));++vi.mock("next/navigation", () => ({+ useRouter: () => ({ push: mockPush }),+ useSearchParams: () => mockSearchParams,+}));++vi.mock("@tanstack/react-query", () => ({+ useQueryClient: () => ({ setQueryData: vi.fn() }),+}));++// Preserve the real sanitizeNextUrl so the "drop unsafe ?next=" behavior is+// exercised rather than silently diverging from the source of truth.+vi.mock("@multica/core/auth", async () => {+ const actual =+ await vi.importActual<typeof import("@multica/core/auth")>(+ "@multica/core/auth",+ );+ return {+ ...actual,+ useAuthStore: (selector: (s: unknown) => unknown) =>+ selector({ loginWithGoogle: mockLoginWithGoogle }),+ };+});++vi.mock("@multica/core/workspace/queries", () => ({+ workspaceKeys: { list: () => ["workspaces"] },+}));++vi.mock("@multica/core/api", () => ({+ api: {+ listWorkspaces: mockListWorkspaces,+ googleLogin: vi.fn(),+ },+}));++import CallbackPage from "./page";++describe("CallbackPage", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockSearchParams.forEach((_v, k) => mockSearchParams.delete(k));+ mockSearchParams.set("code", "test-code");+ mockLoginWithGoogle.mockResolvedValue(undefined);+ mockListWorkspaces.mockResolvedValue([]);+ });++ it("falls back to paths.newWorkspace() when no next= is present and the user has no workspace", async () => {+ render(<CallbackPage />);++ await waitFor(() => {+ expect(mockPush).toHaveBeenCalledWith(paths.newWorkspace());+ });+ });++ it("ignores unsafe next= targets from the OAuth state and still lands on the default destination", async () => {+ mockSearchParams.set("state", "next:https://evil.example");++ render(<CallbackPage />);++ await waitFor(() => {+ expect(mockPush).toHaveBeenCalledWith(paths.newWorkspace());+ });+ expect(mockPush).not.toHaveBeenCalledWith("https://evil.example");+ });++ it("honors a safe next= target (e.g. /invite/{id})", async () => {+ mockSearchParams.set("state", "next:/invite/abc123");++ render(<CallbackPage />);++ await waitFor(() => {+ expect(mockPush).toHaveBeenCalledWith("/invite/abc123");+ });+ });+});diff --git a/apps/web/app/auth/callback/page.tsx b/apps/web/app/auth/callback/page.tsxindex bcc9fd4c88..4af77afea2 100644--- a/apps/web/app/auth/callback/page.tsx+++ b/apps/web/app/auth/callback/page.tsx@@ -3,7 +3,7 @@import { Suspense, useEffect, useState } from "react";import { useSearchParams, useRouter } from "next/navigation";import { useQueryClient } from "@tanstack/react-query";-import { useAuthStore } from "@multica/core/auth";+import { sanitizeNextUrl, useAuthStore } from "@multica/core/auth";import { workspaceKeys } from "@multica/core/workspace/queries";import { paths } from "@multica/core/paths";import { api } from "@multica/core/api";@@ -42,7 +42,9 @@ function CallbackContent() {const stateParts = state.split(",");const isDesktop = stateParts.includes("platform:desktop");const nextPart = stateParts.find((p) => p.startsWith("next:"));- const nextUrl = nextPart ? nextPart.slice(5) : null; // strip "next:" prefix+ // Strip "next:" prefix, then drop anything that isn't a safe relative path+ // so an attacker-controlled `state=next:https://evil` cannot redirect here.+ const nextUrl = sanitizeNextUrl(nextPart ? nextPart.slice(5) : null);const redirectUri = `${window.location.origin}/auth/callback`;diff --git a/packages/core/auth/index.ts b/packages/core/auth/index.tsindex 5d5e5f96fc..2247bca533 100644--- a/packages/core/auth/index.ts+++ b/packages/core/auth/index.ts@@ -1,5 +1,6 @@export { createAuthStore } from "./store";export type { AuthStoreOptions, AuthState } from "./store";+export { sanitizeNextUrl } from "./utils";import type { createAuthStore as CreateAuthStoreFn } from "./store";diff --git a/packages/core/auth/utils.test.ts b/packages/core/auth/utils.test.tsnew file mode 100644index 0000000000..39589602cd--- /dev/null+++ b/packages/core/auth/utils.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";+import { sanitizeNextUrl } from "./utils";++describe("sanitizeNextUrl", () => {+ it("accepts single-slash relative paths", () => {+ expect(sanitizeNextUrl("/issues")).toBe("/issues");+ expect(sanitizeNextUrl("/invite/123")).toBe("/invite/123");+ expect(sanitizeNextUrl("/issues?tab=assigned#top")).toBe(+ "/issues?tab=assigned#top",+ );+ });++ it("returns null for null or empty input", () => {+ expect(sanitizeNextUrl(null)).toBeNull();+ expect(sanitizeNextUrl("")).toBeNull();+ });++ it("rejects absolute URLs", () => {+ expect(sanitizeNextUrl("https://evil.example")).toBeNull();+ expect(sanitizeNextUrl("http://evil.example/path")).toBeNull();+ });++ it("rejects javascript: and other non-http schemes", () => {+ // Caught by the leading-slash rule, but named here so future edits+ // to the regex don't silently drop protection against this vector.+ expect(sanitizeNextUrl("javascript:alert(1)")).toBeNull();+ expect(sanitizeNextUrl("data:text/html,<script>")).toBeNull();+ });++ it("rejects protocol-relative URLs", () => {+ expect(sanitizeNextUrl("//evil.example")).toBeNull();+ expect(sanitizeNextUrl("//evil.example/path")).toBeNull();+ });++ it("rejects paths containing backslashes", () => {+ expect(sanitizeNextUrl("/\\evil.example")).toBeNull();+ expect(sanitizeNextUrl("\\\\evil.example")).toBeNull();+ });++ it("rejects paths containing control characters", () => {+ expect(sanitizeNextUrl("/safe\u0000bad")).toBeNull();+ expect(sanitizeNextUrl("/safe\tbad")).toBeNull();+ expect(sanitizeNextUrl("/safe\r\nbad")).toBeNull();+ });+});diff --git a/packages/core/auth/utils.ts b/packages/core/auth/utils.tsnew file mode 100644index 0000000000..97ebe42c76--- /dev/null+++ b/packages/core/auth/utils.ts@@ -0,0 +1,20 @@+/**+ * Validate a post-login redirect URL and return it only if safe to follow.+ *+ * Only single-slash relative paths (e.g. `/invite/abc`) are accepted. Returns+ * `null` for unsafe or empty input — call sites decide the fallback so this+ * helper never overloads a specific path with "user did not pass next".+ *+ * Rejects:+ * - `null` / empty string+ * - absolute URLs (`https://evil.com`, `javascript:alert(1)`, …)+ * - protocol-relative URLs (`//evil.com`)+ * - paths containing backslashes (Windows-style or `/\\host`)+ * - paths containing ASCII control characters (`\x00`–`\x1f`)+ */+export function sanitizeNextUrl(raw: string | null): string | null {+ if (!raw) return null;+ if (!raw.startsWith("/") || raw.startsWith("//")) return null;+ if (/[\x00-\x1f\\]/.test(raw)) return null;+ return raw;+}