Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions client/src/features/auth/auth.api.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useLogout } from "./auth.api";
import { useAuthStore } from "./auth.store";

function renderWithClient(client: QueryClient) {
return renderHook(() => useLogout(), {
wrapper: ({ children }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>,
});
}

describe("useLogout", () => {
afterEach(() => {
vi.restoreAllMocks();
useAuthStore.getState().clear();
});

it("clears the auth store and the entire query cache on success (BUG #6)", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({ ok: true, json: async () => ({ success: true, data: undefined }) }),
);
useAuthStore.getState().setSession({ accessToken: "token", user: { id: "1", email: "a@b.com", displayName: null } });

const queryClient = new QueryClient();
// Simulates data left over from the session being logged out of -- must not survive into
// whichever account logs in next in this same tab.
queryClient.setQueryData(["projects"], [{ id: "p1", name: "Stale Project" }]);

const { result } = renderWithClient(queryClient);
result.current.mutate();

await waitFor(() => expect(result.current.isSuccess).toBe(true));

expect(useAuthStore.getState().accessToken).toBeNull();
expect(queryClient.getQueryData(["projects"])).toBeUndefined();
});
});
7 changes: 6 additions & 1 deletion client/src/features/auth/auth.api.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";

import { useMutation } from "@tanstack/react-query";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { ApiError, type ApiEnvelope } from "@/lib/api-envelope";
import { useAuthStore, type AuthUser } from "./auth.store";

Expand Down Expand Up @@ -55,6 +55,7 @@ export function useRegister() {
}

