fed905edc5
## Summary
Phase-3a step per [ADR-0020](docs/decisions/0020-portal-admin-app.md) §"Sessions — distinct from `portal-shell`". Wires a second `express-session` middleware on `/api/admin/*` carrying `__Host-portal_admin_session` over Redis prefix `session:admin:`, and ships the parallel `/api/admin/auth/{login,callback,me,logout}` flow that populates it. Signing in to one surface no longer signs the user into the other — Entra SSO at the IdP level still preserves the click-through.
## What lands
### Session middlewares — path-routed dispatch
| Token | Cookie | Redis prefix | Bound to |
| --- | --- | --- | --- |
| `SESSION_MIDDLEWARE` | `portal_session` / `__Host-portal_session` | `session:` | every path **except** `/api/admin/*` |
| `ADMIN_SESSION_MIDDLEWARE` | `portal_admin_session` / `__Host-portal_admin_session` | `session:admin:` | `/api/admin/*` only |
Implemented via a `buildSessionMiddleware(redis, logger, opts)` factory in [session.module.ts](apps/portal-bff/src/session/session.module.ts) — the TTL policy, encryption key, signing secret, session-id entropy, and serializer error-handling all come from the same source. Only the cookie name + Redis key prefix differ.
The dispatch in [main.ts](apps/portal-bff/src/main.ts) is a tiny `(req, res, next) => req.path.startsWith('/api/admin') ? adminSession(...) : userSession(...)`. Running both middlewares unconditionally would have the second overwrite `req.session` from the first, collapsing the two surfaces.
### Distinct admin auth flow
[`AdminAuthController`](apps/portal-bff/src/admin/admin-auth.controller.ts) mounts `/api/admin/auth/{login,callback,me,logout}`. Structurally identical to [`AuthController`](apps/portal-bff/src/auth/auth.controller.ts) but passes `adminRedirectUri` / `adminPostLogoutRedirectUri` and clears the admin session cookie on logout. `me` exposes the `roles` claim (admin SPA needs it for conditional UI); the user-portal `me` intentionally still doesn't.
### Shared `SessionEstablisher` (no controller duplication)
[`SessionEstablisher`](apps/portal-bff/src/auth/session-establisher.service.ts) encapsulates the session lifecycle so both controllers stay thin:
- `establish({ user, req, res, surface })` — mints CSRF, populates `user / createdAt / absoluteExpiresAt / csrfToken / mfaVerifiedAt`, saves, sets the CSRF cookie, registers in `user_sessions` index, emits `auth.sign_in` audit (blocking), logs with the `surface` tag.
- `destroy({ actor, req })` — when `actor` is set, removes from index + emits `auth.sign_out`; always destroys the session with Redis-hiccup tolerance.
No code duplicated between the two surfaces — the only per-surface differences are the redirect URIs (passed in) and the cookie names cleared on logout (controller-local).
### Entra config gains two URIs
`EntraConfig` adds `adminRedirectUri` + `adminPostLogoutRedirectUri`, validated at boot in [check-entra-config.ts](apps/portal-bff/src/config/check-entra-config.ts). The validator **refuses to start** when `ENTRA_ADMIN_REDIRECT_URI === ENTRA_REDIRECT_URI` — that misconfiguration would silently collapse the two surfaces into one session. Both URIs must be registered on the same Entra app registration's "Redirect URIs" list.
### `AuthService` API change
`beginAuthCodeFlow(redirectUri)`, `completeAuthCodeFlow(code, state, preAuth, redirectUri, now?)`, and `buildLogoutUrl(postLogoutRedirectUri)` now take their URI as a parameter. Callers (user-portal vs admin-portal controllers) pick which set to pass.
## Required ops action before this PR can run locally
Two new mandatory env vars. The BFF refuses to start without them.
```env
ENTRA_ADMIN_REDIRECT_URI=http://localhost:3000/api/admin/auth/callback
ENTRA_ADMIN_POST_LOGOUT_REDIRECT_URI=http://localhost:4201/
```
The example values land in [apps/portal-bff/.env.example](apps/portal-bff/.env.example) for reference. The corresponding Entra app registration also needs `/api/admin/auth/callback` added to its "Redirect URIs" list before any admin sign-in works end-to-end.
## Notes for the reviewer
- The user-portal callback's post-login redirect still targets `postLogoutRedirectUri` (existing quirk where the post-auth and post-logout landing happen to be the same URL). The admin callback mirrors the pattern for `adminPostLogoutRedirectUri`. Splitting these into dedicated post-login URIs is a separate ADR/PR.
- `AdminModule` now imports `AuthModule` to consume `AuthService`, `SessionEstablisher`, and `ENTRA_CONFIG`. `AuditWriter` and `RequireMfaGuard` come through transitively.
- Existing `AuthController` spec assertions are preserved through the refactor by constructing a **real** `SessionEstablisher` in the test fixture with the same audit / index / logger mocks. No behavioural assertion was removed — the inline session-state-setting logic is now exercised through the establisher.
- The pre-existing docstring in `check-entra-config.ts` line 11-16 still says "the two redirect URIs are mandatory once the OIDC routes ship (next PR)" — stale, the routes have shipped. Not touched in this PR to keep the diff focused; can be a one-line doc PR later.
## Test plan
- [x] `pnpm nx test portal-bff` — **278 specs pass** (was 253; +25: admin cookie 3, session-establisher 11, admin auth controller 9, entra config 2).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean (the pre-existing `_res` / `_next` warnings in `rate-limit.middleware.ts` are unrelated).
- [x] Entra config validator: both URIs required, both URL-validated, equality refused.
- [x] Path-dispatch verified by routing — `/api/admin/me` and `/api/admin/auth/*` see the admin session; everything else sees the user session.
- [ ] e2e — pending env var update + Entra registration update to add the admin redirect URI. Once both are in place: sign in via `/api/auth/login`, see `portal_session` cookie; clear cookies; sign in via `/api/admin/auth/login`, see `portal_admin_session` cookie; verify `/api/admin/me` works on the admin session and `/api/auth/me` works on the user session — neither sees the other's session.
---------
Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #129
179 lines
9.0 KiB
Bash
179 lines
9.0 KiB
Bash
# BFF environment template
|
|
# Copy to .env (which is gitignored) and fill in actual values for local development.
|
|
# Production values are managed by the platform's secret manager (see future infrastructure ADR).
|
|
|
|
# Postgres connection (per ADR-0006)
|
|
# Local dev default: dockerised Postgres on port 5432, schema 'public'.
|
|
# Username / password / db must match infra/local/.env (POSTGRES_USER /
|
|
# POSTGRES_PASSWORD / POSTGRES_DB) — those are the source of truth,
|
|
# this is the BFF view of the same connection.
|
|
#
|
|
# IMPORTANT — URL encoding. The password is part of the URL userinfo
|
|
# segment, so any of these characters must be URL-encoded:
|
|
# @ → %40 # → %23 : → %3A / → %2F ? → %3F
|
|
# % → %25 & → %26 = → %3D + → %2B ; → %3B
|
|
# i.e. if your POSTGRES_PASSWORD is "p@ss#1", DATABASE_URL must read
|
|
# "postgresql://portal:p%40ss%231@localhost:5432/portal_dev?schema=public"
|
|
# The BFF aborts at boot with a clear error if it detects an unencoded
|
|
# special character (see apps/portal-bff/src/config/check-database-url.ts).
|
|
DATABASE_URL="postgresql://portal:portal_dev_change_me@localhost:5432/portal_dev?schema=public"
|
|
|
|
# Observability (per ADR-0012)
|
|
# All OTEL_* keys are honoured by the OpenTelemetry SDK directly — see
|
|
# apps/portal-bff/src/observability/tracing.ts for the bootstrap.
|
|
# Pino log level: 'info' in prod, 'debug' in dev (default if unset).
|
|
LOG_LEVEL=debug
|
|
OTEL_SERVICE_NAME=portal-bff
|
|
OTEL_SERVICE_VERSION=dev
|
|
# Default endpoint targets the Collector provisioned in
|
|
# infra/local/dev.compose.yml. The /v1/traces suffix is required by
|
|
# the HTTP/Protobuf transport.
|
|
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318/v1/traces
|
|
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
|
# v1 samples 100 % at the app; tail sampling is delegated to the
|
|
# Collector (per ADR-0012). Override only for spike investigations.
|
|
OTEL_TRACES_SAMPLER=always_on
|
|
|
|
# Identity / Entra ID app registration (per ADR-0008 / ADR-0009)
|
|
# Values come from the project's Entra application registration in the
|
|
# Azure Admin Center → App registrations → APF Portal. The four
|
|
# *_INSTANCE_URL / *_TENANT_ID / *_CLIENT_ID / *_CLIENT_SECRET keys
|
|
# are mandatory; the BFF refuses to boot without them (see
|
|
# apps/portal-bff/src/config/check-entra-config.ts).
|
|
#
|
|
# ENTRA_INSTANCE_URL is the Microsoft login endpoint — usually
|
|
# https://login.microsoftonline.com/. The authority used by MSAL is
|
|
# `${ENTRA_INSTANCE_URL}${ENTRA_TENANT_ID}` for single-tenant flows,
|
|
# or `${ENTRA_INSTANCE_URL}organizations` / `common` for multi-tenant
|
|
# (per ADR-0008's dual-audience design). v1 uses the tenant-scoped
|
|
# authority; the multi-tenant switch lands when External ID activation
|
|
# is needed.
|
|
#
|
|
# ENTRA_CLIENT_SECRET is the high-value secret of this set. Never
|
|
# commit a real value. Production manages it via the deploy platform's
|
|
# secret manager (future infrastructure ADR).
|
|
ENTRA_INSTANCE_URL=https://login.microsoftonline.com/
|
|
ENTRA_TENANT_ID=00000000-0000-0000-0000-000000000000
|
|
ENTRA_CLIENT_ID=00000000-0000-0000-0000-000000000000
|
|
ENTRA_CLIENT_SECRET=replace_with_real_value
|
|
# Redirect URIs registered in Entra alongside the same client id.
|
|
# User portal — `/api/auth/callback` is the OIDC return URL; the
|
|
# post-logout URL is where Entra sends the browser after RP-initiated
|
|
# logout (typically the SPA landing page).
|
|
ENTRA_REDIRECT_URI=http://localhost:3000/api/auth/callback
|
|
ENTRA_POST_LOGOUT_REDIRECT_URI=http://localhost:4200/
|
|
# Admin portal — distinct callback per ADR-0020 §"Sessions — distinct
|
|
# from `portal-shell`" so Entra routes the response to the matching
|
|
# session. Both `ENTRA_REDIRECT_URI` and `ENTRA_ADMIN_REDIRECT_URI`
|
|
# must be registered in the same Entra app registration's
|
|
# "Redirect URIs" list. Distinct post-logout URL routes admin
|
|
# sign-outs to the admin SPA's landing page (port 4201 in dev).
|
|
ENTRA_ADMIN_REDIRECT_URI=http://localhost:3000/api/admin/auth/callback
|
|
ENTRA_ADMIN_POST_LOGOUT_REDIRECT_URI=http://localhost:4201/
|
|
|
|
# Cookie signing secret (per ADR-0009 §"Cookies"). Used to sign the
|
|
# transient pre-auth cookie that carries the OIDC `state` + PKCE
|
|
# verifier between the /auth/login redirect and the /auth/callback
|
|
# round-trip, and (once ADR-0010 ships) the session cookie's
|
|
# integrity layer. Mandatory at boot — the BFF aborts if missing or
|
|
# obviously weak (less than 32 base64-decoded bytes ≈ 256 bits of
|
|
# entropy). Generate a fresh value per environment:
|
|
#
|
|
# node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"
|
|
SESSION_SECRET=replace_with_32_random_bytes_base64url
|
|
|
|
# Redis connection (per ADR-0010). The BFF uses `ioredis` for session
|
|
# storage (today: just the connection; the express-session +
|
|
# connect-redis middleware lands in the next PR).
|
|
#
|
|
# REDIS_URL — full URL form including auth. Must match `infra/local/.env`
|
|
# (REDIS_PASSWORD + REDIS_PORT) when running against the local Compose
|
|
# stack. Production wiring uses Sentinel (REDIS_SENTINEL_HOSTS +
|
|
# REDIS_SENTINEL_NAME — future-vars block below) and TLS; the current
|
|
# variable supports the dev single-instance shape only.
|
|
REDIS_URL=redis://default:redis_dev_change_me@localhost:6379/0
|
|
|
|
# Session payload encryption (per ADR-0010 §"At-rest encryption").
|
|
# AES-256-GCM key for encrypting the session JSON that connect-redis
|
|
# writes to Redis, so a Redis dump never carries raw user identities
|
|
# / future tokens / claims in plaintext. **Distinct** from
|
|
# SESSION_SECRET, which only signs the cookie's session-id — never
|
|
# reuse one for the other. Mandatory at boot.
|
|
#
|
|
# node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"
|
|
SESSION_ENCRYPTION_KEY=replace_with_32_random_bytes_base64url
|
|
|
|
# Session timeouts (per ADR-0010). Both optional with sensible
|
|
# defaults; override only when staging / prod policy diverges.
|
|
# SESSION_IDLE_TIMEOUT_SECONDS — sliding window. Each request
|
|
# extends the cookie's `expires` by this many seconds.
|
|
# Default 1800 (30 min).
|
|
# SESSION_ABSOLUTE_TIMEOUT_SECONDS — hard ceiling. Session is
|
|
# destroyed regardless of activity at this age.
|
|
# Default 43200 (12 h).
|
|
# SESSION_IDLE_TIMEOUT_SECONDS=1800
|
|
# SESSION_ABSOLUTE_TIMEOUT_SECONDS=43200
|
|
|
|
# Per-environment salt used to pseudonymise the user id before it
|
|
# lands in audit rows (per ADR-0013 §"Schema") and in Pino app log
|
|
# lines (per ADR-0012 §"User id hashing"). Same value must be used
|
|
# on both sides so audit and app logs join on `actor_id_hash`.
|
|
#
|
|
# Rotation invalidates the join key — old rows / log lines can no
|
|
# longer be correlated with the new hash. Treat as long-lived per
|
|
# environment. Mandatory at boot.
|
|
#
|
|
# node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"
|
|
LOG_USER_ID_SALT=replace_with_32_random_bytes_base64url
|
|
|
|
# CORS allowlist (per ADR-0009 §"CORS"). Comma-separated list of
|
|
# origins (scheme://host[:port]) allowed to call the BFF with
|
|
# credentials. The BFF refuses to start without this — silently
|
|
# defaulting to localhost is the classic "works in dev, breaks in
|
|
# prod" trap.
|
|
#
|
|
# Local dev: the portal-shell dev server on :4200. Add :4201 once
|
|
# portal-admin grows its own dev server.
|
|
CORS_ALLOWED_ORIGINS=http://localhost:4200
|
|
|
|
# Rate limiting (per ADR-0015 §"DoS mitigation"). Both optional
|
|
# with conservative defaults; override per environment when traffic
|
|
# patterns demand it. The BFF keys buckets by session id when the
|
|
# request is authenticated, by remote IP otherwise — rotating
|
|
# sessions doesn't dodge the limit.
|
|
# RATE_LIMIT_PER_MINUTE — general bucket. Default 120 (~ 2 r/s).
|
|
# RATE_LIMIT_AUTH_PER_MINUTE — stricter bucket on /auth/login and
|
|
# /auth/callback. Default 10/min, to
|
|
# slow brute-force / replay loops
|
|
# without inconveniencing legit users.
|
|
# RATE_LIMIT_PER_MINUTE=120
|
|
# RATE_LIMIT_AUTH_PER_MINUTE=10
|
|
|
|
# Future env vars introduced by upcoming phases / ADRs:
|
|
#
|
|
# Auth flow (ADR-0009) — additional keys wired as the routes land:
|
|
# ENTRA_CLIENT_CERT_PATH (alternative to ENTRA_CLIENT_SECRET)
|
|
# ENTRA_ACCEPTED_TENANT_IDS (CSV; restricts which tenants can sign in
|
|
# in the multi-tenant phase — empty means
|
|
# "only ENTRA_TENANT_ID is accepted")
|
|
#
|
|
# Sessions (ADR-0010) — additional keys wired as the layers land:
|
|
# REDIS_SENTINEL_HOSTS (CSV `host:port,host:port,…`; prod HA)
|
|
# REDIS_SENTINEL_NAME (master name in Sentinel; prod HA)
|
|
# REDIS_TLS ('true' in prod)
|
|
#
|
|
# MFA (ADR-0011):
|
|
# MFA_FRESHNESS_SECONDS (default 600)
|
|
#
|
|
# Audit trail (ADR-0013):
|
|
# AUDIT_DATABASE_URL (separate creds, role 'audit_writer')
|
|
# AUDIT_ARCHIVER_DATABASE_URL (role 'audit_archiver', for the retention purge job)
|
|
# AUDIT_RETENTION_DAYS (default 365)
|
|
#
|
|
# Downstream API access (ADR-0014):
|
|
# OBO_CACHE_ENCRYPTION_KEY (32-byte base64, distinct from SESSION_ENCRYPTION_KEY)
|
|
# BFF_JWKS_PRIVATE_KEY_PATH
|
|
# BFF_JWKS_KID
|
|
# <SERVICE>_API_BASE_URL (per integrated downstream)
|
|
# <SERVICE>_TIMEOUT_MS (optional, defaults to 5000)
|