Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

31.2 KB
Raw Blame
import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";
import { act, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { BrowserRouter, MemoryRouter } from "react-router-dom";
import { MantineProvider } from "@mantine/core";
import Login from "@editor/routes/Login";
import { useAuth } from "@editor/auth/UseSession";
import { springAuth } from "@editor/auth/spring/springAuthClient";
import { PreferencesProvider } from "@editor/contexts/PreferencesContext";
import { TestQueryProvider } from "@editor/tests/utils/TestQueryProvider";
import apiClient from "@editor/services/apiClient";
import { configureSpringAuth } from "@editor/auth/config";

// Mock i18n to return fallback text
vi.mock("react-i18next", () => ({
  useTranslation: () => ({
    t: (key: string, fallback?: string | Record<string, unknown>) => {
      if (typeof fallback === "string") return fallback;
      return key;
    },
  }),
  initReactI18next: {
    type: "3rdParty",
    init: vi.fn(),
  },
}));

// Mock i18n module to avoid initialization
vi.mock("@editor/i18n", () => ({
  updateSupportedLanguages: vi.fn(),
  supportedLanguages: { "en-US": "English (US)" },
  rtlLanguages: [],
  default: {
    language: "en-US",
    changeLanguage: vi.fn(),
    options: {},
  },
}));

// Mock useAuth hook
vi.mock("@editor/auth/UseSession", () => ({
  useAuth: vi.fn(),
}));

// Mock springAuth; keep the real redirect-path helpers.
vi.mock("@editor/auth/spring/springAuthClient", async () => {
  const actual = await vi.importActual<
    typeof import("@editor/auth/spring/springAuthClient")
  >("@editor/auth/spring/springAuthClient");
  return {
    ...actual,
    springAuth: {
      signInWithPassword: vi.fn(),
      signInWithOAuth: vi.fn(),
    },
  };
});

// Mock useDocumentMeta
vi.mock("@editor/hooks/useDocumentMeta", () => ({
  useDocumentMeta: vi.fn(),
}));

// Mock apiClient for provider list
vi.mock("@editor/services/apiClient", () => ({
  default: {
    get: vi.fn(),
    post: vi.fn(),
  },
}));

const mockNavigate = vi.fn();
const mockBackendProbeState = {
  status: "up" as const,
  loginDisabled: false,
  loading: false,
};
const mockProbe = vi.fn().mockResolvedValue(mockBackendProbeState);

vi.mock("@editor/hooks/useBackendProbe", () => ({
  useBackendProbe: () => ({
    ...mockBackendProbeState,
    probe: mockProbe,
  }),
}));

vi.mock("react-router-dom", async () => {
  const actual = await vi.importActual("react-router-dom");
  return {
    ...actual,
    useNavigate: () => mockNavigate,
  };
});

// AuthLayout renders <Footer>, which reads useFooterInfo. In the real router
// /login sits inside PlatformProviders, which supplies the client.
const TestWrapper = ({ children }: { children: React.ReactNode }) => (
  <TestQueryProvider>
    <MantineProvider>
      <PreferencesProvider>{children}</PreferencesProvider>
    </MantineProvider>
  </TestQueryProvider>
);

describe("Login", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockBackendProbeState.status = "up";
    mockBackendProbeState.loginDisabled = false;
    mockBackendProbeState.loading = false;
    mockProbe.mockResolvedValue(mockBackendProbeState);

    // Default auth state - not logged in
    vi.mocked(useAuth).mockReturnValue({
      session: null,
      user: null,
      displayName: null,
      isAnonymous: false,
      isAdmin: false,
      portalAccess: false,
      role: null,
      loading: false,
      error: null,
      signOut: vi.fn(),
      refreshSession: vi.fn(),
    });

    // Mock apiClient for login UI data
    vi.mocked(apiClient.get).mockResolvedValue({
      data: {
        enableLogin: true,
        providerList: {},
      },
    });

    // The shared login hook reads getSpringAuthConfig().http; in the real app,
    // startup points that at apiClient. Mirror that here so the mocked apiClient
    // serves the login-ui-data fetch.
    configureSpringAuth({ http: apiClient });
  });

  it("should render login form", async () => {
    render(
      <TestWrapper>
        <BrowserRouter>
          <Login />
        </BrowserRouter>
      </TestWrapper>,
    );

    await waitFor(() => {
      // Check for login form elements - use id since it's more reliable
      const emailInput = document.getElementById("email");
      expect(emailInput).toBeTruthy();
    });
  });

  it("should land an authenticated user on the editor", async () => {
    const mockSession = {
      user: {
        id: "123",
        email: "[email protected]",
        username: "testuser",
        role: "USER",
      },
      access_token: "mock-token",
      expires_in: 3600,
    };

    vi.mocked(useAuth).mockReturnValue({
      session: mockSession,
      user: mockSession.user,
      displayName: mockSession.user.username,
      isAnonymous: false,
      isAdmin: false,
      portalAccess: false,
      role: mockSession.user.role,
      loading: false,
      error: null,
      signOut: vi.fn(),
      refreshSession: vi.fn(),
    });

    render(
      <TestWrapper>
        <BrowserRouter>
          <Login />
        </BrowserRouter>
      </TestWrapper>,
    );

    await waitFor(() => {
      expect(mockNavigate).toHaveBeenCalledWith("/editor", { replace: true });
    });
  });

  // Landing bounces an unauthenticated visitor to /login?from=<where they were>,
  // so signing in returns them there instead of re-running the role routing.
  describe("return path", () => {
    const signedIn = () => {
      const mockSession = {
        user: {
          id: "123",
          email: "[email protected]",
          username: "testuser",
          role: "USER",
        },
        access_token: "mock-token",
        expires_in: 3600,
      };
      vi.mocked(useAuth).mockReturnValue({
        session: mockSession,
        user: mockSession.user,
        displayName: mockSession.user.username,
        isAnonymous: false,
        isAdmin: false,
        portalAccess: false,
        role: mockSession.user.role,
        loading: false,
        error: null,
        signOut: vi.fn(),
        refreshSession: vi.fn(),
      });
    };

    const renderAtLogin = (search: string) => {
      window.history.replaceState({}, "", `/login${search}`);
      return render(
        <TestWrapper>
          <BrowserRouter>
            <Login />
          </BrowserRouter>
        </TestWrapper>,
      );
    };

    afterEach(() => {
      window.history.replaceState({}, "", "/");
      sessionStorage.clear();
    });

    it("returns to where the user came from", async () => {
      signedIn();
      renderAtLogin(`?from=${encodeURIComponent("/compress")}`);

      await waitFor(() => {
        expect(mockNavigate).toHaveBeenCalledWith("/compress", {
          replace: true,
        });
      });
    });

    // A full-page 401 redirect drops router state and Spring can strip ?from=,
    // leaving the return path only in the sessionStorage stash. Without reading
    // it here a processor user refreshing /editor falls through to the role
    // router and lands on the processor.
    it("returns to the stashed path when there is no ?from=", async () => {
      signedIn();
      sessionStorage.setItem("stirling_post_login_path", "/compress");
      renderAtLogin("");

      await waitFor(() => {
        expect(mockNavigate).toHaveBeenCalledWith("/compress", {
          replace: true,
        });
      });
      // Consumed, so a later sign-in can't reuse a stale path.
      expect(sessionStorage.getItem("stirling_post_login_path")).toBeNull();
    });

    // Delegated to the shared isSafePostLoginRedirect, so the backslash form
    // (browsers normalise "\" to "/") and auth routes are covered too.
    it.each([
      ["protocol-relative", "//evil.example.com"],
      ["backslash-escaped", "/\\evil.example.com"],
      ["an auth route", "/login"],
    ])("rejects %s and lands normally", async (_label, from) => {
      signedIn();
      renderAtLogin(`?from=${encodeURIComponent(from)}`);

      await waitFor(() => {
        expect(mockNavigate).toHaveBeenCalledWith("/editor", { replace: true });
      });
      expect(mockNavigate).not.toHaveBeenCalledWith(from, expect.anything());
    });
  });

  it("should show loading state while auth is loading", async () => {
    vi.mocked(useAuth).mockReturnValue({
      session: null,
      user: null,
      displayName: null,
      isAnonymous: false,
      isAdmin: false,
      portalAccess: false,
      role: null,
      loading: true,
      error: null,
      signOut: vi.fn(),
      refreshSession: vi.fn(),
    });

    await act(async () => {
      render(
        <TestWrapper>
          <BrowserRouter>
            <Login />
          </BrowserRouter>
        </TestWrapper>,
      );
    });

    // Component shouldn't redirect or show form while loading
    expect(mockNavigate).not.toHaveBeenCalled();
  });

  it("should handle email/password login", async () => {
    const user = userEvent.setup();
    const mockUser = {
      id: "123",
      email: "[email protected]",
      username: "[email protected]",
      role: "USER",
    };

    const mockSession = {
      user: mockUser,
      access_token: "new-token",
      expires_in: 3600,
    };

    vi.mocked(springAuth.signInWithPassword).mockResolvedValueOnce({
      user: mockUser,
      session: mockSession,
      error: null,
    });

    render(
      <TestWrapper>
        <BrowserRouter>
          <Login />
        </BrowserRouter>
      </TestWrapper>,
    );

    // Wait for form to load
    await waitFor(
      () => {
        const emailInput = document.getElementById("email");
        expect(emailInput).toBeTruthy();
        const passwordInput = document.getElementById("password");
        expect(passwordInput).toBeTruthy();
      },
      { timeout: 3000 },
    );

    // Fill in form using getElementById
    const emailInput = document.getElementById("email") as HTMLInputElement;
    const passwordInput = document.getElementById(
      "password",
    ) as HTMLInputElement;

    if (!emailInput || !passwordInput) {
      throw new Error("Form inputs not found");
    }

    await user.type(emailInput, "[email protected]");
    await user.type(passwordInput, "password123");

    // Submit form - use a more flexible query
    // Look for button with type="submit" in the form
    const submitButton = await waitFor(
      () => {
        const buttons = screen.queryAllByRole("button");
        const submitBtn = buttons.find(
          (btn) => btn.getAttribute("type") === "submit",
        );
        if (!submitBtn) {
          throw new Error("Submit button not found");
        }
        return submitBtn;
      },
      { timeout: 5000 },
    );
    await user.click(submitButton);

    await waitFor(() => {
      expect(springAuth.signInWithPassword).toHaveBeenCalledWith({
        email: "[email protected]",
        password: "password123",
      });
    });
  });

  it("should use actual provider ID for OAuth login (authentik)", async () => {
    const user = userEvent.setup();

    // Mock provider list with authentik
    vi.mocked(apiClient.get).mockResolvedValue({
      data: {
        enableLogin: true,
        providerList: {
          "/oauth2/authorization/authentik": "Authentik",
        },
      },
    });

    vi.mocked(springAuth.signInWithOAuth).mockResolvedValueOnce({
      error: null,
    });

    render(
      <TestWrapper>
        <BrowserRouter>
          <Login />
        </BrowserRouter>
      </TestWrapper>,
    );

    // Wait for OAuth button to appear
    await waitFor(
      () => {
        const button = screen.queryByText(/Authentik/);
        expect(button).toBeTruthy();
      },
      { timeout: 3000 },
    );

    const oauthButton = screen.getByText(/Authentik/);
    await user.click(oauthButton);

    await waitFor(() => {
      // Should use full path directly, NOT map to 'oidc'
      expect(springAuth.signInWithOAuth).toHaveBeenCalledWith({
        provider: "/oauth2/authorization/authentik",
        options: { redirectTo: "/auth/callback" },
      });
    });
  });

  it("should use actual provider ID for OAuth login (custom provider)", async () => {
    const user = userEvent.setup();

    // Mock provider list with custom provider 'mycompany'
    vi.mocked(apiClient.get).mockResolvedValue({
      data: {
        enableLogin: true,
        providerList: {
          "/oauth2/authorization/mycompany": "My Company SSO",
        },
      },
    });

    vi.mocked(springAuth.signInWithOAuth).mockResolvedValueOnce({
      error: null,
    });

    render(
      <TestWrapper>
        <BrowserRouter>
          <Login />
        </BrowserRouter>
      </TestWrapper>,
    );

    // Wait for OAuth button to appear (will show 'Mycompany' as label)
    await waitFor(
      () => {
        const button = screen.queryByText(/Mycompany/);
        expect(button).toBeTruthy();
      },
      { timeout: 3000 },
    );

    const oauthButton = screen.getByText(/Mycompany/);
    await user.click(oauthButton);

    await waitFor(() => {
      // Should use full path directly - this is the critical fix
      // Previously it would map unknown providers to 'oidc'
      expect(springAuth.signInWithOAuth).toHaveBeenCalledWith({
        provider: "/oauth2/authorization/mycompany",
        options: { redirectTo: "/auth/callback" },
      });
    });
  });

  it("should use oidc provider ID when explicitly configured", async () => {
    const user = userEvent.setup();

    // Mock provider list with 'oidc'
    vi.mocked(apiClient.get).mockResolvedValue({
      data: {
        enableLogin: true,
        providerList: {
          "/oauth2/authorization/oidc": "OIDC",
        },
      },
    });

    vi.mocked(springAuth.signInWithOAuth).mockResolvedValueOnce({
      error: null,
    });

    render(
      <TestWrapper>
        <BrowserRouter>
          <Login />
        </BrowserRouter>
      </TestWrapper>,
    );

    // Wait for OAuth button to appear
    await waitFor(
      () => {
        const button = screen.queryByText(/OIDC/);
        expect(button).toBeTruthy();
      },
      { timeout: 3000 },
    );

    const oauthButton = screen.getByText(/OIDC/);
    await user.click(oauthButton);

    await waitFor(() => {
      // Should use full path when explicitly configured
      expect(springAuth.signInWithOAuth).toHaveBeenCalledWith({
        provider: "/oauth2/authorization/oidc",
        options: { redirectTo: "/auth/callback" },
      });
    });
  });

  it("should show error on failed login", async () => {
    const user = userEvent.setup();
    const errorMessage = "Invalid credentials";

    vi.mocked(springAuth.signInWithPassword).mockResolvedValueOnce({
      user: null,
      session: null,
      error: { message: errorMessage },
    });

    render(
      <TestWrapper>
        <BrowserRouter>
          <Login />
        </BrowserRouter>
      </TestWrapper>,
    );

    await waitFor(
      () => {
        const emailInput = document.getElementById("email");
        const passwordInput = document.getElementById("password");
        expect(emailInput).toBeTruthy();
        expect(passwordInput).toBeTruthy();
      },
      { timeout: 3000 },
    );

    const emailInput = document.getElementById("email") as HTMLInputElement;
    const passwordInput = document.getElementById(
      "password",
    ) as HTMLInputElement;

    await user.type(emailInput, "[email protected]");
    await user.type(passwordInput, "wrongpassword");

    const submitButton = await waitFor(
      () => {
        const buttons = screen.queryAllByRole("button");
        const submitBtn = buttons.find(
          (btn) => btn.getAttribute("type") === "submit",
        );
        if (!submitBtn) {
          throw new Error("Submit button not found");
        }
        return submitBtn;
      },
      { timeout: 5000 },
    );
    await user.click(submitButton);

    await waitFor(() => {
      expect(screen.getByText(errorMessage)).toBeInTheDocument();
    });
  });

  it("should validate empty email and password", async () => {
    render(
      <TestWrapper>
        <BrowserRouter>
          <Login />
        </BrowserRouter>
      </TestWrapper>,
    );

    await waitFor(
      () => {
        expect(document.getElementById("email")).toBeTruthy();
      },
      { timeout: 3000 },
    );

    // Find the submit button
    const submitButton = await waitFor(
      () => {
        const buttons = screen.queryAllByRole("button");
        const submitBtn = buttons.find(
          (btn) => btn.getAttribute("type") === "submit",
        );
        if (!submitBtn) {
          throw new Error("Submit button not found");
        }
        return submitBtn;
      },
      { timeout: 5000 },
    );

    // Button should be disabled when email/password are empty
    expect(submitButton).toBeDisabled();

    // Verify sign in was not called
    expect(springAuth.signInWithPassword).not.toHaveBeenCalled();
  });

  it("should display session expired message from URL param", async () => {
    await act(async () => {
      render(
        <TestWrapper>
          <MemoryRouter initialEntries={["/login?expired=true"]}>
            <Login />
          </MemoryRouter>
        </TestWrapper>,
      );
    });

    expect(screen.getByText(/session.*expired/i)).toBeInTheDocument();
  });

  it("should display account created success message", async () => {
    await act(async () => {
      render(
        <TestWrapper>
          <MemoryRouter initialEntries={["/login?messageType=accountCreated"]}>
            <Login />
          </MemoryRouter>
        </TestWrapper>,
      );
    });

    expect(screen.getByText(/account created/i)).toBeInTheDocument();
  });

  it("should prefill email from query param", () => {
    const email = "[email protected]";

    render(
      <TestWrapper>
        <MemoryRouter initialEntries={[`/login?email=${email}`]}>
          <Login />
        </MemoryRouter>
      </TestWrapper>,
    );

    return waitFor(() => {
      const emailInput = document.getElementById("email") as HTMLInputElement;
      expect(emailInput.value).toBe(email);
    });
  });

  it("should redirect to the editor when login disabled", async () => {
    mockBackendProbeState.loginDisabled = true;
    mockProbe.mockResolvedValueOnce({
      status: "up",
      loginDisabled: true,
      loading: false,
    });
    vi.mocked(apiClient.get).mockResolvedValueOnce({
      data: {
        enableLogin: false,
        providerList: {},
      },
    });

    render(
      <TestWrapper>
        <BrowserRouter>
          <Login />
        </BrowserRouter>
      </TestWrapper>,
    );

    await waitFor(() => {
      expect(mockNavigate).toHaveBeenCalledWith("/editor", { replace: true });
    });
  });

  it("should handle OAuth provider click", async () => {
    vi.mocked(apiClient.get).mockResolvedValueOnce({
      data: {
        enableLogin: true,
        providerList: {
          "/oauth2/authorization/github": "GitHub",
        },
      },
    });

    vi.mocked(springAuth.signInWithOAuth).mockResolvedValueOnce({
      error: null,
    });

    render(
      <TestWrapper>
        <BrowserRouter>
          <Login />
        </BrowserRouter>
      </TestWrapper>,
    );

    await waitFor(() => {
      const githubButton = screen.queryByText(/github/i);
      if (githubButton) {
        expect(githubButton).toBeInTheDocument();
      }
    });

    // Since OAuth buttons might be dynamically rendered based on config,
    // we just verify the mock is set up correctly
    expect(springAuth.signInWithOAuth).toBeDefined();
  });

  it("should show email form by default when no SSO providers", async () => {
    vi.mocked(apiClient.get).mockResolvedValueOnce({
      data: {
        enableLogin: true,
        providerList: {}, // No providers
      },
    });

    render(
      <TestWrapper>
        <BrowserRouter>
          <Login />
        </BrowserRouter>
      </TestWrapper>,
    );

    await waitFor(() => {
      expect(document.getElementById("email")).toBeInTheDocument();
      expect(document.getElementById("password")).toBeInTheDocument();
    });
  });

  it("should disable submit button while signing in", async () => {
    const user = userEvent.setup();

    let finishSignIn!: (
      result: Awaited<ReturnType<typeof springAuth.signInWithPassword>>,
    ) => void;
    const signIn = new Promise<
      Awaited<ReturnType<typeof springAuth.signInWithPassword>>
    >((resolve) => {
      finishSignIn = resolve;
    });
    vi.mocked(springAuth.signInWithPassword).mockReturnValueOnce(signIn);

    render(
      <TestWrapper>
        <BrowserRouter>
          <Login />
        </BrowserRouter>
      </TestWrapper>,
    );

    await waitFor(
      () => {
        const emailInput = document.getElementById("email");
        const passwordInput = document.getElementById("password");
        expect(emailInput).toBeTruthy();
        expect(passwordInput).toBeTruthy();
      },
      { timeout: 3000 },
    );

    const emailInput = document.getElementById("email") as HTMLInputElement;
    const passwordInput = document.getElementById(
      "password",
    ) as HTMLInputElement;

    await user.type(emailInput, "[email protected]");
    await user.type(passwordInput, "password123");

    const submitButton = await waitFor(
      () => {
        const buttons = screen.queryAllByRole("button");
        const submitBtn = buttons.find(
          (btn) => btn.getAttribute("type") === "submit",
        );
        if (!submitBtn) {
          throw new Error("Submit button not found");
        }
        return submitBtn;
      },
      { timeout: 5000 },
    );
    await user.click(submitButton);

    // Button should be disabled while signing in
    expect(submitButton).toBeDisabled();

    await act(async () => {
      finishSignIn({
        user: null,
        session: null,
        error: { message: "Error" },
      });
    });
    await waitFor(() => {
      expect(submitButton).not.toBeDisabled();
    });
  });

  it("should persist location.state.from.pathname before triggering SSO so the user returns to their original URL", async () => {
    const user = userEvent.setup();
    sessionStorage.clear();

    vi.mocked(apiClient.get).mockResolvedValue({
      data: {
        enableLogin: true,
        providerList: {
          "/oauth2/authorization/authentik": "Authentik",
        },
      },
    });

    vi.mocked(springAuth.signInWithOAuth).mockResolvedValueOnce({
      error: null,
    });

    render(
      <TestWrapper>
        <MemoryRouter
          initialEntries={[
            {
              pathname: "/login",
              state: { from: { pathname: "/share/abc123" } },
            },
          ]}
        >
          <Login />
        </MemoryRouter>
      </TestWrapper>,
    );

    await waitFor(
      () => {
        expect(screen.getByText(/Authentik/)).toBeTruthy();
      },
      { timeout: 3000 },
    );

    await user.click(screen.getByText(/Authentik/));

    await waitFor(() => {
      expect(springAuth.signInWithOAuth).toHaveBeenCalled();
    });

    // Must be stashed before the cross-origin SSO redirect wipes location.state.
    expect(sessionStorage.getItem("stirling_post_login_path")).toBe(
      "/share/abc123",
    );
  });

  describe("on a fresh server", () => {
    const renderFresh = () =>
      render(
        <TestWrapper>
          <BrowserRouter>
            <Login />
          </BrowserRouter>
        </TestWrapper>,
      );

    beforeEach(() => {
      sessionStorage.clear();
      vi.mocked(apiClient.get).mockResolvedValue({
        data: {
          enableLogin: true,
          providerList: {},
          firstTimeSetup: true,
          showDefaultCredentials: true,
          defaultSignIn: true,
        },
      });
    });

    it("signs in with the default credentials by itself", async () => {
      vi.mocked(springAuth.signInWithPassword).mockReturnValue(
        new Promise(() => {}),
      );
      renderFresh();

      expect(
        await screen.findByText("Signing in with default credentials"),
      ).toBeInTheDocument();
      expect(springAuth.signInWithPassword).toHaveBeenCalledTimes(1);
      expect(springAuth.signInWithPassword).toHaveBeenCalledWith({
        email: "admin",
        password: "stirling",
      });
    });

    it("shows the form, without the default credentials, when they fail", async () => {
      vi.mocked(springAuth.signInWithPassword).mockResolvedValueOnce({
        user: null,
        session: null,
        error: { message: "Invalid credentials" },
      });
      renderFresh();

      await waitFor(() =>
        expect(document.getElementById("email")).toBeTruthy(),
      );
      expect(screen.queryByText("Default Login Credentials")).toBeNull();
    });

    it("does not try again in a tab where it already failed", async () => {
      sessionStorage.setItem("stirling_default_sign_in_failed", "1");
      renderFresh();

      await waitFor(() =>
        expect(document.getElementById("email")).toBeTruthy(),
      );
      expect(springAuth.signInWithPassword).not.toHaveBeenCalled();
    });

    it("only shows the defaults once the server has finished setup", async () => {
      vi.mocked(apiClient.get).mockResolvedValue({
        data: {
          enableLogin: true,
          providerList: {},
          firstTimeSetup: true,
          showDefaultCredentials: true,
          defaultSignIn: false,
        },
      });
      renderFresh();

      expect(
        await screen.findByText("Default Login Credentials"),
      ).toBeInTheDocument();
      expect(springAuth.signInWithPassword).not.toHaveBeenCalled();
    });

    it("leaves a signed-out admin on the form", async () => {
      sessionStorage.setItem("stirling_sso_auto_login_logged_out", "1");
      renderFresh();

      await waitFor(() =>
        expect(document.getElementById("email")).toBeTruthy(),
      );
      expect(springAuth.signInWithPassword).not.toHaveBeenCalled();
    });
  });

  describe("SSO auto-login", () => {
    const mockLoginConfig = (
      loginMethod: string,
      overrides: { firstTimeSetup?: boolean } = {},
    ) =>
      vi.mocked(apiClient.get).mockResolvedValue({
        data: {
          enableLogin: true,
          ssoAutoLogin: true,
          loginMethod,
          providerList: { "/oauth2/authorization/authentik": "Authentik" },
          ...overrides,
        },
      });

    const renderAt = (entry: string) =>
      render(
        <TestWrapper>
          <MemoryRouter initialEntries={[entry]}>
            <Login />
          </MemoryRouter>
        </TestWrapper>,
      );

    beforeEach(() => {
      sessionStorage.clear();
      vi.mocked(springAuth.signInWithOAuth).mockResolvedValue({ error: null });
    });

    it("redirects to the only provider even when password login is allowed", async () => {
      mockLoginConfig("all");
      renderAt("/login");

      await waitFor(() => {
        expect(springAuth.signInWithOAuth).toHaveBeenCalled();
      });
    });

    it("shows the form instead of redirecting on the second view without a sign-in", async () => {
      mockLoginConfig("all");
      const first = renderAt("/login");
      await waitFor(() => {
        expect(springAuth.signInWithOAuth).toHaveBeenCalledTimes(1);
      });
      first.unmount();

      renderAt("/login");

      await waitFor(() => {
        expect(screen.getByText(/Authentik/)).toBeInTheDocument();
        expect(document.getElementById("password")).toBeInTheDocument();
      });
      expect(springAuth.signInWithOAuth).toHaveBeenCalledTimes(1);
    });

    it("resets the visit and error counts once signed in", async () => {
      mockLoginConfig("all");
      sessionStorage.setItem("stirling_sso_auto_login_attempts", "1");
      sessionStorage.setItem("stirling_sso_auto_login_errors", "1");
      vi.mocked(useAuth).mockReturnValue({
        ...vi.mocked(useAuth)(),
        session: {
          user: {
            id: "123",
            email: "[email protected]",
            username: "testuser",
            role: "USER",
          },
          access_token: "mock-token",
          expires_in: 3600,
        },
      });

      renderAt("/login");

      await waitFor(() => {
        expect(
          sessionStorage.getItem("stirling_sso_auto_login_attempts"),
        ).toBeNull();
        expect(
          sessionStorage.getItem("stirling_sso_auto_login_errors"),
        ).toBeNull();
      });
    });

    it("shows the form instead of redirecting when session storage is blocked", async () => {
      mockLoginConfig("all");
      vi.spyOn(window, "sessionStorage", "get").mockImplementation(() => {
        throw new DOMException("blocked", "SecurityError");
      });

      try {
        renderAt("/login");

        await waitFor(() => {
          expect(screen.getByText(/Authentik/)).toBeInTheDocument();
          expect(document.getElementById("password")).toBeInTheDocument();
        });
        expect(springAuth.signInWithOAuth).not.toHaveBeenCalled();
      } finally {
        vi.restoreAllMocks();
      }
    });

    it("shows the form instead of redirecting when the visit cannot be recorded", async () => {
      mockLoginConfig("all");
      vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
        throw new DOMException("full", "QuotaExceededError");
      });

      try {
        renderAt("/login");

        await waitFor(() => {
          expect(screen.getByText(/Authentik/)).toBeInTheDocument();
          expect(document.getElementById("password")).toBeInTheDocument();
        });
        expect(springAuth.signInWithOAuth).not.toHaveBeenCalled();
      } finally {
        vi.restoreAllMocks();
      }
    });

    it("stays on the page with the email form under ?all", async () => {
      mockLoginConfig("all");
      renderAt("/login?all");

      await waitFor(() => {
        expect(screen.getByText(/Authentik/)).toBeInTheDocument();
        expect(document.getElementById("email")).toBeInTheDocument();
        expect(document.getElementById("password")).toBeInTheDocument();
      });
      expect(springAuth.signInWithOAuth).not.toHaveBeenCalled();
    });

    it("stays on the page in SSO-only mode under ?all", async () => {
      mockLoginConfig("oauth2");
      renderAt("/login?all");

      await waitFor(() => {
        expect(screen.getByText(/Authentik/)).toBeInTheDocument();
      });
      expect(document.getElementById("email")).not.toBeInTheDocument();
      expect(springAuth.signInWithOAuth).not.toHaveBeenCalled();
    });

    it("stays on the page during first-time setup when password login is allowed", async () => {
      mockLoginConfig("all", { firstTimeSetup: true });
      renderAt("/login");

      await waitFor(() => {
        expect(screen.getByText(/Authentik/)).toBeInTheDocument();
        expect(document.getElementById("password")).toBeInTheDocument();
      });
      expect(springAuth.signInWithOAuth).not.toHaveBeenCalled();
    });

    it("still redirects during first-time setup in SSO-only mode", async () => {
      mockLoginConfig("oauth2", { firstTimeSetup: true });
      renderAt("/login");

      await waitFor(() => {
        expect(springAuth.signInWithOAuth).toHaveBeenCalled();
      });
    });

    it("stays on the page after a local account is created", async () => {
      mockLoginConfig("all");
      renderAt("/login?messageType=accountCreated");

      await waitFor(() => {
        expect(screen.getByText(/Authentik/)).toBeInTheDocument();
        expect(
          screen.getByText(
            "Account created successfully! You can now sign in.",
          ),
        ).toBeInTheDocument();
        expect(document.getElementById("password")).toBeInTheDocument();
      });
      expect(springAuth.signInWithOAuth).not.toHaveBeenCalled();
    });
  });
});