Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions apps/backend/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
8 changes: 7 additions & 1 deletion apps/backend/Makefile
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -173,6 +178,7 @@ help:
@echo " make new-migration NAME=<x> - 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:"
Expand Down
11 changes: 9 additions & 2 deletions apps/backend/lambdas/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down
3 changes: 3 additions & 0 deletions apps/backend/lambdas/auth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion apps/backend/lambdas/auth/auth.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -17,3 +17,5 @@ export async function authenticateRequest(
export const resolveAuth = createAuthResolver(authenticateRequest, (context) =>
loadRbacSubject(db, context),
);

export const onImpersonatedWrite = recordImpersonationAction;
2 changes: 2 additions & 0 deletions apps/backend/lambdas/auth/controllers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
102 changes: 102 additions & 0 deletions apps/backend/lambdas/auth/controllers/impersonation.ts
Original file line number Diff line number Diff line change
@@ -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<number, { directs: number; member: number }>();
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 });
};
4 changes: 2 additions & 2 deletions apps/backend/lambdas/auth/handler.ts
Original file line number Diff line number Diff line change
@@ -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 });
2 changes: 2 additions & 0 deletions apps/backend/lambdas/auth/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
Loading
Loading