feat(portal-bff): entra config foundation — boot validator + auth module (#102)
CI / check (push) Successful in 2m15s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m1s
CI / a11y (push) Successful in 1m15s
CI / perf (push) Successful in 3m47s

## Summary

First step of ADR-0009 wiring on the BFF: capture the Entra app-registration env vars in the boot pipeline so subsequent PRs can plug `@azure/msal-node` 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`](apps/portal-bff/.env.example)** promotes the Entra block from its previous "future-vars" comment stub to an active section. Six keys:
  - `ENTRA_INSTANCE_URL` — the Microsoft login endpoint (e.g. `https://login.microsoftonline.com/`).
  - `ENTRA_TENANT_ID`, `ENTRA_CLIENT_ID`, `ENTRA_CLIENT_SECRET` — the values from the Entra app-registration UI.
  - `ENTRA_REDIRECT_URI`, `ENTRA_POST_LOGOUT_REDIRECT_URI` — consumed by the OIDC routes in a follow-up PR.

  Multi-tenant `ENTRA_ACCEPTED_TENANT_IDS` stays in the future-vars comment until External ID activation (ADR-0008 phase 2).

- **[`apps/portal-bff/src/config/check-entra-config.ts`](apps/portal-bff/src/config/check-entra-config.ts)** — boot-time validator mirroring `check-database-url.ts`. Verifies every required key is present, the instance URL is `https://` and ends with `/`, tenant + client IDs are UUIDs, none of them are the literal placeholder values from `.env.example`, and the two redirect URIs parse as URLs. Returns a typed `EntraConfig` object with a pre-computed `authority` field (`${instanceUrl}${tenantId}`) so the future MSAL factory does not re-derive it.

- **[`auth.module.ts`](apps/portal-bff/src/auth/auth.module.ts)** — `AuthModule` whose v1 surface is one provider: the parsed `EntraConfig` keyed by the `ENTRA_CONFIG` injection token. Factory delegates to `assertEntraConfig()`. Non-global on purpose — consumers state intent by importing the module.

- **Bootstrap wiring** — `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`.

## Naming choice

Chose `ENTRA_*` rather than `AZURE_AD_*` to align with the 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).

## Decisions worth flagging

- **Validator called twice** — once in `main.ts` (boot-time fail-fast) and once in the `AuthModule` factory (to obtain the value for DI). Both reads are idempotent and trivially cheap. The duplication is intentional: boot-time gives a clear, pre-NestFactory error; the factory call surfaces the typed value to consumers.
- **No `@azure/msal-node` dependency added yet** — introducing the dep without a consumer would be a smell. Lands in the next PR alongside the MSAL client factory.
- **Pre-computed `authority`** in the parsed config rather than letting each MSAL consumer concatenate `instanceUrl + tenantId`. One place to change if the multi-tenant authority (`/organizations`, `/common`) replaces the tenant-scoped one when External ID activates.

## Verification

- `nx run-many -t lint test build --projects=portal-bff` — green.
- **29 / 29 specs** (was 20; +9 from the new entra-config spec + auth.module spec).
- Boot smoke test (manual): with the placeholder values in `.env.example`, `nx serve portal-bff` aborts immediately with `ENTRA_CLIENT_ID is still the .env.example placeholder (…)`. With real values in a local `.env`, the BFF starts normally.

## Test plan

- [x] Lint + test + build green.
- [x] Validator unit-test covers happy path + every documented failure mode.
- [ ] Manual: drop the real Entra values you obtained into `apps/portal-bff/.env`, `nx serve portal-bff` boots clean.
- [ ] Manual: temporarily blank out one of the four `ENTRA_*` keys → BFF aborts at boot with a clear message naming the missing key.

## Next PRs on the auth track

