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:
@@ -0,0 +1,28 @@
|
||||
import { adminSessionCookieName } from './admin-session-cookie';
|
||||
|
||||
describe('adminSessionCookieName', () => {
|
||||
const originalNodeEnv = process.env['NODE_ENV'];
|
||||
|
||||
afterEach(() => {
|
||||
if (originalNodeEnv === undefined) {
|
||||
delete process.env['NODE_ENV'];
|
||||
} else {
|
||||
process.env['NODE_ENV'] = originalNodeEnv;
|
||||
}
|
||||
});
|
||||
|
||||
it('uses the `__Host-` prefixed name in production', () => {
|
||||
process.env['NODE_ENV'] = 'production';
|
||||
expect(adminSessionCookieName()).toBe('__Host-portal_admin_session');
|
||||
});
|
||||
|
||||
it('uses the unprefixed name in development', () => {
|
||||
process.env['NODE_ENV'] = 'development';
|
||||
expect(adminSessionCookieName()).toBe('portal_admin_session');
|
||||
});
|
||||
|
||||
it('defaults to development naming when NODE_ENV is unset', () => {
|
||||
delete process.env['NODE_ENV'];
|
||||
expect(adminSessionCookieName()).toBe('portal_admin_session');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Admin-session cookie name per ADR-0020 §"Sessions — distinct from
|
||||
* `portal-shell`". The admin SPA carries `__Host-portal_admin_session`
|
||||
* (prod) so a browser holding both cookies can switch between
|
||||
* portal-shell and portal-admin without one signing the user in to
|
||||
* the other.
|
||||
*
|
||||
* Same `__Host-` posture as the user-portal session: `Secure` + no
|
||||
* `Domain` + `Path=/`. The dev variant drops the prefix because
|
||||
* local servers are plain HTTP.
|
||||
*
|
||||
* The cookie scoping is the only thing keeping the two sessions
|
||||
* apart at the browser level — the BFF further isolates them in
|
||||
* Redis under a distinct key prefix (`session:admin:`).
|
||||
*/
|
||||
const PRODUCTION_NAME = '__Host-portal_admin_session';
|
||||
const DEVELOPMENT_NAME = 'portal_admin_session';
|
||||
|
||||
export function adminSessionCookieName(): string {
|
||||
return process.env['NODE_ENV'] === 'production' ? PRODUCTION_NAME : DEVELOPMENT_NAME;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { RedisStore } from 'connect-redis';
|
||||
import expressSession from 'express-session';
|
||||
import type { CookieOptions } from 'express';
|
||||
import { Logger } from 'nestjs-pino';
|
||||
import { assertSessionEncryptionKey } from '../config/check-session-encryption-key';
|
||||
import { assertSessionSecret } from '../config/check-session-secret';
|
||||
@@ -9,10 +10,12 @@ import { RedisModule } from '../redis/redis.module';
|
||||
import { REDIS_CLIENT, type Redis } from '../redis/redis.token';
|
||||
import { AuditWriter } from '../audit/audit.service';
|
||||
import { createAbsoluteTimeoutMiddleware } from './absolute-timeout.middleware';
|
||||
import { adminSessionCookieName } from './admin-session-cookie';
|
||||
import { adaptIoredisForConnectRedis } from './ioredis-connect-redis-adapter';
|
||||
import { SessionDecryptError, decrypt, encrypt } from './session-crypto';
|
||||
import { readSessionTimeouts, sessionCookieName, sessionCookieOptions } from './session-cookie';
|
||||
import {
|
||||
ADMIN_SESSION_MIDDLEWARE,
|
||||
SESSION_ABSOLUTE_TIMEOUT_MIDDLEWARE,
|
||||
SESSION_MIDDLEWARE,
|
||||
type RequestHandler,
|
||||
@@ -22,35 +25,108 @@ import {
|
||||
import './session.types';
|
||||
import { UserSessionIndexService } from './user-session-index.service';
|
||||
|
||||
/**
|
||||
* Build a configured `express-session` middleware. Shared between
|
||||
* the user-portal middleware ({@link SESSION_MIDDLEWARE}) and the
|
||||
* admin-portal middleware ({@link ADMIN_SESSION_MIDDLEWARE}) per
|
||||
* ADR-0020 §"Sessions — distinct from `portal-shell`".
|
||||
*
|
||||
* The two surfaces differ only on the cookie name and Redis key
|
||||
* prefix; the TTL policy, encryption key, signing secret, session-id
|
||||
* entropy, and error-handling all come from the same source so a
|
||||
* future hardening (e.g. tighter idle TTL on admin) is a parameter
|
||||
* change rather than a divergent code path.
|
||||
*/
|
||||
function buildSessionMiddleware(
|
||||
redis: Redis,
|
||||
logger: Logger,
|
||||
opts: { cookieName: string; redisKeyPrefix: string; surfaceTag: 'user' | 'admin' },
|
||||
): RequestHandler {
|
||||
const secret = assertSessionSecret();
|
||||
const key = assertSessionEncryptionKey();
|
||||
const timeouts = readSessionTimeouts();
|
||||
|
||||
const store = new RedisStore({
|
||||
// `connect-redis` v9 was rewritten against the `node-redis` v4
|
||||
// command surface; the adapter shims `ioredis` to look the same
|
||||
// for the handful of commands the store actually calls.
|
||||
client: adaptIoredisForConnectRedis(redis) as unknown as never,
|
||||
prefix: opts.redisKeyPrefix,
|
||||
ttl: timeouts.idleSeconds,
|
||||
serializer: {
|
||||
stringify: (sess) => encrypt(JSON.stringify(sess), key),
|
||||
parse: (payload) => {
|
||||
try {
|
||||
return JSON.parse(decrypt(payload, key));
|
||||
} catch (err) {
|
||||
// Tamper, wrong key, or unknown version. The phase-2
|
||||
// audit pipeline (ADR-0013) will turn this into a
|
||||
// first-class audit event; for now we surface a
|
||||
// structured Pino log so ops can spot it. The
|
||||
// `surface` tag lets dashboards split user-portal
|
||||
// decrypt failures from admin-portal ones.
|
||||
logger.warn(
|
||||
{
|
||||
event: 'session.decrypt_failed',
|
||||
surface: opts.surfaceTag,
|
||||
reason: err instanceof SessionDecryptError ? err.message : String(err),
|
||||
},
|
||||
'session',
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const cookie: CookieOptions = sessionCookieOptions(timeouts.idleSeconds);
|
||||
|
||||
return expressSession({
|
||||
name: opts.cookieName,
|
||||
secret,
|
||||
// `crypto.randomBytes(32).toString('base64url')` ⇒ 256
|
||||
// bits of entropy in the session id, per ADR-0010
|
||||
// §"Confirmation".
|
||||
genid: () => randomBytes(32).toString('base64url'),
|
||||
store,
|
||||
// `resave: false` — RedisStore.touch refreshes the TTL on
|
||||
// every request; no need to rewrite the payload.
|
||||
resave: false,
|
||||
// `saveUninitialized: false` — don't create empty session
|
||||
// keys for unauthenticated visitors browsing public
|
||||
// routes. The session is born when the OIDC callback
|
||||
// populates it.
|
||||
saveUninitialized: false,
|
||||
// `rolling: true` — the cookie's `expires` slides forward
|
||||
// on every response, matching the sliding-idle policy.
|
||||
rolling: true,
|
||||
cookie,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Session module — wires `express-session` with a `connect-redis`
|
||||
* store on top of the shared `ioredis` client, with AES-256-GCM
|
||||
* encryption applied to the JSON payload before it lands in Redis.
|
||||
*
|
||||
* The configured middleware is exposed as a NestJS provider under
|
||||
* the {@link SESSION_MIDDLEWARE} token. `main.ts` resolves it from
|
||||
* the application context and mounts it once via `app.use(...)`
|
||||
* after `cookie-parser`. Mounting the express-session middleware
|
||||
* through DI (rather than constructing it in `main.ts`) keeps it on
|
||||
* the same Redis client the rest of the BFF uses, instead of
|
||||
* spinning up a second connection at the bootstrap layer.
|
||||
* Two middlewares are provided, path-routed in `main.ts`:
|
||||
*
|
||||
* What's wired today:
|
||||
* - Express-session middleware on every request (`SESSION_MIDDLEWARE`).
|
||||
* - Absolute-timeout middleware (`SESSION_ABSOLUTE_TIMEOUT_MIDDLEWARE`)
|
||||
* that enforces the 12 h hard ceiling per ADR-0010.
|
||||
* - `UserSessionIndexService`: maintains the
|
||||
* `user_sessions:{userId}` Redis set so a future admin endpoint
|
||||
* can "log out user X everywhere" — write-side hooks live in
|
||||
* the auth controller (create on `/auth/callback`, drop on
|
||||
* `/auth/logout` or absolute-timeout).
|
||||
* - {@link SESSION_MIDDLEWARE} — user-portal. Cookie
|
||||
* `portal_session` / `__Host-portal_session`. Redis prefix
|
||||
* `session:`. Bound to every path except `/api/admin/*`.
|
||||
*
|
||||
* Out of scope, landing in follow-ups:
|
||||
* - The admin "logout everywhere" route that consumes the
|
||||
* `UserSessionIndexService` (waits on the admin module + the
|
||||
* `@RequireAdmin` / `@RequireMfa` guards).
|
||||
* - Audit-pipeline wiring for `session.decrypt_failed` and
|
||||
* `session.absolute_timeout` (ADR-0013).
|
||||
* - {@link ADMIN_SESSION_MIDDLEWARE} — admin-portal per ADR-0020.
|
||||
* Cookie `portal_admin_session` / `__Host-portal_admin_session`.
|
||||
* Redis prefix `session:admin:`. Bound to `/api/admin/*` only.
|
||||
*
|
||||
* The {@link SESSION_ABSOLUTE_TIMEOUT_MIDDLEWARE} (ADR-0010 §"TTL
|
||||
* policy") and {@link UserSessionIndexService} are shared across
|
||||
* both surfaces — the absolute-timeout check reads `req.session`
|
||||
* which the dispatch has already resolved to one surface or the
|
||||
* other; the user-session index is keyed by Entra `oid`, so an
|
||||
* admin sign-in and a user-portal sign-in by the same person
|
||||
* naturally land in different Redis sets only because the session
|
||||
* id namespaces differ.
|
||||
*/
|
||||
@Module({
|
||||
imports: [RedisModule],
|
||||
@@ -68,66 +144,29 @@ import { UserSessionIndexService } from './user-session-index.service';
|
||||
{
|
||||
provide: SESSION_MIDDLEWARE,
|
||||
inject: [REDIS_CLIENT, Logger],
|
||||
useFactory: (redis: Redis, logger: Logger): RequestHandler => {
|
||||
const secret = assertSessionSecret();
|
||||
const key = assertSessionEncryptionKey();
|
||||
const timeouts = readSessionTimeouts();
|
||||
|
||||
const store = new RedisStore({
|
||||
// `connect-redis` v9 was rewritten against the
|
||||
// `node-redis` v4 command surface; the adapter shims
|
||||
// `ioredis` to look the same for the handful of commands
|
||||
// the store actually calls.
|
||||
client: adaptIoredisForConnectRedis(redis) as unknown as never,
|
||||
prefix: 'session:',
|
||||
ttl: timeouts.idleSeconds,
|
||||
serializer: {
|
||||
stringify: (sess) => encrypt(JSON.stringify(sess), key),
|
||||
parse: (payload) => {
|
||||
try {
|
||||
return JSON.parse(decrypt(payload, key));
|
||||
} catch (err) {
|
||||
// Tamper, wrong key, or unknown version. The phase-2
|
||||
// audit pipeline (ADR-0013) will turn this into a
|
||||
// first-class audit event; for now we surface a
|
||||
// structured Pino log so ops can spot it.
|
||||
logger.warn(
|
||||
{
|
||||
event: 'session.decrypt_failed',
|
||||
reason: err instanceof SessionDecryptError ? err.message : String(err),
|
||||
},
|
||||
'session',
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return expressSession({
|
||||
name: sessionCookieName(),
|
||||
secret,
|
||||
// `crypto.randomBytes(32).toString('base64url')` ⇒ 256
|
||||
// bits of entropy in the session id, per ADR-0010
|
||||
// §"Confirmation".
|
||||
genid: () => randomBytes(32).toString('base64url'),
|
||||
store,
|
||||
// `resave: false` — RedisStore.touch refreshes the TTL on
|
||||
// every request; no need to rewrite the payload.
|
||||
resave: false,
|
||||
// `saveUninitialized: false` — don't create empty session
|
||||
// keys for unauthenticated visitors browsing public
|
||||
// routes. The session is born when `/auth/callback`
|
||||
// populates it.
|
||||
saveUninitialized: false,
|
||||
// `rolling: true` — the cookie's `expires` slides forward
|
||||
// on every response, matching the sliding-idle policy.
|
||||
rolling: true,
|
||||
cookie: sessionCookieOptions(timeouts.idleSeconds),
|
||||
});
|
||||
},
|
||||
useFactory: (redis: Redis, logger: Logger): RequestHandler =>
|
||||
buildSessionMiddleware(redis, logger, {
|
||||
cookieName: sessionCookieName(),
|
||||
redisKeyPrefix: 'session:',
|
||||
surfaceTag: 'user',
|
||||
}),
|
||||
},
|
||||
{
|
||||
provide: ADMIN_SESSION_MIDDLEWARE,
|
||||
inject: [REDIS_CLIENT, Logger],
|
||||
useFactory: (redis: Redis, logger: Logger): RequestHandler =>
|
||||
buildSessionMiddleware(redis, logger, {
|
||||
cookieName: adminSessionCookieName(),
|
||||
redisKeyPrefix: 'session:admin:',
|
||||
surfaceTag: 'admin',
|
||||
}),
|
||||
},
|
||||
],
|
||||
exports: [SESSION_MIDDLEWARE, SESSION_ABSOLUTE_TIMEOUT_MIDDLEWARE, UserSessionIndexService],
|
||||
exports: [
|
||||
SESSION_MIDDLEWARE,
|
||||
ADMIN_SESSION_MIDDLEWARE,
|
||||
SESSION_ABSOLUTE_TIMEOUT_MIDDLEWARE,
|
||||
UserSessionIndexService,
|
||||
],
|
||||
})
|
||||
export class SessionModule {}
|
||||
|
||||
@@ -1,17 +1,38 @@
|
||||
import type { RequestHandler } from 'express';
|
||||
|
||||
/**
|
||||
* DI token for the configured `express-session` middleware. Resolved
|
||||
* DI token for the user-portal `express-session` middleware. Resolved
|
||||
* once at bootstrap (`main.ts`) and mounted with `app.use(...)`
|
||||
* after `cookie-parser` so cookies are already parsed when the
|
||||
* session middleware reads the session id.
|
||||
*
|
||||
* Carries the `portal_session` / `__Host-portal_session` cookie and
|
||||
* persists payloads under the `session:` Redis prefix. Bound to
|
||||
* every path EXCEPT `/api/admin/*` by the dispatch in `main.ts`.
|
||||
*
|
||||
* Usage:
|
||||
* const session = app.get<RequestHandler>(SESSION_MIDDLEWARE);
|
||||
* app.use(session);
|
||||
*/
|
||||
export const SESSION_MIDDLEWARE = 'SESSION_MIDDLEWARE';
|
||||
|
||||
/**
|
||||
* DI token for the admin-portal `express-session` middleware. Same
|
||||
* underlying `express-session` + `connect-redis` plumbing as
|
||||
* {@link SESSION_MIDDLEWARE}, but configured for the admin surface
|
||||
* per ADR-0020 §"Sessions — distinct from `portal-shell`":
|
||||
*
|
||||
* - Cookie name: `portal_admin_session` / `__Host-portal_admin_session`.
|
||||
* - Redis key prefix: `session:admin:`.
|
||||
* - Same idle / absolute TTL policy (ADR-0010); admin tightening
|
||||
* can come later through env without code changes.
|
||||
*
|
||||
* Bound to `/api/admin/*` only by the dispatch in `main.ts`. Signing
|
||||
* into one surface does NOT sign the user into the other — Entra
|
||||
* SSO at the IdP level still preserves a click-through experience.
|
||||
*/
|
||||
export const ADMIN_SESSION_MIDDLEWARE = 'ADMIN_SESSION_MIDDLEWARE';
|
||||
|
||||
/**
|
||||
* DI token for the absolute-timeout middleware (per ADR-0010 §"TTL
|
||||
* policy"). Resolved at bootstrap and mounted in `main.ts`
|
||||
|
||||
Reference in New Issue
Block a user