Files
apf_portal/apps/portal-bff/src/auth/auth.service.ts
T
julien 12136f7a8a
CI / commits (push) Has been skipped
CI / check (push) Failing after 20s
CI / a11y (push) Failing after 20s
CI / perf (push) Failing after 44s
CI / scan (push) Failing after 55s
Docs site / build (push) Failing after 29s
feat(auth): authorization catalogues + Principal builder skeleton (ADR-0025) (#206)
## Summary

First implementation PR after [ADR-0025](docs/decisions/0025-authorization-model-privileges-roles-scopes.md) was accepted in #205. Lands the closed-set catalogues + the OIDC-callback hook that composes the session-resident `Principal`. No new guards yet — those come in the next PR per the ADR's `§More Information` phasing.

## What lands

**New shared library: `libs/shared/auth/`** (`scope:shared`, `type:shared`, framework-agnostic, vitest)

| File | Role |
| --- | --- |
| `src/lib/authorization.types.ts` | Closed catalogues: `PRIVILEGES` (4), `FUNCTIONAL_ROLES` (24), `SCOPE_KINDS` (6). `Principal`, `Scope` types. `isPrivilege` / `isFunctionalRole` / `isScopeKind` type-guards for the drift gate. |
| `src/lib/entra-group-to-role.ts` | `parseEntraGroupMap` (validates GUID + slug closedness + dedup) + `EntraGroupToRoleResolver` (translates the Entra `groups` claim into ordered `apf-role-*` slugs, reports unknown GUIDs via callback). |
| `src/lib/*.spec.ts` | 17 unit tests against the catalogue counts + resolver contracts. |

**BFF wiring** (`apps/portal-bff/src/auth/` + `src/config/`)

| File | Role |
| --- | --- |
| `auth.service.ts` | Extracts the Entra `groups` claim. `AuthenticatedUser` grows `groups: readonly string[]`. |
| `principal-builder.ts` | Composes the three axes at sign-in. Filters `roles` claim through `isPrivilege` (drops + WARNs on unknown), resolves `groups` claim through the `EntraGroupToRoleResolver` (drops + WARNs on unknown). |
| `scope-resolver.ts` | `ScopeResolver` abstract class + `StubScopeResolver` returning `[{ kind: 'unrestricted' }]` (per ADR-0025 §331 — replaced by a Prisma implementation when ADR-0026's `user_scopes` table lands). |
| `session-establisher.service.ts` | Calls `PrincipalBuilder.build()` once, persists the result as `req.session.principal`. The legacy `req.session.user` shape is untouched (audit + AI bridge keep working). |
| `session.types.ts` | Adds optional `principal?: Principal` field on the express-session augmentation. |
| `entra-group-to-role.token.ts` | DI token for the lazily-loaded resolver. |
| `config/load-entra-group-map.ts` | Reads the gitignored `infra/<env>-tenant.entra.json` at boot. Missing path → empty resolver + WARN. Malformed file → hard fail (alternative would be silently dropping a role). |

**Tests against the 19 test-tenant personas** (`principal-builder.spec.ts`)

Every persona provisioned in `apfrd.onmicrosoft.com` on 2026-05-20 is exercised end-to-end: `admin`, `directeur-bordeaux`, `directeur-complexe`, `rh-aquitaine`, `rh-siege`, `collaborateur-simple`, `tresorier-bordeaux`, `dpo`, `it`, `benevole-aquitaine`, `chef-equipe-bordeaux`, `chef-service-bordeaux`, `directeur-territorial-aquitaine`, `juriste-siege`, `rssi`, `communication-siege`, `elu-ca-national`, `president-cd-aquitaine`, `secretaire-cd-aquitaine`. A coverage assertion confirms the personas cover all 4 privileges + 23 of 24 functional roles (the `partenaire` gap is intentional per ADR-0025).

**Infra + docs**

| File | Change |
| --- | --- |
| `infra/test-tenant.entra.example.json` | Template GUID → slug map (24 entries, full v1 catalogue). Real file (`*-tenant.entra.json`) gitignored. |
| `infra/README.md` | New row + "Entra group map" section documenting the load semantics + provisioning workflow. |
| `apps/portal-bff/.env.example` | New `ENTRA_GROUP_MAP_PATH` block. |
| `.gitignore` | `infra/*-tenant.entra.json` (except `.example.json`). |
| `tsconfig.base.json` | `shared-auth` path alias. |
| `notes/entra-groups-claim-activation.md` | Operator runbook for the Entra admin-centre step (Token configuration → Add groups claim → Security groups → Group ID). |

**ADR amendment**

| File | Change |
| --- | --- |
| `docs/decisions/0025-authorization-model-privileges-roles-scopes.md` | Path references updated `libs/feature/auth/...` → `libs/shared/auth/...` (4 occurrences), and the `ENTRA_GROUP_TO_ROLE` static-record example replaced by the actual `EntraGroupToRoleResolver` + JSON shape. |

## Notes for the reviewer

- **Why `libs/shared/auth/` and not `libs/feature/auth/` (as the ADR initially said).** The existing `libs/feature/auth/` carries `tags: ['scope:portal-shell', 'type:feature']`, which the Nx `enforce-module-boundaries` rule in `eslint.config.mjs:36-46` blocks the BFF from importing. The catalogue is needed by both sides (BFF builds the `Principal`, SPA will gate UI conditionally later), so a `scope:shared` lib is the correct home. The ADR is patched in the same PR so the document and the code agree.

- **Why drop unknown privileges with a WARN instead of preserving them.** `Portal.GhostRole` in the `roles` claim is either a leftover from a different app registration or a v1+1 experiment that hasn't been added to the catalogue yet. Both paths should not silently grant access — drop with a WARN so an operator notices, and the drift CI gate (next PR) catches the source-side equivalent before merge.

- **Why the principal builder uses a `ScopeResolver` seam now.** Per ADR-0025 §331 the v1 implementation returns `unrestricted` for everyone; the real version queries the `user_scopes` Prisma table that lands with ADR-0026. The seam is here so the next PR replaces only the implementation, not the call-site in `PrincipalBuilder` or its 24 tests. Per-persona stub scope data was deliberately not embedded in this PR — no guard consumes scopes yet, so it would be write-only documentation that drifts from the eventual Prisma seed.

- **Why `user.id` and `user.personId` placeholder to `entraOid`.** Same logic: the real UUIDs land with the `Person` + `User` Prisma schema (proposed ADR-0026). Until then, populating both fields with `entraOid` lets consumers key on `principal.user.id` today and get a real value later without branching on availability. The seam is one place (in the builder), not 24 guards.

- **Why session.types.ts carries both `user` and `principal`.** Additive instead of replacement: the audit module + the AI-bridge controller key on `user.oid` / `user.tid` directly, and migrating them in the same PR would balloon the diff for zero behavioural benefit. New consumers (`@RequirePrivilege` / `@RequireRole` / `@RequireScope` decorators, next PR) reach for `principal`.

- **Map file fails soft on absence, hard on malformation.** Path unset OR file missing → empty resolver + WARN. Sign-in still succeeds, every user gets `roles: []`. This is deliberately fail-soft so a fresh dev environment isn't blocked by an Entra-side dependency. **Bad JSON / unknown slug / duplicate GUID → throws at boot.** The alternative would silently mis-resolve a role.

- **Why `boot-time` validation only (no per-request)** for the map file. Catalogue drift is detected once at boot; per-request validation would re-read the file from disk on every sign-in. The trade-off is that a hot-edit to the file requires a BFF restart — acceptable because the file changes once per tenant lifecycle, not per session.

- **Entra `groups` claim must be activated** on the BFF's app registration before this code does anything useful. The runbook in `notes/entra-groups-claim-activation.md` walks through the steps; if the claim isn't activated, every user signs in with `principal.roles = []` and a future warn for every group GUID that would have arrived (none, in that case).

- **No drift gate yet.** ADR-0025's §"Confirmation" §346 calls for an ESLint custom rule (or `pnpm run` script) that greps every `@RequireRole('...')` literal and asserts membership in the catalogue. That's the third PR in the phasing — there's no `@RequireRole` consumer in the tree yet, so the gate would have nothing to assert against today.

## Test plan

- [x] `pnpm nx affected -t lint test build --base=main` — 13 projects green
  - 497 BFF tests (was 465 — added 4 new `groups`-claim tests in `auth.service.spec.ts`, 1 new test in `session-establisher.service.spec.ts`, 6 new tests in `load-entra-group-map.spec.ts`, 24 new tests in `principal-builder.spec.ts`)
  - 17 `shared-auth` tests (catalogue counts + resolver contracts)
  - 1 `shared-util` test (unchanged)
  - full lint + full build
- [x] `pnpm nx format:check` — clean after `pnpm nx format:write`
- [x] Manual: `tsc --build libs/shared/auth/tsconfig.lib.json` emits `.d.ts` files at the path `portal-bff`'s webpack expects.
- [ ] **Review focus** — the closed catalogues (`PRIVILEGES`, `FUNCTIONAL_ROLES`, `SCOPE_KINDS`) verbatim match ADR-0025; the 19 personas verbatim match `notes/test-tenant-role-assignments.md`; the `Principal` shape matches the ADR §"Principal shape" (modulo the `user.id` / `personId` placeholder); fail-soft on missing map file, hard on malformed.
- [ ] **After merge — operator step** : activate the Entra `groups` claim per `notes/entra-groups-claim-activation.md` and drop the real GUIDs into `infra/test-tenant.entra.json` (gitignored). Then a sign-in with `admin@apfrd.onmicrosoft.com` should land `principal.privileges = ['Portal.Admin']` and `principal.roles = ['collaborateur', 'rh']` in Redis.

## What's next

Per ADR-0025 §"More Information" phasing:

1.  **This PR** — types + Principal builder + group-to-role mapping skeleton.
2. **Next PR** — `@RequirePrivilege` + `@RequireRole` + `@RequireScope` decorators + guard integration tests against the 19 personas.
3. **PR after that** — drift CI gate (ESLint custom rule asserting every `@RequireX('...')` literal is in the catalogue).
4. **Depends on ADR-0026** — `user_scopes` Prisma table + seed + `PrismaScopeResolver` replacing `StubScopeResolver`.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #206
2026-05-23 21:09:13 +02:00

274 lines
10 KiB
TypeScript

import {
ConfidentialClientApplication,
CryptoProvider,
type AuthenticationResult,
} from '@azure/msal-node';
import { Inject, Injectable } from '@nestjs/common';
import { PRE_AUTH_COOKIE_TTL_MS } from './auth.cookie';
import { AuthCodeFlowException } from './auth.errors';
import { ENTRA_CONFIG, type EntraConfig } from './entra-config.token';
import { MSAL_CLIENT } from './msal-client.token';
/**
* Payload carried in the pre-auth cookie between `/auth/login` and
* `/auth/callback`: the OIDC `state` (anti-CSRF nonce) and the PKCE
* `codeVerifier` (secret the BFF sends back to Entra to prove it
* was the one that asked for the code). `createdAt` lets the
* callback reject cookies older than the flow's expected duration.
*/
export interface PreAuthPayload {
readonly state: string;
readonly codeVerifier: string;
readonly createdAt: number;
}
export interface AuthCodeFlowStart {
readonly authUrl: string;
readonly preAuthPayload: PreAuthPayload;
}
/**
* Identity resolved by `completeAuthCodeFlow`. Carries the claims
* the rest of the BFF / SPA care about post-authentication:
* - `oid`: stable per-user object id inside the Entra tenant.
* - `tid`: tenant id the user authenticated against (for the
* dual-audience / multi-tenant logic to come).
* - `username` / `displayName`: surfaced in the UI.
* - `amr`: authentication methods reference — the array used by
* the BFF's MFA sanity-check (ADR-0011) and by `@RequireMfa`
* freshness checks once the session lands.
* - `roles`: Entra app roles assigned to this user on the BFF's
* app registration. These are the four `Portal.*` *privileges*
* per ADR-0025 (`Portal.Admin`, `Portal.Auditor`,
* `Portal.SecurityOfficer`, `Portal.DPO`). Surfaced for the
* existing `@RequireAdmin()` guard and the upcoming
* `@RequirePrivilege()` decorator. Always present in the shape
* — an empty array means the user has no app role on this app
* registration, not that the claim was unparseable.
* - `groups`: Entra security-group GUIDs the user belongs to.
* Emitted by the `groups` claim once the app registration sets
* `groupMembershipClaims: 'SecurityGroup'` (per ADR-0025
* §"Sources of truth — Entra-side configuration"). The
* `PrincipalBuilder` resolves these GUIDs to `apf-role-*` slugs
* via the `EntraGroupToRoleResolver`. Always present — empty
* means either the user has no group membership or the claim
* was not configured on the app registration. Unknown GUIDs
* are dropped at resolve time, not at extraction time, so an
* audit reader still sees the raw claim.
*/
export interface AuthenticatedUser {
readonly oid: string;
readonly tid: string;
readonly username: string;
readonly displayName: string;
readonly amr: readonly string[];
readonly roles: readonly string[];
readonly groups: readonly string[];
}
/**
* The minimum OIDC scopes — `openid` to get an ID token, `profile`
* for the user's display name / preferred_username, `email` for the
* email claim. Refresh tokens (`offline_access`) are deliberately
* omitted in v1: sessions are short-lived (per ADR-0010) and the
* user re-authenticates through Entra rather than the BFF refreshing
* tokens behind their back.
*/
const SCOPES: readonly string[] = ['openid', 'profile', 'email'];
@Injectable()
export class AuthService {
private readonly crypto = new CryptoProvider();
constructor(
@Inject(MSAL_CLIENT) private readonly msal: ConfidentialClientApplication,
@Inject(ENTRA_CONFIG) private readonly config: EntraConfig,
) {}
/**
* First leg of the OIDC Authorization Code + PKCE flow. Builds
* the URL the user gets redirected to (Entra's authorize
* endpoint) and the pre-auth payload the controller stores in a
* signed cookie so the callback can verify the round-trip later.
*
* MSAL Node owns the PKCE code generation (`CryptoProvider`) so
* the verifier / challenge pair is canonical. The state nonce is
* a fresh GUID per flow.
*
* `redirectUri` is passed by the caller (user-portal or
* admin-portal controller) per ADR-0020 §"Sessions — distinct
* from `portal-shell`". Same MSAL client, distinct redirect URI →
* Entra routes the callback to the matching session.
*/
async beginAuthCodeFlow(redirectUri: string): Promise<AuthCodeFlowStart> {
const { verifier, challenge } = await this.crypto.generatePkceCodes();
const state = this.crypto.createNewGuid();
const authUrl = await this.msal.getAuthCodeUrl({
redirectUri,
scopes: [...SCOPES],
state,
codeChallenge: challenge,
codeChallengeMethod: 'S256',
});
return {
authUrl,
preAuthPayload: {
state,
codeVerifier: verifier,
createdAt: Date.now(),
},
};
}
/**
* Second leg. Verifies the state round-trip, refuses cookies
* older than the flow TTL, asks MSAL to exchange the auth code
* for tokens using the stored PKCE verifier, then runs the
* BFF-side sanity-checks ADR-0009 mandates (state, expiry, `amr`).
*
* MSAL Node performs the heavy ID-token validation itself
* (signature against Entra's JWKS, issuer + audience, exp, nbf).
* What this method adds on top is the application-layer policy:
* - anti-CSRF state binding,
* - flow-TTL replay protection,
* - MFA presence (`amr`) per ADR-0011.
*/
async completeAuthCodeFlow(
code: string,
state: string,
preAuth: PreAuthPayload,
redirectUri: string,
now: number = Date.now(),
): Promise<AuthenticatedUser> {
if (state !== preAuth.state) {
throw new AuthCodeFlowException({ kind: 'state-mismatch' });
}
if (now - preAuth.createdAt > PRE_AUTH_COOKIE_TTL_MS) {
throw new AuthCodeFlowException({ kind: 'flow-expired' });
}
let result: AuthenticationResult | null;
try {
result = await this.msal.acquireTokenByCode({
code,
codeVerifier: preAuth.codeVerifier,
redirectUri,
scopes: [...SCOPES],
});
} catch (err) {
throw new AuthCodeFlowException({
kind: 'token-exchange-failed',
cause: errorCause(err),
});
}
if (!result) {
throw new AuthCodeFlowException({
kind: 'token-exchange-failed',
cause: 'msal returned null result',
});
}
return this.toAuthenticatedUser(result);
}
/**
* Build the Entra RP-initiated logout URL. Hits the v2.0 logout
* endpoint on the configured authority and passes the
* `post_logout_redirect_uri` so the browser lands back on the SPA
* after Entra finishes its side of the sign-out.
*
* We deliberately do *not* pass `id_token_hint` (which would skip
* the account-picker on multi-account devices) because v1 doesn't
* persist the id_token in the session yet — token persistence
* lands with downstream API support per ADR-0014. The account
* picker is the safer default in the interim.
*/
buildLogoutUrl(postLogoutRedirectUri: string): string {
const url = new URL(`${this.config.authority}/oauth2/v2.0/logout`);
url.searchParams.set('post_logout_redirect_uri', postLogoutRedirectUri);
return url.toString();
}
private toAuthenticatedUser(result: AuthenticationResult): AuthenticatedUser {
const claims = result.idTokenClaims as Record<string, unknown>;
// `amr` is an optional claim. Entra includes it when it has
// explicit auth-method tracking to report (fresh interactive
// sign-in with MFA, etc.) and may omit it for SSO / refresh
// flows or when no Conditional Access policy requires the
// method to be surfaced. The BFF surfaces whatever is there in
// the audit log / future `@RequireMfa` guard — but it does NOT
// reject the token on empty / missing `amr`. Per ADR-0011, MFA
// enforcement is org-side via Conditional Access, and the
// BFF's "sanity check" is that MSAL accepted the token at all
// (signature + issuer + audience + exp validated). Sensitive
// routes that need a fresh MFA event will assert it explicitly
// through the `@RequireMfa({ freshness: 600 })` decorator once
// it lands.
const amr = Array.isArray(claims['amr'])
? (claims['amr'] as unknown[]).filter((v): v is string => typeof v === 'string')
: [];
// `roles` is an optional claim. Entra includes it when the user
// has at least one app role assigned on the BFF's app
// registration. The value is an array of the role `value`
// strings declared in the registration manifest (e.g. `admin`).
// No role assignment → claim is omitted entirely; we normalise
// to an empty array so consumers can call `.includes('admin')`
// unconditionally. Per ADR-0020, role-based authorisation is the
// single source of authority for admin access; the AdminRoleGuard
// will read this field on every `/api/admin/*` request.
const roles = Array.isArray(claims['roles'])
? (claims['roles'] as unknown[]).filter((v): v is string => typeof v === 'string')
: [];
// `groups` is an optional claim (per ADR-0025 §"Sources of truth
// — Entra-side configuration"). Present only when the app
// registration sets `groupMembershipClaims: 'SecurityGroup'`.
// Empty array if the user is in zero security groups or the
// claim is not configured — both are valid "no functional
// roles" states the rest of the BFF must tolerate. Same
// string-filter as `roles` to defend against a non-string value
// smuggled in via a malformed token.
const groups = Array.isArray(claims['groups'])
? (claims['groups'] as unknown[]).filter((v): v is string => typeof v === 'string')
: [];
return {
oid: requireString(claims['oid'], 'oid'),
tid: requireString(claims['tid'], 'tid'),
username:
typeof claims['preferred_username'] === 'string'
? (claims['preferred_username'] as string)
: (result.account?.username ?? ''),
displayName:
typeof claims['name'] === 'string'
? (claims['name'] as string)
: (result.account?.name ?? ''),
amr,
roles,
groups,
};
}
}
function requireString(value: unknown, claim: string): string {
if (typeof value !== 'string' || value === '') {
throw new AuthCodeFlowException({
kind: 'token-exchange-failed',
cause: `id token missing required string claim: ${claim}`,
});
}
return value;
}
function errorCause(err: unknown): string {
if (err instanceof Error) {
return err.message;
}
return String(err);
}