feat(auth): authorization catalogues + Principal builder skeleton (ADR-0025)
CI / check (pull_request) Failing after 28s
CI / commits (pull_request) Failing after 25s
CI / scan (pull_request) Failing after 56s
CI / a11y (pull_request) Failing after 33s
CI / perf (pull_request) Failing after 47s
Docs site / build (pull_request) Failing after 26s

Per ADR-0025's implementation phasing, lands the closed-set
catalogues + the OIDC-callback hook that composes the
session-resident Principal. No new guards yet.

- libs/shared/auth: framework-agnostic lib hosting
  authorization.types.ts (4 privileges + 24 functional roles + 6
  scope kinds + Principal type) and entra-group-to-role.ts
  (validated GUID -> slug resolver). 17 unit tests against the
  catalogues + resolver contracts.
- BFF: PrincipalBuilder composes the three axes once at sign-in;
  ScopeResolver seam (StubScopeResolver returns unrestricted in
  v1, replaced by a Prisma-backed implementation when ADR-0026's
  user_scopes table lands). 19 persona-driven tests covering the
  test tenant's full provisioning + edge cases (unknown
  privilege drift, unknown group GUID, empty permissions).
- AuthService extracts the Entra "groups" claim; AuthenticatedUser
  grows the groups: readonly string[] field.
- SessionEstablisher builds + persists the principal alongside
  the legacy user shape (additive — guards consuming user.oid
  unchanged).
- ENTRA_GROUP_MAP_PATH env var + load-entra-group-map.ts read
  the tenant-private map from infra/<env>-tenant.entra.json
  (gitignored; .example.json committed with the schema).
- ADR-0025 path references updated from libs/feature/auth
  (Angular-scoped, scope:portal-shell) to libs/shared/auth
  (consumable by both BFF and SPA).
- notes/entra-groups-claim-activation.md: operator runbook for
  the "Token configuration -> Add groups claim" step in the
  Entra admin centre.

Test plan:
- pnpm nx affected -t lint test build : 13 projects green
  (497 BFF tests + 17 shared-auth tests + 1 shared-util test +
  full lint + full build).
