diff --git a/apps/frontend/AGENTS.md b/apps/frontend/AGENTS.md
index 82ee979c..35961658 100644
--- a/apps/frontend/AGENTS.md
+++ b/apps/frontend/AGENTS.md
@@ -58,7 +58,7 @@ Import direction is one-way and must stay that way: `api.ts` ← `authClient.ts`
**No Cognito SDK on the client.** The browser only ever talks to the backend's `/auth/*` routes; the auth lambda does the Cognito work.
-**Session.** Tokens (`branch_access_token` / `branch_id_token` / `branch_refresh_token`) live in localStorage, owned exclusively by `src/lib/authTokens.ts`. `grep -rn "branch_access_token" src/` must only ever match that file.
+**Session.** Tokens (`branch_access_token` / `branch_id_token` / `branch_refresh_token`) live in localStorage, and the staff impersonation session id (`branch_impersonation_session`) in sessionStorage, all owned exclusively by `src/lib/authTokens.ts`. `grep -rn "branch_access_token" src/` must only ever match that file.
**Identity comes from `GET /auth/me`, never from decoding a token.** `is_admin` lives only in Postgres and there is no pre-token-generation trigger, so it is not a JWT claim; a Cognito *access* token carries neither `email` nor `name` either. `AuthProvider` calls `/auth/me` on mount (skipping the call entirely when no tokens are stored) and exposes `user`, `isAuthenticated`, `isAdmin`, `isLoading`. Do not add a "fall back to decoding the ID token" path.
@@ -83,6 +83,8 @@ Both live in `src/app/components/Permission.tsx`. Record-scoped actions take a `
Tests: `test/rbac.ts` has `adminSubject` / `directorSubject` / `memberSubject` and a `session()` builder. The shared `render` from `test/utils.tsx` signs in as an admin by default — pass `{ subject }` to render as someone else, or `renderWithLiveAuth` for the handful of tests that exercise `AuthProvider` itself.
+**Staff impersonation.** A staff account (`rbac.isStaff`) lands on `/staff`, the staff console, which is the only page it can open as itself. `startImpersonation(userId, 'read_only' | 'full')` stores the server's session id in **sessionStorage** (`authTokens.ts`, so the switch-in is per tab) and `authedFetch` sends it as `X-Impersonate-Session` on every call. `/auth/me` then reports the *target*, so every page, permission and nav item is the target's with no further code. `ImpersonationBanner` (mounted in `providers.tsx`) shows who you are viewing as and exits via `stopImpersonation()`. Both calls clear the whole query cache, because every entry was fetched as the other identity; `logout()` now does too. When the server ends a session (`IMPERSONATION_EXPIRED`), `authedFetch` drops the id and retries a GET as the staff account, never a write. Console calls that must go out as staff pass `asSelf: true`. See `shared/rbac/README.md`.
+
**Challenges.** `login()` returns `{ status: 'authenticated' }` or `{ status: 'challenge', ... }`. `NEW_PASSWORD_REQUIRED` is handled by the login page; the other challenge names are plumbed through `respondToChallenge` and become reachable if MFA is switched on in `infrastructure/aws/cognito.tf`, needing only a UI step.
**No self-serve signup.** The backend still serves `/auth/register`, `/auth/verify-email` and `/auth/resend-code`, but the frontend deliberately does not expose them — see the comment in `AuthContext.tsx`. Onboarding is admin-invite.
diff --git a/apps/frontend/src/app/components/ImpersonationBanner.tsx b/apps/frontend/src/app/components/ImpersonationBanner.tsx
new file mode 100644
index 00000000..1801d02f
--- /dev/null
+++ b/apps/frontend/src/app/components/ImpersonationBanner.tsx
@@ -0,0 +1,57 @@
+'use client';
+
+import { useState } from 'react';
+import { useRouter } from 'next/navigation';
+import { useAuth } from '@/context/AuthContext';
+import { STAFF_CONSOLE_PATH } from '@/lib/routes';
+
+function timeOf(iso: string): string {
+ return new Date(iso).toLocaleTimeString([], {
+ hour: 'numeric',
+ minute: '2-digit',
+ });
+}
+
+export default function ImpersonationBanner() {
+ const { user, stopImpersonation } = useAuth();
+ const router = useRouter();
+ const [leaving, setLeaving] = useState(false);
+ const impersonation = user?.impersonation;
+ if (!user || !impersonation) return null;
+
+ const full = impersonation.mode === 'full';
+
+ const exit = async () => {
+ setLeaving(true);
+ try {
+ await stopImpersonation();
+ router.replace(STAFF_CONSOLE_PATH);
+ } finally {
+ setLeaving(false);
+ }
+ };
+
+ // `!` on padding and colours: Chakra's reset outranks unprefixed utilities.
+ return (
+
+ View as is read-only. Act as makes
+ real changes in that user's name. Every change is recorded
+ against your account. A switch-in lasts one hour.
+
+ {error && (
+
+ {error}
+
+ )}
+ t.userId}
+ isLoading={loading}
+ loadingLabel="Loading users"
+ emptyMessage={
+ search ? 'No users match that search.' : 'No users yet.'
+ }
+ />
+
+
+ setConfirmFull(null)}
+ onConfirm={() =>
+ confirmFull ? switchInto(confirmFull, 'full') : undefined
+ }
+ title="Act as this user with full access?"
+ itemName={
+ confirmFull ? `${confirmFull.name} (${confirmFull.email})` : undefined
+ }
+ consequences="Anything you create, edit, approve or delete is real and is saved as this user. Each change is also recorded against your staff account."
+ confirmLabel="Act as"
+ />
+
+ );
+}
diff --git a/apps/frontend/src/context/AuthContext.tsx b/apps/frontend/src/context/AuthContext.tsx
index d24ae702..18a48f49 100644
--- a/apps/frontend/src/context/AuthContext.tsx
+++ b/apps/frontend/src/context/AuthContext.tsx
@@ -14,16 +14,20 @@ import { AUTH_ME_KEY } from '@/lib/queries';
import {
authedFetch,
endSession,
+ onImpersonationEnded,
onSessionExpired,
refreshSession,
refreshSessionOutcome,
} from '@/lib/authClient';
import {
+ clearImpersonationSession,
clearTokens,
getAccessToken,
+ getImpersonationSession,
getRefreshToken,
getTokenExpMs,
saveTokens,
+ setImpersonationSession,
} from '@/lib/authTokens';
// ---------------------------------------------------------------------------
@@ -56,6 +60,19 @@ export interface AuthUser {
* into a signed-in session that is denied everything.
*/
rbac: RbacSubject;
+ isStaff?: boolean;
+ impersonation?: Impersonation | null;
+}
+
+export type ImpersonationMode = 'read_only' | 'full';
+
+export interface Impersonation {
+ userId: number;
+ name: string;
+ email: string;
+ sessionId: string;
+ mode: ImpersonationMode;
+ expiresAt: string;
}
export type ChallengeName =
@@ -100,6 +117,8 @@ interface AuthContextValue {
logout: () => Promise;
refresh: () => Promise;
reloadUser: () => Promise;
+ startImpersonation: (targetUserId: number, mode: ImpersonationMode) => Promise;
+ stopImpersonation: () => Promise;
forgotPassword: (email: string) => Promise;
resetPassword: (
email: string,
@@ -273,6 +292,16 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
[setUser],
);
+ useEffect(
+ () =>
+ onImpersonationEnded(() => {
+ fetchMe()
+ .then((me) => setUser(isValidUser(me) ? me : null))
+ .catch(() => endSession());
+ }),
+ [fetchMe, setUser],
+ );
+
// Proactive refresh, rescheduled from each new token's exp. Without this the
// session silently breaks after the access token's 1-hour lifetime.
useEffect(() => {
@@ -383,7 +412,41 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
[consumeAuthResponse],
);
+ const startImpersonation = useCallback(
+ async (targetUserId: number, mode: ImpersonationMode): Promise => {
+ const { sessionId } = await authedFetch<{ sessionId: string }>('/auth/impersonation', {
+ method: 'POST',
+ body: JSON.stringify({ targetUserId, mode }),
+ asSelf: true,
+ });
+ setImpersonationSession(sessionId);
+ try {
+ const me = await fetchMe();
+ if (!isValidUser(me)) throw new Error('Malformed /auth/me response');
+ setUser(me);
+ return me;
+ } catch (error) {
+ clearImpersonationSession();
+ throw error;
+ }
+ },
+ [fetchMe, setUser],
+ );
+
+ const stopImpersonation = useCallback(async () => {
+ const sessionId = getImpersonationSession();
+ if (!sessionId) return;
+ clearImpersonationSession();
+ await authedFetch(`/auth/impersonation/${encodeURIComponent(sessionId)}`, {
+ method: 'DELETE',
+ asSelf: true,
+ }).catch(() => undefined);
+ const me = await fetchMe();
+ setUser(isValidUser(me) ? me : null);
+ }, [fetchMe, setUser]);
+
const logout = useCallback(async () => {
+ await stopImpersonation().catch(() => undefined);
// retryOn401: false — refreshing a session we are discarding is pointless.
await authedFetch('/auth/logout', {
method: 'POST',
@@ -393,7 +456,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
});
endSession();
setUser(null);
- }, [setUser]);
+ }, [setUser, stopImpersonation]);
const reloadUser = useCallback(async () => {
try {
@@ -439,6 +502,8 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
logout,
refresh: refreshSession,
reloadUser,
+ startImpersonation,
+ stopImpersonation,
forgotPassword,
resetPassword,
}}
diff --git a/apps/frontend/src/lib/authClient.ts b/apps/frontend/src/lib/authClient.ts
index 3b589a2e..d2570422 100644
--- a/apps/frontend/src/lib/authClient.ts
+++ b/apps/frontend/src/lib/authClient.ts
@@ -1,7 +1,9 @@
import { ApiError, apiFetch } from './api';
import {
+ clearImpersonationSession,
clearTokens,
getAccessToken,
+ getImpersonationSession,
getRefreshToken,
isExpiredOrExpiring,
saveTokens,
@@ -47,6 +49,24 @@ export function endSession(): void {
}
}
+const impersonationListeners = new Set<() => void>();
+
+export function onImpersonationEnded(listener: () => void): () => void {
+ impersonationListeners.add(listener);
+ return () => impersonationListeners.delete(listener);
+}
+
+const IMPERSONATION_CODES = new Set([
+ 'IMPERSONATION_EXPIRED',
+ 'IMPERSONATION_FORBIDDEN',
+]);
+
+function isImpersonationFailure(error: unknown): boolean {
+ if (!(error instanceof ApiError)) return false;
+ const code = (error.body as { code?: unknown } | undefined)?.code;
+ return typeof code === 'string' && IMPERSONATION_CODES.has(code);
+}
+
/**
* `rejected`: the server refused the refresh token, so the session is over.
* `unavailable`: network failure, 5xx or 429; the refresh token may still be good.
@@ -119,6 +139,7 @@ async function refreshOrThrow(): Promise {
export interface AuthedRequestOptions extends RequestInit {
/** Set false to skip the refresh-and-retry dance (used when signing out). */
retryOn401?: boolean;
+ asSelf?: boolean;
}
/**
@@ -127,7 +148,30 @@ export interface AuthedRequestOptions extends RequestInit {
*/
export async function authedFetch(
path: string,
- { retryOn401 = true, ...options }: AuthedRequestOptions = {},
+ { asSelf = false, ...options }: AuthedRequestOptions = {},
+): Promise {
+ const sessionId = asSelf ? null : getImpersonationSession();
+ if (!sessionId) return sessionFetch(path, options);
+
+ try {
+ return await sessionFetch(path, {
+ ...options,
+ headers: { ...options.headers, 'X-Impersonate-Session': sessionId },
+ });
+ } catch (error) {
+ if (!isImpersonationFailure(error)) throw error;
+ // Reads retry as staff so bootstrap /auth/me lands on the console; a write is never re-sent as someone else.
+ clearImpersonationSession();
+ for (const listener of impersonationListeners) listener();
+ const method = (options.method ?? 'GET').toUpperCase();
+ if (method !== 'GET') throw error;
+ return sessionFetch(path, options);
+ }
+}
+
+async function sessionFetch(
+ path: string,
+ { retryOn401 = true, ...options }: Omit,
): Promise {
let token = getAccessToken();
@@ -146,7 +190,9 @@ export async function authedFetch(
return await apiFetch(path, { ...options, token: token ?? undefined });
} catch (error) {
const isUnauthorized = error instanceof ApiError && error.status === 401;
- if (!isUnauthorized || !retryOn401) throw error;
+ // An ended switch-in is a 401 too, but the token is fine: never refresh for it.
+ if (!isUnauthorized || !retryOn401 || isImpersonationFailure(error))
+ throw error;
await refreshOrThrow();
@@ -163,4 +209,5 @@ export async function authedFetch(
export function __resetRefreshStateForTests(): void {
refreshInFlight = null;
listeners.clear();
+ impersonationListeners.clear();
}
diff --git a/apps/frontend/src/lib/authTokens.ts b/apps/frontend/src/lib/authTokens.ts
index 40df2d8b..e7400276 100644
--- a/apps/frontend/src/lib/authTokens.ts
+++ b/apps/frontend/src/lib/authTokens.ts
@@ -70,6 +70,7 @@ export function saveTokens({
export function clearTokens(): void {
if (typeof window === 'undefined') return;
+ clearImpersonationSession();
try {
window.localStorage.removeItem(STORAGE_KEYS.ACCESS);
window.localStorage.removeItem(STORAGE_KEYS.ID);
@@ -79,6 +80,36 @@ export function clearTokens(): void {
}
}
+/** sessionStorage, not localStorage: tab-scoped, so other tabs stay the staff account. */
+const IMPERSONATION_KEY = 'branch_impersonation_session';
+
+export function getImpersonationSession(): string | null {
+ if (typeof window === 'undefined') return null;
+ try {
+ return window.sessionStorage.getItem(IMPERSONATION_KEY);
+ } catch {
+ return null;
+ }
+}
+
+export function setImpersonationSession(sessionId: string): void {
+ if (typeof window === 'undefined') return;
+ try {
+ window.sessionStorage.setItem(IMPERSONATION_KEY, sessionId);
+ } catch {
+ // Storage unavailable — the switch-in simply won't survive a reload.
+ }
+}
+
+export function clearImpersonationSession(): void {
+ if (typeof window === 'undefined') return;
+ try {
+ window.sessionStorage.removeItem(IMPERSONATION_KEY);
+ } catch {
+ // Nothing useful to do.
+ }
+}
+
/**
* Decodes a JWT payload without verifying it.
*
diff --git a/apps/frontend/src/lib/routes.ts b/apps/frontend/src/lib/routes.ts
index 139d9e40..2aa8a967 100644
--- a/apps/frontend/src/lib/routes.ts
+++ b/apps/frontend/src/lib/routes.ts
@@ -22,12 +22,14 @@ export const LOGIN_PATH = '/login';
*/
export const DEFAULT_LANDING_PATH = '/projects';
export const ADMIN_LANDING_PATH = '/dashboard';
+export const STAFF_CONSOLE_PATH = '/staff';
/**
* Asks the policy rather than reading `isAdmin`, so widening `dashboard:view`
* later moves the landing page with it instead of leaving this behind.
*/
export function landingPathFor(subject: RbacSubject): string {
+ if (can(subject, 'impersonation:console')) return STAFF_CONSOLE_PATH;
return can(subject, 'dashboard:view') ? ADMIN_LANDING_PATH : DEFAULT_LANDING_PATH;
}
diff --git a/apps/frontend/test/components/ImpersonationBanner.test.tsx b/apps/frontend/test/components/ImpersonationBanner.test.tsx
new file mode 100644
index 00000000..ef036da4
--- /dev/null
+++ b/apps/frontend/test/components/ImpersonationBanner.test.tsx
@@ -0,0 +1,57 @@
+import userEvent from '@testing-library/user-event';
+import { useRouter } from 'next/navigation';
+import { render, screen, waitFor } from '../utils';
+import ImpersonationBanner from '@/app/components/ImpersonationBanner';
+import { directorSubject, session } from '../rbac';
+
+const subject = directorSubject([1], 4);
+const target = session({ subject }).user!;
+
+function userWith(mode: 'read_only' | 'full') {
+ return {
+ ...target,
+ name: 'Sam Okafor',
+ email: 'sam@branch.org',
+ impersonation: {
+ userId: 50,
+ name: 'Hidden Staff',
+ email: 'staff@branch.org',
+ sessionId: 'session-1',
+ mode,
+ expiresAt: new Date().toISOString(),
+ },
+ };
+}
+
+describe('ImpersonationBanner', () => {
+ it('renders nothing for an ordinary session', () => {
+ const { container } = render(, { subject });
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('names the user being viewed and the mode', () => {
+ render(, { subject, auth: { user: userWith('read_only') } });
+ expect(screen.getByRole('status')).toHaveTextContent('Viewing as Sam Okafor (sam@branch.org)');
+ expect(screen.getByRole('status')).toHaveTextContent('Read-only');
+ });
+
+ it('warns that full access changes are real', () => {
+ render(, { subject, auth: { user: userWith('full') } });
+ expect(screen.getByRole('status')).toHaveTextContent('Full access: changes are real');
+ });
+
+ it('exits back to the staff console', async () => {
+ const replace = jest.fn();
+ (useRouter as jest.Mock).mockReturnValue({ replace });
+ const stopImpersonation = jest.fn().mockResolvedValue(undefined);
+ render(, {
+ subject,
+ auth: { user: userWith('read_only'), stopImpersonation },
+ });
+
+ await userEvent.click(screen.getByRole('button', { name: 'Exit' }));
+
+ expect(stopImpersonation).toHaveBeenCalled();
+ await waitFor(() => expect(replace).toHaveBeenCalledWith('/staff'));
+ });
+});
diff --git a/apps/frontend/test/components/StaffConsolePage.test.tsx b/apps/frontend/test/components/StaffConsolePage.test.tsx
new file mode 100644
index 00000000..93e843d3
--- /dev/null
+++ b/apps/frontend/test/components/StaffConsolePage.test.tsx
@@ -0,0 +1,108 @@
+import userEvent from '@testing-library/user-event';
+import { useRouter } from 'next/navigation';
+import { render, screen, waitFor, within } from '../utils';
+import StaffConsolePage from '@/app/staff/page';
+import { directorSubject, staffSubject } from '../rbac';
+
+const mockApiFetch = jest.fn();
+jest.mock('../../src/lib/authClient', () => ({
+ ...jest.requireActual('../../src/lib/authClient'),
+ authedFetch: (...args: Parameters) => mockApiFetch(...args),
+}));
+
+const targets = [
+ {
+ userId: 4,
+ name: 'Sam Okafor',
+ email: 'sam@branch.org',
+ isAdmin: false,
+ pending: false,
+ directorProjectCount: 1,
+ memberProjectCount: 1,
+ },
+ {
+ userId: 6,
+ name: 'Diego Alvarez',
+ email: 'diego@branch.org',
+ isAdmin: false,
+ pending: true,
+ directorProjectCount: 0,
+ memberProjectCount: 1,
+ },
+];
+
+const replace = jest.fn();
+
+beforeEach(() => {
+ mockApiFetch.mockReset();
+ mockApiFetch.mockResolvedValue({ users: targets });
+ replace.mockReset();
+ (useRouter as jest.Mock).mockReturnValue({ replace });
+});
+
+function rowFor(name: string) {
+ return screen.getByText(name).closest('tr') as HTMLElement;
+}
+
+describe('StaffConsolePage', () => {
+ it('lists the users a staff account can switch into, with their role', async () => {
+ render(, { subject: staffSubject() });
+
+ expect(await screen.findByText('Sam Okafor')).toBeInTheDocument();
+ expect(within(rowFor('Sam Okafor')).getByText('Director')).toBeInTheDocument();
+ expect(within(rowFor('Diego Alvarez')).getByText('(never signed in)')).toBeInTheDocument();
+ expect(mockApiFetch).toHaveBeenCalledWith('/auth/impersonation/targets', { method: 'GET' });
+ });
+
+ it('searches on the server', async () => {
+ render(, { subject: staffSubject() });
+ await screen.findByText('Sam Okafor');
+
+ await userEvent.type(screen.getByLabelText('Search by name or email'), 'sam');
+
+ await waitFor(() =>
+ expect(mockApiFetch).toHaveBeenLastCalledWith('/auth/impersonation/targets?search=sam', {
+ method: 'GET',
+ }),
+ );
+ });
+
+ it('"View as" switches in read-only and lands where that user would', async () => {
+ const startImpersonation = jest.fn().mockResolvedValue({ rbac: directorSubject([1], 4) });
+ render(, { subject: staffSubject(), auth: { startImpersonation } });
+ await screen.findByText('Sam Okafor');
+
+ await userEvent.click(within(rowFor('Sam Okafor')).getByRole('button', { name: 'View as' }));
+
+ expect(startImpersonation).toHaveBeenCalledWith(4, 'read_only');
+ await waitFor(() => expect(replace).toHaveBeenCalledWith('/projects'));
+ });
+
+ it('"Act as" asks first, then switches in with full access', async () => {
+ const startImpersonation = jest.fn().mockResolvedValue({ rbac: directorSubject([1], 4) });
+ render(, { subject: staffSubject(), auth: { startImpersonation } });
+ await screen.findByText('Sam Okafor');
+
+ await userEvent.click(within(rowFor('Sam Okafor')).getByRole('button', { name: 'Act as' }));
+ expect(startImpersonation).not.toHaveBeenCalled();
+
+ expect(await screen.findByText('Act as this user with full access?')).toBeInTheDocument();
+ expect(screen.getByText('Sam Okafor (sam@branch.org)')).toBeInTheDocument();
+ // The dialog portals to the end of , so its confirm is the last "Act as".
+ const confirm = screen.getAllByRole('button', { name: 'Act as' }).at(-1)!;
+ await userEvent.click(confirm);
+
+ await waitFor(() => expect(startImpersonation).toHaveBeenCalledWith(4, 'full'));
+ });
+
+ it('shows why a switch failed', async () => {
+ const startImpersonation = jest.fn().mockRejectedValue(new Error('User not found'));
+ render(, { subject: staffSubject(), auth: { startImpersonation } });
+ await screen.findByText('Sam Okafor');
+
+ await userEvent.click(within(rowFor('Sam Okafor')).getByRole('button', { name: 'View as' }));
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('User not found');
+ expect(replace).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/frontend/test/lib/authClient.test.ts b/apps/frontend/test/lib/authClient.test.ts
index a7f22bae..ec1eb24d 100644
--- a/apps/frontend/test/lib/authClient.test.ts
+++ b/apps/frontend/test/lib/authClient.test.ts
@@ -3,10 +3,16 @@ import {
__resetRefreshStateForTests,
authedFetch,
endSession,
+ onImpersonationEnded,
onSessionExpired,
refreshSession,
} from '@/lib/authClient';
-import { STORAGE_KEYS } from '@/lib/authTokens';
+import {
+ STORAGE_KEYS,
+ clearTokens,
+ getImpersonationSession,
+ setImpersonationSession,
+} from '@/lib/authTokens';
function makeToken(claims: Record) {
const payload = btoa(JSON.stringify(claims))
@@ -64,6 +70,7 @@ function callsTo(fetchMock: jest.Mock, fragment: string) {
beforeEach(() => {
localStorage.clear();
+ sessionStorage.clear();
__resetRefreshStateForTests();
});
@@ -267,3 +274,59 @@ describe('ApiError', () => {
expect(error.status).toBe(401);
});
});
+
+describe('authedFetch while impersonating', () => {
+ const SESSION = 'session-1';
+ const ended = { status: 401, body: { message: 'Impersonation session has ended', code: 'IMPERSONATION_EXPIRED' } };
+ const headerOf = (call: unknown[]) =>
+ ((call[1] as RequestInit).headers as Record)['X-Impersonate-Session'];
+
+ beforeEach(() => {
+ seed();
+ setImpersonationSession(SESSION);
+ });
+
+ it('sends the session beside the staff token', async () => {
+ const fetchMock = mockFetch({ '/projects': [{ body: [] }] });
+
+ await authedFetch('/projects');
+
+ expect(headerOf(fetchMock.mock.calls[0])).toBe(SESSION);
+ expect(authHeaderOf(fetchMock.mock.calls[0])).toBe(`Bearer ${VALID_ACCESS}`);
+ });
+
+ it("leaves it off for the staff console's own calls", async () => {
+ const fetchMock = mockFetch({ '/auth/impersonation': [{ body: {} }] });
+
+ await authedFetch('/auth/impersonation', { method: 'POST', asSelf: true });
+
+ expect(headerOf(fetchMock.mock.calls[0])).toBeUndefined();
+ });
+
+ it('drops an ended session and re-reads as the staff account, without refreshing', async () => {
+ const onEnded = jest.fn();
+ onImpersonationEnded(onEnded);
+ const fetchMock = mockFetch({ '/auth/me': [ended, { body: { userId: 50 } }], '/auth/refresh': [{}] });
+
+ await expect(authedFetch('/auth/me')).resolves.toEqual({ userId: 50 });
+
+ expect(getImpersonationSession()).toBeNull();
+ expect(onEnded).toHaveBeenCalledTimes(1);
+ expect(callsTo(fetchMock, '/auth/refresh')).toHaveLength(0);
+ expect(headerOf(callsTo(fetchMock, '/auth/me')[1])).toBeUndefined();
+ });
+
+ it('never re-sends a write as the staff account', async () => {
+ const fetchMock = mockFetch({ '/expenditures': [ended] });
+
+ await expect(authedFetch('/expenditures', { method: 'POST' })).rejects.toMatchObject({ status: 401 });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(getImpersonationSession()).toBeNull();
+ });
+
+ it('is cleared with the tokens on sign-out', () => {
+ clearTokens();
+ expect(getImpersonationSession()).toBeNull();
+ });
+});
diff --git a/apps/frontend/test/lib/routes.test.ts b/apps/frontend/test/lib/routes.test.ts
index ca5dd70a..6d726713 100644
--- a/apps/frontend/test/lib/routes.test.ts
+++ b/apps/frontend/test/lib/routes.test.ts
@@ -9,7 +9,7 @@ import {
safeNextPath,
} from '@/lib/routes';
import { can } from '@branch/rbac';
-import { adminSubject, anonymousSubject, directorSubject, memberSubject } from '../rbac';
+import { adminSubject, anonymousSubject, directorSubject, memberSubject, staffSubject } from '../rbac';
describe('normalizePath', () => {
it.each([
@@ -121,6 +121,12 @@ describe('landingPathFor', () => {
expect(landingPathFor(adminSubject())).toBe(ADMIN_LANDING_PATH);
});
+ it('sends a staff account to the console, the only page it can open', () => {
+ expect(landingPathFor(staffSubject())).toBe('/staff');
+ expect(pagePermission('/staff')).toBe('impersonation:console');
+ expect(can(adminSubject(), 'impersonation:console')).toBe(false);
+ });
+
it('sends everyone else somewhere they can actually load', () => {
// Regression guard: the landing route was /dashboard for every role, so
// making the dashboard admin-only dropped non-admins on the no-access panel
diff --git a/apps/frontend/test/rbac.ts b/apps/frontend/test/rbac.ts
index d89d584c..87903dd8 100644
--- a/apps/frontend/test/rbac.ts
+++ b/apps/frontend/test/rbac.ts
@@ -30,6 +30,8 @@ export const directorSubject = (projectIds: number[] = [1], userId = 2): RbacSub
export const memberSubject = (projectIds: number[] = [1], userId = 3): RbacSubject =>
subjectFor({ userId, memberProjectIds: projectIds });
+export const staffSubject = (userId = 50): RbacSubject => subjectFor({ userId, isStaff: true });
+
export const anonymousSubject = ANONYMOUS;
/** The `useAuth()` value a mocked session should return. */
diff --git a/apps/frontend/test/utils.tsx b/apps/frontend/test/utils.tsx
index e565d2d8..1ccbba12 100644
--- a/apps/frontend/test/utils.tsx
+++ b/apps/frontend/test/utils.tsx
@@ -46,7 +46,7 @@ export function TestQueryProvider({
* render as a director, a project member or nobody, and assert on what they can
* and cannot reach.
*/
-function makeWrapper(subject: RbacSubject | null) {
+function makeWrapper(subject: RbacSubject | null, auth: Record = {}) {
const value = subject
? session({ subject })
: session({ subject: undefined, isAuthenticated: false });
@@ -64,8 +64,11 @@ function makeWrapper(subject: RbacSubject | null) {
logout: jest.fn(),
refresh: jest.fn(),
reloadUser: jest.fn(),
+ startImpersonation: jest.fn(),
+ stopImpersonation: jest.fn(),
forgotPassword: jest.fn(),
resetPassword: jest.fn(),
+ ...auth,
} as never
}
>
@@ -80,10 +83,13 @@ function makeWrapper(subject: RbacSubject | null) {
interface Options extends Omit {
/** `null` renders signed out. Defaults to an admin. */
subject?: RbacSubject | null;
+ auth?: Record;
}
-const customRender = (ui: ReactElement, { subject = adminSubject(), ...options }: Options = {}) =>
- render(ui, { wrapper: makeWrapper(subject), ...options });
+const customRender = (
+ ui: ReactElement,
+ { subject = adminSubject(), auth, ...options }: Options = {},
+) => render(ui, { wrapper: makeWrapper(subject, auth), ...options });
/**
* Renders with the real `AuthProvider`, which bootstraps from token storage and