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 2aa213f8..6069907e 100644 --- a/apps/backend/AGENTS.md +++ b/apps/backend/AGENTS.md @@ -83,6 +83,8 @@ The 403 is intentionally identical in both cases, so registration cannot be used 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..11c3fe11 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,11 @@ types: -e TYPES_OUT=/shared/types/db-types.d.ts \ migrator npm run --silent types +# 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 +178,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/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 diff --git a/apps/backend/lambdas/auth/auth.ts b/apps/backend/lambdas/auth/auth.ts index d5f3b4c8..74ab0e8e 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,5 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/auth/controllers/auth.ts b/apps/backend/lambdas/auth/controllers/auth.ts index cd6267c3..0dc54133 100644 --- a/apps/backend/lambdas/auth/controllers/auth.ts +++ b/apps/backend/lambdas/auth/controllers/auth.ts @@ -218,7 +218,9 @@ export const handleMe: RouteHandler = async ({ auth }) => { email: me.email, name: me.name, isAdmin: me.isAdmin, + isStaff: me.isStaff, profileImage: await resolveProfileImage(me.profileImage), + 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..0978c10f --- /dev/null +++ b/apps/backend/lambdas/auth/controllers/impersonation.ts @@ -0,0 +1,102 @@ +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'; + +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; + +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, + pending: u.cognito_sub === null, + directorProjectCount: counts.get(u.user_id)?.directs ?? 0, + memberProjectCount: counts.get(u.user_id)?.member ?? 0, + })), + }); +}; + +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 }, + }); +}; + +// 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' }); + + 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/jest.config.js b/apps/backend/lambdas/auth/jest.config.js index 3ed2e70d..4aafcdc3 100644 --- a/apps/backend/lambdas/auth/jest.config.js +++ b/apps/backend/lambdas/auth/jest.config.js @@ -2,6 +2,8 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testMatch: ['**/*.test.ts'], + // Two e2e suites reset the same database. + maxWorkers: 1, extensionsToTreatAsEsm: ['.ts'], moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1', 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..50aaa606 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,12 @@ 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 }, + { 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.e2e.test.ts b/apps/backend/lambdas/auth/test/auth.e2e.test.ts index 08d1de61..fa618c28 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/auth/test/auth.login.unit.test.ts b/apps/backend/lambdas/auth/test/auth.login.unit.test.ts index c032ef0b..68627101 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..ebcaaa9d --- /dev/null +++ b/apps/backend/lambdas/auth/test/impersonation.e2e.test.ts @@ -0,0 +1,175 @@ +// 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 }) }), + }, +})); + +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, +}); + +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], + ); + 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..74ab0e8e 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,5 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +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..74ab0e8e 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,5 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +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.e2e.test.ts b/apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts index 60767b2f..534b563d 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/expenditures/test/expenditures.unit.test.ts b/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts index d34b03ee..f1fb1ca0 100644 --- a/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts +++ b/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts @@ -454,7 +454,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..74ab0e8e 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,5 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +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..54d08d6c 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,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. */ +/** 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); @@ -230,6 +232,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/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/project-page.unit.test.ts b/apps/backend/lambdas/projects/test/project-page.unit.test.ts index 10a68fbc..2855339f 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/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 loadRbacSubject(db, context), ); + +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/reports/test/report-service.e2e.test.ts b/apps/backend/lambdas/reports/test/report-service.e2e.test.ts index c7d786fe..c4ecc810 100644 --- a/apps/backend/lambdas/reports/test/report-service.e2e.test.ts +++ b/apps/backend/lambdas/reports/test/report-service.e2e.test.ts @@ -12,7 +12,7 @@ import { fetchReportData, keyFromObjectUrl, objectUrlFor, reportKeyPrefix } from 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/reports/test/reports.e2e.test.ts b/apps/backend/lambdas/reports/test/reports.e2e.test.ts index 02629035..b96dd95d 100644 --- a/apps/backend/lambdas/reports/test/reports.e2e.test.ts +++ b/apps/backend/lambdas/reports/test/reports.e2e.test.ts @@ -46,7 +46,7 @@ process.env.REPORTS_BUCKET_NAME = 'bucket'; 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/users/auth.ts b/apps/backend/lambdas/users/auth.ts index d5f3b4c8..74ab0e8e 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,5 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +export const onImpersonatedWrite = recordImpersonationAction; diff --git a/apps/backend/lambdas/users/controllers/users.ts b/apps/backend/lambdas/users/controllers/users.ts index be06bbb0..3c2a210a 100644 --- a/apps/backend/lambdas/users/controllers/users.ts +++ b/apps/backend/lambdas/users/controllers/users.ts @@ -21,6 +21,17 @@ const cognitoClient = new CognitoIdentityProviderClient({ const USER_POOL_ID = process.env.COGNITO_USER_POOL_ID || ''; +// A staff id answers 404, exactly like a missing one, so none is confirmed. +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 +62,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 +92,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 +106,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 +236,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..8dca5bb2 --- /dev/null +++ b/apps/backend/lambdas/users/scripts/create-staff-account.ts @@ -0,0 +1,57 @@ +// The only way a staff account is created: no route can set users.is_staff. +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..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,14 +59,18 @@ function mockSelfAuth(userId = 1) { } as any); } +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/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, diff --git a/infrastructure/aws/api_gateway.tf b/infrastructure/aws/api_gateway.tf index 4ec13dd7..0ec54f40 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 50d67939..adde7342 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..29949ac9 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,18 @@ export function extractToken(event: any): string | null { return authHeader; } +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 +71,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 +111,149 @@ 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 }; +} + +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 }; +} + +/** 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, + 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..50f910b7 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,107 @@ describe('authenticateRequest', () => { ); }); }); + +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..e5e26430 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,31 @@ export async function dispatch( } } -type Gate = { auth: RequestAuth } | { response: APIGatewayProxyResult }; +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 +117,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..ca3c986e 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,8 @@ interface RouteBase { /** Full prefixed path pattern with `:param` segments, e.g. `/projects/:id/members`. */ pattern: string; handler: RouteHandler; + /** `'blocked'`: for routes acting on the caller's own Cognito session, which while impersonating is the staff account's. */ + impersonation?: 'blocked'; } /** @@ -63,4 +65,11 @@ export interface DispatchOptions { * route without it. */ resolveAuth?: (event: any) => Promise; + /** 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..6650cb09 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,22 @@ export const POLICY = { 'accounts:create': unscoped(ADMIN_ONLY, admin), 'accounts:update': unscoped(ADMIN_ONLY, admin), 'accounts:delete': unscoped(ADMIN_ONLY, admin), + + // -- Impersonation -------------------------------------------------------- + // 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 +285,8 @@ export function authorizeAny( const s = subject ?? ANONYMOUS; + 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..25e95353 100644 --- a/shared/rbac/src/subject.ts +++ b/shared/rbac/src/subject.ts @@ -7,6 +7,7 @@ export interface RbacSubject { userId: number | null; isAdmin: boolean; + isStaff: boolean; /** Every project this user has any membership row on. */ memberProjectIds: number[]; /** @@ -43,6 +44,7 @@ export type MemberDisplayRole = ProjectRole | typeof ADMIN_MEMBER_ROLE; export const ANONYMOUS: RbacSubject = { userId: null, isAdmin: false, + isStaff: false, memberProjectIds: [], directorProjectIds: [], }; @@ -61,7 +63,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 +83,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..4376586d --- /dev/null +++ b/shared/store/src/impersonation.ts @@ -0,0 +1,76 @@ +import type { Impersonator, ImpersonationMode } from '@branch/types' +import { tx } from './tx' + +export interface NewImpersonationSession { + staffUserId: number + targetUserId: number + mode: ImpersonationMode + // Not 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. */ +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(), + ) +} + +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(), + ) +} + +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 bd538549..de5d3365 100644 --- a/shared/store/src/index.ts +++ b/shared/store/src/index.ts @@ -32,6 +32,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..16d9ef80 100644 --- a/shared/store/src/users.ts +++ b/shared/store/src/users.ts @@ -20,6 +20,7 @@ export async function updateUser( .updateTable('branch.users') .set(values) .where('user_id', '=', id) + .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..ab71d277 100644 --- a/shared/types/auth-types.d.ts +++ b/shared/types/auth-types.d.ts @@ -29,15 +29,29 @@ export interface AuthenticatedDbUser { email: string; name: string; isAdmin: boolean; + isStaff: boolean; profileImage: string | null; } +export type ImpersonationMode = 'read_only' | 'full'; + +export interface Impersonator { + userId: number; + name: string; + email: string; + sessionId: string; + mode: ImpersonationMode; + expiresAt: string; +} + export interface AuthenticatedUser { cognitoSub: string; userId?: number; /** The JWT `email` claim. Not the same field as `dbUser.email`. */ email?: string; isAdmin: boolean; + isStaff?: boolean; + impersonator?: Impersonator; cognitoGroups?: string[]; /** Set whenever `AuthContext.isAuthenticated` is true. */ dbUser?: AuthenticatedDbUser; @@ -53,6 +67,13 @@ export interface AuthenticatedUser { export interface AuthContext { user?: AuthenticatedUser; isAuthenticated: boolean; + 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,