export function useLogout() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async () => {
const accessToken = useAuthStore.getState().accessToken;
Expand All @@ -66,6 +67,10 @@ export function useLogout() {
},
onSuccess: () => {
useAuthStore.getState().clear();
// Drops every cached query (projects, graph data, members, ...) so a different account
// logging in next in this same tab never renders the previous account's cached server
// state (BUG #6 -- discovered while investigating a stale "Select a project" header).
queryClient.clear();
},
});
}
39 changes: 25 additions & 14 deletions client/src/features/auth/use-bootstrap-session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,12 @@ vi.mock("next/navigation", () => ({

vi.mock("@/lib/api-client", () => ({
apiRequest: vi.fn(),
refreshAccessToken: vi.fn(),
}));

function jsonResponse(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
}

describe("useBootstrapSession", () => {
beforeEach(() => {
vi.stubGlobal("fetch", vi.fn());
});

afterEach(() => {
cleanup();
vi.unstubAllGlobals();
replace.mockClear();
useAuthStore.getState().clear();
});
Expand All @@ -38,8 +30,8 @@ describe("useBootstrapSession", () => {
});

it("silently refreshes the session on a hard reload and becomes ready", async () => {
const { apiRequest } = await import("@/lib/api-client");
vi.mocked(fetch).mockResolvedValueOnce(jsonResponse(200, { success: true, data: { accessToken: "fresh" } }));
const { apiRequest, refreshAccessToken } = await import("@/lib/api-client");
vi.mocked(refreshAccessToken).mockResolvedValueOnce("fresh");
vi.mocked(apiRequest).mockResolvedValueOnce({ id: "u1", email: "a@b.com", displayName: null });

const { result } = renderHook(() => useBootstrapSession());
Expand All @@ -49,10 +41,29 @@ describe("useBootstrapSession", () => {
expect(replace).not.toHaveBeenCalled();
});

it("still sets the user even though refreshAccessToken flips accessToken mid-bootstrap (BUG #9)", async () => {
// The real `refreshAccessToken` sets `accessToken` on the store as soon as it resolves,
// *before* `/auth/me` returns -- reproduce that here instead of a bare resolved value, since
// a mock that only returns a token (as the test above does) can't expose the effect
// re-running and tearing down the in-flight bootstrap before `setSession` runs.
const { apiRequest, refreshAccessToken } = await import("@/lib/api-client");
vi.mocked(refreshAccessToken).mockImplementationOnce(async () => {
useAuthStore.getState().setAccessToken("fresh");
return "fresh";
});
vi.mocked(apiRequest).mockResolvedValueOnce({ id: "u1", email: "a@b.com", displayName: null });

renderHook(() => useBootstrapSession());

// `isReady` flips true as soon as `accessToken` is set (by design, see auth.store.ts's
// `useIsAuthenticated`), which is exactly what let this race hide before -- so this
// assertion waits on `user` directly rather than on `isReady`.
await waitFor(() => expect(useAuthStore.getState().user).toEqual({ id: "u1", email: "a@b.com", displayName: null }));
});

it("clears the store and redirects to /login when the refresh cookie is missing or invalid", async () => {
vi.mocked(fetch).mockResolvedValueOnce(
jsonResponse(401, { success: false, error: { message: "No session", code: "UNAUTHORIZED", correlationId: "c" } }),
);
const { refreshAccessToken } = await import("@/lib/api-client");
vi.mocked(refreshAccessToken).mockResolvedValueOnce(null);

renderHook(() => useBootstrapSession());

Expand Down
27 changes: 18 additions & 9 deletions client/src/features/auth/use-bootstrap-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { apiRequest } from "@/lib/api-client";
import type { ApiEnvelope } from "@/lib/api-envelope";
import { apiRequest, refreshAccessToken } from "@/lib/api-client";
import { useAuthStore, useIsAuthenticated, type AuthUser } from "./auth.store";

/**
Expand All @@ -19,25 +18,31 @@ export function useBootstrapSession(): { isReady: boolean } {
const [bootstrapped, setBootstrapped] = useState(false);

useEffect(() => {
if (isAuthenticated) {
// Read the store directly instead of depending on the reactive `isAuthenticated` value below.
// `refreshAccessToken()` inside `bootstrap()` calls `setAccessToken` as soon as it resolves,
// which flips `isAuthenticated` true *before* `/auth/me` has returned. If this effect
// depended on `isAuthenticated`, that flip would re-run it -- tearing down this in-flight
// call (`cancelled = true`) right as it awaits `/auth/me`, so `setSession` never lands and
// `user` stays `null` forever even though `accessToken` is set (BUG #9: every user-derived
// UI, e.g. RunDetail's owner/admin-gated "View raw output" button, silently stayed hidden for
// a real owner after any hard reload).
if (useAuthStore.getState().accessToken !== null) {
return;
}

let cancelled = false;

async function bootstrap(): Promise<void> {
try {
const response = await fetch("/api/auth/refresh", { method: "POST", credentials: "include" });
const envelope = (await response.json()) as ApiEnvelope<{ accessToken: string }>;
if (!envelope.success) {
const accessToken = await refreshAccessToken();
if (!accessToken) {
throw new Error("Session expired");
}

useAuthStore.getState().setAccessToken(envelope.data.accessToken);
const user = await apiRequest<AuthUser>("/auth/me");
if (cancelled) return;

useAuthStore.getState().setSession({ accessToken: envelope.data.accessToken, user });
useAuthStore.getState().setSession({ accessToken, user });
setBootstrapped(true);
} catch {
if (cancelled) return;
Expand All @@ -50,7 +55,11 @@ export function useBootstrapSession(): { isReady: boolean } {
return () => {
cancelled = true;
};
}, [isAuthenticated, router]);
// Bootstrap must run exactly once per mount, regardless of `isAuthenticated` or `router`
// identity changing along the way -- see the comment above for why depending on either
// reopens the same race.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return { isReady: isAuthenticated || bootstrapped };
}
30 changes: 30 additions & 0 deletions client/src/features/runs/components/RunDetail.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,36 @@ describe("RunDetail", () => {
expect(screen.queryByRole("button", { name: "View raw output" })).not.toBeInTheDocument();
});

it("shows the run's error message for a failed run (BUG #10)", () => {
const failedRun = { ...RUN, status: "failed" as const, error: { code: "NON_ZERO_EXIT", message: "nmap exited with status 1" } };
vi.mocked(useRun).mockReturnValue({ isLoading: false, isError: false, data: failedRun } as never);
vi.mocked(useCurrentRole).mockReturnValue({ role: "member", isLoading: false, isError: false });

render(<RunDetail projectId={PROJECT_ID} runId={RUN_ID} />);

expect(screen.getByRole("alert")).toHaveTextContent("NON_ZERO_EXIT");
expect(screen.getByRole("alert")).toHaveTextContent("nmap exited with status 1");
});

it("shows nothing extra for a failed run with an unreadable error shape", () => {
const failedRun = { ...RUN, status: "failed" as const, error: "some unstructured string" };
vi.mocked(useRun).mockReturnValue({ isLoading: false, isError: false, data: failedRun } as never);
vi.mocked(useCurrentRole).mockReturnValue({ role: "member", isLoading: false, isError: false });

render(<RunDetail projectId={PROJECT_ID} runId={RUN_ID} />);

expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});

it("does not show an error block for a succeeded run", () => {
vi.mocked(useRun).mockReturnValue({ isLoading: false, isError: false, data: RUN } as never);
vi.mocked(useCurrentRole).mockReturnValue({ role: "member", isLoading: false, isError: false });

render(<RunDetail projectId={PROJECT_ID} runId={RUN_ID} />);

expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});

it("fetches and opens the raw output as a blob URL for an owner", async () => {
vi.mocked(useRun).mockReturnValue({ isLoading: false, isError: false, data: RUN } as never);
vi.mocked(useCurrentRole).mockReturnValue({ role: "owner", isLoading: false, isError: false });
Expand Down
23 changes: 23 additions & 0 deletions client/src/features/runs/components/RunDetail.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use client";

import { useState } from "react";
import { z } from "zod";
import { Badge, runStatusTone } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { useCurrentRole } from "@/features/workspace/api/use-current-role";
Expand All @@ -12,12 +13,24 @@ type Props = {
runId: string;
};

// `ToolRun.error` is typed `z.unknown()` (use-runs.ts) -- the server attaches whatever shape the
// failure came from (orchestrator.worker.ts's `{ code, message }`), so parse it defensively
// instead of casting (no `as`, per the project's "no unsafe casts" standard). Any shape that
// doesn't match is treated as "no readable error" rather than crashing the page.
const runErrorSchema = z
.object({ code: z.string().optional(), message: z.string() })
.nullable()
.catch(null);

/**
* Polls a single run's status until it's terminal. The raw-output link is only surfaced to
* owner/admin roles -- the backend's `GET :runId/raw` endpoint already enforces this
* server-side (`@Roles("owner","admin")`); the UI mirrors it so members don't see a dead link.
* Fetched via `apiRequestBlob` (not a plain `<a href>`) because auth is a Bearer header, not a
* cookie the browser would attach to a bare navigation.
*
* A `failed` run also surfaces `run.error` (BUG #10 -- it used to render only the "failed" badge
* with zero diagnostic information, for every role).
*/
export function RunDetail({ projectId, runId }: Props) {
const runQuery = useRun(projectId, runId);
Expand Down Expand Up @@ -48,6 +61,7 @@ export function RunDetail({ projectId, runId }: Props) {
}

const run = runQuery.data;
const runError = run.status === "failed" ? runErrorSchema.parse(run.error) : null;

return (
<div className="flex flex-col gap-4">
Expand All @@ -63,6 +77,15 @@ export function RunDetail({ projectId, runId }: Props) {
<dt className="text-[var(--color-foreground-muted)]">Queued</dt>
<dd>{run.queuedAt.toLocaleString()}</dd>
</dl>
{runError ? (
<div
role="alert"
className="rounded-[var(--radius-md)] border border-[var(--node-critical)]/30 bg-[var(--node-critical)]/10 p-3 text-sm text-[var(--node-critical)]"
>
<p className="font-medium">{runError.code ?? "Run failed"}</p>
<p>{runError.message}</p>
</div>
) : null}
{canViewRaw ? (
<div className="flex flex-col items-start gap-1">
<Button type="button" size="sm" variant="secondary" onClick={handleViewRaw}>
Expand Down
2 changes: 2 additions & 0 deletions client/src/features/settings/api/use-project-members.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ const MEMBER = {
id: "22222222-2222-2222-2222-222222222222",
projectId: PROJECT_ID,
userId: "33333333-3333-3333-3333-333333333333",
email: "member@example.com",
displayName: null,
role: "admin",
createdAt: new Date().toISOString(),
};
Expand Down
2 changes: 2 additions & 0 deletions client/src/features/settings/api/use-project-members.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export const projectMemberSchema = z.object({
id: z.string().uuid(),
projectId: z.string().uuid(),
userId: z.string().uuid(),
email: z.string().email(),
displayName: z.string().nullable(),
role: z.enum(["owner", "admin", "member", "viewer"]),
createdAt: z.coerce.date(),
});
Expand Down
22 changes: 22 additions & 0 deletions client/src/features/settings/components/MembersPanel.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ function makeMember(overrides: Partial<ProjectMember> = {}): ProjectMember {
id: "22222222-2222-2222-2222-222222222222",
projectId: PROJECT_ID,
userId: "33333333-3333-3333-3333-333333333333",
email: "member@example.com",
displayName: null,
role: "admin",
createdAt: new Date(),
...overrides,
Expand Down Expand Up @@ -80,6 +82,26 @@ describe("MembersPanel", () => {
expect(screen.getByText("admin")).toBeInTheDocument();
});

it("shows a member's identifying email/display name instead of the raw userId (BUG #5)", () => {
vi.mocked(useProjectMembers).mockReturnValue(
queryResult({ data: [makeMember({ email: "ana@example.com", displayName: "Ana" })] }),
);
vi.mocked(useAddOrAssignMember).mockReturnValue(mutationResult({}));
render(<MembersPanel projectId={PROJECT_ID} />);
expect(screen.getByText("Ana")).toBeInTheDocument();
expect(screen.getByText("ana@example.com")).toBeInTheDocument();
expect(screen.queryByText("33333333-3333-3333-3333-333333333333")).not.toBeInTheDocument();
});

it("falls back to the email when a member has no display name (BUG #5)", () => {
vi.mocked(useProjectMembers).mockReturnValue(
queryResult({ data: [makeMember({ email: "no-name@example.com", displayName: null })] }),
);
vi.mocked(useAddOrAssignMember).mockReturnValue(mutationResult({}));
render(<MembersPanel projectId={PROJECT_ID} />);
expect(screen.getByText("no-name@example.com")).toBeInTheDocument();
});

it("opens the add/reassign dialog and submits an email + role", async () => {
const user = userEvent.setup();
const mutate = vi.fn();
Expand Down
7 changes: 6 additions & 1 deletion client/src/features/settings/components/MembersPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,12 @@ export function MembersPanel({ projectId }: Props) {
function MemberRow({ member }: { member: ProjectMember }) {
return (
<li className="flex items-center justify-between gap-4 rounded-[var(--radius-md)] border border-[var(--color-border)] px-4 py-3">
<span className="font-mono text-xs text-[var(--color-foreground-muted)]">{member.userId}</span>
<div className="flex flex-col">
<span className="text-sm">{member.displayName ?? member.email}</span>
{member.displayName ? (
<span className="font-mono text-xs text-[var(--color-foreground-muted)]">{member.email}</span>
) : null}
</div>
<Badge tone="neutral">{member.role}</Badge>
</li>
);
Expand Down
Loading
Loading