feat(portal-bff): /auth/login route — pkce flow start + signed cookie (#105)
CI / scan (push) Successful in 2m27s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m29s
CI / a11y (push) Successful in 1m58s
CI / perf (push) Successful in 4m3s

## Summary

Third step of ADR-0009 wiring. Adds the first OIDC route, `GET /api/auth/login`: it 302s the browser to Entra's authorize endpoint with a freshly-generated state + PKCE challenge, and stashes the matching `{state, codeVerifier}` payload in a short-lived signed cookie so the next-PR callback can verify the round-trip.

## What lands

- **Cookie infra**: `cookie-parser` + `@types/express` deps; `main.ts` mounts the cookie middleware with the `SESSION_SECRET` signing key. Signed cookies are now available via `req.signedCookies` for the upcoming callback.
- **[`.env.example`](apps/portal-bff/.env.example)** promotes `SESSION_SECRET` from a future-vars comment into an active section, with a one-liner showing how to generate 32 random bytes.
- **[`check-session-secret.ts`](apps/portal-bff/src/config/check-session-secret.ts)** — boot-time guard: refuses to start if `SESSION_SECRET` is unset, still the .env.example placeholder, or decodes below 32 bytes of entropy. Same family as `check-database-url` / `check-entra-config`.
- **[`auth.service.ts`](apps/portal-bff/src/auth/auth.service.ts)** — `beginAuthCodeFlow()` uses MSAL's `CryptoProvider` for canonical PKCE verifier / challenge generation and a fresh GUID state per call, calls `msal.getAuthCodeUrl()` with the configured redirect URI + OIDC scopes (`openid profile email` — no `offline_access` in v1), and returns `{ authUrl, preAuthPayload }`.
- **[`auth.cookie.ts`](apps/portal-bff/src/auth/auth.cookie.ts)** — `portal_pre_auth` name, 5-minute TTL, shared `CookieOptions`: `signed`, `httpOnly`, `sameSite: 'lax'` (lets Entra's cross-site top-level redirect back through), `secure` toggled by `NODE_ENV`.
- **[`auth.controller.ts`](apps/portal-bff/src/auth/auth.controller.ts)** — `@Controller('auth') @Get('login')`: writes the cookie then 302s. Thin shell around the service.
- **AuthModule** registers the new controller + service alongside the existing `ENTRA_CONFIG` and `MSAL_CLIENT` providers.

## Decisions worth flagging

- **Scope deliberately stops before the callback.** It's the next PR. Clicking `/auth/login` today round-trips through Entra and lands on a 404 — bounded mid-state, documented in the commit and here.
- **State + verifier in the cookie, not in Redis.** Keeps `/login` stateless (no server-side store), which means the BFF stays horizontally scalable from day one without sticky-session config. The next-PR callback reads `req.signedCookies` to recover the payload.
- **`portal_pre_auth`, not `__Host-portal_pre_auth`.** `__Host-` mandates `Secure`, and local dev is HTTP. The prefix + `Secure: true` lands together with the production TLS hardening ADR.
- **No `offline_access` scope.** Sessions are short-lived (per ADR-0010); the user re-authenticates through Entra rather than the BFF refreshing tokens behind their back. Smaller token footprint, less code to write, easier to reason about.
- **5-minute cookie TTL.** Enough for the Entra round-trip (including a fresh MFA prompt), short enough that a stale cookie can't be replayed long after the user abandoned the flow.

## Verification

- `nx run-many -t lint test build --projects=portal-bff` — green.
- **39 / 39 specs** (was 30; +9 across `check-session-secret`, `auth.service`, `auth.controller`).
- The service spec mocks `getAuthCodeUrl`, asserts the redirect URI / scopes / S256 method, the state-verifier identity between the cookie payload and what's sent to Entra, and fresh-per-call replay protection.
- The controller spec asserts the cookie name + options + serialized payload and the 302 redirect.

## Manual smoke test (next PR completes the loop)

1. `apps/portal-bff/.env` has real `ENTRA_*` + `SESSION_SECRET`.
2. `nx serve portal-bff`.
3. `curl -i http://localhost:3000/api/auth/login` → 302 with `Set-Cookie: portal_pre_auth=…; HttpOnly; SameSite=Lax; Path=/`, `Location: https://login.microsoftonline.com/<tenant>/oauth2/v2.0/authorize?...`.
4. Open the `Location` in a browser, authenticate, Entra redirects to `http://localhost:3000/api/auth/callback?code=…&state=…` → 404 today, will be the next PR.

## Next PR on the auth track

`GET /api/auth/callback` — reads the signed cookie, verifies `state` matches, calls `acquireTokenByCode` with the stored verifier, validates the ID token (issuer, audience, exp, nonce, `amr` per ADR-0011), clears the pre-auth cookie, logs the resolved user identity, redirects to `/` (SPA). Still no session — that's the PR after.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #105
This commit was merged in pull request #105.
This commit is contained in:
2026-05-12 11:20:03 +02:00
parent b7093d61de
commit 0eb404d111
12 changed files with 484 additions and 4 deletions
@@ -0,0 +1,36 @@
import { randomBytes } from 'node:crypto';
import { assertSessionSecret } from './check-session-secret';
const STRONG_SECRET = randomBytes(32).toString('base64url');
describe('assertSessionSecret', () => {
const original = process.env['SESSION_SECRET'];
afterEach(() => {
if (original === undefined) {
delete process.env['SESSION_SECRET'];
} else {
process.env['SESSION_SECRET'] = original;
}
});
it('returns the value when SESSION_SECRET decodes to ≥ 32 bytes', () => {
process.env['SESSION_SECRET'] = STRONG_SECRET;
expect(assertSessionSecret()).toBe(STRONG_SECRET);
});
it('throws when SESSION_SECRET is unset', () => {
delete process.env['SESSION_SECRET'];
expect(() => assertSessionSecret()).toThrow(/SESSION_SECRET is not set/);
});
it('throws when SESSION_SECRET is the .env.example placeholder', () => {
process.env['SESSION_SECRET'] = 'replace_with_32_random_bytes_base64url';
expect(() => assertSessionSecret()).toThrow(/placeholder/);
});
it('throws when SESSION_SECRET decodes below 32 bytes', () => {
process.env['SESSION_SECRET'] = randomBytes(16).toString('base64url');
expect(() => assertSessionSecret()).toThrow(/decodes to 16 bytes/);
});
});
@@ -0,0 +1,61 @@
/**
* Sanity-check the `SESSION_SECRET` env var early in bootstrap so a
* missing or obviously weak value fails fast instead of producing
* weak cookie integrity at runtime.
*
* Wired in `main.ts` alongside `assertDatabaseUrl()` and
* `assertEntraConfig()` — same family of pre-flight check per
* ADR-0018 §"BFF env-var loading".
*
* `SESSION_SECRET` signs the transient pre-auth cookie (state + PKCE
* verifier carried between `/auth/login` and `/auth/callback`, per
* ADR-0009) and will later cover the session cookie's integrity
* layer (per ADR-0010). One secret for the cookie family is enough;
* payload encryption uses dedicated keys (`SESSION_ENCRYPTION_KEY`,
* `OBO_CACHE_ENCRYPTION_KEY`) when those features land.
*/
const PLACEHOLDER = 'replace_with_32_random_bytes_base64url';
const MIN_ENTROPY_BYTES = 32;
export function assertSessionSecret(): string {
const raw = process.env['SESSION_SECRET'];
if (!raw || raw === '') {
throw new Error(
`SESSION_SECRET is not set. Generate one with ` +
`"node -e \\"console.log(require('crypto').randomBytes(32).toString('base64url'))\\"" ` +
`and put it in apps/portal-bff/.env.`,
);
}
if (raw === PLACEHOLDER) {
throw new Error(
`SESSION_SECRET is still set to the .env.example placeholder ` +
`("${PLACEHOLDER}"). Replace with a real random value.`,
);
}
// Decode base64url-ish input — accept base64 too (Node decodes
// both). Anything below 32 bytes of decoded entropy is weaker than
// the AES-256 key family the project uses elsewhere; reject early.
let decoded: Buffer;
try {
decoded = Buffer.from(raw, 'base64url');
} catch {
throw new Error(`SESSION_SECRET must be a base64url-encoded string. Got: ${truncate(raw)}`);
}
if (decoded.length < MIN_ENTROPY_BYTES) {
throw new Error(
`SESSION_SECRET decodes to ${decoded.length} bytes, ` +
`below the ${MIN_ENTROPY_BYTES}-byte minimum (≈ 256 bits of entropy). ` +
`Generate a longer value.`,
);
}
return raw;
}
function truncate(s: string): string {
return s.length > 16 ? `${s.slice(0, 16)}` : s;
}