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: 3 additions & 1 deletion apps/backend/lambdas/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export const getDonor: RouteHandler = async ({ params }) => {
return json(200, { ... });
};
```
- `dispatch()` handles OPTIONS preflight, `GET /<prefix>/health`, 404 and 500 centrally — routes.ts only lists real endpoints.
- `dispatch()` handles OPTIONS preflight, `GET /<prefix>/health` (after awaiting `warmup`), 404 and 500 centrally — routes.ts only lists real endpoints.
- **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.
Expand Down Expand Up @@ -84,6 +84,8 @@ export const onImpersonatedWrite = recordImpersonationAction; // from @branch/st

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.

`auth.ts` also exports `warmup = () => warmAuth(db)` (Cognito JWKS + DB connection). `handler.ts` wraps it in `prewarm()` at module scope, so the work starts during Lambda init, and passes it to `dispatch` as `warmup`. `GET /<prefix>/health` waits for it, and the frontend pings every service's `/health` on page load (`warmServices` in `apps/frontend/src/lib/api.ts`) to absorb cold starts early.

### Two layers, and which one to use

1. **Route level** — declared in `routes.ts`, enforced by `dispatch` before the
Expand Down
8 changes: 7 additions & 1 deletion apps/backend/lambdas/auth/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth';
import {
authenticateRequest as _authenticateRequest,
loadRbacSubject,
warmAuth,
} from '@branch/lambda-auth';
import { createAuthResolver } from '@branch/lambda-http';
import { db, recordImpersonationAction } from '@branch/store';

Expand All @@ -19,3 +23,5 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) =>
);

export const onImpersonatedWrite = recordImpersonationAction;

export const warmup = () => warmAuth(db);
9 changes: 6 additions & 3 deletions apps/backend/lambdas/auth/handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { dispatch } from '@branch/lambda-http';
import { onImpersonatedWrite, resolveAuth } from './auth';
import { dispatch, prewarm } from '@branch/lambda-http';
import { onImpersonatedWrite, resolveAuth, warmup } from './auth';
import { routes } from './routes';

// Module scope, so it starts during init rather than on the first request.
const warm = prewarm(warmup);

export const handler = (event: any) =>
dispatch(event, { prefix: 'auth', routes, resolveAuth, onImpersonatedWrite });
dispatch(event, { prefix: 'auth', routes, resolveAuth, onImpersonatedWrite, warmup: warm });
8 changes: 7 additions & 1 deletion apps/backend/lambdas/donors/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth';
import {
authenticateRequest as _authenticateRequest,
loadRbacSubject,
warmAuth,
} from '@branch/lambda-auth';
import { createAuthResolver } from '@branch/lambda-http';
import { db, recordImpersonationAction } from '@branch/store';

Expand All @@ -19,3 +23,5 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) =>
);

export const onImpersonatedWrite = recordImpersonationAction;

export const warmup = () => warmAuth(db);
9 changes: 6 additions & 3 deletions apps/backend/lambdas/donors/handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { dispatch } from '@branch/lambda-http';
import { onImpersonatedWrite, resolveAuth } from './auth';
import { dispatch, prewarm } from '@branch/lambda-http';
import { onImpersonatedWrite, resolveAuth, warmup } from './auth';
import { routes } from './routes';

// Module scope, so it starts during init rather than on the first request.
const warm = prewarm(warmup);

export const handler = (event: any) =>
dispatch(event, { prefix: 'donors', routes, resolveAuth, onImpersonatedWrite });
dispatch(event, { prefix: 'donors', routes, resolveAuth, onImpersonatedWrite, warmup: warm });
8 changes: 7 additions & 1 deletion apps/backend/lambdas/expenditures/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth';
import {
authenticateRequest as _authenticateRequest,
loadRbacSubject,
warmAuth,
} from '@branch/lambda-auth';
import { createAuthResolver } from '@branch/lambda-http';
import { db, recordImpersonationAction } from '@branch/store';

Expand All @@ -19,3 +23,5 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) =>
);

export const onImpersonatedWrite = recordImpersonationAction;

export const warmup = () => warmAuth(db);
9 changes: 6 additions & 3 deletions apps/backend/lambdas/expenditures/handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { dispatch } from '@branch/lambda-http';
import { onImpersonatedWrite, resolveAuth } from './auth';
import { dispatch, prewarm } from '@branch/lambda-http';
import { onImpersonatedWrite, resolveAuth, warmup } from './auth';
import { routes } from './routes';

// Module scope, so it starts during init rather than on the first request.
const warm = prewarm(warmup);

export const handler = (event: any) =>
dispatch(event, { prefix: 'expenditures', routes, resolveAuth, onImpersonatedWrite });
dispatch(event, { prefix: 'expenditures', routes, resolveAuth, onImpersonatedWrite, warmup: warm });
8 changes: 7 additions & 1 deletion apps/backend/lambdas/projects/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth';
import {
authenticateRequest as _authenticateRequest,
loadRbacSubject,
warmAuth,
} from '@branch/lambda-auth';
import { createAuthResolver } from '@branch/lambda-http';
import { db, recordImpersonationAction } from '@branch/store';

Expand All @@ -19,3 +23,5 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) =>
);

export const onImpersonatedWrite = recordImpersonationAction;

export const warmup = () => warmAuth(db);
9 changes: 6 additions & 3 deletions apps/backend/lambdas/projects/handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { dispatch } from '@branch/lambda-http';
import { onImpersonatedWrite, resolveAuth } from './auth';
import { dispatch, prewarm } from '@branch/lambda-http';
import { onImpersonatedWrite, resolveAuth, warmup } from './auth';
import { routes } from './routes';

// Module scope, so it starts during init rather than on the first request.
const warm = prewarm(warmup);

export const handler = (event: any) =>
dispatch(event, { prefix: 'projects', routes, resolveAuth, onImpersonatedWrite });
dispatch(event, { prefix: 'projects', routes, resolveAuth, onImpersonatedWrite, warmup: warm });
8 changes: 7 additions & 1 deletion apps/backend/lambdas/reports/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth';
import {
authenticateRequest as _authenticateRequest,
loadRbacSubject,
warmAuth,
} from '@branch/lambda-auth';
import { createAuthResolver } from '@branch/lambda-http';
import { db, recordImpersonationAction } from '@branch/store';

Expand All @@ -19,3 +23,5 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) =>
);

export const onImpersonatedWrite = recordImpersonationAction;

export const warmup = () => warmAuth(db);
9 changes: 6 additions & 3 deletions apps/backend/lambdas/reports/handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { dispatch } from '@branch/lambda-http';
import { onImpersonatedWrite, resolveAuth } from './auth';
import { dispatch, prewarm } from '@branch/lambda-http';
import { onImpersonatedWrite, resolveAuth, warmup } from './auth';
import { routes } from './routes';

// Module scope, so it starts during init rather than on the first request.
const warm = prewarm(warmup);

export const handler = (event: any) =>
dispatch(event, { prefix: 'reports', routes, resolveAuth, onImpersonatedWrite });
dispatch(event, { prefix: 'reports', routes, resolveAuth, onImpersonatedWrite, warmup: warm });
8 changes: 7 additions & 1 deletion apps/backend/lambdas/users/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth';
import {
authenticateRequest as _authenticateRequest,
loadRbacSubject,
warmAuth,
} from '@branch/lambda-auth';
import { createAuthResolver } from '@branch/lambda-http';
import { db, recordImpersonationAction } from '@branch/store';

Expand All @@ -19,3 +23,5 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) =>
);

export const onImpersonatedWrite = recordImpersonationAction;

export const warmup = () => warmAuth(db);
9 changes: 6 additions & 3 deletions apps/backend/lambdas/users/handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { dispatch } from '@branch/lambda-http';
import { onImpersonatedWrite, resolveAuth } from './auth';
import { dispatch, prewarm } from '@branch/lambda-http';
import { onImpersonatedWrite, resolveAuth, warmup } from './auth';
import { routes } from './routes';

// Module scope, so it starts during init rather than on the first request.
const warm = prewarm(warmup);

export const handler = (event: any) =>
dispatch(event, { prefix: 'users', routes, resolveAuth, onImpersonatedWrite });
dispatch(event, { prefix: 'users', routes, resolveAuth, onImpersonatedWrite, warmup: warm });
5 changes: 4 additions & 1 deletion apps/frontend/src/app/providers.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
'use client';

import { useState } from 'react';
import { useEffect, useState } from 'react';
import { usePathname } from 'next/navigation';
import { classifyRoute } from '@/lib/routes';
import { ChakraProvider, defaultSystem } from '@chakra-ui/react';
import { QueryClientProvider } from '@tanstack/react-query';
import { AuthProvider } from '@/context/AuthContext';
import { makeQueryClient } from '@/lib/queryClient';
import { warmServices } from '@/lib/api';
import AuthGate from './components/AuthGate';
import ImpersonationBanner from './components/ImpersonationBanner';
import RoutePrefetcher from './components/RoutePrefetcher';
Expand All @@ -25,6 +26,8 @@ export function Providers({ children }: { children: React.ReactNode }) {
const [queryClient] = useState(makeQueryClient);
const pathname = usePathname() ?? '/';

useEffect(warmServices, []);

// Chakra's Emotion styles break hydration on prerendered open pages.
if (classifyRoute(pathname) === 'open') return <>{children}</>;

Expand Down
14 changes: 14 additions & 0 deletions apps/frontend/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,20 @@ function resolveBaseUrl(path: string): string {
return `http://localhost:${port}`;
}

