feat(portal-bff): user directory upserted at sign-in #140

Merged
julien merged 1 commits from feat/portal-bff-user-directory into main 2026-05-14 19:30:13 +02:00
Owner

Summary

First PR of the portal-admin User-list chantier per ADR-0020 §"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 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 " 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/.

UserDirectoryService

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 wiring

The directory call lands right after the existing audit emission:

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 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 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

  • pnpm nx test portal-bff365 specs pass (was 358; +7: UserDirectoryService 4, SessionEstablisher integration 3).
  • 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).
  • 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.
## 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.
julien added 1 commit 2026-05-14 19:28:08 +02:00
feat(portal-bff): user directory upserted at sign-in
CI / scan (pull_request) Successful in 2m36s
CI / commits (pull_request) Successful in 2m36s
CI / check (pull_request) Successful in 2m45s
CI / a11y (pull_request) Successful in 2m14s
CI / perf (pull_request) Successful in 6m30s
bd8a13acb8
First PR of the portal-admin User-list chantier per ADR-0020 §"v1
scope — User list (read-only)". Ships the write side only:
- a `public.users` table that holds the BFF's local cache of
  identities seen sign in to either portal-shell or portal-admin,
- 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 subsequent PRs of the chantier.

Schema

- `public.users` model in `schema.prisma`. Primary key on `oid`
  (Entra's stable per-user identifier inside the tenant — the
  natural choice; per-tenant uniqueness is sufficient for the v1
  single-workforce-tenant design per ADR-0008).
- Columns: `oid`, `tid`, `audience`, `username`, `display_name`,
  `first_seen_at` (default NOW, never overwritten), `last_seen_at`
  (default NOW, updated on every upsert).
- Indexes: `last_seen_at DESC` for the admin "most recently
  active" default sort, plain `username` for prefix filtering.
- Migration in `prisma/migrations/20260514192014_users_directory/`.

UserDirectoryService

- `recordSignIn(entry)` issues `prisma.user.upsert({ where: { oid },
  create: {...}, update: {...} })`. Create sets `first_seen_at` +
  `last_seen_at` via the DEFAULT clauses; update touches
  `last_seen_at` + every mutable identity field but NOT
  `first_seen_at`.
- Best-effort: catches its own errors, logs a Pino warn
  (`user_directory.record_sign_in_failed`) and 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 wiring

- Calls `userDirectory.recordSignIn` AFTER `audit.signIn` so an
  audit failure short-circuits the directory write (audit-first
  invariant per ADR-0013). The await ensures the upsert completes
  before the response is sent — an admin who just signed in sees
  themselves on the user list immediately, without racing the
  response.
- v1 hardcodes `audience: 'workforce'` per ADR-0008's single-
  workforce-tenant simplification. Will read the real audience
  from the session/claims when External ID activates.

Module wiring

- `UsersModule` declared `@Global()` so `SessionEstablisher`
  (which lives in `AuthModule`) injects `UserDirectoryService`
  without re-routing the module graph through an import. The
  directory is a true cross-cutting concern: one writer (auth
  callback), one future reader (admin endpoint).
- Wired into `AppModule` alongside the other v1 modules.

Tests: +7 specs (UserDirectoryService 4, SessionEstablisher
integration 3 — directory called with the right payload, called
AFTER audit, NOT called when audit fails, audience pinned to
workforce).

Pre-existing test updates: `auth.module.spec.ts` now imports
UsersModule (slice-of-graph compile would otherwise fail to
resolve SessionEstablisher's new dep); `auth.controller.spec.ts`
passes a noop directory mock to the SessionEstablisher
constructor — kept noop because that spec's behavioural surface
is about the controller path, not the directory.
julien merged commit aca9e8d155 into main 2026-05-14 19:30:13 +02:00
julien deleted branch feat/portal-bff-user-directory 2026-05-14 19:30:16 +02:00
Sign in to join this conversation.
No Reviewers
No Label
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: julien/apf_portal#140