From 780a0baeb14bb502542a6fac8d2cf495cdfc14dc Mon Sep 17 00:00:00 2001 From: nourshoreibah Date: Thu, 15 Oct 2026 15:56:02 -0400 Subject: [PATCH 1/9] feat(db): add staff accounts and impersonation audit tables users.is_staff hides an account from every user-facing query; the two impersonation tables record each staff switch-in and every write made while switched in. No FKs on the audit tables so the trail outlives the users it names. Co-Authored-By: Claude Opus 5.5 --- .../V20261015195441__add_users_is_staff.sql | 9 ++++++++ ...5195442__create_impersonation_sessions.sql | 14 ++++++++++++ ...15195443__create_impersonation_actions.sql | 12 ++++++++++ shared/types/db-types.d.ts | 22 +++++++++++++++++++ 4 files changed, 57 insertions(+) create mode 100644 apps/backend/db/migrations/V20261015195441__add_users_is_staff.sql create mode 100644 apps/backend/db/migrations/V20261015195442__create_impersonation_sessions.sql create mode 100644 apps/backend/db/migrations/V20261015195443__create_impersonation_actions.sql diff --git a/apps/backend/db/migrations/V20261015195441__add_users_is_staff.sql b/apps/backend/db/migrations/V20261015195441__add_users_is_staff.sql new file mode 100644 index 00000000..498284e5 --- /dev/null +++ b/apps/backend/db/migrations/V20261015195441__add_users_is_staff.sql @@ -0,0 +1,9 @@ +-- V20261015195441__add_users_is_staff +-- +-- Staff accounts are hidden from every user-facing query and can only +-- impersonate. See shared/rbac/README.md. +-- +-- Nullable with no default: DSQL rejects either on ADD COLUMN. NULL means "not +-- staff", so every filter is `is_staff IS NOT TRUE`, never `= false`. + +ALTER TABLE users ADD COLUMN is_staff BOOLEAN; diff --git a/apps/backend/db/migrations/V20261015195442__create_impersonation_sessions.sql b/apps/backend/db/migrations/V20261015195442__create_impersonation_sessions.sql new file mode 100644 index 00000000..96574e13 --- /dev/null +++ b/apps/backend/db/migrations/V20261015195442__create_impersonation_sessions.sql @@ -0,0 +1,14 @@ +-- V20261015195442__create_impersonation_sessions +-- +-- One row per staff switch-in. No foreign keys: the audit trail must outlive +-- the users it names. + +CREATE TABLE impersonation_sessions ( + session_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + staff_user_id INT NOT NULL, + target_user_id INT NOT NULL, + mode VARCHAR(10) NOT NULL CHECK (mode IN ('read_only', 'full')), + started_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + expires_at TIMESTAMP NOT NULL, + ended_at TIMESTAMP +); diff --git a/apps/backend/db/migrations/V20261015195443__create_impersonation_actions.sql b/apps/backend/db/migrations/V20261015195443__create_impersonation_actions.sql new file mode 100644 index 00000000..8c112763 --- /dev/null +++ b/apps/backend/db/migrations/V20261015195443__create_impersonation_actions.sql @@ -0,0 +1,12 @@ +-- V20261015195443__create_impersonation_actions +-- +-- Every mutating request made while impersonating in full mode. + +CREATE TABLE impersonation_actions ( + action_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + session_id UUID NOT NULL, + method VARCHAR(10) NOT NULL, + path TEXT NOT NULL, + status_code INT NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +); diff --git a/shared/types/db-types.d.ts b/shared/types/db-types.d.ts index 4257e19b..ccf6b2e4 100644 --- a/shared/types/db-types.d.ts +++ b/shared/types/db-types.d.ts @@ -52,6 +52,25 @@ export interface BranchExpenditures { status: Generated; } +export interface BranchImpersonationActions { + action_id: Generated; + created_at: Generated; + method: string; + path: string; + session_id: string; + status_code: number; +} + +export interface BranchImpersonationSessions { + ended_at: Timestamp | null; + expires_at: Timestamp; + mode: string; + session_id: Generated; + staff_user_id: number; + started_at: Generated; + target_user_id: number; +} + export interface BranchProjectDonations { amount: Numeric; donated_at: Generated; @@ -103,6 +122,7 @@ export interface BranchUsers { created_at: Generated; email: string; is_admin: Generated; + is_staff: boolean | null; name: string; profile_image: string | null; user_id: Generated; @@ -112,6 +132,8 @@ export interface DB { "branch.donors": BranchDonors; "branch.expenditure_rollup": BranchExpenditureRollup; "branch.expenditures": BranchExpenditures; + "branch.impersonation_actions": BranchImpersonationActions; + "branch.impersonation_sessions": BranchImpersonationSessions; "branch.project_donations": BranchProjectDonations; "branch.project_memberships": BranchProjectMemberships; "branch.project_rollup": BranchProjectRollup; From 4a2fe817d099d2c7ef420fbfc3fc3eb7a3c03d32 Mon Sep 17 00:00:00 2001 From: nourshoreibah Date: Thu, 15 Oct 2026 16:16:43 -0400 Subject: [PATCH 2/9] test(lambdas): read DB_PORT in every e2e fixture pool Every pool but donors' hardcoded 5432, so a suite could only ever run against the shared dev database. Reading DB_PORT (default unchanged) lets a run point at a throwaway Postgres instead. Co-Authored-By: Claude Opus 5.5 --- apps/backend/lambdas/auth/test/auth.e2e.test.ts | 2 +- apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts | 2 +- .../lambdas/projects/test/approved-expenditures.e2e.test.ts | 2 +- apps/backend/lambdas/projects/test/crud.test.ts | 2 +- apps/backend/lambdas/projects/test/example.test.ts | 2 +- apps/backend/lambdas/projects/test/projects.e2e.test.ts | 2 +- apps/backend/lambdas/projects/test/projects.unit.test.ts | 2 +- apps/backend/lambdas/projects/test/rollup-store.e2e.test.ts | 2 +- apps/backend/lambdas/projects/test/rollups.e2e.test.ts | 2 +- apps/backend/lambdas/reports/test/report-service.e2e.test.ts | 2 +- apps/backend/lambdas/reports/test/reports.e2e.test.ts | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/apps/backend/lambdas/auth/test/auth.e2e.test.ts b/apps/backend/lambdas/auth/test/auth.e2e.test.ts index d5349dfb..c14feefa 100644 --- a/apps/backend/lambdas/auth/test/auth.e2e.test.ts +++ b/apps/backend/lambdas/auth/test/auth.e2e.test.ts @@ -3,7 +3,7 @@ import { ensureSchema, resetData } from '../../../db/testkit'; const pool = new Pool({ host: 'localhost', - port: Number(5432), + port: Number(process.env.DB_PORT ?? 5432), user: 'branch_dev', password: 'password', database: 'branch_db', diff --git a/apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts b/apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts index 5f4f8fb4..18ac7448 100644 --- a/apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts +++ b/apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts @@ -39,7 +39,7 @@ const mockSendExpenseStatusEmail = sendExpenseStatusEmail as jest.MockedFunction const pool = new Pool({ host: 'localhost', - port: Number(5432), + port: Number(process.env.DB_PORT ?? 5432), user: 'branch_dev', password: 'password', database: 'branch_db', diff --git a/apps/backend/lambdas/projects/test/approved-expenditures.e2e.test.ts b/apps/backend/lambdas/projects/test/approved-expenditures.e2e.test.ts index ca5967a0..f56688fe 100644 --- a/apps/backend/lambdas/projects/test/approved-expenditures.e2e.test.ts +++ b/apps/backend/lambdas/projects/test/approved-expenditures.e2e.test.ts @@ -47,7 +47,7 @@ const adminAuthResult = { const pool = new Pool({ host: 'localhost', - port: 5432, + port: Number(process.env.DB_PORT ?? 5432), user: 'branch_dev', password: 'password', database: 'branch_db', diff --git a/apps/backend/lambdas/projects/test/crud.test.ts b/apps/backend/lambdas/projects/test/crud.test.ts index d2b9ab6b..87455576 100644 --- a/apps/backend/lambdas/projects/test/crud.test.ts +++ b/apps/backend/lambdas/projects/test/crud.test.ts @@ -38,7 +38,7 @@ const adminAuthResult = { const pool = new Pool({ host: 'localhost', - port: Number(5432), + port: Number(process.env.DB_PORT ?? 5432), user: 'branch_dev', password: 'password', database: 'branch_db', diff --git a/apps/backend/lambdas/projects/test/example.test.ts b/apps/backend/lambdas/projects/test/example.test.ts index 6f59df2b..ac4c6926 100644 --- a/apps/backend/lambdas/projects/test/example.test.ts +++ b/apps/backend/lambdas/projects/test/example.test.ts @@ -38,7 +38,7 @@ const adminAuthResult = { const pool = new Pool({ host: 'localhost', - port: Number(5432), + port: Number(process.env.DB_PORT ?? 5432), user: 'branch_dev', password: 'password', database: 'branch_db', diff --git a/apps/backend/lambdas/projects/test/projects.e2e.test.ts b/apps/backend/lambdas/projects/test/projects.e2e.test.ts index 94ecffe3..ea6ce51f 100644 --- a/apps/backend/lambdas/projects/test/projects.e2e.test.ts +++ b/apps/backend/lambdas/projects/test/projects.e2e.test.ts @@ -44,7 +44,7 @@ const nonAdminAuthResult = { const pool = new Pool({ host: 'localhost', - port: Number(5432), + port: Number(process.env.DB_PORT ?? 5432), user: 'branch_dev', password: 'password', database: 'branch_db', diff --git a/apps/backend/lambdas/projects/test/projects.unit.test.ts b/apps/backend/lambdas/projects/test/projects.unit.test.ts index e11b7463..fcb6e11f 100644 --- a/apps/backend/lambdas/projects/test/projects.unit.test.ts +++ b/apps/backend/lambdas/projects/test/projects.unit.test.ts @@ -33,7 +33,7 @@ const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction Date: Thu, 15 Oct 2026 16:27:06 -0400 Subject: [PATCH 3/9] feat(frontend): staff console and impersonation banner A staff account lands on /staff, the only page it can open as itself, and picks a user to view as (read-only) or act as (full, behind a confirm). The server's session id lives in sessionStorage, so a switch-in is per tab, and authedFetch sends it as X-Impersonate-Session. /auth/me then reports the target, so every page and permission is theirs with no other changes. - ImpersonationBanner, mounted in providers.tsx, names whose data is on screen, the mode and expiry, and exits back to the console. - Starting, stopping and logging out clear the whole query cache: every entry was fetched as the previous identity. - An ended session (IMPERSONATION_EXPIRED) drops the id; a GET is retried as the staff account, a write never is, and no token refresh is tried. Co-Authored-By: Claude Opus 5.5 --- apps/frontend/AGENTS.md | 4 +- .../app/components/ImpersonationBanner.tsx | 62 ++++++ apps/frontend/src/app/providers.tsx | 2 + apps/frontend/src/app/staff/page.tsx | 191 ++++++++++++++++++ apps/frontend/src/context/AuthContext.tsx | 89 +++++++- apps/frontend/src/lib/authClient.ts | 62 +++++- apps/frontend/src/lib/authTokens.ts | 34 ++++ apps/frontend/src/lib/routes.ts | 2 + .../components/ImpersonationBanner.test.tsx | 57 ++++++ .../test/components/StaffConsolePage.test.tsx | 108 ++++++++++ apps/frontend/test/lib/authClient.test.ts | 65 +++++- apps/frontend/test/lib/routes.test.ts | 8 +- apps/frontend/test/rbac.ts | 4 + apps/frontend/test/utils.tsx | 13 +- 14 files changed, 691 insertions(+), 10 deletions(-) create mode 100644 apps/frontend/src/app/components/ImpersonationBanner.tsx create mode 100644 apps/frontend/src/app/staff/page.tsx create mode 100644 apps/frontend/test/components/ImpersonationBanner.test.tsx create mode 100644 apps/frontend/test/components/StaffConsolePage.test.tsx diff --git a/apps/frontend/AGENTS.md b/apps/frontend/AGENTS.md index f6bf8e7f..c33d267d 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. @@ -81,6 +81,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..644816db --- /dev/null +++ b/apps/frontend/src/app/components/ImpersonationBanner.tsx @@ -0,0 +1,62 @@ +'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', + }); +} + +/** + * Shown on every page while a staff account is switched into someone else, so + * nobody forgets whose data they are looking at, or that a full session's + * writes are real. + */ +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 ( +
+ + Viewing as {user.name} ({user.email}) ·{' '} + {full ? 'Full access: changes are real' : 'Read-only'} · ends{' '} + {timeOf(impersonation.expiresAt)} + + +
+ ); +} diff --git a/apps/frontend/src/app/providers.tsx b/apps/frontend/src/app/providers.tsx index 2dbc6d9e..ddf90c5f 100644 --- a/apps/frontend/src/app/providers.tsx +++ b/apps/frontend/src/app/providers.tsx @@ -6,6 +6,7 @@ import { QueryClientProvider } from '@tanstack/react-query'; import { AuthProvider } from '@/context/AuthContext'; import { makeQueryClient } from '@/lib/queryClient'; import AuthGate from './components/AuthGate'; +import ImpersonationBanner from './components/ImpersonationBanner'; import RoutePrefetcher from './components/RoutePrefetcher'; // AuthGate lives here so every route is guarded by construction. Note that @@ -26,6 +27,7 @@ export function Providers({ children }: { children: React.ReactNode }) { + {children} diff --git a/apps/frontend/src/app/staff/page.tsx b/apps/frontend/src/app/staff/page.tsx new file mode 100644 index 00000000..4f816817 --- /dev/null +++ b/apps/frontend/src/app/staff/page.tsx @@ -0,0 +1,191 @@ +'use client'; + +import React, { useEffect, useState } from 'react'; +import { useRouter } from 'next/navigation'; +import Header from '../components/Header'; +import Button from '../components/Button'; +import DataTable, { type DataTableColumn } from '../components/DataTable'; +import ConfirmDeleteDialog from '../components/ConfirmDeleteDialog'; +import TextInputField from '../components/TextInputField'; +import { useApi } from '@/hooks/useApi'; +import { useAuth, type ImpersonationMode } from '@/context/AuthContext'; +import { LOGIN_PATH, landingPathFor } from '@/lib/routes'; + +interface Target { + userId: number; + name: string; + email: string; + isAdmin: boolean; + pending: boolean; + directorProjectCount: number; + memberProjectCount: number; +} + +const SEARCH_DEBOUNCE_MS = 250; + +function roleOf(t: Target): string { + if (t.isAdmin) return 'Admin'; + if (t.directorProjectCount > 0) return 'Director'; + return t.memberProjectCount > 0 ? 'Member' : 'No projects'; +} + +/** + * The staff console: the only page a staff account can open as itself. Picking + * a user starts a session as them; the banner in providers.tsx is the way back. + */ +export default function StaffConsolePage() { + const api = useApi(); + const router = useRouter(); + const { startImpersonation, logout } = useAuth(); + const [search, setSearch] = useState(''); + const [targets, setTargets] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [switching, setSwitching] = useState(null); + const [confirmFull, setConfirmFull] = useState(null); + + useEffect(() => { + let cancelled = false; + const timer = setTimeout(async () => { + setError(null); + try { + const query = search.trim() + ? `?search=${encodeURIComponent(search.trim())}` + : ''; + const json = await api.get<{ users: Target[] }>( + `/auth/impersonation/targets${query}`, + ); + if (!cancelled) setTargets(json.users ?? []); + } catch (err) { + if (!cancelled) + setError(err instanceof Error ? err.message : 'Failed to load users'); + } finally { + if (!cancelled) setLoading(false); + } + }, SEARCH_DEBOUNCE_MS); + return () => { + cancelled = true; + clearTimeout(timer); + }; + }, [api, search]); + + const switchInto = async (target: Target, mode: ImpersonationMode) => { + setSwitching(target.userId); + setError(null); + try { + const me = await startImpersonation(target.userId, mode); + router.replace(landingPathFor(me.rbac)); + } catch (err) { + setSwitching(null); + // Rethrown so the full-access dialog stays open and shows it. + setError( + err instanceof Error ? err.message : 'Could not switch into this user', + ); + throw err; + } + }; + + const columns: DataTableColumn[] = [ + { + key: 'name', + header: 'Name', + cell: (t) => ( + + {t.name} + {t.pending && ( + + (never signed in) + + )} + + ), + }, + { key: 'email', header: 'Email', cell: (t) => t.email }, + { key: 'role', header: 'Role', width: '120px', cell: roleOf }, + { + key: 'actions', + header: '', + width: '220px', + align: 'right', + cell: (t) => ( +
+ + +
+ ), + }, + ]; + + 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 29ed46ec..be3513f4 100644 --- a/apps/frontend/src/context/AuthContext.tsx +++ b/apps/frontend/src/context/AuthContext.tsx @@ -14,15 +14,19 @@ import { AUTH_ME_KEY } from '@/lib/queries'; import { authedFetch, endSession, + onImpersonationEnded, onSessionExpired, refreshSession, } from '@/lib/authClient'; import { + clearImpersonationSession, clearTokens, getAccessToken, + getImpersonationSession, getRefreshToken, getTokenExpMs, saveTokens, + setImpersonationSession, } from '@/lib/authTokens'; // --------------------------------------------------------------------------- @@ -55,6 +59,22 @@ export interface AuthUser { * into a signed-in session that is denied everything. */ rbac: RbacSubject; + /** A staff account acting as itself. False while impersonating. */ + isStaff?: boolean; + /** Set while a staff account is switched into this user. */ + impersonation?: Impersonation | null; +} + +export type ImpersonationMode = 'read_only' | 'full'; + +/** The staff account behind the session, as GET /auth/me reports it. */ +export interface Impersonation { + userId: number; + name: string; + email: string; + sessionId: string; + mode: ImpersonationMode; + expiresAt: string; } export type ChallengeName = @@ -99,6 +119,10 @@ interface AuthContextValue { logout: () => Promise; refresh: () => Promise; reloadUser: () => Promise; + /** Staff only. Resolves with the target's session once it is in place. */ + startImpersonation: (targetUserId: number, mode: ImpersonationMode) => Promise; + /** Back to the staff account. Safe to call when not impersonating. */ + stopImpersonation: () => Promise; forgotPassword: (email: string) => Promise; resetPassword: ( email: string, @@ -196,6 +220,18 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { const fetchMe = useCallback(() => authedFetch('/auth/me'), []); + /** + * Swap whose session this is. The whole cache goes, not just /auth/me: every + * other entry was fetched as the previous identity. + */ + const replaceIdentity = useCallback( + (next: AuthUser | null) => { + queryClient.clear(); + queryClient.setQueryData(AUTH_ME_KEY, next); + }, + [queryClient], + ); + /** Writes the session straight into the cache, the one source of `user`. */ const setUser = useCallback( (next: AuthUser | null) => { @@ -256,6 +292,17 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { [setUser], ); + // The server ended a switch-in (expiry, or another tab): fall back to staff. + useEffect( + () => + onImpersonationEnded(() => { + fetchMe() + .then((me) => replaceIdentity(isValidUser(me) ? me : null)) + .catch(() => endSession()); + }), + [fetchMe, replaceIdentity], + ); + // Proactive refresh, rescheduled from each new token's exp. Without this the // session silently breaks after the access token's 1-hour lifetime. useEffect(() => { @@ -361,7 +408,42 @@ 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'); + replaceIdentity(me); + return me; + } catch (error) { + clearImpersonationSession(); + throw error; + } + }, + [fetchMe, replaceIdentity], + ); + + const stopImpersonation = useCallback(async () => { + const sessionId = getImpersonationSession(); + if (!sessionId) return; + clearImpersonationSession(); + // Best effort: the session expires on its own within the hour regardless. + await authedFetch(`/auth/impersonation/${encodeURIComponent(sessionId)}`, { + method: 'DELETE', + asSelf: true, + }).catch(() => undefined); + const me = await fetchMe(); + replaceIdentity(isValidUser(me) ? me : null); + }, [fetchMe, replaceIdentity]); + const logout = useCallback(async () => { + await stopImpersonation().catch(() => undefined); // retryOn401: false — refreshing a session we are discarding is pointless. await authedFetch('/auth/logout', { method: 'POST', @@ -370,8 +452,9 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { // Best effort: clear locally even if the server call fails. }); endSession(); - setUser(null); - }, [setUser]); + // Clear, not just null: the next account in this tab must not see this one's cache. + replaceIdentity(null); + }, [replaceIdentity, stopImpersonation]); const reloadUser = useCallback(async () => { try { @@ -417,6 +500,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 afe374b6..1971d394 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,28 @@ export function endSession(): void { } } +const impersonationListeners = new Set<() => void>(); + +/** + * Subscribe to the server ending a switch-in (expired, or ended from another + * tab). The staff account's own session is still good when this fires. + */ +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); +} + let refreshInFlight: Promise | null = null; /** @@ -94,6 +118,11 @@ export function refreshSession(): Promise { export interface AuthedRequestOptions extends RequestInit { /** Set false to skip the refresh-and-retry dance (used when signing out). */ retryOn401?: boolean; + /** + * Send as the signed-in staff account even while switched in. For the staff + * console's own calls: starting and ending a session. + */ + asSelf?: boolean; } /** @@ -102,7 +131,33 @@ 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; + // The switch-in is over, not the session: drop it and say so. A read is + // retried as the staff account, so the bootstrap /auth/me lands on the + // console instead of signing staff out; 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(); @@ -124,7 +179,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; if (!(await refreshSession())) { endSession(); @@ -144,4 +201,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..9d89c3aa 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,39 @@ export function clearTokens(): void { } } +/** + * The staff console's switch-in, if any. sessionStorage rather than + * localStorage: it is scoped to one tab, 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 855dcf8e..f7411713 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 7b4d3acf..da8aadf5 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([ @@ -113,6 +113,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 00f3ced7..e1cf5d64 100644 --- a/apps/frontend/test/rbac.ts +++ b/apps/frontend/test/rbac.ts @@ -13,6 +13,7 @@ export function subjectFor( ): RbacSubject { return { isAdmin: false, + isStaff: false, memberProjectIds: [], directorProjectIds: [], ...partial, @@ -29,6 +30,9 @@ export const directorSubject = (projectIds: number[] = [1], userId = 2): RbacSub export const memberSubject = (projectIds: number[] = [1], userId = 3): RbacSubject => subjectFor({ userId, memberProjectIds: projectIds }); +/** A hidden staff account acting as itself: only the staff console is open to it. */ +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..d90415e7 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,14 @@ function makeWrapper(subject: RbacSubject | null) { interface Options extends Omit { /** `null` renders signed out. Defaults to an admin. */ subject?: RbacSubject | null; + /** Overrides merged into the `useAuth()` value, e.g. a `user` or an action mock. */ + 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 From 33104ef1ca30161e99165aecf025a619cb0ec630 Mon Sep 17 00:00:00 2001 From: nourshoreibah Date: Thu, 15 Oct 2026 16:16:43 -0400 Subject: [PATCH 4/9] feat(auth): staff accounts that can impersonate any user A hidden staff account (users.is_staff) holds no rights of its own: the RBAC gate denies it everything but impersonation:*. It starts a session against any non-staff user, then sends X-Impersonate-Session beside its own Bearer token. authenticateRequest swaps in the target's identity and memberships, so policy, scoping and entered_by all see only the target. - read_only sessions get a 403 on every non-GET; full sessions act as the target. Every non-GET impersonated request, refused or not, is recorded in branch.impersonation_actions. - MFA routes are blocked while impersonating: they act on the caller's own Cognito session, which is then the staff account's. - Staff are filtered from every user list, count, roster, picker and member validation, and the column is never returned. A staff id answers like a missing one. - make create-staff provisions one (AdminCreateUser + createStaffUser); no route can set is_staff. - X-Impersonate-Session added to CORS in the lambdas and API Gateway. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 +- apps/backend/AGENTS.md | 2 + apps/backend/Makefile | 11 +- apps/backend/lambdas/AGENTS.md | 11 +- apps/backend/lambdas/auth/auth.ts | 5 +- apps/backend/lambdas/auth/controllers/auth.ts | 3 + .../lambdas/auth/controllers/impersonation.ts | 110 +++++++++++ apps/backend/lambdas/auth/handler.ts | 4 +- apps/backend/lambdas/auth/openapi.yaml | 145 +++++++++++++- apps/backend/lambdas/auth/routes.ts | 18 +- .../lambdas/auth/test/auth.login.unit.test.ts | 3 + .../auth/test/impersonation.e2e.test.ts | 179 +++++++++++++++++ apps/backend/lambdas/donors/auth.ts | 5 +- apps/backend/lambdas/donors/handler.ts | 4 +- apps/backend/lambdas/expenditures/auth.ts | 5 +- apps/backend/lambdas/expenditures/handler.ts | 4 +- .../test/expenditures.unit.test.ts | 2 +- apps/backend/lambdas/projects/auth.ts | 5 +- .../lambdas/projects/controllers/members.ts | 1 + apps/backend/lambdas/projects/handler.ts | 4 +- .../lambdas/projects/services/projects.ts | 9 +- .../projects/test/project-page.unit.test.ts | 18 +- apps/backend/lambdas/reports/auth.ts | 5 +- apps/backend/lambdas/reports/handler.ts | 4 +- apps/backend/lambdas/users/auth.ts | 5 +- .../lambdas/users/controllers/users.ts | 38 +++- apps/backend/lambdas/users/handler.ts | 4 +- apps/backend/lambdas/users/package.json | 1 + .../users/scripts/create-staff-account.ts | 68 +++++++ .../users/test/user.photos.unit.test.ts | 19 +- apps/backend/lambdas/users/test/users.test.ts | 55 +++++- apps/backend/lambdas/users/tsconfig.json | 2 +- infrastructure/aws/api_gateway.tf | 4 +- infrastructure/preview/api_gateway.tf | 2 +- shared/lambda-auth/src/authenticate.ts | 187 ++++++++++++++---- shared/lambda-auth/src/index.ts | 7 +- shared/lambda-auth/src/types.ts | 3 + shared/lambda-auth/test/authenticate.test.ts | 113 +++++++++++ shared/lambda-auth/test/rbac.test.ts | 2 + shared/lambda-http/README.md | 9 +- shared/lambda-http/src/dispatch.ts | 58 +++++- shared/lambda-http/src/response.ts | 2 +- shared/lambda-http/src/types.ts | 18 +- shared/lambda-http/test/authz.test.ts | 1 + shared/lambda-http/test/dispatch.test.ts | 97 +++++++++ shared/rbac/README.md | 24 +++ shared/rbac/src/pages.ts | 1 + shared/rbac/src/policy.ts | 17 ++ shared/rbac/src/subject.ts | 12 +- shared/rbac/test/policy.test.ts | 51 ++++- shared/store/src/impersonation.ts | 79 ++++++++ shared/store/src/index.ts | 7 + shared/store/src/users.ts | 2 + shared/types/auth-types.d.ts | 29 +++ 54 files changed, 1382 insertions(+), 96 deletions(-) create mode 100644 apps/backend/lambdas/auth/controllers/impersonation.ts create mode 100644 apps/backend/lambdas/auth/test/impersonation.e2e.test.ts create mode 100644 apps/backend/lambdas/users/scripts/create-staff-account.ts create mode 100644 shared/store/src/impersonation.ts diff --git a/AGENTS.md b/AGENTS.md index 40ee2bda..688547a4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,8 +36,8 @@ Five `file:`-linked packages dedupe code across the repo: - **`@branch/types`** (`shared/types/`) — types only, no runtime. Exports DB row types (`DB`, `BranchUsers`, ...) + auth DTOs (`AuthContext`, `AuthenticatedUser`, `AccessLevel`, `AuthorizationCheck`). It is the **single declaration** of those DTOs: `@branch/lambda-auth` depends on this package and re-exports them, so never add a second copy anywhere. `db-types.d.ts` is **generated** from `apps/backend/db/migrations/**` by the `Schema Change Checks` workflow (or locally by `make types`) — never hand-edit it. - **`@branch/rbac`** (`shared/rbac/`) — the authorization policy, as one table of rules plus a pure `can`/`authorize`. **The lambdas and the frontend both evaluate this module**, so a disabled button and the 403 behind it cannot disagree. It is the only place a permission is defined; do not re-derive one from `isAdmin` in a component or a controller. Read `shared/rbac/README.md` — it carries the role matrix — before changing who may do what. -- **`@branch/lambda-auth`** (`shared/lambda-auth/`) — runtime auth: `authenticateRequest(db, event)`, `extractToken(event)`, `loadRbacSubject(db, ctx)` (one query for the caller's memberships, which is also what `GET /auth/me` ships to the browser). Lambdas wrap it in their local `auth.ts`. -- **`@branch/lambda-http`** (`shared/lambda-http/`) — runtime routing: `dispatch(event, { prefix, routes, resolveAuth })` replaces the old per-lambda if-chain handler with a declarative `Route[]` table (`routes.ts`). Every route declares `access: 'public' | 'authenticated'` or a `permission`, and dispatch enforces it before the controller runs; the union has no default arm, so omitting the gate is a type error. Also exports `json`, `parseBody`, `requirePermission`, `createAuthResolver`. Depends on `@branch/rbac`'s and `@branch/lambda-auth`'s `dist/`, so build those first (`.github/actions/build-shared-packages` discovers `shared/*/` and builds in `@branch`-dep order). See `apps/backend/lambdas/AGENTS.md`. +- **`@branch/lambda-auth`** (`shared/lambda-auth/`) — runtime auth: `authenticateRequest(db, event)`, `extractToken(event)`, `loadRbacSubject(db, ctx)` (one query for the caller's memberships, which is also what `GET /auth/me` ships to the browser). Lambdas wrap it in their local `auth.ts`. It is also where **staff impersonation** happens: a staff caller sending `X-Impersonate-Session` is swapped for the session's target, with `user.impersonator` naming the staff account. Everything downstream sees only the target (see `shared/rbac/README.md`). +- **`@branch/lambda-http`** (`shared/lambda-http/`) — runtime routing: `dispatch(event, { prefix, routes, resolveAuth })` replaces the old per-lambda if-chain handler with a declarative `Route[]` table (`routes.ts`). Every route declares `access: 'public' | 'authenticated'` or a `permission`, and dispatch enforces it before the controller runs; the union has no default arm, so omitting the gate is a type error. It also enforces read-only impersonation and audits impersonated writes through the `onImpersonatedWrite` hook that every `handler.ts` passes. Also exports `json`, `parseBody`, `requirePermission`, `createAuthResolver`. Depends on `@branch/rbac`'s and `@branch/lambda-auth`'s `dist/`, so build those first (`.github/actions/build-shared-packages` discovers `shared/*/` and builds in `@branch`-dep order). See `apps/backend/lambdas/AGENTS.md`. ## Root commands diff --git a/apps/backend/AGENTS.md b/apps/backend/AGENTS.md index 367974e7..01e1c5ba 100644 --- a/apps/backend/AGENTS.md +++ b/apps/backend/AGENTS.md @@ -83,6 +83,8 @@ The 403 is intentionally identical whether or not the address exists, so registr This is the real control, not the Cognito pool config: `authenticateRequest` rejects any Cognito identity whose `sub` has no `branch.users` row, so a Cognito user created out of band is inert. Full flow: admin `POST /users` → invitee `POST /auth/register` with that email → `POST /auth/verify-email` with the emailed code → `POST /auth/login`. +**Staff accounts** (`users.is_staff`) are hidden developer/support logins that can only switch into other users, from the frontend's `/staff` console. They are created by `make create-staff EMAIL=… NAME=…` and by nothing else: the script runs `AdminCreateUser`, then inserts the row via `@branch/store`'s `createStaffUser`. Run it against production with the DSQL `DB_HOST`, the pool's `COGNITO_USER_POOL_ID`, and credentials for the client account. Sessions, and every write made during them, are in `branch.impersonation_sessions` / `branch.impersonation_actions`. + **Bootstrapping the first admin** is a manual SQL statement in every environment, because `is_admin` can only be set by an existing admin: `make grant-admin EMAIL=…` locally, or the equivalent `UPDATE` against the DSQL cluster in production. The auth lambda uses `USER_PASSWORD_AUTH` via the AWS SDK, not the SRP library. `POST /auth/login` returns either a token set or `{ ChallengeName, Session }`; `POST /auth/respond-challenge` completes it. Adding a challenge type is a row in `CHALLENGE_SPECS` — enabling MFA is a Terraform change, not a code change. diff --git a/apps/backend/Makefile b/apps/backend/Makefile index 8134e5de..3e907668 100644 --- a/apps/backend/Makefile +++ b/apps/backend/Makefile @@ -1,4 +1,4 @@ -.PHONY: up down logs build clean restart ps health migrate show-migrations new-migration seed types db-reset +.PHONY: up down logs build clean restart ps health migrate show-migrations new-migration seed types db-reset create-staff # Default environment file ENV_FILE ?= .env @@ -153,6 +153,14 @@ types: -e TYPES_OUT=/shared/types/db-types.d.ts \ migrator npm run --silent types +# usage: make create-staff EMAIL=dev@example.com NAME="Dev Name" +# +# Hidden staff account (see shared/rbac/README.md). Runs on the host against +# whatever COGNITO_USER_POOL_ID / DB_HOST / AWS credentials are exported. +create-staff: + @test -n "$(EMAIL)" -a -n "$(NAME)" || (echo 'usage: make create-staff EMAIL=dev@example.com NAME="Dev Name"' && exit 1) + @npm --prefix lambdas/users run --silent create-staff -- --email "$(EMAIL)" --name "$(NAME)" + # Rebuild schema "branch" from the migration files and reseed, in place. # Use `make down-v` if you need to destroy the volume itself. db-reset: @@ -173,6 +181,7 @@ help: @echo " make new-migration NAME= - Create a new empty migration file" @echo " make seed - Truncate every table and re-apply db/seed.sql" @echo " make types - Regenerate shared/types/db-types.d.ts" + @echo " make create-staff EMAIL= NAME= - Provision a hidden staff account" @echo " make db-reset - Rebuild schema from migrations + reseed (destroys data)" @echo "" @echo " Services:" diff --git a/apps/backend/lambdas/AGENTS.md b/apps/backend/lambdas/AGENTS.md index ecbcc731..6dcc52e8 100644 --- a/apps/backend/lambdas/AGENTS.md +++ b/apps/backend/lambdas/AGENTS.md @@ -54,7 +54,7 @@ export const getDonor: RouteHandler = async ({ params }) => { - **A caught error is an error Sentry cannot see.** The Sentry layer wraps the handler and records uncaught throws only, and we always catch so API Gateway returns a JSON 500 instead of a 502. `dispatch()` reports what reaches its catch; a controller that returns its own 500 must use `serverError(err, 'Failed to …')` from `@branch/lambda-http` rather than `console.error` + `json(500, …)`. Same status to the caller, one less invisible failure. - **NEVER remove or modify the `ROUTES-START` / `ROUTES-END` markers** — the CLI inserts new table entries between them. - Patterns are always full-prefixed (`/donors/:id`, never `/:id`) so one table works whether the event arrives via API Gateway's `{proxy+}` (full path) or the shared dev-server (prefix stripped) — `dispatch()` canonicalizes both to the prefixed form. -- Responses go through `json(status, body)` from `@branch/lambda-http`, which sets CORS headers (`Access-Control-Allow-Origin: *`, allowed headers `Content-Type,Authorization`). See `shared/lambda-http/README.md` for the full API (`parseBody`, `requirePermission`, `createAuthResolver`, `matchPattern`). +- Responses go through `json(status, body)` from `@branch/lambda-http`, which sets CORS headers (`Access-Control-Allow-Origin: *`, allowed headers `Content-Type,Authorization,X-Impersonate-Session`; keep `infrastructure/{aws,preview}/api_gateway.tf` in step, since API Gateway answers preflights itself). See `shared/lambda-http/README.md` for the full API (`parseBody`, `requirePermission`, `createAuthResolver`, `matchPattern`). ## Auth & authorization @@ -73,9 +73,16 @@ export async function authenticateRequest(event: any) { return _authenticateRequest(db, event); } export const resolveAuth = createAuthResolver(authenticateRequest, (ctx) => loadRbacSubject(db, ctx)); +export const onImpersonatedWrite = recordImpersonationAction; // from @branch/store ``` -`handler.ts` hands `resolveAuth` to `dispatch`, which calls it **once per request**. +`handler.ts` hands `resolveAuth` and `onImpersonatedWrite` to `dispatch`, which calls `resolveAuth` **once per request**. + +### Staff accounts are invisible + +`branch.users.is_staff` marks a hidden staff account (see `shared/rbac/README.md`). **Every query that returns users, counts them, or accepts a user id from a client must filter `.where('is_staff', 'is not', true)`**, and must never return the column. The column is nullable (DSQL cannot add it with a default) and NULL means "not staff", so `= false` would hide every user who predates it. A staff id answers exactly like a missing one (404, "Unknown user ids"). Today that is `users/controllers/users.ts`, `projects/controllers/members.ts` and `projects/services/projects.ts`; staff never author rows, because while impersonating they write as the target. + +A route that acts on the caller's own Cognito session (MFA, today) must declare `impersonation: 'blocked'`: while impersonating, that session is the staff account's. ### Two layers, and which one to use diff --git a/apps/backend/lambdas/auth/auth.ts b/apps/backend/lambdas/auth/auth.ts index d5f3b4c8..37611488 100644 --- a/apps/backend/lambdas/auth/auth.ts +++ b/apps/backend/lambdas/auth/auth.ts @@ -1,6 +1,6 @@ import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth'; import { createAuthResolver } from '@branch/lambda-http'; -import { db } from '@branch/store'; +import { db, recordImpersonationAction } from '@branch/store'; export * from '@branch/lambda-auth'; @@ -17,3 +17,6 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +/** Audit row per write made while a staff account is impersonating. */ +export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/auth/controllers/auth.ts b/apps/backend/lambdas/auth/controllers/auth.ts index cd6267c3..b8bca253 100644 --- a/apps/backend/lambdas/auth/controllers/auth.ts +++ b/apps/backend/lambdas/auth/controllers/auth.ts @@ -218,7 +218,10 @@ export const handleMe: RouteHandler = async ({ auth }) => { email: me.email, name: me.name, isAdmin: me.isAdmin, + isStaff: me.isStaff, profileImage: await resolveProfileImage(me.profileImage), + // Set while a staff account is switched in; the banner reads it. + impersonation: auth.context.user?.impersonator ?? null, // The RBAC subject travels with identity so the browser evaluates the same // policy against the same facts the lambdas used. Without it the frontend // would have to re-derive "is a director" and "which projects am I on" diff --git a/apps/backend/lambdas/auth/controllers/impersonation.ts b/apps/backend/lambdas/auth/controllers/impersonation.ts new file mode 100644 index 00000000..0a2ae4b1 --- /dev/null +++ b/apps/backend/lambdas/auth/controllers/impersonation.ts @@ -0,0 +1,110 @@ +import { json, parseBody } from '@branch/lambda-http'; +import type { RouteHandler } from '@branch/lambda-http'; +import { DIRECTOR_ROLES } from '@branch/lambda-auth'; +import type { ImpersonationMode } from '@branch/lambda-auth'; +import { db, endImpersonationSession, startImpersonationSession } from '@branch/store'; + +/** How long one switch-in lasts before the staff console has to start another. */ +export const SESSION_TTL_MS = 60 * 60 * 1000; + +const MODES: readonly ImpersonationMode[] = ['read_only', 'full']; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const TARGET_LIMIT = 200; + +/** GET /auth/impersonation/targets?search= -- everyone a staff account may switch into. */ +export const handleListTargets: RouteHandler = async ({ event }) => { + const search = String(event.queryStringParameters?.search ?? '').trim(); + + let query = db + .selectFrom('branch.users') + .where('is_staff', 'is not', true) + .select(['user_id', 'name', 'email', 'is_admin', 'cognito_sub']) + .orderBy('name') + .limit(TARGET_LIMIT); + if (search) { + const pattern = `%${search.replace(/[\\%_]/g, (c) => `\\${c}`)}%`; + query = query.where((eb) => + eb.or([eb('name', 'ilike', pattern), eb('email', 'ilike', pattern)]), + ); + } + const users = await query.execute(); + + const ids = users.map((u) => u.user_id); + const memberships = ids.length + ? await db + .selectFrom('branch.project_memberships') + .where('user_id', 'in', ids) + .select(['user_id', 'role']) + .execute() + : []; + + const counts = new Map(); + for (const m of memberships) { + const c = counts.get(m.user_id) ?? { directs: 0, member: 0 }; + c.member += 1; + if ((DIRECTOR_ROLES as readonly string[]).includes(m.role)) c.directs += 1; + counts.set(m.user_id, c); + } + + return json(200, { + users: users.map((u) => ({ + userId: u.user_id, + name: u.name, + email: u.email, + isAdmin: u.is_admin === true, + // Never signed in: their account exists but nothing they see is real yet. + pending: u.cognito_sub === null, + directorProjectCount: counts.get(u.user_id)?.directs ?? 0, + memberProjectCount: counts.get(u.user_id)?.member ?? 0, + })), + }); +}; + +/** POST /auth/impersonation { targetUserId, mode } -- start a switch-in. */ +export const handleStartImpersonation: RouteHandler = async ({ event, auth }) => { + const body = parseBody(event); + const targetUserId = Number(body?.targetUserId); + const mode = body?.mode as ImpersonationMode; + if (!Number.isInteger(targetUserId) || !MODES.includes(mode)) { + return json(400, { message: "targetUserId and mode ('read_only' | 'full') are required" }); + } + + const target = await db + .selectFrom('branch.users') + .where('user_id', '=', targetUserId) + .where('is_staff', 'is not', true) + .select(['user_id', 'name', 'email']) + .executeTakeFirst(); + // 404 for a staff target too: the console must not confirm one exists. + if (!target) return json(404, { message: 'User not found' }); + + const startedAt = new Date(); + const expiresAt = new Date(startedAt.getTime() + SESSION_TTL_MS); + const sessionId = await startImpersonationSession({ + staffUserId: auth.subject.userId!, + targetUserId: target.user_id, + mode, + startedAt, + expiresAt, + }); + + return json(201, { + sessionId, + mode, + expiresAt: expiresAt.toISOString(), + target: { userId: target.user_id, name: target.name, email: target.email }, + }); +}; + +/** + * DELETE /auth/impersonation/:sessionId -- end a switch-in. Called as the staff + * account itself, without the impersonation header, so a read-only session can + * always be left. Idempotent. + */ +export const handleEndImpersonation: RouteHandler = async ({ params, auth }) => { + if (!UUID.test(params.sessionId)) return json(404, { message: 'Session not found' }); + + await endImpersonationSession(params.sessionId, auth.subject.userId!); + + return json(200, { ended: true }); +}; diff --git a/apps/backend/lambdas/auth/handler.ts b/apps/backend/lambdas/auth/handler.ts index 0ff9f22a..8918ec3d 100644 --- a/apps/backend/lambdas/auth/handler.ts +++ b/apps/backend/lambdas/auth/handler.ts @@ -1,6 +1,6 @@ import { dispatch } from '@branch/lambda-http'; -import { resolveAuth } from './auth'; +import { onImpersonatedWrite, resolveAuth } from './auth'; import { routes } from './routes'; export const handler = (event: any) => - dispatch(event, { prefix: 'auth', routes, resolveAuth }); + dispatch(event, { prefix: 'auth', routes, resolveAuth, onImpersonatedWrite }); diff --git a/apps/backend/lambdas/auth/openapi.yaml b/apps/backend/lambdas/auth/openapi.yaml index 722a6970..a44e41a7 100644 --- a/apps/backend/lambdas/auth/openapi.yaml +++ b/apps/backend/lambdas/auth/openapi.yaml @@ -335,11 +335,35 @@ paths: type: string isAdmin: type: boolean + isStaff: + type: boolean + description: A staff account acting as itself; false while impersonating profileImage: type: string nullable: true + impersonation: + type: object + nullable: true + description: Set while a staff account is switched into this user + properties: + userId: + type: integer + name: + type: string + email: + type: string + sessionId: + type: string + mode: + type: string + enum: [read_only, full] + expiresAt: + type: string + format: date-time '401': - description: Authentication required + description: Authentication required, or IMPERSONATION_EXPIRED + '403': + description: IMPERSONATION_FORBIDDEN (the header from a non-staff caller) /auth/verify-email: post: @@ -616,6 +640,125 @@ paths: '401': description: Missing Authorization header, or invalid/expired token + /auth/impersonation/targets: + get: + summary: Staff only. Every non-staff user a staff account may switch into + security: + - bearerAuth: [] + parameters: + - name: search + in: query + required: false + schema: + type: string + description: Case-insensitive match on name or email + responses: + '200': + description: Up to 200 users, ordered by name + content: + application/json: + schema: + type: object + properties: + users: + type: array + items: + type: object + properties: + userId: + type: integer + name: + type: string + email: + type: string + isAdmin: + type: boolean + pending: + type: boolean + description: Invited but never signed in + directorProjectCount: + type: integer + memberProjectCount: + type: integer + '403': + description: Caller is not a staff account, or is impersonating + + /auth/impersonation: + post: + summary: Staff only. Start a session acting as another user + description: > + Send the returned sessionId as the X-Impersonate-Session header, beside the + staff account's own Bearer token, on every request made as the target. + Sessions last one hour. Read-only sessions refuse every non-GET request; + every non-GET request in either mode is recorded in + branch.impersonation_actions. + security: + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [targetUserId, mode] + properties: + targetUserId: + type: integer + mode: + type: string + enum: [read_only, full] + responses: + '201': + description: Session started + content: + application/json: + schema: + type: object + properties: + sessionId: + type: string + format: uuid + mode: + type: string + enum: [read_only, full] + expiresAt: + type: string + format: date-time + target: + type: object + properties: + userId: + type: integer + name: + type: string + email: + type: string + '400': + description: Missing or invalid targetUserId or mode + '403': + description: Caller is not a staff account, or is impersonating + '404': + description: No such user (also returned for a staff target) + + /auth/impersonation/{sessionId}: + delete: + summary: Staff only. End one of the caller's own sessions + description: Call without X-Impersonate-Session, as the staff account itself. Idempotent. + security: + - bearerAuth: [] + parameters: + - name: sessionId + in: path + required: true + schema: + type: string + format: uuid + responses: + '200': + description: Session ended (or was already ended) + '404': + description: sessionId is not a UUID + components: securitySchemes: bearerAuth: diff --git a/apps/backend/lambdas/auth/routes.ts b/apps/backend/lambdas/auth/routes.ts index cc1f2bdc..b18dc031 100644 --- a/apps/backend/lambdas/auth/routes.ts +++ b/apps/backend/lambdas/auth/routes.ts @@ -14,6 +14,11 @@ import { handleMfaDisable, handleMfaStatus, } from './controllers/mfa'; +import { + handleListTargets, + handleStartImpersonation, + handleEndImpersonation, +} from './controllers/impersonation'; /** * The only service with `access: 'public'` routes — everything a caller needs @@ -37,9 +42,14 @@ export const routes: Route[] = [ { method: 'POST', pattern: '/auth/logout', access: 'public', handler: ({ event }) => handleLogout(event) }, { method: 'POST', pattern: '/auth/forgot-password', access: 'public', handler: ({ event }) => handleForgotPassword(event) }, { method: 'POST', pattern: '/auth/reset-password', access: 'public', handler: ({ event }) => handleResetPassword(event) }, - { method: 'POST', pattern: '/auth/mfa-setup', access: 'authenticated', handler: handleMfaSetup }, - { method: 'POST', pattern: '/auth/mfa-verify', access: 'authenticated', handler: handleMfaVerify }, - { method: 'POST', pattern: '/auth/mfa-disable', access: 'authenticated', handler: handleMfaDisable }, - { method: 'GET', pattern: '/auth/mfa-status', access: 'authenticated', handler: handleMfaStatus }, + { method: 'POST', pattern: '/auth/mfa-setup', access: 'authenticated', impersonation: 'blocked', handler: handleMfaSetup }, + { method: 'POST', pattern: '/auth/mfa-verify', access: 'authenticated', impersonation: 'blocked', handler: handleMfaVerify }, + { method: 'POST', pattern: '/auth/mfa-disable', access: 'authenticated', impersonation: 'blocked', handler: handleMfaDisable }, + { method: 'GET', pattern: '/auth/mfa-status', access: 'authenticated', impersonation: 'blocked', handler: handleMfaStatus }, + // Staff console. MFA above is blocked while impersonating: it acts on the + // caller's Cognito session, which is then the staff account's. + { method: 'GET', pattern: '/auth/impersonation/targets', permission: 'impersonation:console', handler: handleListTargets }, + { method: 'POST', pattern: '/auth/impersonation', permission: 'impersonation:start', handler: handleStartImpersonation }, + { method: 'DELETE', pattern: '/auth/impersonation/:sessionId', permission: 'impersonation:start', handler: handleEndImpersonation }, // <<< ROUTES-END ]; diff --git a/apps/backend/lambdas/auth/test/auth.login.unit.test.ts b/apps/backend/lambdas/auth/test/auth.login.unit.test.ts index c1eb98c4..4e8fcb5e 100644 --- a/apps/backend/lambdas/auth/test/auth.login.unit.test.ts +++ b/apps/backend/lambdas/auth/test/auth.login.unit.test.ts @@ -442,6 +442,7 @@ describe('GET /me', () => { email: 'a@b.com', name: 'Ada', isAdmin: true, + isStaff: false, profileImage: 'https://s3/pic.png', }, }, @@ -456,7 +457,9 @@ describe('GET /me', () => { email: 'a@b.com', name: 'Ada', isAdmin: true, + isStaff: false, profileImage: 'https://s3/pic.png', + impersonation: null, // The authorization subject rides along with identity so the browser can // evaluate @branch/rbac without a second round trip. rbac: mockSubject, diff --git a/apps/backend/lambdas/auth/test/impersonation.e2e.test.ts b/apps/backend/lambdas/auth/test/impersonation.e2e.test.ts new file mode 100644 index 00000000..25122da2 --- /dev/null +++ b/apps/backend/lambdas/auth/test/impersonation.e2e.test.ts @@ -0,0 +1,179 @@ +// Real authenticateRequest, real dispatch, real DB: only the JWT signature check +// is faked, and the token is simply the caller's Cognito sub. Mocked by the path +// @branch/lambda-auth resolves it from, which is its own node_modules, not ours. +jest.mock(require.resolve('aws-jwt-verify', { paths: [require.resolve('@branch/lambda-auth')] }), () => ({ + CognitoJwtVerifier: { + create: () => ({ verify: async (token: string) => ({ sub: token }) }), + }, +})); + +import { Pool } from 'pg'; +import { ensureSchema, resetData } from '../../../db/testkit'; +import { closeConnection } from '@branch/store'; +import { handler } from '../handler'; + +const pool = new Pool({ + host: 'localhost', + port: Number(process.env.DB_PORT ?? 5432), + user: 'branch_dev', + password: 'password', + database: 'branch_db', + ssl: false, +}); + +// Seed user 4 directs project 1; user 6 is a student on project 2. +const TARGET = 4; + +beforeAll(async () => { + process.env.COGNITO_USER_POOL_ID = 'us-east-2_test'; + process.env.COGNITO_CLIENT_ID = 'client'; + const client = await pool.connect(); + try { + await ensureSchema(client); + } finally { + client.release(); + } +}); + +beforeEach(async () => { + const client = await pool.connect(); + try { + await resetData(client); + await client.query( + `INSERT INTO branch.users (cognito_sub, name, email, is_admin, is_staff) + VALUES ('staff-sub', 'Hidden Staff', 'staff@branch.org', false, true)`, + ); + await client.query(`UPDATE branch.users SET cognito_sub = 'sam-sub' WHERE user_id = 6`); + } finally { + client.release(); + } +}); + +afterAll(async () => { + await pool.end(); + await closeConnection(); +}); + +function call( + method: string, + path: string, + { as = 'staff-sub', session, body }: { as?: string; session?: string; body?: unknown } = {}, +) { + const headers: Record = { authorization: `Bearer ${as}` }; + if (session) headers['x-impersonate-session'] = session; + return handler({ + rawPath: path, + requestContext: { http: { method } }, + headers, + body: body === undefined ? null : JSON.stringify(body), + }).then((res) => ({ status: res.statusCode, body: JSON.parse(res.body) })); +} + +async function start(mode: 'read_only' | 'full', targetUserId = TARGET): Promise { + const res = await call('POST', '/auth/impersonation', { body: { targetUserId, mode } }); + expect(res.status).toBe(201); + return res.body.sessionId; +} + +test('a staff account on its own sees only the console', async () => { + const me = await call('GET', '/auth/me'); + expect(me.body).toMatchObject({ isStaff: true, impersonation: null, rbac: { isStaff: true } }); + + const targets = await call('GET', '/auth/impersonation/targets'); + expect(targets.status).toBe(200); + const emails = targets.body.users.map((u: any) => u.email); + expect(emails).toContain('sam@branch.org'); + expect(emails).not.toContain('staff@branch.org'); + expect(targets.body.users.find((u: any) => u.userId === TARGET)).toMatchObject({ + directorProjectCount: 1, + memberProjectCount: 1, + }); +}); + +test('nobody but staff can open the console or start a session', async () => { + expect((await call('GET', '/auth/impersonation/targets', { as: 'sam-sub' })).status).toBe(403); + const res = await call('POST', '/auth/impersonation', { + as: 'sam-sub', + body: { targetUserId: TARGET, mode: 'full' }, + }); + expect(res.status).toBe(403); +}); + +test('a staff account cannot be a target, and the answer does not say it exists', async () => { + const { rows } = await pool.query(`SELECT user_id FROM branch.users WHERE is_staff`); + const res = await call('POST', '/auth/impersonation', { + body: { targetUserId: rows[0].user_id, mode: 'read_only' }, + }); + expect(res.status).toBe(404); +}); + +test('read-only: acts as the target, refuses writes, and ends cleanly', async () => { + const session = await start('read_only'); + + const me = await call('GET', '/auth/me', { session }); + expect(me.body).toMatchObject({ + userId: TARGET, + isStaff: false, + rbac: { userId: TARGET, isStaff: false, directorProjectIds: [1] }, + impersonation: { sessionId: session, mode: 'read_only', name: 'Hidden Staff' }, + }); + + const write = await call('POST', '/auth/impersonation', { + session, + body: { targetUserId: 5, mode: 'full' }, + }); + expect(write).toMatchObject({ status: 403, body: { message: 'Read-only impersonation' } }); + const audited = await pool.query( + 'SELECT status_code FROM branch.impersonation_actions WHERE session_id = $1', + [session], + ); + expect(audited.rows).toEqual([{ status_code: 403 }]); + + expect((await call('DELETE', `/auth/impersonation/${session}`)).status).toBe(200); + const after = await call('GET', '/auth/me', { session }); + expect(after).toMatchObject({ status: 401, body: { code: 'IMPERSONATION_EXPIRED' } }); +}); + +test('full: cannot chain a switch, and every write is audited with its outcome', async () => { + const session = await start('full'); + + const chained = await call('POST', '/auth/impersonation', { + session, + body: { targetUserId: 5, mode: 'full' }, + }); + expect(chained.status).toBe(403); + + const mfa = await call('POST', '/auth/mfa-setup', { session }); + expect(mfa).toMatchObject({ status: 403, body: { message: 'Not available while impersonating' } }); + + const { rows } = await pool.query( + `SELECT method, path, status_code FROM branch.impersonation_actions + WHERE session_id = $1 ORDER BY created_at`, + [session], + ); + // Refused attempts are part of the trail, not just writes that landed. + expect(rows).toEqual([ + { method: 'POST', path: '/auth/impersonation', status_code: 403 }, + { method: 'POST', path: '/auth/mfa-setup', status_code: 403 }, + ]); +}); + +test("a staff account cannot use or end another staff account's session", async () => { + const session = await start('full'); + await pool.query( + `INSERT INTO branch.users (cognito_sub, name, email, is_admin, is_staff) + VALUES ('staff-2', 'Other Staff', 'staff2@branch.org', false, true)`, + ); + + const borrowed = await call('GET', '/auth/me', { as: 'staff-2', session }); + expect(borrowed).toMatchObject({ status: 401, body: { code: 'IMPERSONATION_EXPIRED' } }); + + await call('DELETE', `/auth/impersonation/${session}`, { as: 'staff-2' }); + expect((await call('GET', '/auth/me', { session })).body.userId).toBe(TARGET); +}); + +test('the header from a non-staff caller is refused, not ignored', async () => { + const session = await start('full'); + const res = await call('GET', '/auth/me', { as: 'sam-sub', session }); + expect(res).toMatchObject({ status: 403, body: { code: 'IMPERSONATION_FORBIDDEN' } }); +}); diff --git a/apps/backend/lambdas/donors/auth.ts b/apps/backend/lambdas/donors/auth.ts index d5f3b4c8..37611488 100644 --- a/apps/backend/lambdas/donors/auth.ts +++ b/apps/backend/lambdas/donors/auth.ts @@ -1,6 +1,6 @@ import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth'; import { createAuthResolver } from '@branch/lambda-http'; -import { db } from '@branch/store'; +import { db, recordImpersonationAction } from '@branch/store'; export * from '@branch/lambda-auth'; @@ -17,3 +17,6 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +/** Audit row per write made while a staff account is impersonating. */ +export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/donors/handler.ts b/apps/backend/lambdas/donors/handler.ts index 7eb83925..5b47cf7c 100644 --- a/apps/backend/lambdas/donors/handler.ts +++ b/apps/backend/lambdas/donors/handler.ts @@ -1,6 +1,6 @@ import { dispatch } from '@branch/lambda-http'; -import { resolveAuth } from './auth'; +import { onImpersonatedWrite, resolveAuth } from './auth'; import { routes } from './routes'; export const handler = (event: any) => - dispatch(event, { prefix: 'donors', routes, resolveAuth }); + dispatch(event, { prefix: 'donors', routes, resolveAuth, onImpersonatedWrite }); diff --git a/apps/backend/lambdas/expenditures/auth.ts b/apps/backend/lambdas/expenditures/auth.ts index d5f3b4c8..37611488 100644 --- a/apps/backend/lambdas/expenditures/auth.ts +++ b/apps/backend/lambdas/expenditures/auth.ts @@ -1,6 +1,6 @@ import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth'; import { createAuthResolver } from '@branch/lambda-http'; -import { db } from '@branch/store'; +import { db, recordImpersonationAction } from '@branch/store'; export * from '@branch/lambda-auth'; @@ -17,3 +17,6 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +/** Audit row per write made while a staff account is impersonating. */ +export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/expenditures/handler.ts b/apps/backend/lambdas/expenditures/handler.ts index 1d933824..0002312d 100644 --- a/apps/backend/lambdas/expenditures/handler.ts +++ b/apps/backend/lambdas/expenditures/handler.ts @@ -1,6 +1,6 @@ import { dispatch } from '@branch/lambda-http'; -import { resolveAuth } from './auth'; +import { onImpersonatedWrite, resolveAuth } from './auth'; import { routes } from './routes'; export const handler = (event: any) => - dispatch(event, { prefix: 'expenditures', routes, resolveAuth }); \ No newline at end of file + dispatch(event, { prefix: 'expenditures', routes, resolveAuth, onImpersonatedWrite }); \ No newline at end of file diff --git a/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts b/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts index 39e55f78..107b56a3 100644 --- a/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts +++ b/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts @@ -447,7 +447,7 @@ describe('POST /expenditures unit tests', () => { expect(res.headers?.['Content-Type']).toBe('application/json'); expect(res.headers?.['Access-Control-Allow-Origin']).toBe('*'); - expect(res.headers?.['Access-Control-Allow-Headers']).toBe('Content-Type,Authorization'); + expect(res.headers?.['Access-Control-Allow-Headers']).toBe('Content-Type,Authorization,X-Impersonate-Session'); expect(res.headers?.['Access-Control-Allow-Methods']).toContain('POST'); }); }); diff --git a/apps/backend/lambdas/projects/auth.ts b/apps/backend/lambdas/projects/auth.ts index d5f3b4c8..37611488 100644 --- a/apps/backend/lambdas/projects/auth.ts +++ b/apps/backend/lambdas/projects/auth.ts @@ -1,6 +1,6 @@ import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth'; import { createAuthResolver } from '@branch/lambda-http'; -import { db } from '@branch/store'; +import { db, recordImpersonationAction } from '@branch/store'; export * from '@branch/lambda-auth'; @@ -17,3 +17,6 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +/** Audit row per write made while a staff account is impersonating. */ +export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/projects/controllers/members.ts b/apps/backend/lambdas/projects/controllers/members.ts index 06b10c1d..b803aba3 100644 --- a/apps/backend/lambdas/projects/controllers/members.ts +++ b/apps/backend/lambdas/projects/controllers/members.ts @@ -30,6 +30,7 @@ export const getAssignableStaff: RouteHandler = async () => { .selectFrom('branch.users') .select(['user_id', 'name', 'email', 'profile_image']) .where('is_admin', 'is not', true) + .where('is_staff', 'is not', true) .orderBy('name', 'asc') .execute(); return json(200, { staff }); diff --git a/apps/backend/lambdas/projects/handler.ts b/apps/backend/lambdas/projects/handler.ts index 5ac4f62e..239e27fe 100644 --- a/apps/backend/lambdas/projects/handler.ts +++ b/apps/backend/lambdas/projects/handler.ts @@ -1,6 +1,6 @@ import { dispatch } from '@branch/lambda-http'; -import { resolveAuth } from './auth'; +import { onImpersonatedWrite, resolveAuth } from './auth'; import { routes } from './routes'; export const handler = (event: any) => - dispatch(event, { prefix: 'projects', routes, resolveAuth }); + dispatch(event, { prefix: 'projects', routes, resolveAuth, onImpersonatedWrite }); diff --git a/apps/backend/lambdas/projects/services/projects.ts b/apps/backend/lambdas/projects/services/projects.ts index ca2c30db..4d7ecdd2 100644 --- a/apps/backend/lambdas/projects/services/projects.ts +++ b/apps/backend/lambdas/projects/services/projects.ts @@ -155,6 +155,7 @@ export async function listRoster(projectId: number): Promise { .selectFrom('branch.users') .select(['user_id', 'name', 'email', 'profile_image']) .where('is_admin', 'is', true) + .where('is_staff', 'is not', true) .orderBy('name', 'asc') .execute(), db @@ -185,6 +186,7 @@ export async function loadAdminHeadcount(projectIds: number[]): Promise<{ .selectFrom('branch.users') .select((eb) => eb.fn.countAll().as('count')) .where('is_admin', 'is', true) + .where('is_staff', 'is not', true) .executeTakeFirst(), projectIds.length === 0 ? Promise.resolve([]) @@ -222,7 +224,11 @@ export async function findAdminUserIds(members: MemberAssignment[]): Promise row.user_id); } -/** Rejects member ids that are not real users, so FK errors never reach the client as a 500. */ +/** + * Rejects member ids that are not real users, so FK errors never reach the + * client as a 500. A staff account counts as unknown: it can never hold a + * membership, and the error must not confirm one exists. + */ export async function findUnknownUserIds(members: MemberAssignment[]): Promise { if (members.length === 0) return []; const ids = members.map((m) => m.user_id); @@ -230,6 +236,7 @@ export async function findUnknownUserIds(members: MemberAssignment[]): Promise r.user_id)); return ids.filter((id) => !known.has(id)); diff --git a/apps/backend/lambdas/projects/test/project-page.unit.test.ts b/apps/backend/lambdas/projects/test/project-page.unit.test.ts index 9f380c31..d6f6abfa 100644 --- a/apps/backend/lambdas/projects/test/project-page.unit.test.ts +++ b/apps/backend/lambdas/projects/test/project-page.unit.test.ts @@ -39,7 +39,7 @@ const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction< const pool = new Pool({ host: 'localhost', - port: 5432, + port: Number(process.env.DB_PORT ?? 5432), user: 'branch_dev', password: 'password', database: 'branch_db', @@ -109,6 +109,22 @@ test('/projects/assignable-staff is not parsed as a project id', async () => { expect(Object.keys(staff[0]).sort()).toEqual(['email', 'name', 'profile_image', 'user_id']); }); +test('a staff account is neither assignable nor accepted as a member', async () => { + const { rows } = await pool.query( + `INSERT INTO branch.users (cognito_sub, name, email, is_admin, is_staff) + VALUES ('staff-sub', 'Hidden Staff', 'staff@branch.org', false, true) + RETURNING user_id`, + ); + const staffId: number = rows[0].user_id; + + const { staff } = parse(await handler(event('/assignable-staff', 'GET'))); + expect(staff.map((s: { user_id: number }) => s.user_id)).not.toContain(staffId); + + const res = await handler(event('/', 'POST', { name: 'Leak', total_budget: 1, members: [staffId] })); + expect(res.statusCode).toBe(400); + expect(parse(res).message).toBe(`Unknown user ids: ${staffId}`); +}); + test('/projects/dashboard is not parsed as a project id', async () => { const res = await handler(event('/dashboard', 'GET')); expect(res.statusCode).toBe(200); diff --git a/apps/backend/lambdas/reports/auth.ts b/apps/backend/lambdas/reports/auth.ts index d5f3b4c8..37611488 100644 --- a/apps/backend/lambdas/reports/auth.ts +++ b/apps/backend/lambdas/reports/auth.ts @@ -1,6 +1,6 @@ import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth'; import { createAuthResolver } from '@branch/lambda-http'; -import { db } from '@branch/store'; +import { db, recordImpersonationAction } from '@branch/store'; export * from '@branch/lambda-auth'; @@ -17,3 +17,6 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +/** Audit row per write made while a staff account is impersonating. */ +export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/reports/handler.ts b/apps/backend/lambdas/reports/handler.ts index 160c9d75..c5628074 100644 --- a/apps/backend/lambdas/reports/handler.ts +++ b/apps/backend/lambdas/reports/handler.ts @@ -1,6 +1,6 @@ import { dispatch } from '@branch/lambda-http'; -import { resolveAuth } from './auth'; +import { onImpersonatedWrite, resolveAuth } from './auth'; import { routes } from './routes'; export const handler = (event: any) => - dispatch(event, { prefix: 'reports', routes, resolveAuth }); + dispatch(event, { prefix: 'reports', routes, resolveAuth, onImpersonatedWrite }); diff --git a/apps/backend/lambdas/users/auth.ts b/apps/backend/lambdas/users/auth.ts index d5f3b4c8..37611488 100644 --- a/apps/backend/lambdas/users/auth.ts +++ b/apps/backend/lambdas/users/auth.ts @@ -1,6 +1,6 @@ import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth'; import { createAuthResolver } from '@branch/lambda-http'; -import { db } from '@branch/store'; +import { db, recordImpersonationAction } from '@branch/store'; export * from '@branch/lambda-auth'; @@ -17,3 +17,6 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +/** Audit row per write made while a staff account is impersonating. */ +export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/users/controllers/users.ts b/apps/backend/lambdas/users/controllers/users.ts index be06bbb0..a7840f54 100644 --- a/apps/backend/lambdas/users/controllers/users.ts +++ b/apps/backend/lambdas/users/controllers/users.ts @@ -21,6 +21,18 @@ const cognitoClient = new CognitoIdentityProviderClient({ const USER_POOL_ID = process.env.COGNITO_USER_POOL_ID || ''; +// Staff accounts are invisible here: every read filters them out and the column +// itself is never returned. A staff id answers 404, exactly like a missing one. +const USER_COLUMNS = [ + 'user_id', + 'cognito_sub', + 'name', + 'email', + 'is_admin', + 'created_at', + 'profile_image', +] as const; + // Authentication and each route's declared permission are enforced by dispatch // before these run -- see routes.ts. The two self-service routes below are the // exception: `profile:view` / `profile:update` need the target user id, so they @@ -51,10 +63,15 @@ export const listUsers: RouteHandler = async ({ event }) => { // The count does not depend on the page, so both go out at once. const [totalCount, users] = await Promise.all([ - db.selectFrom('branch.users').select(db.fn.count('user_id').as('count')).executeTakeFirst(), db .selectFrom('branch.users') - .selectAll() + .where('is_staff', 'is not', true) + .select(db.fn.count('user_id').as('count')) + .executeTakeFirst(), + db + .selectFrom('branch.users') + .where('is_staff', 'is not', true) + .select(USER_COLUMNS) .orderBy('user_id', 'asc') .limit(limit) .offset(offset) @@ -76,7 +93,8 @@ export const listUsers: RouteHandler = async ({ event }) => { const users = await db .selectFrom('branch.users') - .selectAll() + .where('is_staff', 'is not', true) + .select(USER_COLUMNS) .execute(); return json(200, { users: await withResolvedPhotos(users) }); @@ -89,7 +107,12 @@ export const getUser: RouteHandler = async ({ params, auth }) => { const denied = requirePermission(auth.subject, 'profile:view', { userId: Number(userId) }); if (denied) return denied; - const user = await db.selectFrom("branch.users").where("user_id", "=", Number(userId)).selectAll().executeTakeFirst(); + const user = await db + .selectFrom('branch.users') + .where('user_id', '=', Number(userId)) + .where('is_staff', 'is not', true) + .select(USER_COLUMNS) + .executeTakeFirst(); if (!user) return json(404, { message: 'User not found' }); return json(200, { @@ -214,7 +237,12 @@ export const deleteUser: RouteHandler = async ({ params }) => { const userId = params.userId; if (!/^\d+$/.test(userId)) return json(400, { message: 'userId must be a positive integer' }); - const user = await db.selectFrom('branch.users').where('user_id', '=', Number(userId)).select('email').executeTakeFirst(); + const user = await db + .selectFrom('branch.users') + .where('user_id', '=', Number(userId)) + .where('is_staff', 'is not', true) + .select('email') + .executeTakeFirst(); if (!user) return json(404, { message: 'User not found' }); const deleted = await removeUser(Number(userId)); diff --git a/apps/backend/lambdas/users/handler.ts b/apps/backend/lambdas/users/handler.ts index 0f8204f7..ee5b3215 100644 --- a/apps/backend/lambdas/users/handler.ts +++ b/apps/backend/lambdas/users/handler.ts @@ -1,6 +1,6 @@ import { dispatch } from '@branch/lambda-http'; -import { resolveAuth } from './auth'; +import { onImpersonatedWrite, resolveAuth } from './auth'; import { routes } from './routes'; export const handler = (event: any) => - dispatch(event, { prefix: 'users', routes, resolveAuth }); + dispatch(event, { prefix: 'users', routes, resolveAuth, onImpersonatedWrite }); diff --git a/apps/backend/lambdas/users/package.json b/apps/backend/lambdas/users/package.json index 2aaf82f3..bf9cfcdb 100644 --- a/apps/backend/lambdas/users/package.json +++ b/apps/backend/lambdas/users/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "ts-node --transpile-only dev-server.ts", "build": "tsc", + "create-staff": "ts-node --transpile-only scripts/create-staff-account.ts", "test": "start-server-and-test dev http-get://localhost:3000/users/health jest", "package": "esbuild handler.ts --bundle --platform=node --target=node20 --minify '--external:@aws-sdk/*' --external:@sentry/aws-serverless --outfile=dist/handler.js && cd dist && zip -q ../lambda.zip handler.js" }, diff --git a/apps/backend/lambdas/users/scripts/create-staff-account.ts b/apps/backend/lambdas/users/scripts/create-staff-account.ts new file mode 100644 index 00000000..0dde62d2 --- /dev/null +++ b/apps/backend/lambdas/users/scripts/create-staff-account.ts @@ -0,0 +1,68 @@ +/** + * Provision a hidden staff account. The only way one is ever created: no route + * can set users.is_staff. + * + * COGNITO_USER_POOL_ID=... DB_HOST=... \ + * npm run create-staff -- --email dev@example.com --name "Dev Name" + * + * Mirrors POST /users: AdminCreateUser mails the invite with a temp password, + * then the row is inserted with that sub; a failed insert deletes the Cognito + * user again. Against production, DB_HOST is the DSQL endpoint and the caller's + * AWS credentials mint the IAM token. + */ +import { + AdminCreateUserCommand, + AdminDeleteUserCommand, + CognitoIdentityProviderClient, +} from '@aws-sdk/client-cognito-identity-provider'; +import { closeConnection, createStaffUser } from '@branch/store'; +import { UserValidationUtils } from '../validation-utils'; + +function arg(name: string): string | undefined { + const i = process.argv.indexOf(`--${name}`); + return i === -1 ? undefined : process.argv[i + 1]; +} + +async function main(): Promise { + const userPoolId = process.env.COGNITO_USER_POOL_ID; + const email = UserValidationUtils.validateEmail(arg('email')); + const name = UserValidationUtils.validateName(arg('name')); + if (!userPoolId || !email.isValid || !email.value || !name.isValid || !name.value) { + throw new Error( + 'usage: COGNITO_USER_POOL_ID=... npm run create-staff -- --email --name ', + ); + } + + const cognito = new CognitoIdentityProviderClient({ + region: process.env.AWS_REGION || 'us-east-2', + }); + const created = await cognito.send( + new AdminCreateUserCommand({ + UserPoolId: userPoolId, + Username: email.value, + DesiredDeliveryMediums: ['EMAIL'], + UserAttributes: [ + { Name: 'email', Value: email.value }, + { Name: 'email_verified', Value: 'true' }, + { Name: 'name', Value: name.value }, + ], + }), + ); + const sub = created.User?.Attributes?.find((a) => a.Name === 'sub')?.Value; + if (!sub) throw new Error('AdminCreateUser returned no sub'); + + try { + const userId = await createStaffUser({ cognitoSub: sub, email: email.value, name: name.value }); + console.log(`staff account ${userId} created for ${email.value}; invite sent`); + } catch (err) { + await cognito.send(new AdminDeleteUserCommand({ UserPoolId: userPoolId, Username: email.value })); + throw err; + } +} + +main() + .catch((err) => { + console.error(err instanceof Error ? err.message : err); + process.exitCode = 1; + }) + .finally(() => closeConnection()); diff --git a/apps/backend/lambdas/users/test/user.photos.unit.test.ts b/apps/backend/lambdas/users/test/user.photos.unit.test.ts index 8a8b2885..bbec16f8 100644 --- a/apps/backend/lambdas/users/test/user.photos.unit.test.ts +++ b/apps/backend/lambdas/users/test/user.photos.unit.test.ts @@ -59,14 +59,19 @@ function mockSelfAuth(userId = 1) { } as any); } +/** Any where/select chain ending in executeTakeFirst, whatever its length. */ +function selectChain(row: unknown) { + const chain: any = { + where: jest.fn(() => chain), + select: jest.fn(() => chain), + selectAll: jest.fn(() => chain), + executeTakeFirst: (jest.fn() as any).mockResolvedValue(row), + }; + return chain; +} + function mockUserRow(row: Record) { - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: (jest.fn() as any).mockResolvedValue(row), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(selectChain(row)); } beforeEach(() => { diff --git a/apps/backend/lambdas/users/test/users.test.ts b/apps/backend/lambdas/users/test/users.test.ts index b3fc5691..c7939356 100644 --- a/apps/backend/lambdas/users/test/users.test.ts +++ b/apps/backend/lambdas/users/test/users.test.ts @@ -58,7 +58,7 @@ const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction { test("regular user cannot delete users", async () => { mockRegularUserAuth(); - + const event = createEvent({ method: 'DELETE', path: '/1', }); - + const res = await handler(event); expect(res.statusCode).toBe(403); +}); + +describe('staff accounts', () => { + async function seedStaff(): Promise { + const { rows } = await pool.query( + `INSERT INTO branch.users (cognito_sub, name, email, is_admin, is_staff) + VALUES ('staff-sub', 'Hidden Staff', 'staff@branch.org', false, true) + RETURNING user_id`, + ); + return rows[0].user_id; + } + + test('never appear in the user list, its count, or its columns', async () => { + await seedStaff(); + mockAdminAuth(); + + const all = JSON.parse((await handler(createEvent({ method: 'GET', path: '/users' }))).body); + expect(all.users).toHaveLength(6); + expect(all.users.map((u: any) => u.email)).not.toContain('staff@branch.org'); + expect(all.users[0]).not.toHaveProperty('is_staff'); + + const paged = JSON.parse( + ( + await handler( + createEvent({ + method: 'GET', + path: '/users', + queryStringParameters: { page: '1', limit: '50' }, + }), + ) + ).body, + ); + expect(paged.pagination.totalUsers).toBe(6); + expect(paged.users.map((u: any) => u.email)).not.toContain('staff@branch.org'); + }); + + test('answer 404 to get, patch and delete, like a missing user', async () => { + const staffId = await seedStaff(); + mockAdminAuth(); + + const attempts: [string, unknown][] = [['GET', undefined], ['PATCH', { name: 'Renamed' }], ['DELETE', undefined]]; + for (const [method, body] of attempts) { + const res = await handler(createEvent({ method, path: `/${staffId}`, body })); + expect([method, res.statusCode]).toEqual([method, 404]); + } + + const { rows } = await pool.query('SELECT name FROM branch.users WHERE user_id = $1', [staffId]); + expect(rows[0].name).toBe('Hidden Staff'); + }); }); \ No newline at end of file diff --git a/apps/backend/lambdas/users/tsconfig.json b/apps/backend/lambdas/users/tsconfig.json index dc8dacce..00c390af 100644 --- a/apps/backend/lambdas/users/tsconfig.json +++ b/apps/backend/lambdas/users/tsconfig.json @@ -10,6 +10,6 @@ "outDir": "dist", "sourceMap": true }, - "include": ["*.ts", "controllers/**/*.ts"], + "include": ["*.ts", "controllers/**/*.ts", "scripts/**/*.ts"], "exclude": ["node_modules", "dist", "dev-server.ts", "swagger-utils.ts"] } diff --git a/infrastructure/aws/api_gateway.tf b/infrastructure/aws/api_gateway.tf index 79fb92ce..59fba1e3 100644 --- a/infrastructure/aws/api_gateway.tf +++ b/infrastructure/aws/api_gateway.tf @@ -24,7 +24,7 @@ resource "aws_api_gateway_gateway_response" "cors" { response_parameters = { "gatewayresponse.header.Access-Control-Allow-Origin" = "'*'" - "gatewayresponse.header.Access-Control-Allow-Headers" = "'Content-Type,Authorization'" + "gatewayresponse.header.Access-Control-Allow-Headers" = "'Content-Type,Authorization,X-Impersonate-Session'" "gatewayresponse.header.Access-Control-Allow-Methods" = "'GET,POST,PUT,PATCH,DELETE,OPTIONS'" } @@ -174,7 +174,7 @@ locals { # who answers a preflight, not what a preflight says. cors_headers = { "Access-Control-Allow-Origin" = "'*'" - "Access-Control-Allow-Headers" = "'Content-Type,Authorization'" + "Access-Control-Allow-Headers" = "'Content-Type,Authorization,X-Impersonate-Session'" "Access-Control-Allow-Methods" = "'GET,POST,PUT,PATCH,DELETE,OPTIONS'" "Access-Control-Max-Age" = "'7200'" } diff --git a/infrastructure/preview/api_gateway.tf b/infrastructure/preview/api_gateway.tf index 3fc22f5a..8f28663c 100644 --- a/infrastructure/preview/api_gateway.tf +++ b/infrastructure/preview/api_gateway.tf @@ -20,7 +20,7 @@ resource "aws_api_gateway_gateway_response" "cors" { response_parameters = { "gatewayresponse.header.Access-Control-Allow-Origin" = "'*'" - "gatewayresponse.header.Access-Control-Allow-Headers" = "'Content-Type,Authorization'" + "gatewayresponse.header.Access-Control-Allow-Headers" = "'Content-Type,Authorization,X-Impersonate-Session'" "gatewayresponse.header.Access-Control-Allow-Methods" = "'GET,POST,PUT,DELETE,OPTIONS'" } } diff --git a/shared/lambda-auth/src/authenticate.ts b/shared/lambda-auth/src/authenticate.ts index 23fa96d8..18e96d5f 100644 --- a/shared/lambda-auth/src/authenticate.ts +++ b/shared/lambda-auth/src/authenticate.ts @@ -1,5 +1,11 @@ import { CognitoJwtVerifier } from 'aws-jwt-verify'; -import type { AuthContext, AuthenticatedUser, AuthMembership } from './types'; +import type { + AuthContext, + AuthenticatedUser, + AuthFailure, + AuthMembership, + ImpersonationMode, +} from './types'; // Minimal structural type — avoids a hard dependency on kysely at compile time. // Parameter typed as `any` so Kysely's constrained overload is assignable. @@ -42,6 +48,19 @@ export function extractToken(event: any): string | null { return authHeader; } +/** Sent by the staff console on every request made while switched in. */ +export const IMPERSONATION_HEADER = 'x-impersonate-session'; + +export function extractImpersonationSession(event: any): string | null { + const headers: Record = event?.headers ?? {}; + for (const [name, value] of Object.entries(headers)) { + if (name.toLowerCase() === IMPERSONATION_HEADER && typeof value === 'string') { + return value.trim() || null; + } + } + return null; +} + /** * One row of the identity query. The LEFT JOIN fans the single `branch.users` * row out to one row per membership, so the user columns repeat and the @@ -53,6 +72,7 @@ interface CallerRow { email: string; name: string; is_admin: boolean | null; + is_staff: boolean | null; profile_image: string | null; project_id: number | null; role: string | null; @@ -92,59 +112,160 @@ export async function authenticateRequest( // Uncaught on purpose: a DB outage is not a 401. Catching it hid an unreachable // RDS behind "Authentication required" and logged users out. Handlers map to 500. - const rows: CallerRow[] = await db + const rows = await selectIdentity(db, 'u.cognito_sub', payload.sub); + + // No rows at all means no `branch.users` row — the LEFT JOIN guarantees at + // least one row for a user that exists, membership or not. + const dbUser = rows[0]; + if (!dbUser) { + console.warn( + 'User authenticated with Cognito but not found in database:', + payload.sub, + ); + return { isAuthenticated: false }; + } + + const sessionId = extractImpersonationSession(event); + if (sessionId) return impersonate(db, dbUser, sessionId); + + const user = toAuthenticatedUser(rows, payload.sub); + // Informational only. We deliberately do NOT promote on a Cognito + // "Admins" group: branch.users.is_admin is the single source of truth. + // A second source would make demotion via PATCH /users/{userId} silently + // ineffective, nothing in this codebase writes group membership, and no + // aws_cognito_user_group is defined in infrastructure/aws/cognito.tf. + user.cognitoGroups = payload['cognito:groups'] as string[] | undefined; + // The JWT claim; `dbUser.email` is the column. + user.email = payload.email as string | undefined; + + return { user, isAuthenticated: true }; +} + +/** + * The caller's `branch.users` row fanned out over its memberships, in one round + * trip. LEFT because a user with no memberships must still authenticate; an + * inner join would sign them out. + */ +async function selectIdentity( + db: QueryableDb, + column: 'u.cognito_sub' | 'u.user_id', + value: string | number, +): Promise { + return db .selectFrom('branch.users as u') .leftJoin('branch.project_memberships as pm', 'pm.user_id', 'u.user_id') - .where('u.cognito_sub', '=', payload.sub) + .where(column, '=', value) .select([ 'u.user_id', 'u.cognito_sub', 'u.email', 'u.name', 'u.is_admin', + 'u.is_staff', 'u.profile_image', 'pm.project_id', 'pm.role', ]) .execute(); +} - // No rows at all means no `branch.users` row — the LEFT JOIN guarantees at - // least one row for a user that exists, membership or not. - const dbUser = rows[0]; - if (!dbUser) { - console.warn( - 'User authenticated with Cognito but not found in database:', - payload.sub, - ); - return { isAuthenticated: false }; - } - - const isAdmin = dbUser.is_admin === true; - - const user: AuthenticatedUser = { - cognitoSub: payload.sub, - userId: dbUser.user_id, - email: payload.email as string | undefined, +function toAuthenticatedUser( + rows: readonly CallerRow[], + cognitoSub: string, +): AuthenticatedUser { + const row = rows[0]; + const isAdmin = row.is_admin === true; + const isStaff = row.is_staff === true; + return { + cognitoSub, + userId: row.user_id, isAdmin, - // Informational only. We deliberately do NOT promote on a Cognito - // "Admins" group: branch.users.is_admin is the single source of truth. - // A second source would make demotion via PATCH /users/{userId} silently - // ineffective, nothing in this codebase writes group membership, and no - // aws_cognito_user_group is defined in infrastructure/aws/cognito.tf. - cognitoGroups: payload['cognito:groups'] as string[] | undefined, - // The same row, under the names `GET /auth/me` reports. `email` above stays - // the token claim; this one is the column. + isStaff, + // The same row, under the names `GET /auth/me` reports. dbUser: { - userId: dbUser.user_id, - cognitoSub: dbUser.cognito_sub, - email: dbUser.email, - name: dbUser.name, + userId: row.user_id, + cognitoSub: row.cognito_sub, + email: row.email, + name: row.name, isAdmin, - profileImage: dbUser.profile_image, + isStaff, + profileImage: row.profile_image, }, memberships: collectMemberships(rows), }; +} + +interface SessionRow { + session_id: string; + target_user_id: number; + mode: ImpersonationMode; + expires_at: Date; + ended_at: Date | null; +} + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +const EXPIRED: AuthFailure = { + status: 401, + code: 'IMPERSONATION_EXPIRED', + message: 'Impersonation session has ended', +}; + +function refuse(failure: AuthFailure): AuthContext { + return { isAuthenticated: false, failure }; +} +/** + * Swap a staff caller for the user their session names. Everything downstream — + * the subject, list scoping, `entered_by` — then sees only the target. + * + * A header from a non-staff caller is refused rather than ignored: silently + * serving them as themselves would hide a client bug or a probe. + */ +async function impersonate( + db: QueryableDb, + staff: CallerRow, + sessionId: string, +): Promise { + if (staff.is_staff !== true) { + return refuse({ + status: 403, + code: 'IMPERSONATION_FORBIDDEN', + message: 'Only staff accounts can impersonate', + }); + } + if (!UUID.test(sessionId)) return refuse(EXPIRED); + + const sessions: SessionRow[] = await db + .selectFrom('branch.impersonation_sessions') + .where('session_id', '=', sessionId) + .where('staff_user_id', '=', staff.user_id) + .select(['session_id', 'target_user_id', 'mode', 'expires_at', 'ended_at']) + .execute(); + const session = sessions[0]; + if (!session || session.ended_at !== null || session.expires_at <= new Date()) { + return refuse(EXPIRED); + } + + const rows = await selectIdentity(db, 'u.user_id', session.target_user_id); + if (!rows[0]) return refuse(EXPIRED); + if (rows[0].is_staff === true) { + return refuse({ + status: 403, + code: 'IMPERSONATION_FORBIDDEN', + message: 'Staff accounts cannot be impersonated', + }); + } + + const user = toAuthenticatedUser(rows, rows[0].cognito_sub ?? ''); + user.impersonator = { + userId: staff.user_id, + name: staff.name, + email: staff.email, + sessionId: session.session_id, + mode: session.mode, + expiresAt: session.expires_at.toISOString(), + }; return { user, isAuthenticated: true }; } diff --git a/shared/lambda-auth/src/index.ts b/shared/lambda-auth/src/index.ts index 5574d4c9..6791207c 100644 --- a/shared/lambda-auth/src/index.ts +++ b/shared/lambda-auth/src/index.ts @@ -1,5 +1,10 @@ export * from './types'; -export { extractToken, authenticateRequest } from './authenticate'; +export { + extractToken, + authenticateRequest, + extractImpersonationSession, + IMPERSONATION_HEADER, +} from './authenticate'; export { loadRbacSubject, preloadedSubject } from './rbac'; // The policy itself is re-exported so a lambda needs one import for auth and // authorization, the same way this package already re-exports the auth DTOs. diff --git a/shared/lambda-auth/src/types.ts b/shared/lambda-auth/src/types.ts index cf085392..15cc718e 100644 --- a/shared/lambda-auth/src/types.ts +++ b/shared/lambda-auth/src/types.ts @@ -5,4 +5,7 @@ export type { AuthenticatedUser, AuthenticatedDbUser, AuthMembership, + AuthFailure, + Impersonator, + ImpersonationMode, } from '@branch/types'; diff --git a/shared/lambda-auth/test/authenticate.test.ts b/shared/lambda-auth/test/authenticate.test.ts index 19de2f8b..c8ff303c 100644 --- a/shared/lambda-auth/test/authenticate.test.ts +++ b/shared/lambda-auth/test/authenticate.test.ts @@ -15,6 +15,7 @@ function userRow(over: Record = {}) { email: 'row@b.com', name: 'Ada', is_admin: false, + is_staff: false, profile_image: null, project_id: null, role: null, @@ -184,6 +185,7 @@ describe('authenticateRequest', () => { // The JWT claim, deliberately not the column -- see dbUser.email. email: 'claim@b.com', isAdmin: true, + isStaff: false, cognitoGroups: undefined, dbUser: { userId: 7, @@ -191,6 +193,7 @@ describe('authenticateRequest', () => { email: 'row@b.com', name: 'Ada', isAdmin: true, + isStaff: false, profileImage: null, }, memberships: [], @@ -223,6 +226,7 @@ describe('authenticateRequest', () => { 'u.email', 'u.name', 'u.is_admin', + 'u.is_staff', 'u.profile_image', 'pm.project_id', 'pm.role', @@ -352,3 +356,112 @@ describe('authenticateRequest', () => { ); }); }); + +/** + * Routes each query by table. The identity query is filtered by its one + * `where`; the session query by all of them, so a test proves the session is + * bound to the calling staff account and not just looked up by id. + */ +function makeImpersonationDb(users: any[], sessions: any[]) { + const chain = (run: (filters: [string, unknown][]) => unknown[]) => { + const filters: [string, unknown][] = []; + const c: any = { + leftJoin: () => c, + where: (col: string, _op: string, val: unknown) => { + filters.push([col, val]); + return c; + }, + select: () => c, + execute: async () => run(filters), + }; + return c; + }; + return { + selectFrom: (table: string) => + table === 'branch.users as u' + ? chain(([[col, val]]) => + users.filter((u) => + col === 'u.cognito_sub' ? u.cognito_sub === val : u.user_id === val, + ), + ) + : chain((filters) => + sessions.filter((s) => filters.every(([col, val]) => s[col] === val)), + ), + }; +} + +describe('impersonation', () => { + const SESSION = '0b6a3c1e-8a4f-4c55-9a43-0f3c5c0b1d2e'; + const STAFF = userRow({ user_id: 50, cognito_sub: 'sub-staff', name: 'Staff', email: 's@b.com', is_staff: true }); + const TARGET = userRow({ user_id: 7, cognito_sub: 'sub-7', project_id: 1, role: 'Director' }); + const future = () => new Date(Date.now() + 60_000); + const session = (over: Record = {}) => ({ + session_id: SESSION, + staff_user_id: 50, + target_user_id: 7, + mode: 'read_only', + expires_at: future(), + ended_at: null, + ...over, + }); + const event = (id = SESSION) => ({ + headers: { Authorization: 'Bearer good', 'X-Impersonate-Session': id }, + }); + + beforeEach(() => mockVerify.mockResolvedValue({ sub: 'sub-staff' })); + + it('authenticates as the target and names the staff account behind it', async () => { + const { authenticateRequest } = await loadModule(); + const db = makeImpersonationDb([STAFF, TARGET], [session()]); + + const ctx = await authenticateRequest(db, event()); + + expect(ctx.isAuthenticated).toBe(true); + expect(ctx.user?.userId).toBe(7); + expect(ctx.user?.isStaff).toBe(false); + expect(ctx.user?.memberships).toEqual([{ project_id: 1, role: 'Director' }]); + expect(ctx.user?.impersonator).toMatchObject({ + userId: 50, + name: 'Staff', + sessionId: SESSION, + mode: 'read_only', + }); + }); + + it('refuses a non-staff caller instead of ignoring the header', async () => { + mockVerify.mockResolvedValue({ sub: 'sub-7' }); + const { authenticateRequest } = await loadModule(); + const db = makeImpersonationDb([STAFF, TARGET], [session()]); + + const ctx = await authenticateRequest(db, event()); + + expect(ctx).toEqual({ + isAuthenticated: false, + failure: expect.objectContaining({ status: 403, code: 'IMPERSONATION_FORBIDDEN' }), + }); + }); + + it.each([ + ['ended', [session({ ended_at: new Date() })], SESSION], + ['expired', [session({ expires_at: new Date(Date.now() - 1) })], SESSION], + ["another staff account's", [session({ staff_user_id: 51 })], SESSION], + ['malformed', [session()], 'not-a-uuid'], + ])('treats an %s session as expired', async (_label, sessions, id) => { + const { authenticateRequest } = await loadModule(); + const db = makeImpersonationDb([STAFF, TARGET], sessions); + + const ctx = await authenticateRequest(db, event(id)); + + expect(ctx.failure).toMatchObject({ status: 401, code: 'IMPERSONATION_EXPIRED' }); + }); + + it('never lets a staff account be the target', async () => { + const { authenticateRequest } = await loadModule(); + const other = userRow({ user_id: 7, cognito_sub: 'sub-7', is_staff: true }); + const db = makeImpersonationDb([STAFF, other], [session()]); + + const ctx = await authenticateRequest(db, event()); + + expect(ctx.failure).toMatchObject({ status: 403, code: 'IMPERSONATION_FORBIDDEN' }); + }); +}); diff --git a/shared/lambda-auth/test/rbac.test.ts b/shared/lambda-auth/test/rbac.test.ts index 55dfa961..2b463a53 100644 --- a/shared/lambda-auth/test/rbac.test.ts +++ b/shared/lambda-auth/test/rbac.test.ts @@ -32,6 +32,7 @@ describe('preloadedSubject', () => { expect(subject).toEqual({ userId: 7, isAdmin: false, + isStaff: false, memberProjectIds: [1, 2], directorProjectIds: [1], }); @@ -43,6 +44,7 @@ describe('preloadedSubject', () => { expect(preloadedSubject(context({ memberships: [] }))).toEqual({ userId: 7, isAdmin: false, + isStaff: false, memberProjectIds: [], directorProjectIds: [], }); diff --git a/shared/lambda-http/README.md b/shared/lambda-http/README.md index bac61294..a1657814 100644 --- a/shared/lambda-http/README.md +++ b/shared/lambda-http/README.md @@ -49,6 +49,13 @@ the row is loaded. Paths are canonicalized to the prefixed form, so one table serves both. - **Authentication and the route's permission**, resolved once per request via `resolveAuth`. A controller that runs has already cleared its route's gate. +- **Impersonation.** When `resolveAuth` returns a context with an + `impersonator`, a read-only session gets a 403 on any non-GET request, and a + route with `impersonation: 'blocked'` refuses it in either mode. Use + `'blocked'` for routes that act on the caller's own Cognito session, which + while impersonating is the staff account's. Every non-GET impersonated + request, refused or not, is then handed to `onImpersonatedWrite`. Each + lambda passes `@branch/store`'s `recordImpersonationAction`. - OPTIONS preflight, `GET //health`, 404, and 500. - CORS headers on every response, via `json`. - **Sentry reporting for the 500 path.** The Sentry Lambda layer wraps the @@ -62,7 +69,7 @@ the row is loaded. | Export | Purpose | | --- | --- | -| `dispatch(event, { prefix, routes, resolveAuth })` | Route an event; returns a response. | +| `dispatch(event, { prefix, routes, resolveAuth, onImpersonatedWrite })` | Route an event; returns a response. | | `json(status, body)` | JSON response with CORS headers. | | `parseBody(event)` | Parse a JSON body; `null` when malformed. | | `requirePermission(subject, action, resource?)` | 403 carrying the policy's own reason, or `undefined` when allowed. | diff --git a/shared/lambda-http/src/dispatch.ts b/shared/lambda-http/src/dispatch.ts index d54770db..05146814 100644 --- a/shared/lambda-http/src/dispatch.ts +++ b/shared/lambda-http/src/dispatch.ts @@ -4,6 +4,7 @@ import { json } from './response'; import { matchPattern } from './match'; import { ANONYMOUS_AUTH } from './authz'; import { reportError } from './errors'; +import type { Impersonator } from '@branch/lambda-auth'; import type { DispatchOptions, RequestAuth, Route } from './types'; /** @@ -21,7 +22,7 @@ import type { DispatchOptions, RequestAuth, Route } from './types'; */ export async function dispatch( event: any, - { prefix, routes, resolveAuth }: DispatchOptions, + { prefix, routes, resolveAuth, onImpersonatedWrite }: DispatchOptions, ): Promise { // Hoisted out of the try so the catch can name the route that failed. const rawPath: string = event?.rawPath || event?.path || '/'; @@ -50,10 +51,17 @@ export async function dispatch( const params = matchPattern(route.pattern, path); if (!params) continue; - const gate = await enforce(route, event, resolveAuth); - if ('response' in gate) return gate.response; + const gate = await enforce(route, method, event, resolveAuth); + const result = + gate.response ?? + (await route.handler({ event, params, method, path, auth: gate.auth! })); - return await route.handler({ event, params, method, path, auth: gate.auth }); + // Refused writes too: an attempt is part of the trail. + const impersonator = gate.auth?.context.user?.impersonator; + if (impersonator && !READ_METHODS.has(method)) { + await audit(onImpersonatedWrite, impersonator, method, path, result.statusCode); + } + return result; } return json(404, { message: 'Not Found', path, method }); @@ -66,10 +74,32 @@ export async function dispatch( } } -type Gate = { auth: RequestAuth } | { response: APIGatewayProxyResult }; +/** `auth` is kept on a refusal when the caller was identified, so it can be audited. */ +type Gate = + | { auth: RequestAuth; response?: undefined } + | { auth?: RequestAuth; response: APIGatewayProxyResult }; + +const READ_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']); + +async function audit( + hook: DispatchOptions['onImpersonatedWrite'], + impersonator: Impersonator, + method: string, + path: string, + statusCode: number, +): Promise { + if (!hook) return; + try { + await hook(impersonator, method, path, statusCode); + } catch (err) { + console.error('Impersonation audit failed:', err); + reportError(err, { method, path }); + } +} async function enforce( route: Route, + method: string, event: any, resolveAuth: DispatchOptions['resolveAuth'], ): Promise { @@ -88,13 +118,29 @@ async function enforce( const auth = await resolveAuth(event); if (!auth.context.isAuthenticated) { + const failure = auth.context.failure; + if (failure) { + return { + response: json(failure.status, { message: failure.message, code: failure.code }), + }; + } return { response: json(401, { message: 'Authentication required' }) }; } + const impersonator = auth.context.user?.impersonator; + if (impersonator) { + if (route.impersonation === 'blocked') { + return { auth, response: json(403, { message: 'Not available while impersonating' }) }; + } + if (impersonator.mode === 'read_only' && !READ_METHODS.has(method)) { + return { auth, response: json(403, { message: 'Read-only impersonation' }) }; + } + } + if (route.permission) { const decision = authorize(auth.subject, route.permission); if (!decision.allowed) { - return { response: json(403, { message: decision.reason ?? 'Forbidden' }) }; + return { auth, response: json(403, { message: decision.reason ?? 'Forbidden' }) }; } } diff --git a/shared/lambda-http/src/response.ts b/shared/lambda-http/src/response.ts index b4ff8626..eedd9383 100644 --- a/shared/lambda-http/src/response.ts +++ b/shared/lambda-http/src/response.ts @@ -7,7 +7,7 @@ export function json(statusCode: number, body: unknown): APIGatewayProxyResult { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Headers': 'Content-Type,Authorization', + 'Access-Control-Allow-Headers': 'Content-Type,Authorization,X-Impersonate-Session', 'Access-Control-Allow-Methods': 'GET,POST,PUT,PATCH,DELETE,OPTIONS', }, body: JSON.stringify(body), diff --git a/shared/lambda-http/src/types.ts b/shared/lambda-http/src/types.ts index 95f9270d..b0ab2843 100644 --- a/shared/lambda-http/src/types.ts +++ b/shared/lambda-http/src/types.ts @@ -1,5 +1,5 @@ import type { APIGatewayProxyResult } from 'aws-lambda'; -import type { AuthContext } from '@branch/lambda-auth'; +import type { AuthContext, Impersonator } from '@branch/lambda-auth'; import type { GlobalAction, RbacSubject } from '@branch/rbac'; /** Who is calling, resolved once per request by `dispatch`. */ @@ -35,6 +35,12 @@ interface RouteBase { /** Full prefixed path pattern with `:param` segments, e.g. `/projects/:id/members`. */ pattern: string; handler: RouteHandler; + /** + * `'blocked'` refuses the route to an impersonated request in either mode: + * for routes that act on the caller's own Cognito session, which while + * impersonating is the staff account's, not the target's. + */ + impersonation?: 'blocked'; } /** @@ -63,4 +69,14 @@ export interface DispatchOptions { * route without it. */ resolveAuth?: (event: any) => Promise; + /** + * Audit hook, awaited after every mutating request made while impersonating. + * A failure is reported, never surfaced: the write has already happened. + */ + onImpersonatedWrite?: ( + impersonator: Impersonator, + method: string, + path: string, + statusCode: number, + ) => Promise; } diff --git a/shared/lambda-http/test/authz.test.ts b/shared/lambda-http/test/authz.test.ts index d79d1d68..37b1af0a 100644 --- a/shared/lambda-http/test/authz.test.ts +++ b/shared/lambda-http/test/authz.test.ts @@ -12,6 +12,7 @@ const context = (userId: number, isAdmin = false): AuthContext => ({ const subject = (userId: number, isAdmin = false, projects: number[] = []): RbacSubject => ({ userId, isAdmin, + isStaff: false, memberProjectIds: projects, directorProjectIds: [], }); diff --git a/shared/lambda-http/test/dispatch.test.ts b/shared/lambda-http/test/dispatch.test.ts index dc325e71..acb20f08 100644 --- a/shared/lambda-http/test/dispatch.test.ts +++ b/shared/lambda-http/test/dispatch.test.ts @@ -28,6 +28,7 @@ const routes: Route[] = [ const subject = (userId: number, isAdmin = false): RbacSubject => ({ userId, isAdmin, + isStaff: false, memberProjectIds: [], directorProjectIds: [], }); @@ -204,3 +205,99 @@ describe('dispatch authorization', () => { expect(resolveAuth).toHaveBeenCalledTimes(1); }); }); + +describe('dispatch impersonation', () => { + const impersonated = (mode: 'read_only' | 'full') => async (): Promise => ({ + context: { + isAuthenticated: true, + user: { + cognitoSub: 'x', + userId: 7, + isAdmin: true, + impersonator: { + userId: 50, + name: 'Staff', + email: 's@b.com', + sessionId: 'sess-1', + mode, + expiresAt: new Date().toISOString(), + }, + }, + }, + subject: subject(7, true), + }); + const withRoutes = (resolveAuth: () => Promise, extra: Partial<{ onImpersonatedWrite: jest.Mock }> = {}) => ({ + prefix: 'projects', + routes: [ + ...routes, + { method: 'POST', pattern: '/projects/mfa', access: 'authenticated', impersonation: 'blocked', handler: ok('mfa') } as Route, + ], + resolveAuth, + ...extra, + }); + + it('serves reads in read-only mode', async () => { + const res = await dispatch(event('GET', '/projects/7'), withRoutes(impersonated('read_only'))); + expect(res.statusCode).toBe(200); + }); + + it('refuses writes in read-only mode before the controller runs, and audits the attempt', async () => { + const onImpersonatedWrite = jest.fn().mockResolvedValue(undefined); + const res = await dispatch( + event('PUT', '/projects/7'), + withRoutes(impersonated('read_only'), { onImpersonatedWrite }), + ); + expect(res.statusCode).toBe(403); + expect(body(res).message).toBe('Read-only impersonation'); + expect(body(res).label).toBeUndefined(); + expect(onImpersonatedWrite).toHaveBeenCalledWith(expect.anything(), 'PUT', '/projects/7', 403); + }); + + it('refuses a blocked route in full mode too', async () => { + const res = await dispatch(event('POST', '/projects/mfa'), withRoutes(impersonated('full'))); + expect(res.statusCode).toBe(403); + }); + + it('audits each full-mode write with its outcome, and never a read', async () => { + const onImpersonatedWrite = jest.fn().mockResolvedValue(undefined); + const opts = withRoutes(impersonated('full'), { onImpersonatedWrite }); + + await dispatch(event('GET', '/projects/7'), opts); + const res = await dispatch(event('PUT', '/projects/7'), opts); + + expect(res.statusCode).toBe(200); + expect(onImpersonatedWrite).toHaveBeenCalledTimes(1); + expect(onImpersonatedWrite).toHaveBeenCalledWith( + expect.objectContaining({ sessionId: 'sess-1' }), + 'PUT', + '/projects/7', + 200, + ); + }); + + it('still answers when the audit write fails, and reports it', async () => { + jest.spyOn(console, 'error').mockImplementation(() => undefined); + const onImpersonatedWrite = jest.fn().mockRejectedValue(new Error('db down')); + + const res = await dispatch( + event('PUT', '/projects/7'), + withRoutes(impersonated('full'), { onImpersonatedWrite }), + ); + + expect(res.statusCode).toBe(200); + expect(Sentry.captureException).toHaveBeenCalled(); + }); + + it('surfaces the failure code instead of a bare 401', async () => { + const expired = async (): Promise => ({ + context: { + isAuthenticated: false, + failure: { status: 401, code: 'IMPERSONATION_EXPIRED', message: 'Impersonation session has ended' }, + }, + subject: ANONYMOUS, + }); + const res = await dispatch(event('GET', '/projects/7'), withRoutes(expired)); + expect(res.statusCode).toBe(401); + expect(body(res).code).toBe('IMPERSONATION_EXPIRED'); + }); +}); diff --git a/shared/rbac/README.md b/shared/rbac/README.md index a2ad4b38..87891b7e 100644 --- a/shared/rbac/README.md +++ b/shared/rbac/README.md @@ -61,6 +61,10 @@ a member of (enforced in SQL, so out-of-scope rows never leave the database). | | Manage members, list staff | ✅ | ❌ | ❌ | ❌ | | **Reports** | View / create / generate / delete | ✅ | ❌ | ❌ | ❌ | | **Accounts** | View / create / edit / delete | ✅ | ❌ | ❌ | ❌ | +| **Impersonation** | Open the staff console, switch into a user | ❌ | ❌ | ❌ | ❌ | + +A fifth subject, **Staff** (`users.is_staff`), passes the Impersonation row and +nothing else; see below. Notes on the rows that are easy to misread: @@ -78,6 +82,26 @@ Notes on the rows that are easy to misread: - **An author keeps access to what they filed** even after leaving the project, which is why `expense:view` has an author clause on top of membership. +## Staff accounts and impersonation + +A staff account is a hidden developer/support login. It never appears in any +user list, count, roster or picker, and only `make create-staff` (in +`apps/backend`) can create one. + +- **On its own** a staff subject (`isStaff: true`) passes `impersonation:*` and + is denied everything else. That is one gate at the top of `authorizeAny`, not + a clause in each rule, so a new rule cannot forget it. +- **Switched in**, the request carries the staff token plus + `X-Impersonate-Session`, and `@branch/lambda-auth` hands back the *target's* + identity and memberships. The subject is the target's, with `isStaff: false`, + so every row of the matrix above applies to it as written, and + `impersonation:*` denies. A switch therefore cannot be chained, and a staff + account can never be a target. +- **Read-only** sessions refuse every non-GET request in `dispatch`. **Full** + sessions act as the target, so an expense filed this way has the target as its + `entered_by`. Either way, every non-GET request is written to + `branch.impersonation_actions`, refused or not. + ## Using it ```ts diff --git a/shared/rbac/src/pages.ts b/shared/rbac/src/pages.ts index 767557c9..cb63f29b 100644 --- a/shared/rbac/src/pages.ts +++ b/shared/rbac/src/pages.ts @@ -20,6 +20,7 @@ export const PAGE_PERMISSIONS: Record = { '/projects': 'projects:view', '/reports': 'reports:view', '/accounts': 'accounts:view', + '/staff': 'impersonation:console', }; /** diff --git a/shared/rbac/src/policy.ts b/shared/rbac/src/policy.ts index 5d2de336..6dafadab 100644 --- a/shared/rbac/src/policy.ts +++ b/shared/rbac/src/policy.ts @@ -97,6 +97,8 @@ const ADMIN_ONLY = 'Only administrators can do this'; const ADMIN_OR_DIRECTOR = 'Only administrators and project directors can do this'; const MEMBER_ONLY = 'You are not a member of this project'; const SIGN_IN = 'You must be signed in'; +const STAFF_ONLY = 'Only staff accounts can do this'; +const STAFF_MUST_SWITCH = 'Staff accounts must switch into a user first'; function unscoped( reason: string, @@ -215,12 +217,24 @@ export const POLICY = { 'accounts:create': unscoped(ADMIN_ONLY, admin), 'accounts:update': unscoped(ADMIN_ONLY, admin), 'accounts:delete': unscoped(ADMIN_ONLY, admin), + + // -- Impersonation -------------------------------------------------------- + // The only actions a staff subject passes; see the gate in authorizeAny. + // While impersonating the subject is the target's, so these deny and a + // switch cannot be chained. + 'impersonation:console': unscoped(STAFF_ONLY, (s) => s.isStaff), + 'impersonation:start': unscoped(STAFF_ONLY, (s) => s.isStaff), } satisfies Record>; export type Action = keyof typeof POLICY; export const ACTIONS = Object.keys(POLICY) as Action[]; +const STAFF_ACTIONS: ReadonlySet = new Set([ + 'impersonation:console', + 'impersonation:start', +]); + /** Actions whose own entry declares that its rule reads a resource. */ export type ScopedAction = { [K in Action]: (typeof POLICY)[K]['needsResource'] extends true ? K : never; @@ -273,6 +287,9 @@ export function authorizeAny( const s = subject ?? ANONYMOUS; + // A staff account holds no rights of its own, whatever a rule below says. + if (s.isStaff && !STAFF_ACTIONS.has(action)) return deny(STAFF_MUST_SWITCH); + // Fail closed. A caller that forgot the resource must not get a rule // evaluated against `undefined`, which reads as "no project" and can be // truthy for the wrong reason. diff --git a/shared/rbac/src/subject.ts b/shared/rbac/src/subject.ts index c96bd39d..17d29bd5 100644 --- a/shared/rbac/src/subject.ts +++ b/shared/rbac/src/subject.ts @@ -7,6 +7,11 @@ export interface RbacSubject { userId: number | null; isAdmin: boolean; + /** + * A hidden staff account acting as itself. Always false while impersonating: + * the subject is then the target's. + */ + isStaff: boolean; /** Every project this user has any membership row on. */ memberProjectIds: number[]; /** @@ -43,6 +48,7 @@ export type MemberDisplayRole = ProjectRole | typeof ADMIN_MEMBER_ROLE; export const ANONYMOUS: RbacSubject = { userId: null, isAdmin: false, + isStaff: false, memberProjectIds: [], directorProjectIds: [], }; @@ -61,7 +67,10 @@ export interface MembershipRow { * "director". */ export function buildSubject( - user: { userId?: number | null; isAdmin?: boolean | null } | null | undefined, + user: + | { userId?: number | null; isAdmin?: boolean | null; isStaff?: boolean | null } + | null + | undefined, memberships: readonly MembershipRow[], ): RbacSubject { if (!user?.userId) return ANONYMOUS; @@ -78,6 +87,7 @@ export function buildSubject( return { userId: user.userId, isAdmin: user.isAdmin === true, + isStaff: user.isStaff === true, memberProjectIds, directorProjectIds, }; diff --git a/shared/rbac/test/policy.test.ts b/shared/rbac/test/policy.test.ts index 4f80050a..ff89a94b 100644 --- a/shared/rbac/test/policy.test.ts +++ b/shared/rbac/test/policy.test.ts @@ -18,21 +18,39 @@ import { const ADMIN: RbacSubject = { userId: 1, isAdmin: true, + isStaff: false, memberProjectIds: [], directorProjectIds: [], }; const DIRECTOR: RbacSubject = { userId: 2, isAdmin: false, + isStaff: false, memberProjectIds: [1], directorProjectIds: [1], }; const STUDENT: RbacSubject = { userId: 3, isAdmin: false, + isStaff: false, memberProjectIds: [2], directorProjectIds: [], }; +const STAFF: RbacSubject = { + userId: 4, + isAdmin: false, + isStaff: true, + memberProjectIds: [], + directorProjectIds: [], +}; + +const STAFF_ACTIONS: Action[] = ['impersonation:console', 'impersonation:start']; +const ANY_RESOURCE = { + projectId: 3, + userId: 4, + enteredBy: 4, + status: 'pending', +}; const OWN_PROJECT = { projectId: 2 }; const OTHER_PROJECT = { projectId: 3 }; @@ -94,8 +112,8 @@ describe('anonymous callers', () => { }); describe('admins', () => { - it('are allowed every action', () => { - for (const action of ACTIONS) { + it('are allowed every action but impersonation', () => { + for (const action of ACTIONS.filter((a) => !STAFF_ACTIONS.includes(a))) { const decision = (authorize as any)(ADMIN, action, { projectId: 3, userId: 999, @@ -107,6 +125,35 @@ describe('admins', () => { }); }); +describe('staff', () => { + it('may only open the console and switch in', () => { + for (const action of ACTIONS) { + const decision = (authorize as any)(STAFF, action, ANY_RESOURCE); + expect([action, decision.allowed]).toEqual([ + action, + STAFF_ACTIONS.includes(action), + ]); + } + }); + + it('explains the denial', () => { + expect(authorize(STAFF, 'projects:view').reason).toBe( + 'Staff accounts must switch into a user first', + ); + }); + + it('is never granted impersonation to anyone else', () => { + for (const subject of [ADMIN, DIRECTOR, STUDENT, ANONYMOUS]) { + expect(can(subject, 'impersonation:start')).toBe(false); + } + }); + + it('reads the flag from the user row', () => { + expect(buildSubject({ userId: 4, isStaff: true }, []).isStaff).toBe(true); + expect(buildSubject({ userId: 4 }, []).isStaff).toBe(false); + }); +}); + describe('donors', () => { it('is readable by admins and directors only', () => { expect(can(ADMIN, 'donors:view')).toBe(true); diff --git a/shared/store/src/impersonation.ts b/shared/store/src/impersonation.ts new file mode 100644 index 00000000..e8df39e9 --- /dev/null +++ b/shared/store/src/impersonation.ts @@ -0,0 +1,79 @@ +import type { Impersonator, ImpersonationMode } from '@branch/types' +import { tx } from './tx' + +export interface NewImpersonationSession { + staffUserId: number + targetUserId: number + mode: ImpersonationMode + // Passed in rather than defaulted by the column, so expiry is compared against + // one clock: the lambda's. + startedAt: Date + expiresAt: Date +} + +export async function startImpersonationSession(values: NewImpersonationSession): Promise { + return tx(async (trx) => { + const row = await trx + .insertInto('branch.impersonation_sessions') + .values({ + staff_user_id: values.staffUserId, + target_user_id: values.targetUserId, + mode: values.mode, + started_at: values.startedAt, + expires_at: values.expiresAt, + }) + .returning('session_id') + .executeTakeFirstOrThrow() + return row.session_id + }) +} + +/** Bound to the staff account, so one cannot end another's session. Idempotent. */ +export async function endImpersonationSession(sessionId: string, staffUserId: number): Promise { + await tx(async (trx) => + trx + .updateTable('branch.impersonation_sessions') + .set({ ended_at: new Date() }) + .where('session_id', '=', sessionId) + .where('staff_user_id', '=', staffUserId) + .where('ended_at', 'is', null) + .execute(), + ) +} + +/** The `onImpersonatedWrite` hook for `dispatch`. */ +export async function recordImpersonationAction( + impersonator: Pick, + method: string, + path: string, + statusCode: number, +): Promise { + await tx(async (trx) => + trx + .insertInto('branch.impersonation_actions') + .values({ session_id: impersonator.sessionId, method, path, status_code: statusCode }) + .execute(), + ) +} + +/** Only the provisioning script creates these; no route can set is_staff. */ +export async function createStaffUser(values: { + cognitoSub: string + email: string + name: string +}): Promise { + return tx(async (trx) => { + const row = await trx + .insertInto('branch.users') + .values({ + cognito_sub: values.cognitoSub, + email: values.email, + name: values.name, + is_admin: false, + is_staff: true, + }) + .returning('user_id') + .executeTakeFirstOrThrow() + return row.user_id + }) +} diff --git a/shared/store/src/index.ts b/shared/store/src/index.ts index cdf8d430..609745b5 100644 --- a/shared/store/src/index.ts +++ b/shared/store/src/index.ts @@ -27,6 +27,13 @@ export { recordDonation, removeDonation, createDonor, removeDonor } from './dona export { createProject, updateProject, removeProject } from './projects' export { recordReport, removeReport } from './reports' export { createUser, updateUser, claimUser, removeUser } from './users' +export { + startImpersonationSession, + endImpersonationSession, + recordImpersonationAction, + createStaffUser, +} from './impersonation' +export type { NewImpersonationSession } from './impersonation' export type { NewExpenditure, diff --git a/shared/store/src/users.ts b/shared/store/src/users.ts index 0abb6478..26b2d4ad 100644 --- a/shared/store/src/users.ts +++ b/shared/store/src/users.ts @@ -20,6 +20,8 @@ export async function updateUser( .updateTable('branch.users') .set(values) .where('user_id', '=', id) + // Staff rows are not editable through the app; the provisioning script owns them. + .where('is_staff', 'is not', true) .returningAll() .executeTakeFirst(), ) diff --git a/shared/types/auth-types.d.ts b/shared/types/auth-types.d.ts index d4aa3e67..276bae05 100644 --- a/shared/types/auth-types.d.ts +++ b/shared/types/auth-types.d.ts @@ -29,15 +29,33 @@ export interface AuthenticatedDbUser { email: string; name: string; isAdmin: boolean; + isStaff: boolean; profileImage: string | null; } +export type ImpersonationMode = 'read_only' | 'full'; + +/** The staff account behind an impersonated request. */ +export interface Impersonator { + userId: number; + name: string; + email: string; + sessionId: string; + mode: ImpersonationMode; + /** ISO timestamp. */ + expiresAt: string; +} + export interface AuthenticatedUser { cognitoSub: string; userId?: number; /** The JWT `email` claim. Not the same field as `dbUser.email`. */ email?: string; isAdmin: boolean; + /** False while impersonating: every identity field is then the target's. */ + isStaff?: boolean; + /** Set when a staff account is acting as this user. */ + impersonator?: Impersonator; cognitoGroups?: string[]; /** Set whenever `AuthContext.isAuthenticated` is true. */ dbUser?: AuthenticatedDbUser; @@ -53,6 +71,17 @@ export interface AuthenticatedUser { export interface AuthContext { user?: AuthenticatedUser; isAuthenticated: boolean; + /** + * Why an otherwise valid token was refused, when "Authentication required" + * would mislead. Only impersonation sets it today. + */ + failure?: AuthFailure; +} + +export interface AuthFailure { + status: 401 | 403; + code: 'IMPERSONATION_EXPIRED' | 'IMPERSONATION_FORBIDDEN'; + message: string; } // AccessLevel / AuthorizationCheck used to live here: a flat enum of PUBLIC, From fa0c7677a1fca3c66c899b7e64572dbc41a384a3 Mon Sep 17 00:00:00 2001 From: nourshoreibah Date: Fri, 16 Oct 2026 19:07:58 -0400 Subject: [PATCH 5/9] chore: trim comments Co-Authored-By: Claude Opus 5.5 --- apps/backend/Makefile | 5 +---- .../V20261015195441__add_users_is_staff.sql | 8 +------- ...261015195442__create_impersonation_sessions.sql | 5 +---- ...0261015195443__create_impersonation_actions.sql | 4 ---- apps/backend/lambdas/auth/auth.ts | 1 - apps/backend/lambdas/auth/controllers/auth.ts | 1 - .../lambdas/auth/controllers/impersonation.ts | 10 +--------- apps/backend/lambdas/auth/routes.ts | 2 -- .../lambdas/auth/test/impersonation.e2e.test.ts | 6 +----- apps/backend/lambdas/donors/auth.ts | 1 - apps/backend/lambdas/expenditures/auth.ts | 1 - apps/backend/lambdas/projects/auth.ts | 1 - apps/backend/lambdas/projects/services/projects.ts | 6 +----- apps/backend/lambdas/reports/auth.ts | 1 - apps/backend/lambdas/users/auth.ts | 1 - apps/backend/lambdas/users/controllers/users.ts | 3 +-- .../lambdas/users/scripts/create-staff-account.ts | 13 +------------ .../lambdas/users/test/user.photos.unit.test.ts | 1 - .../src/app/components/ImpersonationBanner.tsx | 5 ----- apps/frontend/src/app/staff/page.tsx | 5 ----- apps/frontend/src/context/AuthContext.tsx | 13 +------------ apps/frontend/src/lib/authClient.ts | 13 +------------ apps/frontend/src/lib/authTokens.ts | 5 +---- apps/frontend/test/rbac.ts | 1 - apps/frontend/test/utils.tsx | 1 - shared/lambda-auth/src/authenticate.ts | 14 +------------- shared/lambda-auth/test/authenticate.test.ts | 5 ----- shared/lambda-http/src/dispatch.ts | 1 - shared/lambda-http/src/types.ts | 11 ++--------- shared/rbac/src/policy.ts | 5 +---- shared/rbac/src/subject.ts | 4 ---- shared/store/src/impersonation.ts | 7 ++----- shared/store/src/users.ts | 1 - shared/types/auth-types.d.ts | 8 -------- 34 files changed, 17 insertions(+), 152 deletions(-) diff --git a/apps/backend/Makefile b/apps/backend/Makefile index 3e907668..11c3fe11 100644 --- a/apps/backend/Makefile +++ b/apps/backend/Makefile @@ -153,10 +153,7 @@ types: -e TYPES_OUT=/shared/types/db-types.d.ts \ migrator npm run --silent types -# usage: make create-staff EMAIL=dev@example.com NAME="Dev Name" -# -# Hidden staff account (see shared/rbac/README.md). Runs on the host against -# whatever COGNITO_USER_POOL_ID / DB_HOST / AWS credentials are exported. +# Runs on the host, against whatever COGNITO_USER_POOL_ID / DB_HOST / AWS credentials are exported. create-staff: @test -n "$(EMAIL)" -a -n "$(NAME)" || (echo 'usage: make create-staff EMAIL=dev@example.com NAME="Dev Name"' && exit 1) @npm --prefix lambdas/users run --silent create-staff -- --email "$(EMAIL)" --name "$(NAME)" diff --git a/apps/backend/db/migrations/V20261015195441__add_users_is_staff.sql b/apps/backend/db/migrations/V20261015195441__add_users_is_staff.sql index 498284e5..e4693586 100644 --- a/apps/backend/db/migrations/V20261015195441__add_users_is_staff.sql +++ b/apps/backend/db/migrations/V20261015195441__add_users_is_staff.sql @@ -1,9 +1,3 @@ --- V20261015195441__add_users_is_staff --- --- Staff accounts are hidden from every user-facing query and can only --- impersonate. See shared/rbac/README.md. --- --- Nullable with no default: DSQL rejects either on ADD COLUMN. NULL means "not --- staff", so every filter is `is_staff IS NOT TRUE`, never `= false`. +-- Nullable, no default: DSQL rejects both on ADD COLUMN, so filter with `is_staff IS NOT TRUE`. ALTER TABLE users ADD COLUMN is_staff BOOLEAN; diff --git a/apps/backend/db/migrations/V20261015195442__create_impersonation_sessions.sql b/apps/backend/db/migrations/V20261015195442__create_impersonation_sessions.sql index 96574e13..db1d3246 100644 --- a/apps/backend/db/migrations/V20261015195442__create_impersonation_sessions.sql +++ b/apps/backend/db/migrations/V20261015195442__create_impersonation_sessions.sql @@ -1,7 +1,4 @@ --- V20261015195442__create_impersonation_sessions --- --- One row per staff switch-in. No foreign keys: the audit trail must outlive --- the users it names. +-- No foreign keys: the audit trail must outlive the users it names. CREATE TABLE impersonation_sessions ( session_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), diff --git a/apps/backend/db/migrations/V20261015195443__create_impersonation_actions.sql b/apps/backend/db/migrations/V20261015195443__create_impersonation_actions.sql index 8c112763..8c945e64 100644 --- a/apps/backend/db/migrations/V20261015195443__create_impersonation_actions.sql +++ b/apps/backend/db/migrations/V20261015195443__create_impersonation_actions.sql @@ -1,7 +1,3 @@ --- V20261015195443__create_impersonation_actions --- --- Every mutating request made while impersonating in full mode. - CREATE TABLE impersonation_actions ( action_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), session_id UUID NOT NULL, diff --git a/apps/backend/lambdas/auth/auth.ts b/apps/backend/lambdas/auth/auth.ts index 37611488..74ab0e8e 100644 --- a/apps/backend/lambdas/auth/auth.ts +++ b/apps/backend/lambdas/auth/auth.ts @@ -18,5 +18,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** Audit row per write made while a staff account is impersonating. */ export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/auth/controllers/auth.ts b/apps/backend/lambdas/auth/controllers/auth.ts index b8bca253..0dc54133 100644 --- a/apps/backend/lambdas/auth/controllers/auth.ts +++ b/apps/backend/lambdas/auth/controllers/auth.ts @@ -220,7 +220,6 @@ export const handleMe: RouteHandler = async ({ auth }) => { isAdmin: me.isAdmin, isStaff: me.isStaff, profileImage: await resolveProfileImage(me.profileImage), - // Set while a staff account is switched in; the banner reads it. impersonation: auth.context.user?.impersonator ?? null, // The RBAC subject travels with identity so the browser evaluates the same // policy against the same facts the lambdas used. Without it the frontend diff --git a/apps/backend/lambdas/auth/controllers/impersonation.ts b/apps/backend/lambdas/auth/controllers/impersonation.ts index 0a2ae4b1..0978c10f 100644 --- a/apps/backend/lambdas/auth/controllers/impersonation.ts +++ b/apps/backend/lambdas/auth/controllers/impersonation.ts @@ -4,14 +4,12 @@ import { DIRECTOR_ROLES } from '@branch/lambda-auth'; import type { ImpersonationMode } from '@branch/lambda-auth'; import { db, endImpersonationSession, startImpersonationSession } from '@branch/store'; -/** How long one switch-in lasts before the staff console has to start another. */ export const SESSION_TTL_MS = 60 * 60 * 1000; const MODES: readonly ImpersonationMode[] = ['read_only', 'full']; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const TARGET_LIMIT = 200; -/** GET /auth/impersonation/targets?search= -- everyone a staff account may switch into. */ export const handleListTargets: RouteHandler = async ({ event }) => { const search = String(event.queryStringParameters?.search ?? '').trim(); @@ -52,7 +50,6 @@ export const handleListTargets: RouteHandler = async ({ event }) => { name: u.name, email: u.email, isAdmin: u.is_admin === true, - // Never signed in: their account exists but nothing they see is real yet. pending: u.cognito_sub === null, directorProjectCount: counts.get(u.user_id)?.directs ?? 0, memberProjectCount: counts.get(u.user_id)?.member ?? 0, @@ -60,7 +57,6 @@ export const handleListTargets: RouteHandler = async ({ event }) => { }); }; -/** POST /auth/impersonation { targetUserId, mode } -- start a switch-in. */ export const handleStartImpersonation: RouteHandler = async ({ event, auth }) => { const body = parseBody(event); const targetUserId = Number(body?.targetUserId); @@ -96,11 +92,7 @@ export const handleStartImpersonation: RouteHandler = async ({ event, auth }) => }); }; -/** - * DELETE /auth/impersonation/:sessionId -- end a switch-in. Called as the staff - * account itself, without the impersonation header, so a read-only session can - * always be left. Idempotent. - */ +// Called as the staff account, without the impersonation header, so a read-only session can always be left. export const handleEndImpersonation: RouteHandler = async ({ params, auth }) => { if (!UUID.test(params.sessionId)) return json(404, { message: 'Session not found' }); diff --git a/apps/backend/lambdas/auth/routes.ts b/apps/backend/lambdas/auth/routes.ts index b18dc031..50aaa606 100644 --- a/apps/backend/lambdas/auth/routes.ts +++ b/apps/backend/lambdas/auth/routes.ts @@ -46,8 +46,6 @@ export const routes: Route[] = [ { method: 'POST', pattern: '/auth/mfa-verify', access: 'authenticated', impersonation: 'blocked', handler: handleMfaVerify }, { method: 'POST', pattern: '/auth/mfa-disable', access: 'authenticated', impersonation: 'blocked', handler: handleMfaDisable }, { method: 'GET', pattern: '/auth/mfa-status', access: 'authenticated', impersonation: 'blocked', handler: handleMfaStatus }, - // Staff console. MFA above is blocked while impersonating: it acts on the - // caller's Cognito session, which is then the staff account's. { method: 'GET', pattern: '/auth/impersonation/targets', permission: 'impersonation:console', handler: handleListTargets }, { method: 'POST', pattern: '/auth/impersonation', permission: 'impersonation:start', handler: handleStartImpersonation }, { method: 'DELETE', pattern: '/auth/impersonation/:sessionId', permission: 'impersonation:start', handler: handleEndImpersonation }, diff --git a/apps/backend/lambdas/auth/test/impersonation.e2e.test.ts b/apps/backend/lambdas/auth/test/impersonation.e2e.test.ts index 25122da2..ebcaaa9d 100644 --- a/apps/backend/lambdas/auth/test/impersonation.e2e.test.ts +++ b/apps/backend/lambdas/auth/test/impersonation.e2e.test.ts @@ -1,6 +1,4 @@ -// Real authenticateRequest, real dispatch, real DB: only the JWT signature check -// is faked, and the token is simply the caller's Cognito sub. Mocked by the path -// @branch/lambda-auth resolves it from, which is its own node_modules, not ours. +// Mocked at the path @branch/lambda-auth resolves it from: its own node_modules, not ours. jest.mock(require.resolve('aws-jwt-verify', { paths: [require.resolve('@branch/lambda-auth')] }), () => ({ CognitoJwtVerifier: { create: () => ({ verify: async (token: string) => ({ sub: token }) }), @@ -21,7 +19,6 @@ const pool = new Pool({ ssl: false, }); -// Seed user 4 directs project 1; user 6 is a student on project 2. const TARGET = 4; beforeAll(async () => { @@ -151,7 +148,6 @@ test('full: cannot chain a switch, and every write is audited with its outcome', WHERE session_id = $1 ORDER BY created_at`, [session], ); - // Refused attempts are part of the trail, not just writes that landed. expect(rows).toEqual([ { method: 'POST', path: '/auth/impersonation', status_code: 403 }, { method: 'POST', path: '/auth/mfa-setup', status_code: 403 }, diff --git a/apps/backend/lambdas/donors/auth.ts b/apps/backend/lambdas/donors/auth.ts index 37611488..74ab0e8e 100644 --- a/apps/backend/lambdas/donors/auth.ts +++ b/apps/backend/lambdas/donors/auth.ts @@ -18,5 +18,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** Audit row per write made while a staff account is impersonating. */ export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/expenditures/auth.ts b/apps/backend/lambdas/expenditures/auth.ts index 37611488..74ab0e8e 100644 --- a/apps/backend/lambdas/expenditures/auth.ts +++ b/apps/backend/lambdas/expenditures/auth.ts @@ -18,5 +18,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** Audit row per write made while a staff account is impersonating. */ export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/projects/auth.ts b/apps/backend/lambdas/projects/auth.ts index 37611488..74ab0e8e 100644 --- a/apps/backend/lambdas/projects/auth.ts +++ b/apps/backend/lambdas/projects/auth.ts @@ -18,5 +18,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** Audit row per write made while a staff account is impersonating. */ export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/projects/services/projects.ts b/apps/backend/lambdas/projects/services/projects.ts index 4d7ecdd2..54d08d6c 100644 --- a/apps/backend/lambdas/projects/services/projects.ts +++ b/apps/backend/lambdas/projects/services/projects.ts @@ -224,11 +224,7 @@ export async function findAdminUserIds(members: MemberAssignment[]): Promise row.user_id); } -/** - * Rejects member ids that are not real users, so FK errors never reach the - * client as a 500. A staff account counts as unknown: it can never hold a - * membership, and the error must not confirm one exists. - */ +/** Rejects member ids that are not real users, so FK errors never 500; a staff id counts as unknown so none is confirmed. */ export async function findUnknownUserIds(members: MemberAssignment[]): Promise { if (members.length === 0) return []; const ids = members.map((m) => m.user_id); diff --git a/apps/backend/lambdas/reports/auth.ts b/apps/backend/lambdas/reports/auth.ts index 37611488..74ab0e8e 100644 --- a/apps/backend/lambdas/reports/auth.ts +++ b/apps/backend/lambdas/reports/auth.ts @@ -18,5 +18,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** Audit row per write made while a staff account is impersonating. */ export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/users/auth.ts b/apps/backend/lambdas/users/auth.ts index 37611488..74ab0e8e 100644 --- a/apps/backend/lambdas/users/auth.ts +++ b/apps/backend/lambdas/users/auth.ts @@ -18,5 +18,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** Audit row per write made while a staff account is impersonating. */ export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/users/controllers/users.ts b/apps/backend/lambdas/users/controllers/users.ts index a7840f54..3c2a210a 100644 --- a/apps/backend/lambdas/users/controllers/users.ts +++ b/apps/backend/lambdas/users/controllers/users.ts @@ -21,8 +21,7 @@ const cognitoClient = new CognitoIdentityProviderClient({ const USER_POOL_ID = process.env.COGNITO_USER_POOL_ID || ''; -// Staff accounts are invisible here: every read filters them out and the column -// itself is never returned. A staff id answers 404, exactly like a missing one. +// A staff id answers 404, exactly like a missing one, so none is confirmed. const USER_COLUMNS = [ 'user_id', 'cognito_sub', diff --git a/apps/backend/lambdas/users/scripts/create-staff-account.ts b/apps/backend/lambdas/users/scripts/create-staff-account.ts index 0dde62d2..8dca5bb2 100644 --- a/apps/backend/lambdas/users/scripts/create-staff-account.ts +++ b/apps/backend/lambdas/users/scripts/create-staff-account.ts @@ -1,15 +1,4 @@ -/** - * Provision a hidden staff account. The only way one is ever created: no route - * can set users.is_staff. - * - * COGNITO_USER_POOL_ID=... DB_HOST=... \ - * npm run create-staff -- --email dev@example.com --name "Dev Name" - * - * Mirrors POST /users: AdminCreateUser mails the invite with a temp password, - * then the row is inserted with that sub; a failed insert deletes the Cognito - * user again. Against production, DB_HOST is the DSQL endpoint and the caller's - * AWS credentials mint the IAM token. - */ +// The only way a staff account is created: no route can set users.is_staff. import { AdminCreateUserCommand, AdminDeleteUserCommand, diff --git a/apps/backend/lambdas/users/test/user.photos.unit.test.ts b/apps/backend/lambdas/users/test/user.photos.unit.test.ts index bbec16f8..843369fe 100644 --- a/apps/backend/lambdas/users/test/user.photos.unit.test.ts +++ b/apps/backend/lambdas/users/test/user.photos.unit.test.ts @@ -59,7 +59,6 @@ function mockSelfAuth(userId = 1) { } as any); } -/** Any where/select chain ending in executeTakeFirst, whatever its length. */ function selectChain(row: unknown) { const chain: any = { where: jest.fn(() => chain), diff --git a/apps/frontend/src/app/components/ImpersonationBanner.tsx b/apps/frontend/src/app/components/ImpersonationBanner.tsx index 644816db..1801d02f 100644 --- a/apps/frontend/src/app/components/ImpersonationBanner.tsx +++ b/apps/frontend/src/app/components/ImpersonationBanner.tsx @@ -12,11 +12,6 @@ function timeOf(iso: string): string { }); } -/** - * Shown on every page while a staff account is switched into someone else, so - * nobody forgets whose data they are looking at, or that a full session's - * writes are real. - */ export default function ImpersonationBanner() { const { user, stopImpersonation } = useAuth(); const router = useRouter(); diff --git a/apps/frontend/src/app/staff/page.tsx b/apps/frontend/src/app/staff/page.tsx index 4f816817..a68eb60b 100644 --- a/apps/frontend/src/app/staff/page.tsx +++ b/apps/frontend/src/app/staff/page.tsx @@ -29,10 +29,6 @@ function roleOf(t: Target): string { return t.memberProjectCount > 0 ? 'Member' : 'No projects'; } -/** - * The staff console: the only page a staff account can open as itself. Picking - * a user starts a session as them; the banner in providers.tsx is the way back. - */ export default function StaffConsolePage() { const api = useApi(); const router = useRouter(); @@ -77,7 +73,6 @@ export default function StaffConsolePage() { router.replace(landingPathFor(me.rbac)); } catch (err) { setSwitching(null); - // Rethrown so the full-access dialog stays open and shows it. setError( err instanceof Error ? err.message : 'Could not switch into this user', ); diff --git a/apps/frontend/src/context/AuthContext.tsx b/apps/frontend/src/context/AuthContext.tsx index be3513f4..0ce4d00e 100644 --- a/apps/frontend/src/context/AuthContext.tsx +++ b/apps/frontend/src/context/AuthContext.tsx @@ -59,15 +59,12 @@ export interface AuthUser { * into a signed-in session that is denied everything. */ rbac: RbacSubject; - /** A staff account acting as itself. False while impersonating. */ isStaff?: boolean; - /** Set while a staff account is switched into this user. */ impersonation?: Impersonation | null; } export type ImpersonationMode = 'read_only' | 'full'; -/** The staff account behind the session, as GET /auth/me reports it. */ export interface Impersonation { userId: number; name: string; @@ -119,9 +116,7 @@ interface AuthContextValue { logout: () => Promise; refresh: () => Promise; reloadUser: () => Promise; - /** Staff only. Resolves with the target's session once it is in place. */ startImpersonation: (targetUserId: number, mode: ImpersonationMode) => Promise; - /** Back to the staff account. Safe to call when not impersonating. */ stopImpersonation: () => Promise; forgotPassword: (email: string) => Promise; resetPassword: ( @@ -220,10 +215,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { const fetchMe = useCallback(() => authedFetch('/auth/me'), []); - /** - * Swap whose session this is. The whole cache goes, not just /auth/me: every - * other entry was fetched as the previous identity. - */ + /** Clears the whole cache, not just /auth/me: every entry was fetched as the previous identity. */ const replaceIdentity = useCallback( (next: AuthUser | null) => { queryClient.clear(); @@ -292,7 +284,6 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { [setUser], ); - // The server ended a switch-in (expiry, or another tab): fall back to staff. useEffect( () => onImpersonationEnded(() => { @@ -433,7 +424,6 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { const sessionId = getImpersonationSession(); if (!sessionId) return; clearImpersonationSession(); - // Best effort: the session expires on its own within the hour regardless. await authedFetch(`/auth/impersonation/${encodeURIComponent(sessionId)}`, { method: 'DELETE', asSelf: true, @@ -452,7 +442,6 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { // Best effort: clear locally even if the server call fails. }); endSession(); - // Clear, not just null: the next account in this tab must not see this one's cache. replaceIdentity(null); }, [replaceIdentity, stopImpersonation]); diff --git a/apps/frontend/src/lib/authClient.ts b/apps/frontend/src/lib/authClient.ts index 1971d394..9429f92d 100644 --- a/apps/frontend/src/lib/authClient.ts +++ b/apps/frontend/src/lib/authClient.ts @@ -51,10 +51,6 @@ export function endSession(): void { const impersonationListeners = new Set<() => void>(); -/** - * Subscribe to the server ending a switch-in (expired, or ended from another - * tab). The staff account's own session is still good when this fires. - */ export function onImpersonationEnded(listener: () => void): () => void { impersonationListeners.add(listener); return () => impersonationListeners.delete(listener); @@ -118,10 +114,6 @@ export function refreshSession(): Promise { export interface AuthedRequestOptions extends RequestInit { /** Set false to skip the refresh-and-retry dance (used when signing out). */ retryOn401?: boolean; - /** - * Send as the signed-in staff account even while switched in. For the staff - * console's own calls: starting and ending a session. - */ asSelf?: boolean; } @@ -143,10 +135,7 @@ export async function authedFetch( }); } catch (error) { if (!isImpersonationFailure(error)) throw error; - // The switch-in is over, not the session: drop it and say so. A read is - // retried as the staff account, so the bootstrap /auth/me lands on the - // console instead of signing staff out; a write is never re-sent as someone - // else. + // 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(); diff --git a/apps/frontend/src/lib/authTokens.ts b/apps/frontend/src/lib/authTokens.ts index 9d89c3aa..e7400276 100644 --- a/apps/frontend/src/lib/authTokens.ts +++ b/apps/frontend/src/lib/authTokens.ts @@ -80,10 +80,7 @@ export function clearTokens(): void { } } -/** - * The staff console's switch-in, if any. sessionStorage rather than - * localStorage: it is scoped to one tab, so other tabs stay the staff account. - */ +/** sessionStorage, not localStorage: tab-scoped, so other tabs stay the staff account. */ const IMPERSONATION_KEY = 'branch_impersonation_session'; export function getImpersonationSession(): string | null { diff --git a/apps/frontend/test/rbac.ts b/apps/frontend/test/rbac.ts index e1cf5d64..87903dd8 100644 --- a/apps/frontend/test/rbac.ts +++ b/apps/frontend/test/rbac.ts @@ -30,7 +30,6 @@ export const directorSubject = (projectIds: number[] = [1], userId = 2): RbacSub export const memberSubject = (projectIds: number[] = [1], userId = 3): RbacSubject => subjectFor({ userId, memberProjectIds: projectIds }); -/** A hidden staff account acting as itself: only the staff console is open to it. */ export const staffSubject = (userId = 50): RbacSubject => subjectFor({ userId, isStaff: true }); export const anonymousSubject = ANONYMOUS; diff --git a/apps/frontend/test/utils.tsx b/apps/frontend/test/utils.tsx index d90415e7..1ccbba12 100644 --- a/apps/frontend/test/utils.tsx +++ b/apps/frontend/test/utils.tsx @@ -83,7 +83,6 @@ function makeWrapper(subject: RbacSubject | null, auth: Record interface Options extends Omit { /** `null` renders signed out. Defaults to an admin. */ subject?: RbacSubject | null; - /** Overrides merged into the `useAuth()` value, e.g. a `user` or an action mock. */ auth?: Record; } diff --git a/shared/lambda-auth/src/authenticate.ts b/shared/lambda-auth/src/authenticate.ts index 18e96d5f..29949ac9 100644 --- a/shared/lambda-auth/src/authenticate.ts +++ b/shared/lambda-auth/src/authenticate.ts @@ -48,7 +48,6 @@ export function extractToken(event: any): string | null { return authHeader; } -/** Sent by the staff console on every request made while switched in. */ export const IMPERSONATION_HEADER = 'x-impersonate-session'; export function extractImpersonationSession(event: any): string | null { @@ -141,11 +140,6 @@ export async function authenticateRequest( return { user, isAuthenticated: true }; } -/** - * The caller's `branch.users` row fanned out over its memberships, in one round - * trip. LEFT because a user with no memberships must still authenticate; an - * inner join would sign them out. - */ async function selectIdentity( db: QueryableDb, column: 'u.cognito_sub' | 'u.user_id', @@ -215,13 +209,7 @@ function refuse(failure: AuthFailure): AuthContext { return { isAuthenticated: false, failure }; } -/** - * Swap a staff caller for the user their session names. Everything downstream — - * the subject, list scoping, `entered_by` — then sees only the target. - * - * A header from a non-staff caller is refused rather than ignored: silently - * serving them as themselves would hide a client bug or a probe. - */ +/** A header from a non-staff caller is refused, not ignored: ignoring it would hide a client bug or a probe. */ async function impersonate( db: QueryableDb, staff: CallerRow, diff --git a/shared/lambda-auth/test/authenticate.test.ts b/shared/lambda-auth/test/authenticate.test.ts index c8ff303c..50f910b7 100644 --- a/shared/lambda-auth/test/authenticate.test.ts +++ b/shared/lambda-auth/test/authenticate.test.ts @@ -357,11 +357,6 @@ describe('authenticateRequest', () => { }); }); -/** - * Routes each query by table. The identity query is filtered by its one - * `where`; the session query by all of them, so a test proves the session is - * bound to the calling staff account and not just looked up by id. - */ function makeImpersonationDb(users: any[], sessions: any[]) { const chain = (run: (filters: [string, unknown][]) => unknown[]) => { const filters: [string, unknown][] = []; diff --git a/shared/lambda-http/src/dispatch.ts b/shared/lambda-http/src/dispatch.ts index 05146814..e5e26430 100644 --- a/shared/lambda-http/src/dispatch.ts +++ b/shared/lambda-http/src/dispatch.ts @@ -74,7 +74,6 @@ export async function dispatch( } } -/** `auth` is kept on a refusal when the caller was identified, so it can be audited. */ type Gate = | { auth: RequestAuth; response?: undefined } | { auth?: RequestAuth; response: APIGatewayProxyResult }; diff --git a/shared/lambda-http/src/types.ts b/shared/lambda-http/src/types.ts index b0ab2843..ca3c986e 100644 --- a/shared/lambda-http/src/types.ts +++ b/shared/lambda-http/src/types.ts @@ -35,11 +35,7 @@ interface RouteBase { /** Full prefixed path pattern with `:param` segments, e.g. `/projects/:id/members`. */ pattern: string; handler: RouteHandler; - /** - * `'blocked'` refuses the route to an impersonated request in either mode: - * for routes that act on the caller's own Cognito session, which while - * impersonating is the staff account's, not the target's. - */ + /** `'blocked'`: for routes acting on the caller's own Cognito session, which while impersonating is the staff account's. */ impersonation?: 'blocked'; } @@ -69,10 +65,7 @@ export interface DispatchOptions { * route without it. */ resolveAuth?: (event: any) => Promise; - /** - * Audit hook, awaited after every mutating request made while impersonating. - * A failure is reported, never surfaced: the write has already happened. - */ + /** A failure is reported, never surfaced: the write has already happened. */ onImpersonatedWrite?: ( impersonator: Impersonator, method: string, diff --git a/shared/rbac/src/policy.ts b/shared/rbac/src/policy.ts index 6dafadab..6650cb09 100644 --- a/shared/rbac/src/policy.ts +++ b/shared/rbac/src/policy.ts @@ -219,9 +219,7 @@ export const POLICY = { 'accounts:delete': unscoped(ADMIN_ONLY, admin), // -- Impersonation -------------------------------------------------------- - // The only actions a staff subject passes; see the gate in authorizeAny. - // While impersonating the subject is the target's, so these deny and a - // switch cannot be chained. + // While impersonating the subject is the target's, so these deny and a switch cannot be chained. 'impersonation:console': unscoped(STAFF_ONLY, (s) => s.isStaff), 'impersonation:start': unscoped(STAFF_ONLY, (s) => s.isStaff), } satisfies Record>; @@ -287,7 +285,6 @@ export function authorizeAny( const s = subject ?? ANONYMOUS; - // A staff account holds no rights of its own, whatever a rule below says. if (s.isStaff && !STAFF_ACTIONS.has(action)) return deny(STAFF_MUST_SWITCH); // Fail closed. A caller that forgot the resource must not get a rule diff --git a/shared/rbac/src/subject.ts b/shared/rbac/src/subject.ts index 17d29bd5..25e95353 100644 --- a/shared/rbac/src/subject.ts +++ b/shared/rbac/src/subject.ts @@ -7,10 +7,6 @@ export interface RbacSubject { userId: number | null; isAdmin: boolean; - /** - * A hidden staff account acting as itself. Always false while impersonating: - * the subject is then the target's. - */ isStaff: boolean; /** Every project this user has any membership row on. */ memberProjectIds: number[]; diff --git a/shared/store/src/impersonation.ts b/shared/store/src/impersonation.ts index e8df39e9..4376586d 100644 --- a/shared/store/src/impersonation.ts +++ b/shared/store/src/impersonation.ts @@ -5,8 +5,7 @@ export interface NewImpersonationSession { staffUserId: number targetUserId: number mode: ImpersonationMode - // Passed in rather than defaulted by the column, so expiry is compared against - // one clock: the lambda's. + // Not defaulted by the column, so expiry is compared against one clock: the lambda's. startedAt: Date expiresAt: Date } @@ -28,7 +27,7 @@ export async function startImpersonationSession(values: NewImpersonationSession) }) } -/** Bound to the staff account, so one cannot end another's session. Idempotent. */ +/** Bound to the staff account, so one cannot end another's session. */ export async function endImpersonationSession(sessionId: string, staffUserId: number): Promise { await tx(async (trx) => trx @@ -41,7 +40,6 @@ export async function endImpersonationSession(sessionId: string, staffUserId: nu ) } -/** The `onImpersonatedWrite` hook for `dispatch`. */ export async function recordImpersonationAction( impersonator: Pick, method: string, @@ -56,7 +54,6 @@ export async function recordImpersonationAction( ) } -/** Only the provisioning script creates these; no route can set is_staff. */ export async function createStaffUser(values: { cognitoSub: string email: string diff --git a/shared/store/src/users.ts b/shared/store/src/users.ts index 26b2d4ad..16d9ef80 100644 --- a/shared/store/src/users.ts +++ b/shared/store/src/users.ts @@ -20,7 +20,6 @@ export async function updateUser( .updateTable('branch.users') .set(values) .where('user_id', '=', id) - // Staff rows are not editable through the app; the provisioning script owns them. .where('is_staff', 'is not', true) .returningAll() .executeTakeFirst(), diff --git a/shared/types/auth-types.d.ts b/shared/types/auth-types.d.ts index 276bae05..ab71d277 100644 --- a/shared/types/auth-types.d.ts +++ b/shared/types/auth-types.d.ts @@ -35,14 +35,12 @@ export interface AuthenticatedDbUser { export type ImpersonationMode = 'read_only' | 'full'; -/** The staff account behind an impersonated request. */ export interface Impersonator { userId: number; name: string; email: string; sessionId: string; mode: ImpersonationMode; - /** ISO timestamp. */ expiresAt: string; } @@ -52,9 +50,7 @@ export interface AuthenticatedUser { /** The JWT `email` claim. Not the same field as `dbUser.email`. */ email?: string; isAdmin: boolean; - /** False while impersonating: every identity field is then the target's. */ isStaff?: boolean; - /** Set when a staff account is acting as this user. */ impersonator?: Impersonator; cognitoGroups?: string[]; /** Set whenever `AuthContext.isAuthenticated` is true. */ @@ -71,10 +67,6 @@ export interface AuthenticatedUser { export interface AuthContext { user?: AuthenticatedUser; isAuthenticated: boolean; - /** - * Why an otherwise valid token was refused, when "Authentication required" - * would mislead. Only impersonation sets it today. - */ failure?: AuthFailure; } From 3d5256b405e65b26908fdc145c4887aec1e62c07 Mon Sep 17 00:00:00 2001 From: nourshoreibah Date: Fri, 16 Oct 2026 19:08:06 -0400 Subject: [PATCH 6/9] chore: trim comments Co-Authored-By: Claude Opus 5.5 --- apps/backend/Makefile | 5 +---- .../V20261015195441__add_users_is_staff.sql | 8 +------- ...261015195442__create_impersonation_sessions.sql | 5 +---- ...0261015195443__create_impersonation_actions.sql | 4 ---- apps/backend/lambdas/auth/auth.ts | 1 - apps/backend/lambdas/auth/controllers/auth.ts | 1 - .../lambdas/auth/controllers/impersonation.ts | 10 +--------- apps/backend/lambdas/auth/routes.ts | 2 -- .../lambdas/auth/test/impersonation.e2e.test.ts | 6 +----- apps/backend/lambdas/donors/auth.ts | 1 - apps/backend/lambdas/expenditures/auth.ts | 1 - apps/backend/lambdas/projects/auth.ts | 1 - apps/backend/lambdas/projects/services/projects.ts | 6 +----- apps/backend/lambdas/reports/auth.ts | 1 - apps/backend/lambdas/users/auth.ts | 1 - apps/backend/lambdas/users/controllers/users.ts | 3 +-- .../lambdas/users/scripts/create-staff-account.ts | 13 +------------ .../lambdas/users/test/user.photos.unit.test.ts | 1 - shared/lambda-auth/src/authenticate.ts | 14 +------------- shared/lambda-auth/test/authenticate.test.ts | 5 ----- shared/lambda-http/src/dispatch.ts | 1 - shared/lambda-http/src/types.ts | 11 ++--------- shared/rbac/src/policy.ts | 5 +---- shared/rbac/src/subject.ts | 4 ---- shared/store/src/impersonation.ts | 7 ++----- shared/store/src/users.ts | 1 - shared/types/auth-types.d.ts | 8 -------- 27 files changed, 14 insertions(+), 112 deletions(-) diff --git a/apps/backend/Makefile b/apps/backend/Makefile index 3e907668..11c3fe11 100644 --- a/apps/backend/Makefile +++ b/apps/backend/Makefile @@ -153,10 +153,7 @@ types: -e TYPES_OUT=/shared/types/db-types.d.ts \ migrator npm run --silent types -# usage: make create-staff EMAIL=dev@example.com NAME="Dev Name" -# -# Hidden staff account (see shared/rbac/README.md). Runs on the host against -# whatever COGNITO_USER_POOL_ID / DB_HOST / AWS credentials are exported. +# Runs on the host, against whatever COGNITO_USER_POOL_ID / DB_HOST / AWS credentials are exported. create-staff: @test -n "$(EMAIL)" -a -n "$(NAME)" || (echo 'usage: make create-staff EMAIL=dev@example.com NAME="Dev Name"' && exit 1) @npm --prefix lambdas/users run --silent create-staff -- --email "$(EMAIL)" --name "$(NAME)" diff --git a/apps/backend/db/migrations/V20261015195441__add_users_is_staff.sql b/apps/backend/db/migrations/V20261015195441__add_users_is_staff.sql index 498284e5..e4693586 100644 --- a/apps/backend/db/migrations/V20261015195441__add_users_is_staff.sql +++ b/apps/backend/db/migrations/V20261015195441__add_users_is_staff.sql @@ -1,9 +1,3 @@ --- V20261015195441__add_users_is_staff --- --- Staff accounts are hidden from every user-facing query and can only --- impersonate. See shared/rbac/README.md. --- --- Nullable with no default: DSQL rejects either on ADD COLUMN. NULL means "not --- staff", so every filter is `is_staff IS NOT TRUE`, never `= false`. +-- Nullable, no default: DSQL rejects both on ADD COLUMN, so filter with `is_staff IS NOT TRUE`. ALTER TABLE users ADD COLUMN is_staff BOOLEAN; diff --git a/apps/backend/db/migrations/V20261015195442__create_impersonation_sessions.sql b/apps/backend/db/migrations/V20261015195442__create_impersonation_sessions.sql index 96574e13..db1d3246 100644 --- a/apps/backend/db/migrations/V20261015195442__create_impersonation_sessions.sql +++ b/apps/backend/db/migrations/V20261015195442__create_impersonation_sessions.sql @@ -1,7 +1,4 @@ --- V20261015195442__create_impersonation_sessions --- --- One row per staff switch-in. No foreign keys: the audit trail must outlive --- the users it names. +-- No foreign keys: the audit trail must outlive the users it names. CREATE TABLE impersonation_sessions ( session_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), diff --git a/apps/backend/db/migrations/V20261015195443__create_impersonation_actions.sql b/apps/backend/db/migrations/V20261015195443__create_impersonation_actions.sql index 8c112763..8c945e64 100644 --- a/apps/backend/db/migrations/V20261015195443__create_impersonation_actions.sql +++ b/apps/backend/db/migrations/V20261015195443__create_impersonation_actions.sql @@ -1,7 +1,3 @@ --- V20261015195443__create_impersonation_actions --- --- Every mutating request made while impersonating in full mode. - CREATE TABLE impersonation_actions ( action_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), session_id UUID NOT NULL, diff --git a/apps/backend/lambdas/auth/auth.ts b/apps/backend/lambdas/auth/auth.ts index 37611488..74ab0e8e 100644 --- a/apps/backend/lambdas/auth/auth.ts +++ b/apps/backend/lambdas/auth/auth.ts @@ -18,5 +18,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** Audit row per write made while a staff account is impersonating. */ export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/auth/controllers/auth.ts b/apps/backend/lambdas/auth/controllers/auth.ts index b8bca253..0dc54133 100644 --- a/apps/backend/lambdas/auth/controllers/auth.ts +++ b/apps/backend/lambdas/auth/controllers/auth.ts @@ -220,7 +220,6 @@ export const handleMe: RouteHandler = async ({ auth }) => { isAdmin: me.isAdmin, isStaff: me.isStaff, profileImage: await resolveProfileImage(me.profileImage), - // Set while a staff account is switched in; the banner reads it. impersonation: auth.context.user?.impersonator ?? null, // The RBAC subject travels with identity so the browser evaluates the same // policy against the same facts the lambdas used. Without it the frontend diff --git a/apps/backend/lambdas/auth/controllers/impersonation.ts b/apps/backend/lambdas/auth/controllers/impersonation.ts index 0a2ae4b1..0978c10f 100644 --- a/apps/backend/lambdas/auth/controllers/impersonation.ts +++ b/apps/backend/lambdas/auth/controllers/impersonation.ts @@ -4,14 +4,12 @@ import { DIRECTOR_ROLES } from '@branch/lambda-auth'; import type { ImpersonationMode } from '@branch/lambda-auth'; import { db, endImpersonationSession, startImpersonationSession } from '@branch/store'; -/** How long one switch-in lasts before the staff console has to start another. */ export const SESSION_TTL_MS = 60 * 60 * 1000; const MODES: readonly ImpersonationMode[] = ['read_only', 'full']; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const TARGET_LIMIT = 200; -/** GET /auth/impersonation/targets?search= -- everyone a staff account may switch into. */ export const handleListTargets: RouteHandler = async ({ event }) => { const search = String(event.queryStringParameters?.search ?? '').trim(); @@ -52,7 +50,6 @@ export const handleListTargets: RouteHandler = async ({ event }) => { name: u.name, email: u.email, isAdmin: u.is_admin === true, - // Never signed in: their account exists but nothing they see is real yet. pending: u.cognito_sub === null, directorProjectCount: counts.get(u.user_id)?.directs ?? 0, memberProjectCount: counts.get(u.user_id)?.member ?? 0, @@ -60,7 +57,6 @@ export const handleListTargets: RouteHandler = async ({ event }) => { }); }; -/** POST /auth/impersonation { targetUserId, mode } -- start a switch-in. */ export const handleStartImpersonation: RouteHandler = async ({ event, auth }) => { const body = parseBody(event); const targetUserId = Number(body?.targetUserId); @@ -96,11 +92,7 @@ export const handleStartImpersonation: RouteHandler = async ({ event, auth }) => }); }; -/** - * DELETE /auth/impersonation/:sessionId -- end a switch-in. Called as the staff - * account itself, without the impersonation header, so a read-only session can - * always be left. Idempotent. - */ +// Called as the staff account, without the impersonation header, so a read-only session can always be left. export const handleEndImpersonation: RouteHandler = async ({ params, auth }) => { if (!UUID.test(params.sessionId)) return json(404, { message: 'Session not found' }); diff --git a/apps/backend/lambdas/auth/routes.ts b/apps/backend/lambdas/auth/routes.ts index b18dc031..50aaa606 100644 --- a/apps/backend/lambdas/auth/routes.ts +++ b/apps/backend/lambdas/auth/routes.ts @@ -46,8 +46,6 @@ export const routes: Route[] = [ { method: 'POST', pattern: '/auth/mfa-verify', access: 'authenticated', impersonation: 'blocked', handler: handleMfaVerify }, { method: 'POST', pattern: '/auth/mfa-disable', access: 'authenticated', impersonation: 'blocked', handler: handleMfaDisable }, { method: 'GET', pattern: '/auth/mfa-status', access: 'authenticated', impersonation: 'blocked', handler: handleMfaStatus }, - // Staff console. MFA above is blocked while impersonating: it acts on the - // caller's Cognito session, which is then the staff account's. { method: 'GET', pattern: '/auth/impersonation/targets', permission: 'impersonation:console', handler: handleListTargets }, { method: 'POST', pattern: '/auth/impersonation', permission: 'impersonation:start', handler: handleStartImpersonation }, { method: 'DELETE', pattern: '/auth/impersonation/:sessionId', permission: 'impersonation:start', handler: handleEndImpersonation }, diff --git a/apps/backend/lambdas/auth/test/impersonation.e2e.test.ts b/apps/backend/lambdas/auth/test/impersonation.e2e.test.ts index 25122da2..ebcaaa9d 100644 --- a/apps/backend/lambdas/auth/test/impersonation.e2e.test.ts +++ b/apps/backend/lambdas/auth/test/impersonation.e2e.test.ts @@ -1,6 +1,4 @@ -// Real authenticateRequest, real dispatch, real DB: only the JWT signature check -// is faked, and the token is simply the caller's Cognito sub. Mocked by the path -// @branch/lambda-auth resolves it from, which is its own node_modules, not ours. +// Mocked at the path @branch/lambda-auth resolves it from: its own node_modules, not ours. jest.mock(require.resolve('aws-jwt-verify', { paths: [require.resolve('@branch/lambda-auth')] }), () => ({ CognitoJwtVerifier: { create: () => ({ verify: async (token: string) => ({ sub: token }) }), @@ -21,7 +19,6 @@ const pool = new Pool({ ssl: false, }); -// Seed user 4 directs project 1; user 6 is a student on project 2. const TARGET = 4; beforeAll(async () => { @@ -151,7 +148,6 @@ test('full: cannot chain a switch, and every write is audited with its outcome', WHERE session_id = $1 ORDER BY created_at`, [session], ); - // Refused attempts are part of the trail, not just writes that landed. expect(rows).toEqual([ { method: 'POST', path: '/auth/impersonation', status_code: 403 }, { method: 'POST', path: '/auth/mfa-setup', status_code: 403 }, diff --git a/apps/backend/lambdas/donors/auth.ts b/apps/backend/lambdas/donors/auth.ts index 37611488..74ab0e8e 100644 --- a/apps/backend/lambdas/donors/auth.ts +++ b/apps/backend/lambdas/donors/auth.ts @@ -18,5 +18,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** Audit row per write made while a staff account is impersonating. */ export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/expenditures/auth.ts b/apps/backend/lambdas/expenditures/auth.ts index 37611488..74ab0e8e 100644 --- a/apps/backend/lambdas/expenditures/auth.ts +++ b/apps/backend/lambdas/expenditures/auth.ts @@ -18,5 +18,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** Audit row per write made while a staff account is impersonating. */ export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/projects/auth.ts b/apps/backend/lambdas/projects/auth.ts index 37611488..74ab0e8e 100644 --- a/apps/backend/lambdas/projects/auth.ts +++ b/apps/backend/lambdas/projects/auth.ts @@ -18,5 +18,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** Audit row per write made while a staff account is impersonating. */ export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/projects/services/projects.ts b/apps/backend/lambdas/projects/services/projects.ts index 4d7ecdd2..54d08d6c 100644 --- a/apps/backend/lambdas/projects/services/projects.ts +++ b/apps/backend/lambdas/projects/services/projects.ts @@ -224,11 +224,7 @@ export async function findAdminUserIds(members: MemberAssignment[]): Promise row.user_id); } -/** - * Rejects member ids that are not real users, so FK errors never reach the - * client as a 500. A staff account counts as unknown: it can never hold a - * membership, and the error must not confirm one exists. - */ +/** Rejects member ids that are not real users, so FK errors never 500; a staff id counts as unknown so none is confirmed. */ export async function findUnknownUserIds(members: MemberAssignment[]): Promise { if (members.length === 0) return []; const ids = members.map((m) => m.user_id); diff --git a/apps/backend/lambdas/reports/auth.ts b/apps/backend/lambdas/reports/auth.ts index 37611488..74ab0e8e 100644 --- a/apps/backend/lambdas/reports/auth.ts +++ b/apps/backend/lambdas/reports/auth.ts @@ -18,5 +18,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** Audit row per write made while a staff account is impersonating. */ export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/users/auth.ts b/apps/backend/lambdas/users/auth.ts index 37611488..74ab0e8e 100644 --- a/apps/backend/lambdas/users/auth.ts +++ b/apps/backend/lambdas/users/auth.ts @@ -18,5 +18,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** Audit row per write made while a staff account is impersonating. */ export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/users/controllers/users.ts b/apps/backend/lambdas/users/controllers/users.ts index a7840f54..3c2a210a 100644 --- a/apps/backend/lambdas/users/controllers/users.ts +++ b/apps/backend/lambdas/users/controllers/users.ts @@ -21,8 +21,7 @@ const cognitoClient = new CognitoIdentityProviderClient({ const USER_POOL_ID = process.env.COGNITO_USER_POOL_ID || ''; -// Staff accounts are invisible here: every read filters them out and the column -// itself is never returned. A staff id answers 404, exactly like a missing one. +// A staff id answers 404, exactly like a missing one, so none is confirmed. const USER_COLUMNS = [ 'user_id', 'cognito_sub', diff --git a/apps/backend/lambdas/users/scripts/create-staff-account.ts b/apps/backend/lambdas/users/scripts/create-staff-account.ts index 0dde62d2..8dca5bb2 100644 --- a/apps/backend/lambdas/users/scripts/create-staff-account.ts +++ b/apps/backend/lambdas/users/scripts/create-staff-account.ts @@ -1,15 +1,4 @@ -/** - * Provision a hidden staff account. The only way one is ever created: no route - * can set users.is_staff. - * - * COGNITO_USER_POOL_ID=... DB_HOST=... \ - * npm run create-staff -- --email dev@example.com --name "Dev Name" - * - * Mirrors POST /users: AdminCreateUser mails the invite with a temp password, - * then the row is inserted with that sub; a failed insert deletes the Cognito - * user again. Against production, DB_HOST is the DSQL endpoint and the caller's - * AWS credentials mint the IAM token. - */ +// The only way a staff account is created: no route can set users.is_staff. import { AdminCreateUserCommand, AdminDeleteUserCommand, diff --git a/apps/backend/lambdas/users/test/user.photos.unit.test.ts b/apps/backend/lambdas/users/test/user.photos.unit.test.ts index bbec16f8..843369fe 100644 --- a/apps/backend/lambdas/users/test/user.photos.unit.test.ts +++ b/apps/backend/lambdas/users/test/user.photos.unit.test.ts @@ -59,7 +59,6 @@ function mockSelfAuth(userId = 1) { } as any); } -/** Any where/select chain ending in executeTakeFirst, whatever its length. */ function selectChain(row: unknown) { const chain: any = { where: jest.fn(() => chain), diff --git a/shared/lambda-auth/src/authenticate.ts b/shared/lambda-auth/src/authenticate.ts index 18e96d5f..29949ac9 100644 --- a/shared/lambda-auth/src/authenticate.ts +++ b/shared/lambda-auth/src/authenticate.ts @@ -48,7 +48,6 @@ export function extractToken(event: any): string | null { return authHeader; } -/** Sent by the staff console on every request made while switched in. */ export const IMPERSONATION_HEADER = 'x-impersonate-session'; export function extractImpersonationSession(event: any): string | null { @@ -141,11 +140,6 @@ export async function authenticateRequest( return { user, isAuthenticated: true }; } -/** - * The caller's `branch.users` row fanned out over its memberships, in one round - * trip. LEFT because a user with no memberships must still authenticate; an - * inner join would sign them out. - */ async function selectIdentity( db: QueryableDb, column: 'u.cognito_sub' | 'u.user_id', @@ -215,13 +209,7 @@ function refuse(failure: AuthFailure): AuthContext { return { isAuthenticated: false, failure }; } -/** - * Swap a staff caller for the user their session names. Everything downstream — - * the subject, list scoping, `entered_by` — then sees only the target. - * - * A header from a non-staff caller is refused rather than ignored: silently - * serving them as themselves would hide a client bug or a probe. - */ +/** A header from a non-staff caller is refused, not ignored: ignoring it would hide a client bug or a probe. */ async function impersonate( db: QueryableDb, staff: CallerRow, diff --git a/shared/lambda-auth/test/authenticate.test.ts b/shared/lambda-auth/test/authenticate.test.ts index c8ff303c..50f910b7 100644 --- a/shared/lambda-auth/test/authenticate.test.ts +++ b/shared/lambda-auth/test/authenticate.test.ts @@ -357,11 +357,6 @@ describe('authenticateRequest', () => { }); }); -/** - * Routes each query by table. The identity query is filtered by its one - * `where`; the session query by all of them, so a test proves the session is - * bound to the calling staff account and not just looked up by id. - */ function makeImpersonationDb(users: any[], sessions: any[]) { const chain = (run: (filters: [string, unknown][]) => unknown[]) => { const filters: [string, unknown][] = []; diff --git a/shared/lambda-http/src/dispatch.ts b/shared/lambda-http/src/dispatch.ts index 05146814..e5e26430 100644 --- a/shared/lambda-http/src/dispatch.ts +++ b/shared/lambda-http/src/dispatch.ts @@ -74,7 +74,6 @@ export async function dispatch( } } -/** `auth` is kept on a refusal when the caller was identified, so it can be audited. */ type Gate = | { auth: RequestAuth; response?: undefined } | { auth?: RequestAuth; response: APIGatewayProxyResult }; diff --git a/shared/lambda-http/src/types.ts b/shared/lambda-http/src/types.ts index b0ab2843..ca3c986e 100644 --- a/shared/lambda-http/src/types.ts +++ b/shared/lambda-http/src/types.ts @@ -35,11 +35,7 @@ interface RouteBase { /** Full prefixed path pattern with `:param` segments, e.g. `/projects/:id/members`. */ pattern: string; handler: RouteHandler; - /** - * `'blocked'` refuses the route to an impersonated request in either mode: - * for routes that act on the caller's own Cognito session, which while - * impersonating is the staff account's, not the target's. - */ + /** `'blocked'`: for routes acting on the caller's own Cognito session, which while impersonating is the staff account's. */ impersonation?: 'blocked'; } @@ -69,10 +65,7 @@ export interface DispatchOptions { * route without it. */ resolveAuth?: (event: any) => Promise; - /** - * Audit hook, awaited after every mutating request made while impersonating. - * A failure is reported, never surfaced: the write has already happened. - */ + /** A failure is reported, never surfaced: the write has already happened. */ onImpersonatedWrite?: ( impersonator: Impersonator, method: string, diff --git a/shared/rbac/src/policy.ts b/shared/rbac/src/policy.ts index 6dafadab..6650cb09 100644 --- a/shared/rbac/src/policy.ts +++ b/shared/rbac/src/policy.ts @@ -219,9 +219,7 @@ export const POLICY = { 'accounts:delete': unscoped(ADMIN_ONLY, admin), // -- Impersonation -------------------------------------------------------- - // The only actions a staff subject passes; see the gate in authorizeAny. - // While impersonating the subject is the target's, so these deny and a - // switch cannot be chained. + // While impersonating the subject is the target's, so these deny and a switch cannot be chained. 'impersonation:console': unscoped(STAFF_ONLY, (s) => s.isStaff), 'impersonation:start': unscoped(STAFF_ONLY, (s) => s.isStaff), } satisfies Record>; @@ -287,7 +285,6 @@ export function authorizeAny( const s = subject ?? ANONYMOUS; - // A staff account holds no rights of its own, whatever a rule below says. if (s.isStaff && !STAFF_ACTIONS.has(action)) return deny(STAFF_MUST_SWITCH); // Fail closed. A caller that forgot the resource must not get a rule diff --git a/shared/rbac/src/subject.ts b/shared/rbac/src/subject.ts index 17d29bd5..25e95353 100644 --- a/shared/rbac/src/subject.ts +++ b/shared/rbac/src/subject.ts @@ -7,10 +7,6 @@ export interface RbacSubject { userId: number | null; isAdmin: boolean; - /** - * A hidden staff account acting as itself. Always false while impersonating: - * the subject is then the target's. - */ isStaff: boolean; /** Every project this user has any membership row on. */ memberProjectIds: number[]; diff --git a/shared/store/src/impersonation.ts b/shared/store/src/impersonation.ts index e8df39e9..4376586d 100644 --- a/shared/store/src/impersonation.ts +++ b/shared/store/src/impersonation.ts @@ -5,8 +5,7 @@ export interface NewImpersonationSession { staffUserId: number targetUserId: number mode: ImpersonationMode - // Passed in rather than defaulted by the column, so expiry is compared against - // one clock: the lambda's. + // Not defaulted by the column, so expiry is compared against one clock: the lambda's. startedAt: Date expiresAt: Date } @@ -28,7 +27,7 @@ export async function startImpersonationSession(values: NewImpersonationSession) }) } -/** Bound to the staff account, so one cannot end another's session. Idempotent. */ +/** Bound to the staff account, so one cannot end another's session. */ export async function endImpersonationSession(sessionId: string, staffUserId: number): Promise { await tx(async (trx) => trx @@ -41,7 +40,6 @@ export async function endImpersonationSession(sessionId: string, staffUserId: nu ) } -/** The `onImpersonatedWrite` hook for `dispatch`. */ export async function recordImpersonationAction( impersonator: Pick, method: string, @@ -56,7 +54,6 @@ export async function recordImpersonationAction( ) } -/** Only the provisioning script creates these; no route can set is_staff. */ export async function createStaffUser(values: { cognitoSub: string email: string diff --git a/shared/store/src/users.ts b/shared/store/src/users.ts index 26b2d4ad..16d9ef80 100644 --- a/shared/store/src/users.ts +++ b/shared/store/src/users.ts @@ -20,7 +20,6 @@ export async function updateUser( .updateTable('branch.users') .set(values) .where('user_id', '=', id) - // Staff rows are not editable through the app; the provisioning script owns them. .where('is_staff', 'is not', true) .returningAll() .executeTakeFirst(), diff --git a/shared/types/auth-types.d.ts b/shared/types/auth-types.d.ts index 276bae05..ab71d277 100644 --- a/shared/types/auth-types.d.ts +++ b/shared/types/auth-types.d.ts @@ -35,14 +35,12 @@ export interface AuthenticatedDbUser { export type ImpersonationMode = 'read_only' | 'full'; -/** The staff account behind an impersonated request. */ export interface Impersonator { userId: number; name: string; email: string; sessionId: string; mode: ImpersonationMode; - /** ISO timestamp. */ expiresAt: string; } @@ -52,9 +50,7 @@ export interface AuthenticatedUser { /** The JWT `email` claim. Not the same field as `dbUser.email`. */ email?: string; isAdmin: boolean; - /** False while impersonating: every identity field is then the target's. */ isStaff?: boolean; - /** Set when a staff account is acting as this user. */ impersonator?: Impersonator; cognitoGroups?: string[]; /** Set whenever `AuthContext.isAuthenticated` is true. */ @@ -71,10 +67,6 @@ export interface AuthenticatedUser { export interface AuthContext { user?: AuthenticatedUser; isAuthenticated: boolean; - /** - * Why an otherwise valid token was refused, when "Authentication required" - * would mislead. Only impersonation sets it today. - */ failure?: AuthFailure; } From e262892dae1755c1e0eb1df7ee272efddfcc48fc Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Fri, 16 Oct 2026 23:10:03 +0000 Subject: [PATCH 7/9] chore: regenerate lambda READMEs --- apps/backend/lambdas/auth/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/backend/lambdas/auth/README.md b/apps/backend/lambdas/auth/README.md index 90ba6bee..bc59f407 100644 --- a/apps/backend/lambdas/auth/README.md +++ b/apps/backend/lambdas/auth/README.md @@ -23,6 +23,9 @@ Lambda for auth handler. | POST | /auth/mfa-verify | | | POST | /auth/mfa-disable | | | GET | /auth/mfa-status | | +| GET | /auth/impersonation/targets | | +| POST | /auth/impersonation | | +| DELETE | /auth/impersonation/{sessionId} | | ## Setup From 331bd613a6db1eca87cfbcab7d895240c861632c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Fri, 16 Oct 2026 23:10:20 +0000 Subject: [PATCH 8/9] chore: regenerate lambda READMEs --- apps/backend/lambdas/auth/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/backend/lambdas/auth/README.md b/apps/backend/lambdas/auth/README.md index 90ba6bee..bc59f407 100644 --- a/apps/backend/lambdas/auth/README.md +++ b/apps/backend/lambdas/auth/README.md @@ -23,6 +23,9 @@ Lambda for auth handler. | POST | /auth/mfa-verify | | | POST | /auth/mfa-disable | | | GET | /auth/mfa-status | | +| GET | /auth/impersonation/targets | | +| POST | /auth/impersonation | | +| DELETE | /auth/impersonation/{sessionId} | | ## Setup From 436ca4f88204dc6bf40bcae70b3949b523d0915e Mon Sep 17 00:00:00 2001 From: nourshoreibah Date: Fri, 16 Oct 2026 21:17:11 -0400 Subject: [PATCH 9/9] test(frontend): give the rbac fixture the new isStaff field RbacSubject.isStaff is required as of this PR; the frontend fixture builder failed typecheck without it. Co-Authored-By: Claude Opus 5.5 --- apps/frontend/test/rbac.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/frontend/test/rbac.ts b/apps/frontend/test/rbac.ts index 00f3ced7..d89d584c 100644 --- a/apps/frontend/test/rbac.ts +++ b/apps/frontend/test/rbac.ts @@ -13,6 +13,7 @@ export function subjectFor( ): RbacSubject { return { isAdmin: false, + isStaff: false, memberProjectIds: [], directorProjectIds: [], ...partial,