feat(portal-bff): @RequireMfa decorator + freshness guard (ADR-0011) (#128)
## 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:
@@ -0,0 +1,58 @@
|
||||
import { readMfaConfig } from './check-mfa-config';
|
||||
|
||||
describe('readMfaConfig', () => {
|
||||
const original = process.env['MFA_FRESHNESS_SECONDS'];
|
||||
|
||||
afterEach(() => {
|
||||
if (original === undefined) {
|
||||
delete process.env['MFA_FRESHNESS_SECONDS'];
|
||||
} else {
|
||||
process.env['MFA_FRESHNESS_SECONDS'] = original;
|
||||
}
|
||||
});
|
||||
|
||||
it('defaults to 600 seconds when MFA_FRESHNESS_SECONDS is unset', () => {
|
||||
delete process.env['MFA_FRESHNESS_SECONDS'];
|
||||
expect(readMfaConfig()).toEqual({ freshnessSeconds: 600 });
|
||||
});
|
||||
|
||||
it('defaults to 600 seconds when MFA_FRESHNESS_SECONDS is the empty string', () => {
|
||||
process.env['MFA_FRESHNESS_SECONDS'] = '';
|
||||
expect(readMfaConfig()).toEqual({ freshnessSeconds: 600 });
|
||||
});
|
||||
|
||||
it('accepts a positive integer above the minimum', () => {
|
||||
process.env['MFA_FRESHNESS_SECONDS'] = '1200';
|
||||
expect(readMfaConfig()).toEqual({ freshnessSeconds: 1200 });
|
||||
});
|
||||
|
||||
it('accepts the minimum (60) exactly', () => {
|
||||
process.env['MFA_FRESHNESS_SECONDS'] = '60';
|
||||
expect(readMfaConfig()).toEqual({ freshnessSeconds: 60 });
|
||||
});
|
||||
|
||||
it('throws when MFA_FRESHNESS_SECONDS is below the 60 s floor', () => {
|
||||
process.env['MFA_FRESHNESS_SECONDS'] = '30';
|
||||
expect(() => readMfaConfig()).toThrow(/must be ≥ 60/);
|
||||
});
|
||||
|
||||
it('throws when MFA_FRESHNESS_SECONDS is not a positive integer', () => {
|
||||
process.env['MFA_FRESHNESS_SECONDS'] = '0';
|
||||
expect(() => readMfaConfig()).toThrow(/positive integer/);
|
||||
});
|
||||
|
||||
it('throws when MFA_FRESHNESS_SECONDS is negative', () => {
|
||||
process.env['MFA_FRESHNESS_SECONDS'] = '-600';
|
||||
expect(() => readMfaConfig()).toThrow(/positive integer/);
|
||||
});
|
||||
|
||||
it('throws when MFA_FRESHNESS_SECONDS is non-numeric', () => {
|
||||
process.env['MFA_FRESHNESS_SECONDS'] = 'soon';
|
||||
expect(() => readMfaConfig()).toThrow(/positive integer/);
|
||||
});
|
||||
|
||||
it('throws when MFA_FRESHNESS_SECONDS is a decimal', () => {
|
||||
process.env['MFA_FRESHNESS_SECONDS'] = '600.5';
|
||||
expect(() => readMfaConfig()).toThrow(/positive integer/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Reads + validates the MFA-related env vars at boot.
|
||||
*
|
||||
* MFA_FRESHNESS_SECONDS — default 600 (10 min). Window during
|
||||
* which a session's `mfaVerifiedAt` is considered "fresh enough"
|
||||
* for routes decorated with `@RequireMfa()`. The decorator can
|
||||
* override it per-route; the env value is the global default.
|
||||
*
|
||||
* Minimum: 60 s. Anything below would mean the user has to re-MFA
|
||||
* basically on every navigation; the floor catches a misconfigured
|
||||
* `MFA_FRESHNESS_SECONDS=30` before the BFF starts. ADR-0011's
|
||||
* confirmation list explicitly calls out this floor.
|
||||
*
|
||||
* No upper bound — operators can pick a long window for low-risk
|
||||
* surfaces if they want; the trade-off is theirs to record in their
|
||||
* runbook, not the BFF's to refuse.
|
||||
*/
|
||||
const DEFAULT_FRESHNESS_SECONDS = 600;
|
||||
const MIN_FRESHNESS_SECONDS = 60;
|
||||
|
||||
export interface MfaConfig {
|
||||
readonly freshnessSeconds: number;
|
||||
}
|
||||
|
||||
export function readMfaConfig(): MfaConfig {
|
||||
const raw = process.env['MFA_FRESHNESS_SECONDS'];
|
||||
if (raw === undefined || raw === '') {
|
||||
return { freshnessSeconds: DEFAULT_FRESHNESS_SECONDS };
|
||||
}
|
||||
const value = Number(raw);
|
||||
if (!Number.isInteger(value) || value <= 0) {
|
||||
throw new Error(`MFA_FRESHNESS_SECONDS must be a positive integer (got "${raw}").`);
|
||||
}
|
||||
if (value < MIN_FRESHNESS_SECONDS) {
|
||||
throw new Error(
|
||||
`MFA_FRESHNESS_SECONDS must be ≥ ${MIN_FRESHNESS_SECONDS} (got ${value}). ` +
|
||||
`Anything shorter forces re-MFA on every navigation and is almost certainly a misconfiguration.`,
|
||||
);
|
||||
}
|
||||
return { freshnessSeconds: value };
|
||||
}
|
||||
Reference in New Issue
Block a user