feat(portal-bff): @RequireMfa decorator + freshness guard (ADR-0011) (#128)
CI / check (push) Successful in 2m24s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m10s
CI / a11y (push) Successful in 1m11s
CI / perf (push) Successful in 4m0s

## Summary

Third step in the `portal-admin` audit-log-viewer workstream — ships the `@RequireMfa({ freshness })` decorator + guard called out in [ADR-0011](docs/decisions/0011-mfa-enforcement-entra-conditional-access.md) and referenced as the gate on the admin entry route in [ADR-0020](docs/decisions/0020-portal-admin-app.md). Designed-in, dormant: no v1 route uses the decorator yet. First consumer will be the admin entry route once the distinct admin session lands (next PR).

## What ships

- **[`auth/mfa.ts`](apps/portal-bff/src/auth/mfa.ts)** — `MFA_AMR_VALUES = ['mfa', 'otp', 'fido', 'wia', 'phr']` allow-list and `wasMultiFactor(amr): boolean`. The list mirrors ADR-0011 §"BFF verification"; the spec pins it so an ad-hoc edit can't bypass review.
- **[`config/check-mfa-config.ts`](apps/portal-bff/src/config/check-mfa-config.ts)** — `readMfaConfig()` reads `MFA_FRESHNESS_SECONDS` (default **600 s**, minimum **60 s**). Anything below the floor throws at boot — the floor catches a misconfigured "MFA on every navigation" before the BFF starts.
- **[`auth/require-mfa.guard.ts`](apps/portal-bff/src/auth/require-mfa.guard.ts)** — four branches:

  | Branch | HTTP | Code | Audit |
  | --- | --- | --- | --- |
  | No session | 401 | `unauthenticated` | none (noise) |
  | Session, no MFA-class `amr` | 401 | `mfa_required` | `auth.mfa_required reason=no-mfa-in-amr` |
  | Session, no `mfaVerifiedAt` | 401 | `mfa_required` | `auth.mfa_required reason=no-mfa-verified-at` |
  | Session, stale `mfaVerifiedAt` | 401 | `mfa_required` | `auth.mfa_required reason=mfa-stale, mfaAgeMs=…` |

  The `reason` discriminator is **not** surfaced over the wire — only the audit row carries it. An attacker probing for "stale vs no-MFA" can't distinguish the two from the response.

- **[`auth/require-mfa.decorator.ts`](apps/portal-bff/src/auth/require-mfa.decorator.ts)** — `@RequireMfa({ freshness? })` built via `applyDecorators(SetMetadata, UseGuards)`. The per-route `freshness` override wins over the env default. Designed to compose with `@RequireAdmin()` — apply `@RequireMfa` outside `@RequireAdmin` so the freshness gate runs only after role is established.
- **[`AuditWriter.mfaRequired()`](apps/portal-bff/src/audit/audit.service.ts)** — new typed method using `outcome=denied`, captures `reason`, `freshnessSeconds`, and `mfaAgeMs` (when applicable) in the JSONB payload.
- **`session.mfaVerifiedAt: number`** — augmented onto `express-session`'s `SessionData` in [`session.types.ts`](apps/portal-bff/src/session/session.types.ts). Set to `Date.now()` at sign-in by the callback ([`auth.controller.ts`](apps/portal-bff/src/auth/auth.controller.ts)). Entra's CA policy is the authority on whether MFA actually happened; the BFF stamps "now" when persisting a session whose `amr` reflects MFA.

## Deferred — for the SPA-interceptor PR

ADR-0011 §"Step-up MFA — designed-in" step 2 calls for a `WWW-Authenticate` header carrying a **claims challenge** (MSAL-produced blob) on the 401. That requires:

1. MSAL Node integration to mint the challenge — adds wire-format coupling to MSAL we don't have anywhere else yet.
2. The Angular SPA interceptor to consume the header, redirect to `/auth/login?claims=…`, and retry the original request.

Neither side has a consumer in this PR. Shipping a `code: 'mfa_required'` in the structured envelope is sufficient signalling for the SPA interceptor once it lands — the interceptor PR can layer the `WWW-Authenticate` header and the MSAL claims blob without changing the guard's audit contract.

## Composability with `@RequireAdmin`

The admin entry route (next-PR consumer) will read:

```ts
@Controller('admin')
@RequireMfa({ freshness: 600 })
@RequireAdmin()
export class AdminController { … }
```

Apply order matters — Nest runs guards in the order their decorators were applied (innermost first). Putting `@RequireMfa()` outside `@RequireAdmin()` means a non-admin user gets a clean 403 from `AdminRoleGuard` without a spurious `auth.mfa_required` audit row. The decorator's JSDoc spells this out for future consumers.

## Notes for the reviewer

- The `RequireMfaGuard` is registered as a provider in `AuthModule` and re-exported. Per the existing convention ("`AuthModule` stays non-global; modules state 'I depend on auth' by importing it"), any future module using `@RequireMfa()` will need to `imports: [AuthModule]`. The `AdminModule` already does this transitively via shared `AuditWriter`; the explicit import will follow when the decorator is first applied.
- `mfaChallenge(reason)` takes the reason argument deliberately even though it ignores it in the response — keeps the call sites readable (`throw this.mfaChallenge('mfa-stale')`) and parks a hook for the day we want to localise / differentiate the message.
- New env var `MFA_FRESHNESS_SECONDS` is **optional** (default 600). No production env change is required to ship this PR.

## Test plan

- [x] `pnpm nx test portal-bff` — **251 specs pass** (was 214; +37 covering helpers, config reader, guard branches, audit typed method, callback stamp).
- [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] `MFA_FRESHNESS_SECONDS` boot validator: default + valid + below-floor + non-integer + decimal + non-numeric all covered.
- [x] Guard timing-boundary cases covered (age == freshness passes; age == freshness + 1 ms fails — implicitly via the 700-s-vs-600-s test).
- [ ] e2e — pending real Entra session with `amr` carrying an MFA token. Will be exercised when the admin entry route applies the decorator.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #128
This commit was merged in pull request #128.
This commit is contained in:
2026-05-14 01:34:45 +02:00
parent 3ed6dae3a5
commit d51ccebe6a
14 changed files with 726 additions and 1 deletions
@@ -316,6 +316,57 @@ describe('AuditWriter — typed event methods', () => {
});
});
describe('mfaRequired()', () => {
it('records auth.mfa_required (denied) with reason + freshnessSeconds in payload', async () => {
const { writer, prisma, hashUserId } = await createSubject();
await writer.mfaRequired({
actor: { oid: 'user-oid' },
attemptedRoute: 'GET /api/admin/me',
reason: 'no-mfa-in-amr',
freshnessSeconds: 600,
});
expect(hashUserId.hash).toHaveBeenCalledWith('user-oid');
const row = extractInsertedRow(prisma);
expect(row.eventType).toBe('auth.mfa_required');
expect(row.audience).toBe('workforce');
expect(row.outcome).toBe('denied');
expect(row.actorIdHash).toBe('hash(user-oid)');
expect(row.subject).toBe('GET /api/admin/me');
expect(row.payloadJson).toBe(
JSON.stringify({ reason: 'no-mfa-in-amr', freshnessSeconds: 600 }),
);
});
it('includes mfaAgeMs in the payload when supplied (stale-session path)', async () => {
const { writer, prisma } = await createSubject();
await writer.mfaRequired({
actor: { oid: 'user-oid' },
attemptedRoute: 'POST /api/admin/cms/pages',
reason: 'mfa-stale',
freshnessSeconds: 600,
mfaAgeMs: 720_000,
});
expect(extractInsertedRow(prisma).payloadJson).toBe(
JSON.stringify({ reason: 'mfa-stale', freshnessSeconds: 600, mfaAgeMs: 720_000 }),
);
});
it('omits mfaAgeMs from the payload when undefined (no-mfa-verified-at path)', async () => {
const { writer, prisma } = await createSubject();
await writer.mfaRequired({
actor: { oid: 'user-oid' },
attemptedRoute: 'GET /api/admin/me',
reason: 'no-mfa-verified-at',
freshnessSeconds: 600,
});
const payload = JSON.parse(extractInsertedRow(prisma).payloadJson as string) as Record<
string,
unknown
>;
expect(payload).not.toHaveProperty('mfaAgeMs');
});
});
describe('adminAccessDenied()', () => {
it('records admin.access_denied with outcome=denied, attempted route as subject, and rolesHeld payload', async () => {
const { writer, prisma, hashUserId } = await createSubject();
@@ -5,6 +5,7 @@ import { PrismaService } from 'nestjs-prisma';
import type {
AdminAccessDeniedInput,
AuditEventInput,
MfaRequiredInput,
SignInActor,
SignInFailedInput,
SignOutInput,
@@ -114,6 +115,32 @@ export class AuditWriter {
});
}
/**
* Typed event: a request was rejected by `RequireMfaGuard` because
* the session did not satisfy the route's MFA freshness gate.
* Per ADR-0011 §"Step-up MFA — designed-in, dormant", every
* step-up challenge emitted by the BFF lands here so auditors can
* track the distribution of step-up prompts (and the rate of stale
* `mfaVerifiedAt` rejections that would suggest the default
* freshness is too tight). `outcome=denied` matches the
* `AdminRoleGuard` posture: the user *is* authenticated, the
* action is just refused.
*/
async mfaRequired(input: MfaRequiredInput): Promise<void> {
await this.recordEvent({
eventType: 'auth.mfa_required',
audience: 'workforce',
outcome: 'denied',
actorIdHash: this.hashUserId.hash(input.actor.oid),
subject: input.attemptedRoute,
payload: {
reason: input.reason,
freshnessSeconds: input.freshnessSeconds,
...(input.mfaAgeMs !== undefined ? { mfaAgeMs: input.mfaAgeMs } : {}),
},
});
}
/**
* Typed event: `/api/admin/*` request rejected by `AdminRoleGuard`
* because the session's `roles` claim does not include `admin`.
+18
View File
@@ -100,3 +100,21 @@ export interface AdminAccessDeniedInput {
*/
rolesHeld: readonly string[];
}
/** Reason `RequireMfaGuard` rejected a request — fed into the audit payload. */
export type MfaRequiredReason = 'no-mfa-in-amr' | 'no-mfa-verified-at' | 'mfa-stale';
export interface MfaRequiredInput {
actor: { oid: string };
/** Canonical "{METHOD} {originalUrl}" of the rejected request. */
attemptedRoute: string;
reason: MfaRequiredReason;
/**
* Freshness window (seconds) the guard checked against. Captured
* so an auditor can tell apart a 10-min default rejection from a
* tighter per-route override.
*/
freshnessSeconds: number;
/** Age (ms) of the session's `mfaVerifiedAt` at the moment of rejection — undefined when the session had none. */
mfaAgeMs?: number;
}