diff --git a/client/src/features/auth/auth.api.test.tsx b/client/src/features/auth/auth.api.test.tsx new file mode 100644 index 0000000..e0f703d --- /dev/null +++ b/client/src/features/auth/auth.api.test.tsx @@ -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 }) => {children}, + }); +} + +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(); + }); +}); diff --git a/client/src/features/auth/auth.api.ts b/client/src/features/auth/auth.api.ts index 45f08f6..6ee0547 100644 --- a/client/src/features/auth/auth.api.ts +++ b/client/src/features/auth/auth.api.ts @@ -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"; @@ -55,6 +55,7 @@ export function useRegister() { } export function useLogout() { + const queryClient = useQueryClient(); return useMutation({ mutationFn: async () => { const accessToken = useAuthStore.getState().accessToken; @@ -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(); }, }); } diff --git a/client/src/features/auth/use-bootstrap-session.test.ts b/client/src/features/auth/use-bootstrap-session.test.ts index c2855b2..8ee3940 100644 --- a/client/src/features/auth/use-bootstrap-session.test.ts +++ b/client/src/features/auth/use-bootstrap-session.test.ts @@ -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(); }); @@ -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()); @@ -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()); diff --git a/client/src/features/auth/use-bootstrap-session.ts b/client/src/features/auth/use-bootstrap-session.ts index 7202519..544aa2e 100644 --- a/client/src/features/auth/use-bootstrap-session.ts +++ b/client/src/features/auth/use-bootstrap-session.ts @@ -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"; /** @@ -19,7 +18,15 @@ 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; } @@ -27,17 +34,15 @@ export function useBootstrapSession(): { isReady: boolean } { async function bootstrap(): Promise { 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("/auth/me"); if (cancelled) return; - useAuthStore.getState().setSession({ accessToken: envelope.data.accessToken, user }); + useAuthStore.getState().setSession({ accessToken, user }); setBootstrapped(true); } catch { if (cancelled) return; @@ -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 }; } diff --git a/client/src/features/runs/components/RunDetail.test.tsx b/client/src/features/runs/components/RunDetail.test.tsx index 0826b46..9652e82 100644 --- a/client/src/features/runs/components/RunDetail.test.tsx +++ b/client/src/features/runs/components/RunDetail.test.tsx @@ -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(); + + 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(); + + 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(); + + 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 }); diff --git a/client/src/features/runs/components/RunDetail.tsx b/client/src/features/runs/components/RunDetail.tsx index 55e5468..0780c51 100644 --- a/client/src/features/runs/components/RunDetail.tsx +++ b/client/src/features/runs/components/RunDetail.tsx @@ -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"; @@ -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 ``) 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); @@ -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 (
@@ -63,6 +77,15 @@ export function RunDetail({ projectId, runId }: Props) {
Queued
{run.queuedAt.toLocaleString()}
+ {runError ? ( +
+

{runError.code ?? "Run failed"}

+

{runError.message}

+
+ ) : null} {canViewRaw ? (
{projects && projects.length > 0 ? (
diff --git a/client/src/features/workspace/graph/WorkspaceGraphView.tsx b/client/src/features/workspace/graph/WorkspaceGraphView.tsx index 8b39fdb..333a099 100644 --- a/client/src/features/workspace/graph/WorkspaceGraphView.tsx +++ b/client/src/features/workspace/graph/WorkspaceGraphView.tsx @@ -57,7 +57,17 @@ export function WorkspaceGraphView({ projectId }: Props) {

{project.data?.name}

- + {/* + * `h-full` on GraphEngine's own wrapper can resolve to 0 here: this ancestor's height + * comes purely from flex-grow (no explicit CSS height anywhere in the chain up to + * WorkspaceShell's `min-h-screen`), and percentage heights are unreliable against that. + * `absolute inset-0` sizes against the actual laid-out box of this `relative` parent + * instead, which is the same trick used to make anything fill a flex-grown container + * reliably (BUG #7 -- the graph silently failed to render for any project with data). + */} +
+ +
); diff --git a/client/src/lib/api-client.test.ts b/client/src/lib/api-client.test.ts index 1247ba7..37ca53e 100644 --- a/client/src/lib/api-client.test.ts +++ b/client/src/lib/api-client.test.ts @@ -68,6 +68,39 @@ describe("apiRequest", () => { expect(fetch).toHaveBeenCalledTimes(3); }); + it("coalesces concurrent 401s into a single refresh call (BUG #1 regression)", async () => { + // Two requests expire at once (e.g. two parallel queries after the access token TTL elapses). + // Each hits a 401 independently; without de-duplication, both would call /api/auth/refresh + // with the same pre-rotation cookie, and the backend's single-use rotation would treat the + // second call as a replay -- revoking the whole session chain and logging the user out. + useAuthStore.getState().setSession({ accessToken: "stale-token", user: { id: "u1", email: "a@b.com", displayName: null } }); + vi.mocked(fetch).mockImplementation((input) => { + const url = typeof input === "string" ? input : (input as Request).url; + if (url.includes("/api/auth/refresh")) { + return Promise.resolve(jsonResponse(200, { success: true, data: { accessToken: "fresh-token" } })); + } + if (url.includes("/projects/a") || url.includes("/projects/b")) { + const alreadyRefreshed = useAuthStore.getState().accessToken === "fresh-token"; + return Promise.resolve( + alreadyRefreshed + ? jsonResponse(200, { success: true, data: { ok: true } }) + : jsonResponse(401, { success: false, error: { message: "Unauthorized", code: "UNAUTHORIZED", correlationId: "c" } }), + ); + } + throw new Error(`Unexpected fetch to ${url}`); + }); + + const [resultA, resultB] = await Promise.all([apiRequest("/projects/a"), apiRequest("/projects/b")]); + + expect(resultA).toEqual({ ok: true }); + expect(resultB).toEqual({ ok: true }); + const refreshCalls = vi.mocked(fetch).mock.calls.filter(([input]) => { + const url = typeof input === "string" ? input : (input as Request).url; + return url.includes("/api/auth/refresh"); + }); + expect(refreshCalls).toHaveLength(1); + }); + it("clears the session when the refresh itself fails", async () => { useAuthStore.getState().setSession({ accessToken: "stale-token", user: { id: "u1", email: "a@b.com", displayName: null } }); vi.mocked(fetch) diff --git a/client/src/lib/api-client.ts b/client/src/lib/api-client.ts index d468871..0b74063 100644 --- a/client/src/lib/api-client.ts +++ b/client/src/lib/api-client.ts @@ -37,21 +37,40 @@ async function rawRequest(path: string, options: RequestOptions): Promise<{ s return { status: response.status, envelope }; } +// Coalesces concurrent refresh attempts into a single in-flight request. The refresh token is +// single-use and rotates server-side (SEC-004); if multiple 401s fired one refresh call each, +// every call after the first would replay an already-rotated token, tripping reuse-detection +// and revoking the whole session chain -- including the just-issued one -- and spuriously +// logging out a legitimately-authenticated user (BUG #1). +let inFlightRefresh: Promise | null = null; + /** * Refreshes the access token once via the BFF route (never the backend directly -- only the * route handler can read the httpOnly refresh cookie, SEC-035). Returns the new token, or null - * if the refresh itself failed (session is gone; caller must sign the user out). + * if the refresh itself failed (session is gone; caller must sign the user out). Safe to call + * concurrently -- overlapping callers share the same underlying request. Exported so every call + * site (the 401-retry path here and `useBootstrapSession`'s hard-reload bootstrap) shares this + * one de-duped implementation rather than each racing its own raw `fetch` (BUG #2, same root + * cause as BUG #1 -- React Strict Mode's double-effect-invoke on mount was enough to trigger it). */ -async function refreshAccessToken(): Promise { - try { - const response = await fetch("/api/auth/refresh", { method: "POST", credentials: "include" }); - const envelope = (await response.json()) as ApiEnvelope<{ accessToken: string }>; - if (!envelope.success) return null; - useAuthStore.getState().setAccessToken(envelope.data.accessToken); - return envelope.data.accessToken; - } catch { - return null; - } +export async function refreshAccessToken(): Promise { + if (inFlightRefresh) return inFlightRefresh; + + inFlightRefresh = (async () => { + try { + const response = await fetch("/api/auth/refresh", { method: "POST", credentials: "include" }); + const envelope = (await response.json()) as ApiEnvelope<{ accessToken: string }>; + if (!envelope.success) return null; + useAuthStore.getState().setAccessToken(envelope.data.accessToken); + return envelope.data.accessToken; + } catch { + return null; + } finally { + inFlightRefresh = null; + } + })(); + + return inFlightRefresh; } /** diff --git a/client/src/modules/graph-engine/store/graphStore.test.ts b/client/src/modules/graph-engine/store/graphStore.test.ts new file mode 100644 index 0000000..39d0c16 --- /dev/null +++ b/client/src/modules/graph-engine/store/graphStore.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vitest"; +import { createGraphStore } from "./graphStore"; +import type { NodeModel } from "../types/node.types"; +import type { EdgeModel } from "../types/edge.types"; + +const nodeA: NodeModel = { id: "a", type: "asset", data: { label: "a" } }; +const nodeB: NodeModel = { id: "b", type: "finding", data: { label: "b" } }; +const edgeAB: EdgeModel = { id: "e1", source: "a", target: "b", type: "discovery" }; + +describe("graphStore setGraphData", () => { + it("reveals nodes/edges immediately when not mid-timeline (BUG #3 regression)", () => { + // Interactive consumers (Workspace graph, Report builder's node picker) never play a + // timeline script -- `useGraphTimeline` flips status to 'interactive' before this ever runs. + // Without the fix, setGraphData always reset visibility to empty and nothing repopulated it, + // so real graph data silently never rendered. + const store = createGraphStore(); + store.getState().setStatus("interactive"); + + store.getState().setGraphData([nodeA, nodeB], [edgeAB], null); + + const state = store.getState(); + expect(state.visibleNodeIds).toEqual(new Set(["a", "b"])); + expect(state.visibleEdgeIds).toEqual(new Set(["e1"])); + }); + + it("reveals nodes/edges immediately in the default idle status", () => { + const store = createGraphStore(); + + store.getState().setGraphData([nodeA], [], null); + + expect(store.getState().visibleNodeIds).toEqual(new Set(["a"])); + }); + + it("keeps visibility empty while a scripted timeline is playing", () => { + // Preserves the Hero's progressive-reveal animation: nodes only become visible as the + // timeline script explicitly calls revealNode/revealEdge. + const store = createGraphStore(); + store.getState().setStatus("playing"); + + store.getState().setGraphData([nodeA, nodeB], [edgeAB], null); + + const state = store.getState(); + expect(state.visibleNodeIds).toEqual(new Set()); + expect(state.visibleEdgeIds).toEqual(new Set()); + }); + + it("re-reveals newly loaded data (e.g. a refetch) once already interactive", () => { + const store = createGraphStore(); + store.getState().setStatus("interactive"); + store.getState().setGraphData([nodeA], [], null); + + store.getState().setGraphData([nodeA, nodeB], [edgeAB], null); + + expect(store.getState().visibleNodeIds).toEqual(new Set(["a", "b"])); + }); +}); diff --git a/client/src/modules/graph-engine/store/graphStore.ts b/client/src/modules/graph-engine/store/graphStore.ts index fda616f..dee03d9 100644 --- a/client/src/modules/graph-engine/store/graphStore.ts +++ b/client/src/modules/graph-engine/store/graphStore.ts @@ -80,8 +80,24 @@ export function createGraphStore() { rootNodeId: null, visibleNodeIds: new Set(), visibleEdgeIds: new Set(), + // Interactive consumers (no timeline script, e.g. the Workspace graph and the Report + // builder's node picker) reveal everything up front -- `useGraphTimeline` flips `status` to + // 'interactive' synchronously on mount before this ever runs (child effects fire before the + // parent `GraphProvider` effect that calls this), so gating on `status` here means real graph + // data actually renders instead of staying hidden behind an empty visibility set that nothing + // else would ever repopulate (BUG #3). A scripted Hero timeline is still mid-'playing' at this + // point and keeps its empty-then-progressively-revealed behavior untouched. setGraphData: (nodes, edges, rootNodeId) => - set({ nodes, edges, rootNodeId: rootNodeId ?? null, visibleNodeIds: new Set(), visibleEdgeIds: new Set() }), + set((state) => { + const revealImmediately = state.status !== 'playing' + return { + nodes, + edges, + rootNodeId: rootNodeId ?? null, + visibleNodeIds: revealImmediately ? new Set(nodes.map((n) => n.id)) : new Set(), + visibleEdgeIds: revealImmediately ? new Set(edges.map((e) => e.id)) : new Set(), + } + }), revealNode: (nodeId) => set((state) => ({ visibleNodeIds: new Set(state.visibleNodeIds).add(nodeId) })), revealEdge: (edgeId) => set((state) => ({ visibleEdgeIds: new Set(state.visibleEdgeIds).add(edgeId) })), revealAll: () => diff --git a/server/src/core/database/pg-error.ts b/server/src/core/database/pg-error.ts index 10681d2..6c7839a 100644 --- a/server/src/core/database/pg-error.ts +++ b/server/src/core/database/pg-error.ts @@ -1,15 +1,39 @@ /** Postgres error code for a unique-constraint violation (23505). */ const UNIQUE_VIOLATION_CODE = "23505"; +/** Bounds how far up an `error.cause` chain we'll look before giving up (BUG #4). */ +const MAX_CAUSE_DEPTH = 5; + +function getPgErrorCode(error: unknown): unknown { + return typeof error === "object" && error !== null && "code" in error + ? (error as { code?: unknown }).code + : undefined; +} + +function getCause(error: unknown): unknown { + return typeof error === "object" && error !== null && "cause" in error + ? (error as { cause?: unknown }).cause + : undefined; +} + /** * Narrows an unknown thrown value to a node-postgres error carrying a `code`, without pulling * in the `pg` package types here (repositories only depend on Drizzle's `Database` type). + * + * Drizzle wraps the real driver error in a `DrizzleQueryError` whose own `code` is undefined -- + * the actual pg error (and its `23505` code) lives on `.cause` instead. Checking only the + * top-level `code` silently missed every real unique-violation raised through a Drizzle query, + * letting it escape as an unhandled 500 instead of the intended `ConflictError` (BUG #4). Walk + * the `cause` chain so this works whether the code sits on the error itself or is nested behind + * one (or more) wrapping layers. */ export function isUniqueViolation(error: unknown): boolean { - return ( - typeof error === "object" && - error !== null && - "code" in error && - (error as { code?: unknown }).code === UNIQUE_VIOLATION_CODE - ); + let current = error; + for (let depth = 0; depth < MAX_CAUSE_DEPTH && current; depth += 1) { + if (getPgErrorCode(current) === UNIQUE_VIOLATION_CODE) { + return true; + } + current = getCause(current); + } + return false; } diff --git a/server/src/modules/projects/mappers/project.mapper.ts b/server/src/modules/projects/mappers/project.mapper.ts index 67fb97f..f4a03be 100644 --- a/server/src/modules/projects/mappers/project.mapper.ts +++ b/server/src/modules/projects/mappers/project.mapper.ts @@ -1,5 +1,5 @@ import type { ProjectRow } from "../repositories/projects.repository"; -import type { ProjectMemberRow } from "../repositories/project-members.repository"; +import type { ProjectMemberWithUserRow } from "../repositories/project-members.repository"; export interface ProjectDto { id: string; @@ -14,7 +14,9 @@ export interface ProjectMemberDto { id: string; projectId: string; userId: string; - role: ProjectMemberRow["role"]; + email: string; + displayName: string | null; + role: ProjectMemberWithUserRow["role"]; createdAt: Date; } @@ -30,11 +32,13 @@ export function toProjectDto(row: ProjectRow): ProjectDto { }; } -export function toProjectMemberDto(row: ProjectMemberRow): ProjectMemberDto { +export function toProjectMemberDto(row: ProjectMemberWithUserRow): ProjectMemberDto { return { id: row.id, projectId: row.projectId, userId: row.userId, + email: row.email, + displayName: row.displayName, role: row.role, createdAt: row.createdAt, }; diff --git a/server/src/modules/projects/projects.service.ts b/server/src/modules/projects/projects.service.ts index bbe4c4f..605edb4 100644 --- a/server/src/modules/projects/projects.service.ts +++ b/server/src/modules/projects/projects.service.ts @@ -103,7 +103,9 @@ export class ProjectsService { if (!result) { throw new NotFoundError("Project membership not found"); } - return toProjectMemberDto(result); + // addMember/updateRole only touch project_members, so they can't return the joined user + // fields listMembers does -- attach them from targetUser, already fetched above (BUG #5). + return toProjectMemberDto({ ...result, email: targetUser.email, displayName: targetUser.displayName }); } async removeMember(actingUserId: string, projectId: string, targetUserId: string): Promise { diff --git a/server/src/modules/projects/repositories/project-members.repository.ts b/server/src/modules/projects/repositories/project-members.repository.ts index a896979..88c418e 100644 --- a/server/src/modules/projects/repositories/project-members.repository.ts +++ b/server/src/modules/projects/repositories/project-members.repository.ts @@ -1,7 +1,7 @@ import { and, eq, sql } from "drizzle-orm"; import type { Database } from "../../../core/database/client"; import { isUniqueViolation } from "../../../core/database/pg-error"; -import { projectMembers } from "../../../core/database/schema"; +import { projectMembers, users } from "../../../core/database/schema"; import { ConflictError } from "../../../core/http/domain-error"; import { extractTotal, @@ -21,6 +21,17 @@ export interface ProjectMemberRow { createdAt: Date; } +/** + * A member row joined with the identifying fields off `users` -- everything the UI needs to show + * *who* a member actually is instead of a bare `userId` (BUG #5). `addMember`/`updateRole` don't + * join (their `.returning()` only covers `project_members`); callers that already have the target + * `UserRow` in hand (e.g. `addOrAssignMember`, which looked it up by email) attach it themselves. + */ +export interface ProjectMemberWithUserRow extends ProjectMemberRow { + email: string; + displayName: string | null; +} + export interface ProjectMemberCreateInput { projectId: string; userId: string; @@ -34,7 +45,7 @@ export interface ProjectMemberCreateInput { export interface ProjectMembersRepository { addMember(input: ProjectMemberCreateInput): Promise; findByProjectAndUser(projectId: string, userId: string): Promise; - listByProject(projectId: string, pagination?: PaginationParams): Promise>; + listByProject(projectId: string, pagination?: PaginationParams): Promise>; updateRole(projectId: string, userId: string, role: ProjectRole): Promise; removeMember(projectId: string, userId: string): Promise; } @@ -66,16 +77,30 @@ export class DrizzleProjectMembersRepository implements ProjectMembersRepository return (row as ProjectMemberRow) ?? null; } - async listByProject(projectId: string, pagination?: PaginationParams): Promise> { + async listByProject(projectId: string, pagination?: PaginationParams): Promise> { const { page, pageSize, offset } = normalizePagination(pagination); const where = eq(projectMembers.projectId, projectId); - const [items, countRows] = await Promise.all([ - this.db.select().from(projectMembers).where(where).limit(pageSize).offset(offset), + const [rows, countRows] = await Promise.all([ + this.db + .select({ + id: projectMembers.id, + projectId: projectMembers.projectId, + userId: projectMembers.userId, + role: projectMembers.role, + createdAt: projectMembers.createdAt, + email: users.email, + displayName: users.displayName, + }) + .from(projectMembers) + .innerJoin(users, eq(projectMembers.userId, users.id)) + .where(where) + .limit(pageSize) + .offset(offset), this.db.select({ count: sql`count(*)::int` }).from(projectMembers).where(where), ]); - return { items: items as ProjectMemberRow[], page, pageSize, total: extractTotal(countRows) }; + return { items: rows as ProjectMemberWithUserRow[], page, pageSize, total: extractTotal(countRows) }; } async updateRole(projectId: string, userId: string, role: ProjectRole): Promise { diff --git a/server/tests/integration/project-members.repository.test.ts b/server/tests/integration/project-members.repository.test.ts index 05418e8..43a3ce9 100644 --- a/server/tests/integration/project-members.repository.test.ts +++ b/server/tests/integration/project-members.repository.test.ts @@ -40,7 +40,7 @@ describe("ProjectMembersRepository", () => { expect(await repo.findByProjectAndUser(project.id, user.id)).toMatchObject({ id: created.id }); }); - it("lists members for a project, paginated", async () => { + it("lists members for a project, paginated, joined with their identifying user fields (BUG #5)", async () => { const { project, user } = await createFixtures(); await repo.addMember({ projectId: project.id, userId: user.id, role: "owner" }); @@ -48,6 +48,7 @@ describe("ProjectMembersRepository", () => { expect(page.items).toHaveLength(1); expect(page.total).toBe(1); + expect(page.items[0]).toMatchObject({ userId: user.id, email: "owner@example.com", displayName: null }); }); it("updates a member's role", async () => { diff --git a/server/tests/unit/core/pg-error.test.ts b/server/tests/unit/core/pg-error.test.ts new file mode 100644 index 0000000..3ed91d0 --- /dev/null +++ b/server/tests/unit/core/pg-error.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vitest"; +import { isUniqueViolation } from "../../../src/core/database/pg-error"; + +describe("isUniqueViolation", () => { + it("recognizes a bare pg error with a top-level code (BUG #4 baseline case)", () => { + expect(isUniqueViolation({ code: "23505" })).toBe(true); + }); + + it("recognizes a Drizzle-wrapped error, where the real pg error is nested in `cause` (BUG #4 regression)", () => { + // Mirrors drizzle-orm's DrizzleQueryError: the top-level error has no `code` of its own, + // the real node-postgres error (with the actual 23505) is one level down in `.cause`. + const pgError = { code: "23505", message: "duplicate key value violates unique constraint" }; + const drizzleQueryError = new Error("Failed query: select * from create_project_with_owner(...)", { + cause: pgError, + }); + + expect(isUniqueViolation(drizzleQueryError)).toBe(true); + }); + + it("walks multiple levels of nested causes", () => { + const pgError = { code: "23505" }; + const wrapped = new Error("outer", { cause: new Error("inner", { cause: pgError }) }); + + expect(isUniqueViolation(wrapped)).toBe(true); + }); + + it("returns false for an unrelated error code", () => { + expect(isUniqueViolation({ code: "23503" })).toBe(false); + }); + + it("returns false for a wrapped error whose cause has an unrelated code", () => { + const wrapped = new Error("outer", { cause: { code: "23503" } }); + expect(isUniqueViolation(wrapped)).toBe(false); + }); + + it("returns false for non-object and nullish values", () => { + expect(isUniqueViolation(null)).toBe(false); + expect(isUniqueViolation(undefined)).toBe(false); + expect(isUniqueViolation("some string")).toBe(false); + expect(isUniqueViolation(new Error("plain error, no cause"))).toBe(false); + }); + + it("does not loop forever on a cause cycle", () => { + const a: { cause?: unknown } = {}; + const b: { cause?: unknown } = { cause: a }; + a.cause = b; + + expect(isUniqueViolation(a)).toBe(false); + }); +});