Files
apf_portal/apps/portal-bff/src/auth/session-establisher.service.ts
T
julien aca9e8d155
CI / check (push) Successful in 3m2s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m54s
CI / a11y (push) Successful in 1m25s
CI / perf (push) Successful in 4m23s
feat(portal-bff): user directory upserted at sign-in (#140)
## Summary

First PR of the **portal-admin User-list chantier** per [ADR-0020](docs/decisions/0020-portal-admin-app.md) §"v1 scope — User list (read-only)". Ships the **write side** only:

1. A new `public.users` table that holds the BFF's local cache of identities seen sign in to either portal-shell or portal-admin.
2. A `UserDirectoryService.recordSignIn(user)` upsert called from `SessionEstablisher.establish` after the blocking audit write.

The read side (`GET /api/admin/users` + the admin viewer SPA screen) lands in two follow-up PRs of the same chantier.

## Schema

[`prisma/schema.prisma`](apps/portal-bff/prisma/schema.prisma) gains a `User` model in the `public` schema:

| Column | Type | Notes |
| --- | --- | --- |
| `oid` | TEXT, PK | Entra's stable per-user identifier inside the tenant. Per-tenant uniqueness is sufficient for v1's single-workforce-tenant design (ADR-0008). |
| `tid` | TEXT | Tenant id. Updated on every upsert because a dual-audience future may legitimately change it. |
| `audience` | TEXT | `'workforce'` \| `'customer'`. Hardcoded to `workforce` in v1 per ADR-0008's simplification; will read from session/claims when External ID activates. |
| `username` | TEXT | Updated on every upsert (Entra-side rename possible). |
| `display_name` | TEXT | Same. |
| `first_seen_at` | TIMESTAMPTZ | Set once at first sign-in via DEFAULT NOW(); **never overwritten** thereafter. Enables "users since <date>" without joining anything. |
| `last_seen_at` | TIMESTAMPTZ | Updated on every upsert. Enables "most recently active" without scanning `audit.events`. |

Indexes:
- `last_seen_at DESC` — admin default sort.
- `username` — prefix filtering.

Migration in [`prisma/migrations/20260514192014_users_directory/`](apps/portal-bff/prisma/migrations/20260514192014_users_directory/migration.sql).

## [`UserDirectoryService`](apps/portal-bff/src/users/user-directory.service.ts)

```ts
async recordSignIn(entry): Promise<void> {
  try {
    await prisma.user.upsert({
      where: { oid },
      create: { oid, tid, audience, username, displayName },
      update: { tid, audience, username, displayName, lastSeenAt: new Date() },
    });
  } catch (err) {
    // logged, never propagated
  }
}
```

**Best-effort write.** Catches its own errors, logs a Pino warn (`user_directory.record_sign_in_failed`), returns `undefined`. The directory is a convenience for admin browsing, not a security boundary — a Postgres hiccup must not lock a user out of sign-in. ADR-0013's "no audit ⇒ no action" applies to the audit module only.

## [`SessionEstablisher`](apps/portal-bff/src/auth/session-establisher.service.ts) wiring

The directory call lands right after the existing audit emission:

```ts
await this.audit.signIn({ actor: user, sessionId: req.sessionID }); // blocking per ADR-0013
await this.userDirectory.recordSignIn({ ...user, audience: 'workforce' }); // best-effort
this.logger.log(...);
```

Two invariants the tests pin:

1. **Audit-first**: when `audit.signIn` throws, `userDirectory.recordSignIn` is NOT called. The directory never holds a row for a sign-in the audit log doesn't carry.
2. **Awaited**: an admin who just signed in sees themselves on the user list immediately — no race between the upsert and the response.

## Module wiring

[`UsersModule`](apps/portal-bff/src/users/users.module.ts) is declared `@Global()` so `SessionEstablisher` (which lives in `AuthModule`) injects `UserDirectoryService` without forcing `AuthModule` to import `UsersModule`. The directory is a true cross-cutting concern: one writer (the auth callback) and one future reader (the admin endpoint).

Wired into [`AppModule`](apps/portal-bff/src/app/app.module.ts) alongside the other v1 modules. `auth.module.spec.ts` updated to also import `UsersModule` in its slice-of-graph compile (otherwise the test fails to resolve the new `SessionEstablisher` dep).

## Notes for the reviewer

- The directory write **awaits** (not fire-and-forget). The cost is one round-trip per sign-in on the response-critical path; the benefit is the no-race property called out above. If sign-in p95 becomes an issue we can revisit (e.g. background job) but the simpler shape is correct first.
- `firstSeenAt` is intentionally absent from the `update` payload. The Prisma upsert's `update` block is precisely what changes on conflict; omitting the field leaves it untouched at the column level (Postgres-side default doesn't refire on UPDATE).
- The model lives in `public`, not in a dedicated `identity` or `cms` schema. ADR-0020 enumerates `cms.*` for editorial data and `audit.*` for the audit ledger but doesn't require a separate schema for user-directory data. We can promote it to its own schema later if a role-isolation need emerges; the migration would be a `ALTER TABLE users SET SCHEMA …`.
- `audit.events.actor_id_hash` is **not** stored on `public.users`. A future admin endpoint that joins sign-in counts from `audit.events` can compute the hash on-the-fly via `HashUserIdService` — keeping the salted-hash invariant from ADR-0013 intact (the salt stays inside the audit module).

