feat: update local authentication mode to require a non-placeholder token of at least 50 characters
This commit is contained in:
115
frontend/src/components/organisms/LocalAuthLogin.test.tsx
Normal file
115
frontend/src/components/organisms/LocalAuthLogin.test.tsx
Normal file
@@ -0,0 +1,115 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
|
||||
import { LocalAuthLogin } from "./LocalAuthLogin";
|
||||
|
||||
const setLocalAuthTokenMock = vi.hoisted(() => vi.fn());
|
||||
const fetchMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("@/auth/localAuth", async () => {
|
||||
const actual = await vi.importActual<typeof import("@/auth/localAuth")>(
|
||||
"@/auth/localAuth",
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
setLocalAuthToken: setLocalAuthTokenMock,
|
||||
};
|
||||
});
|
||||
|
||||
describe("LocalAuthLogin", () => {
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset();
|
||||
setLocalAuthTokenMock.mockReset();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
vi.stubEnv("NEXT_PUBLIC_API_URL", "http://localhost:8000/");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("requires a non-empty token", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LocalAuthLogin />);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Continue" }));
|
||||
|
||||
expect(screen.getByText("Bearer token is required.")).toBeInTheDocument();
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(setLocalAuthTokenMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires token length of at least 50 characters", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LocalAuthLogin />);
|
||||
|
||||
await user.type(screen.getByPlaceholderText("Paste token"), "x".repeat(49));
|
||||
await user.click(screen.getByRole("button", { name: "Continue" }));
|
||||
|
||||
expect(
|
||||
screen.getByText("Bearer token must be at least 50 characters."),
|
||||
).toBeInTheDocument();
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(setLocalAuthTokenMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects invalid token values", async () => {
|
||||
const onAuthenticatedMock = vi.fn();
|
||||
fetchMock.mockResolvedValueOnce(new Response(null, { status: 401 }));
|
||||
const user = userEvent.setup();
|
||||
render(<LocalAuthLogin onAuthenticated={onAuthenticatedMock} />);
|
||||
|
||||
await user.type(screen.getByPlaceholderText("Paste token"), "x".repeat(50));
|
||||
await user.click(screen.getByRole("button", { name: "Continue" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText("Token is invalid.")).toBeInTheDocument(),
|
||||
);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"http://localhost:8000/api/v1/users/me",
|
||||
expect.objectContaining({
|
||||
method: "GET",
|
||||
headers: { Authorization: `Bearer ${"x".repeat(50)}` },
|
||||
}),
|
||||
);
|
||||
expect(setLocalAuthTokenMock).not.toHaveBeenCalled();
|
||||
expect(onAuthenticatedMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("saves token only after successful backend validation", async () => {
|
||||
const onAuthenticatedMock = vi.fn();
|
||||
fetchMock.mockResolvedValueOnce(new Response(null, { status: 200 }));
|
||||
const user = userEvent.setup();
|
||||
render(<LocalAuthLogin onAuthenticated={onAuthenticatedMock} />);
|
||||
|
||||
const token = ` ${"g".repeat(50)} `;
|
||||
await user.type(screen.getByPlaceholderText("Paste token"), token);
|
||||
await user.click(screen.getByRole("button", { name: "Continue" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(setLocalAuthTokenMock).toHaveBeenCalledWith("g".repeat(50)),
|
||||
);
|
||||
expect(onAuthenticatedMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("shows a clear error when backend is unreachable", async () => {
|
||||
const onAuthenticatedMock = vi.fn();
|
||||
fetchMock.mockRejectedValueOnce(new TypeError("network error"));
|
||||
const user = userEvent.setup();
|
||||
render(<LocalAuthLogin onAuthenticated={onAuthenticatedMock} />);
|
||||
|
||||
await user.type(screen.getByPlaceholderText("Paste token"), "t".repeat(50));
|
||||
await user.click(screen.getByRole("button", { name: "Continue" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByText("Unable to reach backend to validate token."),
|
||||
).toBeInTheDocument(),
|
||||
);
|
||||
expect(setLocalAuthTokenMock).not.toHaveBeenCalled();
|
||||
expect(onAuthenticatedMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -8,54 +8,132 @@ import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
export function LocalAuthLogin() {
|
||||
const LOCAL_AUTH_TOKEN_MIN_LENGTH = 50;
|
||||
|
||||
async function validateLocalToken(token: string): Promise<string | null> {
|
||||
const rawBaseUrl = process.env.NEXT_PUBLIC_API_URL;
|
||||
if (!rawBaseUrl) {
|
||||
return "NEXT_PUBLIC_API_URL is not set.";
|
||||
}
|
||||
|
||||
const baseUrl = rawBaseUrl.replace(/\/+$/, "");
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${baseUrl}/api/v1/users/me`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
return "Unable to reach backend to validate token.";
|
||||
}
|
||||
|
||||
if (response.ok) {
|
||||
return null;
|
||||
}
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
return "Token is invalid.";
|
||||
}
|
||||
return `Unable to validate token (HTTP ${response.status}).`;
|
||||
}
|
||||
|
||||
type LocalAuthLoginProps = {
|
||||
onAuthenticated?: () => void;
|
||||
};
|
||||
|
||||
const defaultOnAuthenticated = () => window.location.reload();
|
||||
|
||||
export function LocalAuthLogin({ onAuthenticated }: LocalAuthLoginProps) {
|
||||
const [token, setToken] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isValidating, setIsValidating] = useState(false);
|
||||
|
||||
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
const cleaned = token.trim();
|
||||
if (!cleaned) {
|
||||
setError("Bearer token is required.");
|
||||
return;
|
||||
}
|
||||
if (cleaned.length < LOCAL_AUTH_TOKEN_MIN_LENGTH) {
|
||||
setError(
|
||||
`Bearer token must be at least ${LOCAL_AUTH_TOKEN_MIN_LENGTH} characters.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsValidating(true);
|
||||
const validationError = await validateLocalToken(cleaned);
|
||||
setIsValidating(false);
|
||||
if (validationError) {
|
||||
setError(validationError);
|
||||
return;
|
||||
}
|
||||
|
||||
setLocalAuthToken(cleaned);
|
||||
setError(null);
|
||||
window.location.reload();
|
||||
(onAuthenticated ?? defaultOnAuthenticated)();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="space-y-3">
|
||||
<div className="mx-auto rounded-full bg-slate-100 p-3 text-slate-700">
|
||||
<Lock className="h-5 w-5" />
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-app px-4 py-10">
|
||||
<div className="pointer-events-none absolute inset-0">
|
||||
<div className="absolute -top-28 -left-24 h-72 w-72 rounded-full bg-[color:var(--accent-soft)] blur-3xl" />
|
||||
<div className="absolute -right-28 -bottom-24 h-80 w-80 rounded-full bg-[rgba(14,165,233,0.12)] blur-3xl" />
|
||||
</div>
|
||||
|
||||
<Card className="relative w-full max-w-lg animate-fade-in-up">
|
||||
<CardHeader className="space-y-5 border-b border-[color:var(--border)] pb-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="rounded-full border border-[color:var(--border)] bg-[color:var(--surface-muted)] px-3 py-1 text-xs font-semibold uppercase tracking-[0.08em] text-muted">
|
||||
Self-host mode
|
||||
</span>
|
||||
<div className="rounded-xl bg-[color:var(--accent-soft)] p-2 text-[color:var(--accent)]">
|
||||
<Lock className="h-5 w-5" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1 text-center">
|
||||
<h1 className="text-xl font-semibold text-slate-900">
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-strong">
|
||||
Local Authentication
|
||||
</h1>
|
||||
<p className="text-sm text-slate-600">
|
||||
Enter the shared local token configured as
|
||||
<code className="mx-1 rounded bg-slate-100 px-1 py-0.5 text-xs">
|
||||
LOCAL_AUTH_TOKEN
|
||||
</code>
|
||||
on the backend.
|
||||
<p className="text-sm text-muted">
|
||||
Enter your access token to unlock Mission Control.
|
||||
</p>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-3">
|
||||
<Input
|
||||
type="password"
|
||||
value={token}
|
||||
onChange={(event) => setToken(event.target.value)}
|
||||
placeholder="Paste token"
|
||||
autoFocus
|
||||
/>
|
||||
{error ? <p className="text-sm text-red-600">{error}</p> : null}
|
||||
<Button type="submit" className="w-full">
|
||||
Continue
|
||||
<CardContent className="pt-5">
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="local-auth-token"
|
||||
className="text-xs font-semibold uppercase tracking-[0.08em] text-muted"
|
||||
>
|
||||
Access token
|
||||
</label>
|
||||
<Input
|
||||
id="local-auth-token"
|
||||
type="password"
|
||||
value={token}
|
||||
onChange={(event) => setToken(event.target.value)}
|
||||
placeholder="Paste token"
|
||||
autoFocus
|
||||
disabled={isValidating}
|
||||
className="font-mono"
|
||||
/>
|
||||
</div>
|
||||
{error ? (
|
||||
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
|
||||
{error}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted">
|
||||
Token must be at least {LOCAL_AUTH_TOKEN_MIN_LENGTH} characters.
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" className="w-full" size="lg" disabled={isValidating}>
|
||||
{isValidating ? "Validating..." : "Continue"}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
|
||||
Reference in New Issue
Block a user