bd8a13acb86e9ea30bfb1e5edce7516cc4860be7
2 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
bd8a13acb8 |
feat(portal-bff): user directory upserted at sign-in
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.
|
||
|
|
02ac44e498 |
feat(portal-bff): audit log foundation per ADR-0013 (#76)
## Summary Lays down the append-only audit log per ADR-0013: schema declaration, first migration with role grants, NestJS `AuditWriter` service. Typed event-family methods, the separate `AUDIT_DATABASE_URL` pool, the retention job, and the live-DB integration tests are explicitly listed as "wired as features land" in the ADR's confirmation block — they ship when the matching feature ADRs do. ## What lands **Prisma schema** ([`apps/portal-bff/prisma/schema.prisma`](apps/portal-bff/prisma/schema.prisma)): - `multiSchema` preview enabled; datasource declares `public` + `audit` schemas. - `AuditEvent` model: `id` (uuid), `createdAt`, `eventType` (free-form in v1), `audience` enum (`workforce | customer`), `actorIdHash`, `traceId`, `subject`, `outcome` enum (`success | failure | denied`), `payload` (jsonb). - Indexes on `createdAt`, `eventType`, `traceId` — covering the three obvious query shapes. **Migration** ([`prisma/migrations/*_init_audit_schema/migration.sql`](apps/portal-bff/prisma/migrations/20260510011453_init_audit_schema/migration.sql)): - Standard Prisma `CREATE TABLE` / enums output, then the **append-only contract** re-applied explicitly: - `ALTER TABLE/TYPE OWNER TO audit_owner`. - `GRANT INSERT` to `audit_writer`, `SELECT` to `audit_reader`, **`SELECT, DELETE`** to `audit_archiver` (SELECT is needed to evaluate the `created_at` predicate of "delete older than retention" — Postgres requires SELECT on every column referenced in DELETE's WHERE). - `GRANT USAGE` on the enum types to all three roles (without it `audit_writer.INSERT` fails with "permission denied for type"). - **No** GRANT for `UPDATE` / `TRUNCATE` to anyone — including `audit_owner` at runtime; only fresh schema migrations amend the table. **Service** ([`apps/portal-bff/src/audit/`](apps/portal-bff/src/audit/)): - `AuditWriter.recordEvent(input)` — single entry point. Wraps every INSERT in a transaction whose first statement is `SET LOCAL ROLE audit_writer`, so the role contract holds at runtime even from the otherwise-privileged BFF connection. - `traceId` auto-resolved from the active OTel span (so audit row joins with traces and Pino logs on the same `trace_id`). - `actorIdHash` auto-resolved from CLS (key `actorIdHash`) with explicit input-side override; `null` when neither is set (placeholder until ADR-0009 / ADR-0010 guards populate CLS). - Errors propagate (no catch-and-swallow), per ADR-0013's "blocking writes: no audit ⇒ no action". **Tests** — 8 unit tests on `AuditWriter` (mocked Prisma + CLS): role-locking ordering, input pass-through, `Prisma.JsonNull` for missing payload, CLS-vs-input precedence on `actorIdHash`, OTel trace capture, error propagation. ## End-to-end verification (manual, against local-dev Postgres) ``` INSERT under audit_writer: ok UPDATE under audit_writer: permission denied for table events DELETE under audit_writer: permission denied for table events DELETE under audit_archiver: ok, row removed (after the SELECT-grant fix) ``` ## ADR-0013 §Confirmation rewritten Two-block split: "wired in foundation PR" lists what landed here; "wired as features land" lists the typed event-family methods, AUDIT_DATABASE_URL connection split, startup self-test probe, retention purge job, salt-shared cross-correlation test, and live-DB role-contract integration tests — each anchored to the feature ADR that triggers it. ## Recovery for anyone with a pre-existing local-dev DB If your local-dev Postgres already had the audit migration applied **before** the SELECT-grant fix, the archiver's DELETE will fail. Two options: 1. Apply the missing grant directly: ```bash psql "$DATABASE_URL" -c "GRANT SELECT ON audit.events TO audit_archiver;" ``` 2. Or wipe the volume and re-migrate cleanly: ```bash ./infra/local/dev.sh down -v ./infra/local/dev.sh up pnpm --filter @apf-portal/source exec prisma migrate deploy # or `cd apps/portal-bff && pnpm exec prisma migrate deploy` ``` Fresh DBs land with the corrected migration directly. ## Out of scope (separate PRs) - Typed event-family methods (`signIn`, `signInFailed`, …) — added per matching feature ADR. - `AUDIT_DATABASE_URL` separate connection pool — defense-in-depth, when production needs it. - Startup self-test probe (deliberate failing UPDATE asserting rejection) — lands with the connection split. - Retention purge job (`audit_archiver` daily cron) — phase-3b infra. - Live-DB integration tests asserting the role contract — Testcontainers-style harness, separate PR. ## Test plan - [ ] CI green on this PR. - [ ] `prisma migrate deploy` succeeds on a fresh DB (the recovery instructions cover the SELECT-grant gap for already-migrated dev DBs). - [ ] `psql -c "\dp audit.events"` shows the expected privilege matrix: `audit_owner=arwdDxtm/audit_owner`, `audit_writer=a/audit_owner`, `audit_reader=r/audit_owner`, `audit_archiver=rd/audit_owner`. - [ ] BFF boots; calling `AuditWriter.recordEvent` from a controller (manual smoke once a real flow lands) writes to `audit.events` with the expected `trace_id` matching the request's Jaeger span. --------- Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr> Reviewed-on: #76 |