## Test plan

- [x] `pnpm nx test portal-bff` — **365 specs pass** (was 358; +7: UserDirectoryService 4, SessionEstablisher integration 3).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean (the pre-existing rate-limit warnings + one unused-eslint-disable from PR #137 are unrelated).
- [x] Prisma `migrate diff` confirms the model matches the migration SQL.
- [ ] e2e — after merge: sign in via portal-shell or portal-admin, expect a row in `public.users` with the right `oid` / `last_seen_at`; sign in again, expect the same row's `last_seen_at` to advance and `first_seen_at` to stay put.

## What's next

The chantier sequence:

1. **This PR** — write side: schema + service + sign-in upsert.
2. **PR 2** — BFF `GET /api/admin/users` (paginated + filterable, gated by `@RequireAdmin`, emits `admin.users.query` audit).
3. **PR 3** — portal-admin `/users` screen (table + filter form), promote the sidebar entry from "Soon" badge to live link.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #140
2026-05-14 19:30:12 +02:00

179 lines
6.9 KiB
TypeScript

import { randomBytes } from 'node:crypto';
import { Injectable } from '@nestjs/common';
import type { Request, Response } from 'express';
import { Logger } from 'nestjs-pino';
import { AuditWriter } from '../audit/audit.service';
import { csrfCookieName, csrfCookieOptions } from '../security/csrf-cookie';
import { readSessionTimeouts } from '../session/session-cookie';
import { UserSessionIndexService } from '../session/user-session-index.service';
import { UserDirectoryService } from '../users/user-directory.service';
import type { AuthenticatedUser } from './auth.service';
export type AuthSurface = 'user' | 'admin';
/**
* Shared session-establishment recipe used by both `AuthController`
* (user-portal) and `AdminAuthController` (admin-portal). Per
* ADR-0020 §"Sessions — distinct from `portal-shell`", the two
* surfaces use distinct cookies / Redis namespaces — but the
* *recipe* for persisting an authenticated user into a session is
* identical:
*
* 1. Mint a CSRF token (per ADR-0009 §"Double-submit CSRF").
* 2. Populate the session fields (`user`, `createdAt`,
* `absoluteExpiresAt`, `csrfToken`, `mfaVerifiedAt`).
* 3. Force `req.session.save()` before the 302 — `express-session`
* writes on response end, but the redirect closes the response
* before the async store write would otherwise complete.
* 4. Mirror the CSRF token to the JS-readable cookie.
* 5. Register the session id in the per-user index for future
* "logout everywhere" — best-effort, a Redis hiccup does NOT
* fail the sign-in.
* 6. Emit the `auth.sign_in` audit row (blocking per ADR-0013).
* 7. Log the success event.
*
* Surface-specific concerns — the redirect destination, the pre-auth
* cookie clearing, the error paths — stay in the controllers.
*
* The middleware in `main.ts` has already resolved `req.session` to
* the correct surface (user vs admin) by the time the controller's
* callback handler runs; this service therefore writes to whichever
* session was loaded without needing to know which one.
*/
@Injectable()
export class SessionEstablisher {
constructor(
private readonly logger: Logger,
private readonly userSessionIndex: UserSessionIndexService,
private readonly audit: AuditWriter,
private readonly userDirectory: UserDirectoryService,
) {}
async establish(opts: {
user: AuthenticatedUser;
req: Request;
res: Response;
/**
* Tag forwarded into the success log so dashboards can split
* user-portal sign-ins from admin-portal sign-ins. Audit rows
* keep the same `auth.sign_in` event type in both cases —
* adding a surface field to the audit catalogue is a follow-up
* decision (current ADR-0013 catalogue is single-tier).
*/
surface: AuthSurface;
}): Promise<void> {
const { user, req, res, surface } = opts;
const now = Date.now();
const { idleSeconds, absoluteSeconds } = readSessionTimeouts();
const csrfToken = randomBytes(32).toString('base64url');
req.session.user = user;
req.session.createdAt = now;
// Hard ceiling per ADR-0010 §"TTL policy" — checked on every
// request by the absolute-timeout middleware, independent of
// idle TTL.
req.session.absoluteExpiresAt = now + absoluteSeconds * 1000;
req.session.csrfToken = csrfToken;
// MFA freshness anchor per ADR-0011 §"Confirmation". Entra's
// CA policy decides whether MFA actually happened — the BFF
// does not re-validate factors. Refreshed by future step-up
// re-auth flows.
req.session.mfaVerifiedAt = now;
await saveSession(req);
// Cookie maxAge matches the session's idle TTL so the CSRF
// cookie expires alongside the session itself (rolling,
// refreshed on each request).
res.cookie(csrfCookieName(), csrfToken, csrfCookieOptions(idleSeconds * 1000));
// Best-effort: a Redis hiccup here doesn't fail sign-in.
await this.userSessionIndex.add(user.oid, req.sessionID);
// Blocking audit per ADR-0013. If this throws the user does
// NOT see a successful sign-in: the exception propagates and
// the controller emits a 5xx via the StructuredErrorFilter.
await this.audit.signIn({ actor: user, sessionId: req.sessionID });
// Best-effort directory upsert (ADR-0020 §"User list"). MUST
// NOT fail the sign-in — the directory is a convenience for
// admin browsing, not a security boundary. The service catches
// its own errors and logs them; awaiting it means an admin
// that just signed in sees themselves on the user list
// immediately, without racing the response.
await this.userDirectory.recordSignIn({
oid: user.oid,
tid: user.tid,
username: user.username,
displayName: user.displayName,
// v1: single workforce-tenant audience per ADR-0008. The
// dual-audience design ships a real value here when External
// ID is activated.
audience: 'workforce',
});
this.logger.log(
{
event: 'auth.signed_in',
surface,
oid: user.oid,
tid: user.tid,
username: user.username,
amr: user.amr,
},
'AuthCallback',
);
}
/**
* Symmetric helper for the sign-out path. When `actor` is set,
* removes the session id from the per-user index and emits the
* `auth.sign_out` audit row (blocking per ADR-0013 — if the audit
* row can't be written, the user does NOT get a "you're logged
* out" experience). Then tears the session down unconditionally
* — anonymous sign-outs still benefit from a `req.session.destroy()`
* call to clear any orphan state in the store. A Redis hiccup on
* `destroy()` is logged but non-fatal: clearing the cookie at the
* HTTP layer (the controller's job) is sufficient to log the user
* out from the BFF's point of view; the orphan Redis key will hit
* its idle TTL on its own.
*
* The controller is responsible for HTTP-layer cleanup — the
* session-cookie name is surface-specific (`portal_session` vs
* `portal_admin_session`) and lives on the controller.
*/
async destroy(opts: { actor: AuthenticatedUser | undefined; req: Request }): Promise<void> {
const { actor, req } = opts;
if (actor !== undefined) {
const sessionId = req.sessionID;
await this.userSessionIndex.remove(actor.oid, sessionId);
await this.audit.signOut({ actor, sessionId });
}
try {
await destroySession(req);
} catch (err) {
this.logger.error(
{
event: 'session.destroy_failed',
message: err instanceof Error ? err.message : String(err),
},
'AuthLogout',
);
}
}
}
function saveSession(req: Request): Promise<void> {
return new Promise((resolve, reject) => {
req.session.save((err) => (err ? reject(err) : resolve()));
});
}
function destroySession(req: Request): Promise<void> {
return new Promise((resolve, reject) => {
req.session.destroy((err) => (err ? reject(err) : resolve()));
});
}