7992a5ba144f90a133c0321a0b9746fef63e4639
3 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
7992a5ba14 |
feat(portal-bff): entra config foundation — boot validator + auth module
First step of ADR-0009 wiring. Captures the Entra app-registration
env vars in the boot pipeline so subsequent PRs can plug
`@azure/msal-node` straight onto a typed, already-validated config
without re-reading process.env. No MSAL client, no OIDC routes, no
session integration yet — those land in follow-up PRs.
What lands:
- `.env.example` promotes the Entra block from its previous "Future
env vars" comment stub to an active configuration section. Six
keys: `ENTRA_INSTANCE_URL`, `ENTRA_TENANT_ID`, `ENTRA_CLIENT_ID`,
`ENTRA_CLIENT_SECRET`, `ENTRA_REDIRECT_URI`,
`ENTRA_POST_LOGOUT_REDIRECT_URI`. UUID + URL placeholders so the
spec test for the "still-the-placeholder" guard has a real target.
Multi-tenant `ENTRA_ACCEPTED_TENANT_IDS` stays in the future-vars
comment until External ID activation lands.
- `apps/portal-bff/src/config/check-entra-config.ts` — boot
validator mirroring `check-database-url.ts`. Asserts every required
key is present, validates the instance URL is `https://` and ends
with `/`, the tenant + client IDs are UUIDs, none of them are the
literal .env.example placeholder, and the two redirect URIs are
parseable URLs. Returns a typed `EntraConfig` object with a
pre-computed `authority` field (`${instanceUrl}${tenantId}`) so
the MSAL factory in the next PR does not re-derive it.
- `check-entra-config.spec.ts` — covers the happy path plus eight
failure modes (missing keys, non-https instance, missing trailing
slash, non-UUID tenant, placeholder UUID, placeholder secret,
invalid redirect URI, http redirect for local dev).
- `apps/portal-bff/src/auth/auth.module.ts` — `AuthModule` whose
v1 surface is a single provider: the parsed `EntraConfig` keyed by
the `ENTRA_CONFIG` injection token. Factory delegates to
`assertEntraConfig()`. Module is non-global so consumers state
intent by importing it.
- `apps/portal-bff/src/auth/entra-config.token.ts` —
`ENTRA_CONFIG` string token + `EntraConfig` type re-export. The
pattern subsequent modules will use:
`@Inject(ENTRA_CONFIG) private readonly entra: EntraConfig`.
- `auth.module.spec.ts` — verifies the provider resolves the typed
config, and that compilation fails when an env var is missing
(boot-failure behaviour is preserved across the DI boundary).
- `main.ts` calls `assertEntraConfig()` alongside
`assertDatabaseUrl()` so misconfiguration fails fast at boot
rather than mid-request (per ADR-0018 §"BFF env-var loading").
- `AppModule` imports `AuthModule`.
Verification: 29 / 29 specs (was 20; +9 from the new entra-config
spec + auth.module spec), lint clean, webpack build green.
Naming: chose `ENTRA_*` rather than `AZURE_AD_*` to align with ADR
text (Microsoft Entra ID, post-2023 rebrand). The values you copy
from the Entra app-registration UI go into `apps/portal-bff/.env`
(git-ignored).
|
||
|
|
b74d3f1b9b |
feat(portal-bff): observability foundations (Pino + CLS + OTel) (#70)
## Summary
Implements ADR-0012 phase 1, BFF side. The SPA wiring is a separate phase-2 PR.
The BFF now emits structured JSON logs to stdout, tagged with `trace_id` / `span_id` from the active OTel context, and exports OTLP traces over HTTP/Protobuf to the Collector that already runs in the local-dev compose. Anything Nest, Express, HTTP-out, Prisma (Postgres) or `ioredis` does is auto-spanned. A `GET /api/health` liveness endpoint is added to round things out.
## What lands
**Runtime libs added** (production deps):
- `nestjs-pino`, `pino`, `pino-http` — structured logging
- `nestjs-cls` — request-scoped context
- `@opentelemetry/api` / `sdk-node` / `resources` / `semantic-conventions`
- `@opentelemetry/exporter-trace-otlp-proto` (HTTP/Protobuf, port 4318)
- `@opentelemetry/instrumentation-{http,express,nestjs-core,pg,ioredis,pino}` — curated, **no** `auto-instrumentations-node` mass-import (anti-bricolage)
Dev: `pino-pretty` (gated by `NODE_ENV`).
**Code:**
- `apps/portal-bff/src/observability/tracing.ts` — OTel `NodeSDK` bootstrap. Documents the load-order constraint inline (must be the very first import of `main.ts`). Pure side-effect module.
- `apps/portal-bff/src/observability/observability.module.ts` — composes `ClsModule` (UUID per request stored as `request_id`) and `LoggerModule` (`pino-pretty` in dev, raw JSON in prod, `LOG_LEVEL` env-driven, `/health` excluded from auto-logging, `X-Request-Id` honoured if inbound).
- `apps/portal-bff/src/health/{health.controller,health.module,health.controller.spec}.ts` — `GET /api/health` returning `{status, uptimeSeconds, service, version}`. Cheap liveness only — `/readiness` lands when dependencies have a readiness story.
- `apps/portal-bff/src/config/check-database-url.{ts,spec.ts}` — fail-fast validator called from `main.ts` before NestFactory boots. Catches the same family of bug that bit pgweb in #63: a literal special character in `POSTGRES_PASSWORD` that needs URL-encoding in `DATABASE_URL`. Prisma requires a URL string (no discrete-flag escape hatch), so early validation + a clear error message is the v1 mitigation. Six unit tests cover happy path, missing URL, wrong scheme, encoded special chars, literal `@` in password, malformed URL.
**Wiring:**
- `main.ts` imports `./observability/tracing` as line 1, then uses `app.get(Logger)` from `nestjs-pino` with `bufferLogs: true` so early-bootstrap lines are not lost.
- `app.module.ts` imports `ObservabilityModule` first, then `PrismaModule`, then `HealthModule`.
- `apps/portal-bff/.env.example` promotes `LOG_LEVEL`, `OTEL_SERVICE_NAME`, `OTEL_SERVICE_VERSION`, `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_PROTOCOL`, `OTEL_TRACES_SAMPLER` from the "future" comment to active settings — defaults target the local-dev Collector.
- Both `apps/portal-bff/.env.example` and `infra/local/.env.example` now spell out the URL-encoding constraint on `POSTGRES_PASSWORD` with the char-by-char encoding table (`@` → `%40`, etc.).
**ADR-0012 §Confirmation** rewritten to distinguish what landed in this PR from what is wired as the corresponding feature ADRs ship (CLS keys for `session_id` / `user_id_hash` / `audience`, `LOG_USER_ID_SALT` enforcement, redact list, custom spans, SPA-side SDK, full integration tests, prod Collector config).
## Trace ↔ log correlation
Automatic via `@opentelemetry/instrumentation-pino` — every Pino record gets `trace_id` and `span_id` injected from the active OTel context. No CLS gymnastics needed for that concern.
## Verification
```bash
pnpm exec nx run-many -t lint test build # 8 projects green
pnpm audit --audit-level=moderate # 0 vulnerabilities
./infra/local/dev.sh up observability # start Collector + Jaeger
cp apps/portal-bff/.env.example apps/portal-bff/.env
pnpm nx serve portal-bff
curl http://localhost:3000/api/health
# → {"status":"ok","uptimeSeconds":N,"service":"portal-bff","version":"dev"}
```
Then hit `GET http://localhost:3000/api` once or twice and open http://localhost:16686 — the corresponding spans appear in Jaeger, and Pino logs on stdout carry the matching `trace_id`.
## Test plan
- [ ] `nx run-many -t lint test build` green on this PR's CI run.
- [ ] `pnpm audit` clean.
- [ ] BFF boots, `/api/health` returns the expected JSON.
- [ ] Pino logs in dev are colourised one-liners; in prod they would be raw JSON (toggled by `NODE_ENV=production`).
- [ ] With the local-dev stack's `--profile observability` active, traces are visible in Jaeger UI.
- [ ] Each Pino log line for a request carries the same `trace_id` as the trace span in Jaeger.
---------
Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #70
|
||
|
|
2b0e20bd85 |
chore: wire PostgreSQL + Prisma per ADR-0006
Add Prisma 7 + nestjs-prisma. The schema lives at
apps/portal-bff/prisma/schema.prisma with provider postgresql; the new
prisma-client generator (Prisma 7 default) outputs the typed client to
apps/portal-bff/generated/prisma/ which is gitignored.
apps/portal-bff/src/app/app.module.ts imports PrismaModule.forRoot
({ isGlobal: true }) so PrismaService is injectable across the BFF
without per-module imports.
apps/portal-bff/.env.example documents DATABASE_URL with a local-dev
default, plus a forward list of env vars introduced by upcoming phases
and ADRs (auth, sessions, MFA, observability, audit, downstream APIs)
- catalog reference, not implementation. The actual .env stays
gitignored at both repo root and app levels.
prisma.config.ts (Prisma 7's TypeScript config) is committed; it loads
DATABASE_URL via dotenv. Schema and migrations paths are pinned to
prisma/ relative to the bff app.
PostgreSQL provisioning, RLS policies for the dual-audience design,
the dedicated audit schema with role grants (audit_owner / audit_writer
/ audit_reader / audit_archiver per ADR-0013), and column-level
encryption for L3-scoped data are out of scope of this commit -
they belong with the future on-prem infrastructure ADR.
|