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
64 changes: 46 additions & 18 deletions src/api/identity-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ beforeEach(() => {
});

describe("getPerson", () => {
it("POSTs /profiles with an {email} body and maps the profile", async () => {
it("POSTs /profiles with a person_id body and maps the profile", async () => {
mockFetch.mockResolvedValueOnce(
response({
person_id: "p-1",
person_id: "019e27bc-dec0-7626-81a9-c5524662a6a9",
insight_tenant_id: "t-1",
email: "bob.park@example.com",
display_name: "Bob Park",
Expand All @@ -33,17 +33,17 @@ describe("getPerson", () => {
}),
);

const person = await getPerson("bob.park@example.com");
const person = await getPerson("019e27bc-dec0-7626-81a9-c5524662a6a9");

const [url, init] = mockFetch.mock.calls[0];
expect(url).toBe("/api/identity/v1/profiles");
expect(init).toMatchObject({ method: "POST" });
expect(JSON.parse((init as RequestInit).body as string)).toEqual({
value_type: "email",
value: "bob.park@example.com",
value_type: "person_id",
value: "019e27bc-dec0-7626-81a9-c5524662a6a9",
});

expect(person.person_id).toBe("p-1");
expect(person.person_id).toBe("019e27bc-dec0-7626-81a9-c5524662a6a9");
expect(person.email).toBe("bob.park@example.com");
expect(person.job_title).toBe("Lead");
expect(person.supervisor_email).toBe("ceo@example.com");
Expand All @@ -53,24 +53,49 @@ describe("getPerson", () => {
expect(person.parent_email).toBeNull();
});

it("maps subordinates recursively and drops any without an email", async () => {
it("keeps subordinates without an email — person_id is the key now", async () => {
mockFetch.mockResolvedValueOnce(
response({
person_id: "p-lead",
person_id: "019e27bc-dec0-7626-81a9-c5524662a6aa",
insight_tenant_id: "t-1",
email: "lead@example.com",
subordinates: [
{ person_id: "p-2", insight_tenant_id: "t-1", email: "ic1@example.com" },
// no email -> dropped (would be a broken link + duplicate "" key)
{ person_id: "p-3", insight_tenant_id: "t-1" },
{ person_id: "p-4", insight_tenant_id: "t-1", email: " " },
{ person_id: "019e27bc-dec0-7626-81a9-c5524662a6ab", insight_tenant_id: "t-1", email: "ic1@example.com" },
// No email is legitimate: identity serves persons whose log carries
// none, and links/keys read person_id.
{ person_id: "019e27bc-dec0-7626-81a9-c5524662a6a9", insight_tenant_id: "t-1" },
],
}),
);

const person = await getPerson("lead@example.com");
const person = await getPerson("019e27bc-dec0-7626-81a9-c5524662a6aa");

expect(person.subordinates.map((s) => s.email)).toEqual(["ic1@example.com"]);
expect(person.subordinates.map((s) => s.person_id)).toEqual([
"019e27bc-dec0-7626-81a9-c5524662a6ab",
"019e27bc-dec0-7626-81a9-c5524662a6a9",
]);
expect(person.subordinates.map((s) => s.email)).toEqual([
"ic1@example.com",
"",
]);
});

it("drops a subordinate without a person_id — a keyless node breaks links and React keys", async () => {
mockFetch.mockResolvedValueOnce(
response({
person_id: "019e27bc-dec0-7626-81a9-c5524662a6aa",
insight_tenant_id: "t-1",
subordinates: [
{ person_id: "019e27bc-dec0-7626-81a9-c5524662a6ab", insight_tenant_id: "t-1" },
{ insight_tenant_id: "t-1", email: "keyless@example.com" },
{ person_id: " ", insight_tenant_id: "t-1" },
],
} as never),
);

const person = await getPerson("019e27bc-dec0-7626-81a9-c5524662a6aa");

expect(person.subordinates.map((s) => s.person_id)).toEqual(["019e27bc-dec0-7626-81a9-c5524662a6ab"]);
});

it("throws IdentityApiError with the status + body on a non-ok response", async () => {
Expand Down Expand Up @@ -100,13 +125,16 @@ describe("getPerson", () => {
});
});

it("rejects a profile missing the required email", async () => {
it("rejects a profile missing the required person_id", async () => {
mockFetch.mockResolvedValueOnce(
response({ person_id: "p-1", insight_tenant_id: "t-1" }),
response({ insight_tenant_id: "t-1", email: "bob@example.com" } as never),
);

const err = await getPerson("bob@example.com").catch((e: unknown) => e);
const err = await getPerson("019e27bc-dec0-7626-81a9-c5524662a6a9").catch((e: unknown) => e);
expect(err).toBeInstanceOf(IdentityApiError);
expect((err as IdentityApiError).body).toEqual({ error: "missing_email" });
expect((err as IdentityApiError).body).toEqual({
error: "missing_person_id",
});
});

});
48 changes: 35 additions & 13 deletions src/api/identity-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
*/

import { fetchWithAuth } from "@/api/fetch-with-auth";
import { normalizePersonId } from "@/lib/metrics/entity";
import type { IdentityPerson } from "@/types/insight";

const BASE =
Expand Down Expand Up @@ -54,12 +55,13 @@ export class IdentityApiError extends Error {
}

/**
* Normalize a `ProfileResponse` into the FE `IdentityPerson`. `email` is the UI
* identity (org-tree sidebar links + React keys), so the top-level profile is
* guaranteed to carry one by `getPerson`; subordinates the wire returns without
* an email are dropped rather than projected to `""` — an empty email would make
* broken sidebar links and collide as duplicate React keys across siblings. Other
* optional strings default to `""`; omitted parent/supervisor fields stay `null`.
* Normalize a `ProfileResponse` into the FE `IdentityPerson`. `person_id` is the
* UI identity (route links + React keys), so the top-level profile is guaranteed
* to carry one by `getPerson`; subordinates the wire returns without one are
* dropped rather than projected to `""` — a keyless node would make broken links
* and collide as duplicate React keys across siblings. `email` is display-only
* now and may legitimately be absent. Other optional strings default to `""`;
* omitted parent/supervisor fields stay `null`.
*/
function toIdentityPerson(p: ProfileResponse): IdentityPerson {
return {
Expand All @@ -79,17 +81,35 @@ function toIdentityPerson(p: ProfileResponse): IdentityPerson {
supervisor_email: p.supervisor_email ?? null,
supervisor_name: p.supervisor_name ?? null,
subordinates: (p.subordinates ?? [])
.filter((s) => Boolean(s.email?.trim()))
.filter((s) => Boolean(s.person_id?.trim()))
.map(toIdentityPerson),
};
}

export async function getPerson(email: string): Promise<IdentityPerson> {
/**
* Resolve one profile by canonical person id — the key the SPA routes on and
* the metrics API filters by since the identity cutover. Identity applies the
* caller's visible set here, so a person's name and their metrics answer to
* one permission: an id outside it is a 404, not a nameless dashboard.
*/
export async function getPerson(personId: string): Promise<IdentityPerson> {
// Normalized on the way out, matching the query key: one spelling of an id
// must not become two requests, or two cache entries for one person.
return resolveProfile({
value_type: "person_id",
value: normalizePersonId(personId),
});
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

async function resolveProfile(body: {
value_type: "person_id";
value: string;
}): Promise<IdentityPerson> {
const url = `${BASE}/profiles`;
const res = await fetchWithAuth(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ value_type: "email", value: email }),
body: JSON.stringify(body),
});
if (!res.ok) {
const body = await res.json().catch(() => null);
Expand All @@ -101,10 +121,12 @@ export async function getPerson(email: string): Promise<IdentityPerson> {
} catch {
throw new IdentityApiError(res.status, { error: "invalid_json" });
}
// `email` is the queried identity + the UI's key; a profile without it is
// unusable, so surface it rather than projecting an empty-string person.
if (!profile.email?.trim()) {
throw new IdentityApiError(res.status, { error: "missing_email" });
// `person_id` is the queried identity + the UI's key; a profile without it
// is unusable, so surface it rather than projecting a keyless person. The
// email is NOT required — identity resolves persons whose observation log
// carries no current email, and nothing keys on it any more.
if (!profile.person_id?.trim()) {
throw new IdentityApiError(res.status, { error: "missing_person_id" });
}
return toIdentityPerson(profile);
}
6 changes: 5 additions & 1 deletion src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,9 @@ export { consumeOverrideParam } from "./override";
export { loadSession } from "./session";
export { startSessionRefresh } from "./refresh";
export { useAuth, signIn, signOut } from "./use-auth";
export { getViewerEmail, useViewer, type Viewer } from "./use-viewer";
export {
getViewerPersonId,
useViewer,
type Viewer,
} from "./use-viewer";
export type { AuthSnapshot, AuthStatus, Session } from "./types";
12 changes: 6 additions & 6 deletions src/auth/use-viewer.test.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import { afterEach, describe, expect, it } from "vitest";

import { authStore } from "./auth-store";
import { getViewerEmail } from "./use-viewer";
import { getViewerPersonId } from "./use-viewer";
import { makeSession } from "@/test/session";

afterEach(() => {
authStore.reset();
});

describe("getViewerEmail", () => {
it("returns the session email when authenticated", () => {
authStore.setAuthenticated(makeSession({ email: "bob@example.com", tenantId: "", roles: [] }));
describe("getViewerPersonId", () => {
it("returns the session person id when authenticated", () => {
authStore.setAuthenticated(makeSession({ personId: "p-1", tenantId: "", roles: [] }));

expect(getViewerEmail()).toBe("bob@example.com");
expect(getViewerPersonId()).toBe("p-1");
});

it("returns null when there is no session", () => {
authStore.setUnauthenticated();

expect(getViewerEmail()).toBeNull();
expect(getViewerPersonId()).toBeNull();
});
});
12 changes: 7 additions & 5 deletions src/auth/use-viewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { useSyncExternalStore } from "react";
import { authStore } from "./auth-store";

/**
* The current viewer, derived from the session summary (`/auth/me`). The SPA is
* email-keyed (org tree, IC routes), so `email` is the primary handle;
* `personId` (the gateway JWT `sub`) is exposed for callers that need the UUID.
* The current viewer, derived from the session summary (`/auth/me`).
* `personId` (the gateway JWT `sub`) is the SPA's person key since the identity
* cutover — routes, metric requests and profile lookups all use it. `email`
* stays for display and for the email-shaped protocols (`__override`).
*/
export type Viewer = {
email: string | null;
Expand All @@ -29,6 +30,7 @@ export function useViewer(): Viewer {
return resolve();
}

export function getViewerEmail(): string | null {
return resolve().email;

export function getViewerPersonId(): string | null {
return resolve().personId;
}
48 changes: 35 additions & 13 deletions src/components/app-sidebar.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { IdentityPerson } from "@/types/insight";

let currentPath = "/";
let viewerEmail: string | null = "alice@x.io";
let viewerPersonId: string | null = null;
let viewerData: IdentityPerson | undefined;

vi.mock("@tanstack/react-router", () => ({
Expand All @@ -31,7 +32,7 @@ vi.mock("@tanstack/react-router", () => ({
}));

vi.mock("@/auth", () => ({
useViewer: () => ({ email: viewerEmail }),
useViewer: () => ({ email: viewerEmail, personId: viewerPersonId }),
}));

vi.mock("@/queries/ic-dashboard", () => ({
Expand Down Expand Up @@ -89,23 +90,33 @@ vi.mock("@/components/ui/sidebar", () => {

import { AppSidebar } from "./app-sidebar";

const PERSON_IDS = {
alice: "019e2800-0000-7000-8000-00000000a11c",
bob: "019e2800-0000-7000-8000-00000000b0b0",
carol: "019e2800-0000-7000-8000-00000000ca01",
erin: "019e2800-0000-7000-8000-00000000e21e",
} as const;

function person(
personId: string,
email: string,
name: string,
subordinates: IdentityPerson[] = []
): IdentityPerson {
return {
person_id: email,
person_id: personId,
email,
display_name: name,
subordinates,
} as IdentityPerson;
}

// Alice manages Bob (who manages Carol) and Erin.
const tree = person("alice@x.io", "Alice", [
person("bob@x.io", "Bob", [person("carol@x.io", "Carol")]),
person("erin@x.io", "Erin"),
const tree = person(PERSON_IDS.alice, "alice@x.io", "Alice", [
person(PERSON_IDS.bob, "bob@x.io", "Bob", [
person(PERSON_IDS.carol, "carol@x.io", "Carol"),
]),
person(PERSON_IDS.erin, "erin@x.io", "Erin"),
]);

// Scoped to the tree area: the footer repeats the viewer's name/email.
Expand All @@ -118,6 +129,7 @@ function buttonFor(label: string): HTMLElement | null {
beforeEach(() => {
currentPath = "/";
viewerEmail = "alice@x.io";
viewerPersonId = PERSON_IDS.alice;
viewerData = tree;
});

Expand All @@ -134,7 +146,7 @@ describe("AppSidebar", () => {
});

it("activates the person from an /ic/ path and opens their subtree", () => {
currentPath = "/ic/bob%40x.io/personal";
currentPath = `/ic/${PERSON_IDS.bob}/personal`;
render(<AppSidebar />);

expect(buttonFor("Bob")).toHaveAttribute("data-active", "true");
Expand All @@ -144,7 +156,7 @@ describe("AppSidebar", () => {
});

it("keeps ancestor chains open when a deep descendant is active", () => {
currentPath = "/ic/carol%40x.io/personal";
currentPath = `/ic/${PERSON_IDS.carol}/personal`;
render(<AppSidebar />);

expect(buttonFor("Carol")).toHaveAttribute("data-active", "true");
Expand All @@ -154,6 +166,7 @@ describe("AppSidebar", () => {
it("renders no tree while the viewer query has no data and no footer user without an email", () => {
viewerData = undefined;
viewerEmail = null;
viewerPersonId = null;
render(<AppSidebar />);

expect(screen.queryByText("Alice")).not.toBeInTheDocument();
Expand All @@ -180,18 +193,18 @@ describe("AppSidebar", () => {
});

it("links every person node to their personal dashboard", () => {
currentPath = "/ic/carol%40x.io/personal";
currentPath = `/ic/${PERSON_IDS.carol}/personal`;
render(<AppSidebar />);

const links = screen.getAllByTestId("link");
const personLinks = links.filter(
(link) => link.dataset.to === "/ic/$person/personal"
);
expect(personLinks.map((link) => link.dataset.person)).toEqual([
"alice@x.io",
"bob@x.io",
"carol@x.io",
"erin@x.io",
PERSON_IDS.alice,
PERSON_IDS.bob,
PERSON_IDS.carol,
PERSON_IDS.erin,
]);
});

Expand All @@ -208,12 +221,21 @@ describe("AppSidebar", () => {
});

it("falls back to the email as the node label when display_name is empty", () => {
viewerData = person("alice@x.io", "");
viewerData = person(PERSON_IDS.alice, "alice@x.io", "");
render(<AppSidebar />);

expect(buttonFor("alice@x.io")).toBeInTheDocument();
});

it("labels a person with neither name nor email so the node stays readable", () => {
// The identity contract admits both being absent; an empty node would be an
// unclickable sliver.
viewerData = person(PERSON_IDS.alice, "", "");
render(<AppSidebar />);

expect(buttonFor("Unnamed person")).toBeInTheDocument();
});

it("shows the metric catalog entry, active on its route", () => {
currentPath = "/metrics";
render(<AppSidebar />);
Expand Down
Loading