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.
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])
|
|
}
|