aca9e8d155
## 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
136 lines
5.1 KiB
Plaintext
136 lines
5.1 KiB
Plaintext
// Prisma schema for portal-bff.
|
|
//
|
|
// `multiSchema` preview is enabled because per ADR-0013 the audit log
|
|
// lives in its own `audit` schema with role-based append-only access
|
|
// (audit_owner / audit_writer / audit_reader / audit_archiver). The
|
|
// public schema holds the regular business data; only audit.events
|
|
// lives in audit.
|
|
|
|
generator client {
|
|
provider = "prisma-client-js"
|
|
previewFeatures = ["multiSchema"]
|
|
}
|
|
|
|
datasource db {
|
|
provider = "postgresql"
|
|
url = env("DATABASE_URL")
|
|
schemas = ["public", "audit"]
|
|
}
|
|
|
|
// ============================================================
|
|
// Audit log (per ADR-0013)
|
|
// ============================================================
|
|
//
|
|
// Append-only by Postgres role grants — the schema, roles, and
|
|
// default privileges are provisioned by infra/local/init/postgres/
|
|
// 01-init.sql in dev and the equivalent production manifest. The
|
|
// migration that creates this table re-applies the grants
|
|
// explicitly and ALTERs the table owner to `audit_owner` so the
|
|
// runtime role contract holds even when the migration runs as a
|
|
// privileged migrator account.
|
|
//
|
|
// At runtime, the BFF wraps every INSERT into this table in a
|
|
// transaction that begins with `SET LOCAL ROLE audit_writer`, so
|
|
// even a compromised BFF connection cannot UPDATE / TRUNCATE /
|
|
// DELETE — those grants are not on `audit_writer`.
|
|
|
|
enum AuditAudience {
|
|
workforce
|
|
customer
|
|
|
|
@@schema("audit")
|
|
}
|
|
|
|
enum AuditOutcome {
|
|
success
|
|
failure
|
|
denied
|
|
|
|
@@schema("audit")
|
|
}
|
|
|
|
// ============================================================
|
|
// User directory (per ADR-0020 §"v1 scope — User list")
|
|
// ============================================================
|
|
//
|
|
// Persistent ledger of every identity that has signed in to either
|
|
// portal-shell or portal-admin. Upserted at sign-in by
|
|
// `UserDirectoryService.recordSignIn` (called from
|
|
// `SessionEstablisher.establish`), read by the future
|
|
// `GET /api/admin/users` endpoint per ADR-0020 §"User list
|
|
// (read-only)".
|
|
//
|
|
// **Not the source of truth for identity.** Entra ID is. This table
|
|
// is a cache the BFF maintains so the admin UI can list "everyone
|
|
// who's ever signed in" without re-querying the directory at
|
|
// every render. Per-tenant `oid` is the join key on the audit side
|
|
// (combined with the salted hash) — never the BFF's primary actor
|
|
// identifier elsewhere.
|
|
//
|
|
// **No PII redaction on read.** Per ADR-0013 the audit module
|
|
// hashes the actor id to defend against an audit-log dump leaking
|
|
// who-did-what. This table is the *deliberate* PII storage: an
|
|
// admin browsing the user list explicitly wants display names and
|
|
// usernames. The trust boundary is the admin role gate
|
|
// (ADR-0020 §"Auth — `admin` role claim").
|
|
|
|
model User {
|
|
// Entra `oid` — stable per-user identifier inside the tenant.
|
|
// Used as the natural primary key. Per-tenant uniqueness is
|
|
// sufficient: the dual-audience design (ADR-0008) currently
|
|
// assumes single workforce tenant; cross-tenant collisions
|
|
// become a separate ADR when we onboard the second one.
|
|
oid String @id
|
|
tid String
|
|
audience String
|
|
username String
|
|
displayName String @map("display_name")
|
|
// `first_seen_at` is set once at first sign-in and never
|
|
// updated thereafter. Lets the admin list "users since
|
|
// <date>" without joining anything.
|
|
firstSeenAt DateTime @default(now()) @map("first_seen_at") @db.Timestamptz(6)
|
|
// `last_seen_at` is set every time the upsert fires (one upsert
|
|
// per sign-in), so "most recently active" can be computed
|
|
// without scanning audit.events.
|
|
lastSeenAt DateTime @default(now()) @map("last_seen_at") @db.Timestamptz(6)
|
|
|
|
@@map("users")
|
|
@@schema("public")
|
|
@@index([lastSeenAt(sort: Desc)])
|
|
@@index([username])
|
|
}
|
|
|
|
model AuditEvent {
|
|
id String @id @default(uuid()) @db.Uuid
|
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
|
|
eventType String @map("event_type")
|
|
audience AuditAudience
|
|
// Salted hash (LOG_USER_ID_SALT) of the actor's stable id. NULL
|
|
// when the actor is unauthenticated (e.g. failed login attempt
|
|
// before resolving an identity). The same salt is used by the
|
|
// BFF Pino logger so audit and app logs cross-correlate on this
|
|
// field.
|
|
actorIdHash String? @map("actor_id_hash")
|
|
// W3C trace id (32 hex chars) of the request that produced the
|
|
// event. Cross-correlates with traces in Jaeger and with Pino
|
|
// log lines that carry the same `trace_id` field. NULL only if
|
|
// the event was emitted outside any inbound request (e.g. a
|
|
// future cron job).
|
|
traceId String? @map("trace_id")
|
|
// Free-form identifier of what the event is *about* — typically
|
|
// a domain entity URI like `user:42` or `dossier:xyz`. NULL when
|
|
// the event is system-wide and has no clear subject.
|
|
subject String?
|
|
outcome AuditOutcome
|
|
// Event-specific structured detail. Redaction of PII is the
|
|
// caller's responsibility; the BFF Pino redact list is the
|
|
// reference allow-/deny-list.
|
|
payload Json?
|
|
|
|
@@map("events")
|
|
@@schema("audit")
|
|
@@index([createdAt])
|
|
@@index([eventType])
|
|
@@index([traceId])
|
|
}
|