feat(portal-bff): distinct admin session + /api/admin/auth flow (#129)
## 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
This commit was merged in pull request #129.
This commit is contained in:
@@ -11,6 +11,8 @@ const ENTRA: EntraConfig = {
|
||||
clientSecret: 's3cret',
|
||||
redirectUri: 'http://localhost:3000/api/auth/callback',
|
||||
postLogoutRedirectUri: 'http://localhost:4200/',
|
||||
adminRedirectUri: 'http://localhost:3000/api/admin/auth/callback',
|
||||
adminPostLogoutRedirectUri: 'http://localhost:4201/',
|
||||
authority: 'https://login.microsoftonline.com/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
|
||||
};
|
||||
|
||||
@@ -71,7 +73,7 @@ const PRE_AUTH_OK: PreAuthPayload = {
|
||||
describe('AuthService.beginAuthCodeFlow', () => {
|
||||
it('builds the auth URL with the configured redirect, OIDC scopes, S256 challenge', async () => {
|
||||
const { service, getAuthCodeUrl } = makeService();
|
||||
await service.beginAuthCodeFlow();
|
||||
await service.beginAuthCodeFlow(ENTRA.redirectUri);
|
||||
expect(getAuthCodeUrl).toHaveBeenCalledTimes(1);
|
||||
const arg = getAuthCodeUrl.mock.calls[0]?.[0] as Record<string, unknown>;
|
||||
expect(arg['redirectUri']).toBe(ENTRA.redirectUri);
|
||||
@@ -83,7 +85,7 @@ describe('AuthService.beginAuthCodeFlow', () => {
|
||||
|
||||
it('returns the pre-auth payload with state + codeVerifier matching what MSAL was called with', async () => {
|
||||
const { service, getAuthCodeUrl } = makeService();
|
||||
const { preAuthPayload } = await service.beginAuthCodeFlow();
|
||||
const { preAuthPayload } = await service.beginAuthCodeFlow(ENTRA.redirectUri);
|
||||
const arg = getAuthCodeUrl.mock.calls[0]?.[0] as Record<string, unknown>;
|
||||
expect(preAuthPayload.state).toBe(arg['state']);
|
||||
expect(preAuthPayload.codeVerifier).not.toBe(arg['codeChallenge']);
|
||||
@@ -92,8 +94,8 @@ describe('AuthService.beginAuthCodeFlow', () => {
|
||||
|
||||
it('generates a fresh state + verifier on every call', async () => {
|
||||
const { service } = makeService();
|
||||
const a = await service.beginAuthCodeFlow();
|
||||
const b = await service.beginAuthCodeFlow();
|
||||
const a = await service.beginAuthCodeFlow(ENTRA.redirectUri);
|
||||
const b = await service.beginAuthCodeFlow(ENTRA.redirectUri);
|
||||
expect(a.preAuthPayload.state).not.toBe(b.preAuthPayload.state);
|
||||
expect(a.preAuthPayload.codeVerifier).not.toBe(b.preAuthPayload.codeVerifier);
|
||||
});
|
||||
@@ -106,6 +108,7 @@ describe('AuthService.completeAuthCodeFlow', () => {
|
||||
'auth-code',
|
||||
PRE_AUTH_OK.state,
|
||||
PRE_AUTH_OK,
|
||||
ENTRA.redirectUri,
|
||||
PRE_AUTH_OK.createdAt + 1_000,
|
||||
);
|
||||
expect(acquireTokenByCode).toHaveBeenCalledWith({
|
||||
@@ -127,7 +130,13 @@ describe('AuthService.completeAuthCodeFlow', () => {
|
||||
it('throws state-mismatch when the query state differs from the cookie state', async () => {
|
||||
const { service } = makeService();
|
||||
await expect(
|
||||
service.completeAuthCodeFlow('code', 'other-state', PRE_AUTH_OK, PRE_AUTH_OK.createdAt),
|
||||
service.completeAuthCodeFlow(
|
||||
'code',
|
||||
'other-state',
|
||||
PRE_AUTH_OK,
|
||||
ENTRA.redirectUri,
|
||||
PRE_AUTH_OK.createdAt,
|
||||
),
|
||||
).rejects.toMatchObject({ failure: { kind: 'state-mismatch' } });
|
||||
});
|
||||
|
||||
@@ -135,7 +144,7 @@ describe('AuthService.completeAuthCodeFlow', () => {
|
||||
const { service } = makeService();
|
||||
const now = PRE_AUTH_OK.createdAt + PRE_AUTH_COOKIE_TTL_MS + 1;
|
||||
await expect(
|
||||
service.completeAuthCodeFlow('code', PRE_AUTH_OK.state, PRE_AUTH_OK, now),
|
||||
service.completeAuthCodeFlow('code', PRE_AUTH_OK.state, PRE_AUTH_OK, ENTRA.redirectUri, now),
|
||||
).rejects.toMatchObject({ failure: { kind: 'flow-expired' } });
|
||||
});
|
||||
|
||||
@@ -146,6 +155,7 @@ describe('AuthService.completeAuthCodeFlow', () => {
|
||||
'code',
|
||||
PRE_AUTH_OK.state,
|
||||
PRE_AUTH_OK,
|
||||
ENTRA.redirectUri,
|
||||
PRE_AUTH_OK.createdAt,
|
||||
);
|
||||
// `amr` flows through as an empty array; MFA enforcement is
|
||||
@@ -163,6 +173,7 @@ describe('AuthService.completeAuthCodeFlow', () => {
|
||||
'code',
|
||||
PRE_AUTH_OK.state,
|
||||
PRE_AUTH_OK,
|
||||
ENTRA.redirectUri,
|
||||
PRE_AUTH_OK.createdAt,
|
||||
);
|
||||
expect(user.roles).toEqual(['admin', 'editor']);
|
||||
@@ -175,6 +186,7 @@ describe('AuthService.completeAuthCodeFlow', () => {
|
||||
'code',
|
||||
PRE_AUTH_OK.state,
|
||||
PRE_AUTH_OK,
|
||||
ENTRA.redirectUri,
|
||||
PRE_AUTH_OK.createdAt,
|
||||
);
|
||||
expect(user.roles).toEqual([]);
|
||||
@@ -187,6 +199,7 @@ describe('AuthService.completeAuthCodeFlow', () => {
|
||||
'code',
|
||||
PRE_AUTH_OK.state,
|
||||
PRE_AUTH_OK,
|
||||
ENTRA.redirectUri,
|
||||
PRE_AUTH_OK.createdAt,
|
||||
);
|
||||
expect(user.roles).toEqual([]);
|
||||
@@ -201,6 +214,7 @@ describe('AuthService.completeAuthCodeFlow', () => {
|
||||
'code',
|
||||
PRE_AUTH_OK.state,
|
||||
PRE_AUTH_OK,
|
||||
ENTRA.redirectUri,
|
||||
PRE_AUTH_OK.createdAt,
|
||||
);
|
||||
expect(user.roles).toEqual(['admin', 'editor']);
|
||||
@@ -210,7 +224,13 @@ describe('AuthService.completeAuthCodeFlow', () => {
|
||||
const acquireTokenByCode = jest.fn().mockRejectedValue(new Error('AADSTS70008'));
|
||||
const { service } = makeService({ acquireTokenByCode });
|
||||
await expect(
|
||||
service.completeAuthCodeFlow('code', PRE_AUTH_OK.state, PRE_AUTH_OK, PRE_AUTH_OK.createdAt),
|
||||
service.completeAuthCodeFlow(
|
||||
'code',
|
||||
PRE_AUTH_OK.state,
|
||||
PRE_AUTH_OK,
|
||||
ENTRA.redirectUri,
|
||||
PRE_AUTH_OK.createdAt,
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
failure: { kind: 'token-exchange-failed', cause: 'AADSTS70008' },
|
||||
});
|
||||
@@ -220,7 +240,13 @@ describe('AuthService.completeAuthCodeFlow', () => {
|
||||
const acquireTokenByCode = jest.fn().mockResolvedValue(null);
|
||||
const { service } = makeService({ acquireTokenByCode });
|
||||
await expect(
|
||||
service.completeAuthCodeFlow('code', PRE_AUTH_OK.state, PRE_AUTH_OK, PRE_AUTH_OK.createdAt),
|
||||
service.completeAuthCodeFlow(
|
||||
'code',
|
||||
PRE_AUTH_OK.state,
|
||||
PRE_AUTH_OK,
|
||||
ENTRA.redirectUri,
|
||||
PRE_AUTH_OK.createdAt,
|
||||
),
|
||||
).rejects.toBeInstanceOf(AuthCodeFlowException);
|
||||
});
|
||||
|
||||
@@ -231,7 +257,13 @@ describe('AuthService.completeAuthCodeFlow', () => {
|
||||
} as unknown as AuthenticationResult);
|
||||
const { service } = makeService({ acquireTokenByCode });
|
||||
await expect(
|
||||
service.completeAuthCodeFlow('code', PRE_AUTH_OK.state, PRE_AUTH_OK, PRE_AUTH_OK.createdAt),
|
||||
service.completeAuthCodeFlow(
|
||||
'code',
|
||||
PRE_AUTH_OK.state,
|
||||
PRE_AUTH_OK,
|
||||
ENTRA.redirectUri,
|
||||
PRE_AUTH_OK.createdAt,
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
failure: { kind: 'token-exchange-failed', cause: /oid/ },
|
||||
});
|
||||
@@ -241,19 +273,19 @@ describe('AuthService.completeAuthCodeFlow', () => {
|
||||
describe('AuthService.buildLogoutUrl', () => {
|
||||
it('targets the v2.0 logout endpoint on the configured authority', () => {
|
||||
const { service } = makeService();
|
||||
const url = new URL(service.buildLogoutUrl());
|
||||
const url = new URL(service.buildLogoutUrl(ENTRA.postLogoutRedirectUri));
|
||||
expect(url.origin + url.pathname).toBe(`${ENTRA.authority}/oauth2/v2.0/logout`);
|
||||
});
|
||||
|
||||
it('includes the post_logout_redirect_uri query param', () => {
|
||||
const { service } = makeService();
|
||||
const url = new URL(service.buildLogoutUrl());
|
||||
const url = new URL(service.buildLogoutUrl(ENTRA.postLogoutRedirectUri));
|
||||
expect(url.searchParams.get('post_logout_redirect_uri')).toBe(ENTRA.postLogoutRedirectUri);
|
||||
});
|
||||
|
||||
it('does not pass id_token_hint (v1 does not persist the id_token yet)', () => {
|
||||
const { service } = makeService();
|
||||
const url = new URL(service.buildLogoutUrl());
|
||||
const url = new URL(service.buildLogoutUrl(ENTRA.postLogoutRedirectUri));
|
||||
expect(url.searchParams.has('id_token_hint')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user