This commit is contained in:
Julien Gautier
2026-05-23 19:48:39 +02:00
parent c9a1e195fe
commit 540d9dc28a
35 changed files with 1709 additions and 29 deletions
@@ -63,7 +63,7 @@ The four privileges above are the entire v1 catalogue. The last three were provi
**Definition.** A _functional role_ is what someone does in APF. Multiple per user is the norm (a Directeur is also a Collaborateur; an RH-Aquitaine might also be a Bénévole de la Délégation 33). Functional roles carry **no** privilege flags and **no** scope by themselves — those live on the other axes.
**Source of truth.** Entra security groups, named `apf-role-<role-slug>`. Memberships emitted in the `groups` claim. The BFF's OIDC callback resolves each Entra group GUID to a role slug via a static mapping (`libs/feature/auth/src/lib/entra-group-to-role.ts`) and populates `Principal.roles`.
**Source of truth.** Entra security groups, named `apf-role-<role-slug>`. Memberships emitted in the `groups` claim. The BFF's OIDC callback resolves each Entra group GUID to a role slug via a static mapping (`libs/shared/auth/src/lib/entra-group-to-role.ts`) and populates `Principal.roles`.
**v1 catalogue.** Grouped for readability; the slugs are kebab-case and intent-bearing.
@@ -234,18 +234,26 @@ Two configurations live on the Entra app registration:
so the ID token includes the user's group GUIDs in the `groups` claim. The BFF's OIDC callback resolves group GUIDs to role slugs via a static map (committed to the repo). Unknown group GUIDs are logged at WARN and ignored — they do not break sign-in, but they signal a tenant misconfiguration that should be cleaned up.
**The group GUIDs are tenant-specific.** The map file (`libs/feature/auth/src/lib/entra-group-to-role.ts`) keys the slug on the GUID _per environment_ — the dev/test/preprod/prod tenants all have distinct GUIDs for the same role slug. The map is structured as:
**The group GUIDs are tenant-specific.** The map _data_ is keyed on Entra group GUID _per environment_ — the dev/test/preprod/prod tenants all have distinct GUIDs for the same role slug. The data lives in a gitignored `infra/<env>-tenant.entra.json` (see `infra/test-tenant.entra.example.json` for the schema). The BFF loads it at boot through the `EntraGroupToRoleResolver` exported from `libs/shared/auth/src/lib/entra-group-to-role.ts`:
```ts
export const ENTRA_GROUP_TO_ROLE: Record<string, FunctionalRole> = {
// test tenant — sourced from `infra/test-tenant.entra.json`
'11111111-1111-1111-1111-111111111111': 'collaborateur',
'22222222-2222-2222-2222-222222222222': 'rh',
// …
};
```json
{
"11111111-1111-1111-1111-111111111111": "collaborateur",
"22222222-2222-2222-2222-222222222222": "rh"
}
```
A dedicated config file per environment (`apps/portal-bff/.env.*`) holds an override token if needed. The `groups`-claim overage scenario (Entra emits a `_claim_sources` hint instead of the full list when the user is in too many groups) is handled by the BFF calling Microsoft Graph at sign-in — out of scope for v1's small test tenant, lands when the production rollout brings real population in.
```ts
// libs/shared/auth/src/lib/entra-group-to-role.ts
export class EntraGroupToRoleResolver {
resolve(
groupIds: ReadonlyArray<string>,
onUnknownGroup?: (groupId: string) => void,
): ReadonlyArray<FunctionalRole>;
}
```
The map file path is passed via `ENTRA_GROUP_MAP_PATH` (per-environment in `apps/portal-bff/.env.*`). The `groups`-claim overage scenario (Entra emits a `_claim_sources` hint instead of the full list when the user is in too many groups) is handled by the BFF calling Microsoft Graph at sign-in — out of scope for v1's small test tenant, lands when the production rollout brings real population in.
### Sources of truth — apf_portal-side `user_scopes` table
@@ -326,7 +334,7 @@ The four privileges live in the `apfrd.onmicrosoft.com` app registration with th
| `Portal.SecurityOfficer` | `6f50ce58-a1e1-496b-a3c0-655559c66a28` |
| `Portal.DPO` | `39b8815f-b3fd-4597-9679-77dcbf788a07` |
The 24 `apf-role-*` security groups were provisioned with the membership matrix above. Their GUIDs are tenant-specific and stay out of the repo; the implementation PR captures them in a gitignored `infra/test-tenant.entra.json` and references them by name in `libs/feature/auth/src/lib/entra-group-to-role.ts`.
The 24 `apf-role-*` security groups were provisioned with the membership matrix above. Their GUIDs are tenant-specific and stay out of the repo; the implementation PR captures them in a gitignored `infra/test-tenant.entra.json` and references them by name in `libs/shared/auth/src/lib/entra-group-to-role.ts`.
Scopes are **not** carried by Entra. They live in the portal-side `user_scopes` table, populated by `prisma/seed.ts` once the `Person` + `User` schema (proposed ADR-0026) lands. Until then the implementation skeleton honours the `unrestricted` default for testing.
@@ -343,7 +351,7 @@ Scopes are **not** carried by Entra. They live in the portal-side `user_scopes`
### Confirmation
- **Schema test** in `apps/portal-bff/src/auth/principal.spec.ts` (lands with the auth wiring PR): every guard composition produces the expected allow/deny on each of the 10 test personas. Theory-style test matrix mirrors `apf-ai-service/tests/Apf.Ai.Tests/Rbac/RbacMatrix.cs`.
- **Catalogue-vs-code drift check** in CI: a small ESLint custom rule (or a `pnpm run` script) greps every `@RequireRole('...')` / `@RequirePrivilege('...')` / scope literal in the codebase and asserts each one exists in the catalogue constants exported from `libs/feature/auth/src/lib/authorization.types.ts`. Fails the build on drift.
- **Catalogue-vs-code drift check** in CI: a small ESLint custom rule (or a `pnpm run` script) greps every `@RequireRole('...')` / `@RequirePrivilege('...')` / scope literal in the codebase and asserts each one exists in the catalogue constants exported from `libs/shared/auth/src/lib/authorization.types.ts`. Fails the build on drift.
- **Audit-event linkage**: every `403 Forbidden` from `@RequireRole` / `@RequireScope` writes an `admin.access_denied` row (per [ADR-0013](0013-audit-trail-separated-postgres-append-only.md) §"v1 events"), with the missing role/scope in the payload. Auditors can spot privilege-escalation attempts by pivoting on `outcome=denied`.
- **PrincipalProjector test**: snapshot test asserting that the AI-service projection of a known persona produces a known flat-list output. Same fixture is reused on the AI service side as part of its RBAC matrix.
@@ -393,7 +401,7 @@ This door is recorded here so a future contributor does not feel they have to re
## More Information
- **Phasing.** This ADR is decision-only. The implementation phasing is:
1. **PR — `Authorization` types + Principal builder + `entra-group-to-role` mapping skeleton.** Lands `libs/feature/auth/src/lib/authorization.types.ts` (the catalogues) and the OIDC callback hook that populates the new `privileges` / `roles` / `scopes` fields on the session principal. No new guards yet.
1. **PR — `Authorization` types + Principal builder + `entra-group-to-role` mapping skeleton.** Lands `libs/shared/auth/src/lib/authorization.types.ts` (the catalogues) and the OIDC callback hook that populates the new `privileges` / `roles` / `scopes` fields on the session principal. No new guards yet.
2. **PR — `@RequireRole` + `@RequireScope` decorators + guard tests.** Adds the guards against a stubbed principal; integration with the actual session lands in the same PR.
3. **PR — Drift CI gate.** ESLint rule (or `pnpm run` script) that asserts every role / privilege / scope literal in the codebase is in the catalogue.
4. **PR — Test-tenant seed.** `prisma/seed.ts` populating the 10 test personas' `user_scopes` rows. Depends on the `Person` + `User` schema landing first (proposed ADR-0026).