1. Install `@azure/msal-node`, add the `MsalConfidentialClient` factory provider in `AuthModule`, expose it via DI.
2. First OIDC routes: `/api/auth/login` (PKCE-initiated redirect to Entra) + `/api/auth/callback` (token exchange + ID-token validation, audit-logged, no session persistence yet).
3. Session persistence per ADR-0010 (Redis + AES-GCM, `__Host-portal_session` cookie). Closes the auth loop.
4. RP-initiated logout, CSRF protection, route guards.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #102
This commit was merged in pull request #102.
This commit is contained in:
2026-05-12 02:27:55 +02:00
parent cb69a692e7
commit 58e3b65bd9
8 changed files with 348 additions and 8 deletions
@@ -0,0 +1,131 @@
/**
* Sanity-check the Entra ID app-registration env vars early in
* bootstrap so a missing or malformed value fails fast with a clear,
* actionable message instead of a deep `@azure/msal-node` error
* thrown on the first auth request.
*
* Wired in `main.ts` alongside `assertDatabaseUrl()` — same family
* of "fail before any request lands" guard recommended by ADR-0018
* §"BFF env-var loading".
*
* The four `*_INSTANCE_URL` / `*_TENANT_ID` / `*_CLIENT_ID` /
* `*_CLIENT_SECRET` keys are mandatory; the two redirect URIs are
* mandatory once the OIDC routes ship (next PR). Until then the
* validator returns the parsed config but does not consume it; the
* `AuthModule` exposes it via DI so the future MSAL client factory
* picks it up by constructor injection.
*/
export interface EntraConfig {
/**
* Microsoft login endpoint, e.g. `https://login.microsoftonline.com/`.
* Combined with `tenantId` to build the MSAL `authority`.
*/
readonly instanceUrl: string;
/** Directory (tenant) UUID. */
readonly tenantId: string;
/** App registration UUID. */
readonly clientId: string;
/** Confidential client secret. */
readonly clientSecret: string;
/** Where Entra sends the user after authentication — `/auth/callback`. */
readonly redirectUri: string;
/** Where Entra sends the user after RP-initiated logout. */
readonly postLogoutRedirectUri: string;
/**
* Convenience: the full authority URL passed to MSAL Node
* (`${instanceUrl}${tenantId}`). Computed once so the rest of the
* codebase does not re-derive it on every call.
*/
readonly authority: string;
}
const REQUIRED_KEYS = [
'ENTRA_INSTANCE_URL',
'ENTRA_TENANT_ID',
'ENTRA_CLIENT_ID',
'ENTRA_CLIENT_SECRET',
'ENTRA_REDIRECT_URI',
'ENTRA_POST_LOGOUT_REDIRECT_URI',
] as const;
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const PLACEHOLDER_TENANT_OR_CLIENT = '00000000-0000-0000-0000-000000000000';
const PLACEHOLDER_SECRET = 'replace_with_real_value';
export function assertEntraConfig(): EntraConfig {
const missing = REQUIRED_KEYS.filter((k) => !process.env[k] || process.env[k] === '');
if (missing.length > 0) {
throw new Error(
`Missing Entra config env vars: ${missing.join(', ')}. ` +
`Copy apps/portal-bff/.env.example to apps/portal-bff/.env ` +
`and fill in the values from the Entra app registration.`,
);
}
// After the `missing` check, every required key is present.
const instanceUrl = process.env['ENTRA_INSTANCE_URL'] as string;
const tenantId = process.env['ENTRA_TENANT_ID'] as string;
const clientId = process.env['ENTRA_CLIENT_ID'] as string;
const clientSecret = process.env['ENTRA_CLIENT_SECRET'] as string;
const redirectUri = process.env['ENTRA_REDIRECT_URI'] as string;
const postLogoutRedirectUri = process.env['ENTRA_POST_LOGOUT_REDIRECT_URI'] as string;
assertUrl('ENTRA_INSTANCE_URL', instanceUrl, ['https:']);
if (!instanceUrl.endsWith('/')) {
throw new Error(
`ENTRA_INSTANCE_URL must end with a trailing "/" so the authority ` +
`(${instanceUrl}<tenant-id>) concatenates correctly. Got: ${instanceUrl}`,
);
}
assertUuid('ENTRA_TENANT_ID', tenantId);
assertUuid('ENTRA_CLIENT_ID', clientId);
assertNotPlaceholder('ENTRA_TENANT_ID', tenantId, PLACEHOLDER_TENANT_OR_CLIENT);
assertNotPlaceholder('ENTRA_CLIENT_ID', clientId, PLACEHOLDER_TENANT_OR_CLIENT);
assertNotPlaceholder('ENTRA_CLIENT_SECRET', clientSecret, PLACEHOLDER_SECRET);
assertUrl('ENTRA_REDIRECT_URI', redirectUri, ['http:', 'https:']);
assertUrl('ENTRA_POST_LOGOUT_REDIRECT_URI', postLogoutRedirectUri, ['http:', 'https:']);
return {
instanceUrl,
tenantId,
clientId,
clientSecret,
redirectUri,
postLogoutRedirectUri,
authority: `${instanceUrl}${tenantId}`,
};
}
function assertUrl(key: string, value: string, allowedProtocols: readonly string[]): void {
let parsed: URL;
try {
parsed = new URL(value);
} catch {
throw new Error(`${key} is not a valid URL. Got: ${value}`);
}
if (!allowedProtocols.includes(parsed.protocol)) {
throw new Error(
`${key} must use one of [${allowedProtocols.join(', ')}]; got "${parsed.protocol}".`,
);
}
}
function assertUuid(key: string, value: string): void {
if (!UUID_RE.test(value)) {
throw new Error(
`${key} must be a UUID (e.g. "0123abcd-0123-4567-89ab-cdef01234567"). Got: ${value}`,
);
}
}
function assertNotPlaceholder(key: string, value: string, placeholder: string): void {
if (value === placeholder) {
throw new Error(
`${key} is still set to the .env.example placeholder ("${placeholder}"). ` +
`Replace with the real value from the Entra app registration.`,
);
}
}