let servicesWarmed = false;

export function warmServices(): void {
if (servicesWarmed) return;
servicesWarmed = true;
for (const service of Object.keys(SERVICE_PORTS)) {
const path = `/${service}/health`;
// no-cors GET is a CORS simple request: no preflight.
fetch(`${resolveBaseUrl(path)}${path}`, { mode: 'no-cors' }).catch(
() => {},
);
}
}

/**
* A failed HTTP response, carrying the status so callers can branch on it.
*
Expand Down
17 changes: 17 additions & 0 deletions apps/frontend/test/lib/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,20 @@ describe('apiFetch', () => {
await expect(apiFetch('/auth/login')).rejects.toThrow('Bad Request');
});
});

describe('warmServices', () => {
it('pings every service health endpoint once, without a preflight', async () => {
const { warmServices } = await import('@/lib/api');
global.fetch = jest.fn().mockResolvedValue({} as Response);
warmServices();
warmServices();

const calls = (global.fetch as jest.Mock).mock.calls;
expect(calls.map(([url]) => new URL(url as string).pathname).sort()).toEqual(
['auth', 'donors', 'expenditures', 'projects', 'reports', 'users'].map(
(s) => `/${s}/health`,
),
);
for (const [, init] of calls) expect(init).toEqual({ mode: 'no-cors' });
});
});
12 changes: 12 additions & 0 deletions shared/lambda-auth/src/authenticate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,18 @@ function getVerifier() {
return verifier;
}

export async function warmAuth(db: QueryableDb): Promise<void> {
await Promise.all([
getVerifier().hydrate(),
db
.selectFrom('branch.users')
.select('user_id')
.where('deleted_at', 'is', null)
.limit(1)
.execute(),
]);
}

export function extractToken(event: any): string | null {
const authHeader = event.headers?.Authorization || event.headers?.authorization;
if (!authHeader) return null;
Expand Down
1 change: 1 addition & 0 deletions shared/lambda-auth/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export {
authenticateRequest,
extractImpersonationSession,
IMPERSONATION_HEADER,
warmAuth,
} from './authenticate';
export { loadRbacSubject, preloadedSubject } from './rbac';
// The policy itself is re-exported so a lambda needs one import for auth and
Expand Down
17 changes: 17 additions & 0 deletions shared/lambda-auth/test/authenticate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,23 @@ describe('authenticateRequest', () => {
});
});

describe('warmAuth', () => {
it('hydrates the JWKS and opens the DB connection in parallel', async () => {
const hydrate = jest.fn().mockResolvedValue(undefined);
mockCreate.mockReturnValueOnce({ verify: mockVerify, hydrate } as any);
const execute = jest.fn().mockResolvedValue([]);
const chain = { select: () => chain, where: () => chain, limit: () => chain, execute };
const db = { selectFrom: jest.fn(() => chain) };

const { warmAuth } = await loadModule();
await warmAuth(db);

expect(hydrate).toHaveBeenCalledTimes(1);
expect(db.selectFrom).toHaveBeenCalledWith('branch.users');
expect(execute).toHaveBeenCalledTimes(1);
});
});

function makeImpersonationDb(users: any[], sessions: any[]) {
const chain = (run: (filters: [string, unknown][]) => unknown[]) => {
const filters: [string, unknown][] = [];
Expand Down
7 changes: 5 additions & 2 deletions shared/lambda-http/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ the row is loaded.
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 /<prefix>/health`, 404, and 500.
- OPTIONS preflight, `GET /<prefix>/health`, 404, and 500. Health awaits the
optional `warmup` first, so the frontend's load-time ping leaves a cold
container with its JWKS and DB connection ready.
- CORS headers on every response, via `json`.
- **Sentry reporting for the 500 path.** The Sentry Lambda layer wraps the
handler and records *uncaught throws* only. Every lambda catches instead, so
Expand All @@ -69,7 +71,8 @@ the row is loaded.

| Export | Purpose |
| --- | --- |
| `dispatch(event, { prefix, routes, resolveAuth, onImpersonatedWrite })` | Route an event; returns a response. |
| `dispatch(event, { prefix, routes, resolveAuth, onImpersonatedWrite, warmup })` | Route an event; returns a response. |
| `prewarm(warm)` | Start `warm` at module scope (Lambda only) and return the `warmup` health awaits. |
| `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. |
Expand Down
3 changes: 2 additions & 1 deletion shared/lambda-http/src/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import type { DispatchOptions, RequestAuth, Route } from './types';
*/
export async function dispatch(
event: any,
{ prefix, routes, resolveAuth, onImpersonatedWrite }: DispatchOptions,
{ prefix, routes, resolveAuth, onImpersonatedWrite, warmup }: DispatchOptions,
): Promise<APIGatewayProxyResult> {
// Hoisted out of the try so the catch can name the route that failed.
const rawPath: string = event?.rawPath || event?.path || '/';
Expand All @@ -43,6 +43,7 @@ export async function dispatch(
if (method === 'OPTIONS') return json(200, {});

if (path === `${base}/health` && method === 'GET') {
await warmup?.();
return json(200, { ok: true, timestamp: new Date().toISOString() });
}

Expand Down
1 change: 1 addition & 0 deletions shared/lambda-http/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export { dispatch } from './dispatch';
export { parseBody } from './body';
export { requirePermission, createAuthResolver, ANONYMOUS_AUTH } from './authz';
export { reportError, serverError } from './errors';
export { prewarm } from './warmup';
1 change: 1 addition & 0 deletions shared/lambda-http/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,5 @@ export interface DispatchOptions {
path: string,
statusCode: number,
) => Promise<void>;
warmup?: () => Promise<void>;
}
9 changes: 9 additions & 0 deletions shared/lambda-http/src/warmup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// /health awaits this so Lambda does not freeze the container mid-warm-up.
export function prewarm(warm: () => Promise<unknown>): () => Promise<void> {
if (!process.env.AWS_LAMBDA_FUNCTION_NAME) return async () => {};
const pending = warm().then(
() => undefined,
(err) => console.warn('Warm-up failed:', err),
);
return () => pending;
}
23 changes: 23 additions & 0 deletions shared/lambda-http/test/dispatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,29 @@ describe('dispatch routing', () => {
}
});

it('holds the health response until warmup settles', async () => {
let release!: () => void;
const warmup = jest.fn(() => new Promise<void>((r) => (release = r)));
let settled = false;
const pending = dispatch(event('GET', '/projects/health'), {
prefix: 'projects',
routes,
warmup,
}).then((res) => ((settled = true), res));

await Promise.resolve();
expect(warmup).toHaveBeenCalledTimes(1);
expect(settled).toBe(false);
release();
expect((await pending).statusCode).toBe(200);
});

it('does not run warmup on ordinary routes', async () => {
const warmup = jest.fn(async () => {});
await dispatch(event('GET', '/projects'), { ...opts(), warmup });
expect(warmup).not.toHaveBeenCalled();
});

it('404s an unmatched path', async () => {
const res = await dispatch(event('GET', '/projects/7/nope'), opts());
expect(res.statusCode).toBe(404);
Expand Down
Loading
Loading