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
248 lines
9.0 KiB
TypeScript
248 lines
9.0 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. Surfaced for the future `@RequireAdmin` /
|
|
* `@RequireRole(...)` guards (ADR-0020 admin module). 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.
|
|
*/
|
|
export interface AuthenticatedUser {
|
|
readonly oid: string;
|
|
readonly tid: string;
|
|
readonly username: string;
|
|
readonly displayName: string;
|
|
readonly amr: readonly string[];
|
|
readonly roles: 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')
|
|
: [];
|
|
|
|
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,
|
|
};
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|