feat(users): add Person + User + UserScope + lazy provisioner (ADR-0026 PR 1) #232

Merged
julien merged 1 commits from feat/adr-0026-pr1-person-user-userscope into main 2026-05-26 13:57:38 +02:00
Owner

Summary

First implementation PR for ADR-0026 (portal-side identity model). Ships:

  • Person golden record + User portal-account overlay + UserScope Prisma models;
  • PersonAndUserProvisioner service called from SessionEstablisher.establish (blocking — lazy-creates Person + User at first OIDC callback);
  • PERSON_SOURCES closed-set catalogue + drift-gate extension;
  • PrincipalBuilder.build(user, identity) signature update + ScopeResolver.resolve({ userId }) seam change — Principal.user.{id, personId} now carry real portal UUIDs, no longer the entraOid placeholder.

No consumer for UserScope yet — PrismaScopeResolver lands in ADR-0026 PR 2. The StubScopeResolver continues to return [{ kind: 'unrestricted' }] for everyone.

What lands

File Change
apps/portal-bff/prisma/schema.prisma +3 models in the public schema: Person (UUID PK + PII + nullable email indexed-not-unique + source catalogue + nullable externalId + back-ref to User), User (UUID PK + 1-to-1 personId FK + unique entraOid + tenantId + lastSignInAt + scopes[]), UserScope (UUID PK + userId FK with onDelete: Cascade + kind + opaque value with @default("") + source + nullable expiresAt + @@unique([userId, kind, value])). All comments explain the cross-references to ADR-0025 / ADR-0027 / ADR-0029.
apps/portal-bff/prisma/migrations/20260526210000_add_person_user_userscope/migration.sql New hand-written migration. DDL for the 3 tables, indexes (Person: source/externalId/email; User: unique personId + unique entraOid; UserScope: unique composite + plain userId), FKs with the correct ON DELETE actions (User.personId → RESTRICT; UserScope.userId → CASCADE — both Prisma defaults given the schema's Delegation? / explicit onDelete: Cascade).
apps/portal-bff/src/users/person-source.ts + .spec.ts New catalogue. PERSON_SOURCES = ['self-signin', 'admin-ui', 'seed'] as const, PersonSource type union, isPersonSource type guard. Spec follows the structure-kind shape (catalogue content, no duplicates, type guard true/false, narrowing test via String() to widen).
apps/portal-bff/src/users/person-and-user-provisioner.service.ts + .spec.ts New blocking provisioner. Fast path: findUnique by entraOid + update lastSignInAt. Cold path: nested create of Person + linked User in a single transaction. Race-condition handling: catches P2002 on User.entraOid and re-runs ensureUser (loser of a concurrent first-sign-in falls through to the now-warm fast path). Defense-in-depth isPersonSource check on the constant. Spec covers cold/warm/race/non-P2002-propagation paths + splitDisplayName cases (single token / trailing whitespace / empty / multi-word).
scripts/check-catalogue-drift.mjs Property-literal scanner generalised. Adds extractPersonSources + findPersonSourceViolationsInFile (property source instead of kind, otherwise identical to the structure-kind scanner). The two extractors share extractAsConstArray(path, constName) and the two property scanners share findPropertyLiteralViolations(path, validValues, sourceText, opts). Error-message formatter unchanged. Closing hint extended to reference all three catalogue locations.
scripts/check-catalogue-drift.spec.mjs Fixture now writes a person-source.ts alongside structure-kind.ts. 7 new tests: extractPersonSources (2), findPersonSourceViolationsInFile (5: skip-no-import, no-violation, flag, non-literal, line/col). Aggregation test updated to assert decorator + Structure.kind + Person.source violations all surface together. 29 tests total, all passing.
apps/portal-bff/src/auth/scope-resolver.ts resolve(input: { entraOid })resolve(input: { userId }). Stub still ignores its argument; PR 2's PrismaScopeResolver will key queries on User.id. Comment block updated to reflect that ADR-0026 PR 1 is now landed (no longer "proposed").
apps/portal-bff/src/auth/principal-builder.ts Signature: build(user)build(user, identity: { userId, personId }). Principal.user.id / Principal.user.personId populated from identity instead of user.oid. Scope resolver called with { userId: identity.userId }. Doc comment block updated to remove the "placeholder" caveat and document the new wiring.
apps/portal-bff/src/auth/principal-builder.spec.ts New TEST_IDENTITY constant. Every builder.build(...) call gets the second arg. New assertions on principal.user.id / principal.user.personId carrying the test identity. Edge-case test "asks the scope resolver to resolve by entraOid" renamed + retargeted to { userId }. All 19 persona tests + 5 edge cases pass.
apps/portal-bff/src/auth/session-establisher.service.ts New constructor arg personUserProvisioner: PersonAndUserProvisioner. establish() calls ensureUser({ oid, tenantId, displayName, email: user.username }) before principalBuilder.build so the identity is available. Comment block explains the Entra preferred_usernamePerson.email mapping and the blocking-vs-best-effort distinction with UserDirectoryService.recordSignIn.
apps/portal-bff/src/auth/session-establisher.service.spec.ts Fixture extended with provisioner mock + PROVISIONED_IDENTITY constant. STUB_PRINCIPAL now carries those UUIDs instead of user.oid. New tests: (1) provisioner is called with the right input shape; (2) provisioner runs before principalBuilder.build (mock.invocationCallOrder assertion); (3) provisioner failure propagates and nothing downstream runs (build / audit / directory).
apps/portal-bff/src/auth/auth.controller.spec.ts Provisioner mock added to the controller fixture (the controller's specs don't exercise provisioning themselves but SessionEstablisher's constructor needs the arg). Principal stub's UUIDs aligned with the new provisioned shape.
apps/portal-bff/src/users/users.module.ts PersonAndUserProvisioner registered + exported alongside UserDirectoryService. @Global so the auth module's SessionEstablisher can inject both without re-routing the module graph. Comment block updated to document the blocking/best-effort distinction between the two.

Key choices

  • Provisioner is blocking, not best-effort. Distinct from UserDirectoryService.recordSignIn which is still best-effort (ADR-0020 admin-list cache, swallows its own errors). Both run from SessionEstablisher.establish per the new ordering: (1) provisioner — blocking, (2) build principal — uses identity, (3) save session, (4) cookie, (5) user-session index (best-effort), (6) audit (blocking ADR-0013), (7) UserDirectoryService.recordSignIn (best-effort), (8) log. A provisioner failure short-circuits the whole flow before any of (3)..(8) — the spec asserts this explicitly.
  • No email-based dedup in v1. Person.email is indexed (not unique). The provisioner keys ONLY on entraOid. ADR-0026 §"Why no email-based merging in v1" — two distinct humans genuinely share emails; ADR-0029's sync flow handles operator-confirmed reconciliation.
  • Race-condition handling on first sign-in. Two concurrent first-sign-ins for the same entraOid both fall through to create. The unique constraint on User.entraOid rejects the loser with P2002; the provisioner catches that specific code and re-runs ensureUser — fast path now warm. Pathological infinite-loop guarded by the warm-path behaviour on the second attempt. Spec covers the success retry + the non-P2002 propagation paths.
  • ScopeResolver seam moved from { entraOid } to { userId }. The stub doesn't care about its argument either way; the change is the seam for ADR-0026 PR 2's PrismaScopeResolver, which keys userScope queries on User.id (UUID). Doing the rename now keeps PR 2 to "swap the implementation" only.
  • PersonAndUserProvisioner.SELF_SIGNIN_SOURCE is a typed constant inside the class, not a magic string. Defense in depth: TS type union (compile-time) + drift gate (source: 'self-signin' literal is in a file importing person-source.ts — flagged if it ever drifts off-catalogue) + runtime isPersonSource check (error log + throw if the constant is mutated to an off-catalogue value).
  • UserDirectoryService stays. ADR-0020's admin-list cache is functionally redundant with Person + User now, but folding it would extend the PR scope (DTO + reader + admin UI + migration of existing rows). Out of scope here — flagged as a follow-up.

Local verification

  • node scripts/check-catalogue-drift.mjs — clean (4 privileges, 24 roles, 7 structure kinds, 3 person sources).
  • node --test scripts/check-catalogue-drift.spec.mjs29 tests passing (was 22 — +7 for PERSON_SOURCES).
  • pnpm exec nx lint portal-bff0 errors, 13 warnings (all pre-existing, none from this PR).
  • pnpm exec nx test portal-bff (filtered to the 6 affected spec files) — 766 tests passing.
  • pnpm exec prisma generate — client regenerated with the 3 new models.

Test plan — remaining (on a fresh dev DB)

  • ./infra/local/dev.sh down -v && ./infra/local/dev.sh up (wipe + reboot) then cd apps/portal-bff && pnpm exec prisma migrate dev — applies the new migration cleanly, no drift prompt.
  • pnpm exec prisma studiopersons / users / user_scopes tables visible, all empty (no seed in this PR).
  • Sign in via apf-portal against the test tenant — users table gets one row, persons table gets one row, user_scopes stays empty. Principal in the session carries the provisioned UUIDs (not the entraOid).
  • Review focus — the provisioner's race-handling logic; the Entra preferred_username → Person.email mapping in SessionEstablisher; the ScopeResolver seam change rationale; the FK actions in the migration SQL (especially CASCADE on UserScope.userId vs RESTRICT on User.personId).

What's next

  • ADR-0026 PR 2PrismaScopeResolver replacing StubScopeResolver + /admin/users/:id/scopes admin-app screen + prisma/seed.ts populating the 19 test personas' user_scopes per notes/test-tenant-role-assignments.md (referencing this PR's User.id and ADR-0027 PR 1's Structure.code values).
  • Future PR (out of this scope) — fold UserDirectoryEntry into Person + User now that the latter exists. Touches AdminUsersReader, the DTO, the admin SPA, and a data migration for existing rows. Defer until ADR-0026 PR 2 stabilises.
## Summary First implementation PR for [ADR-0026](docs/decisions/0026-person-user-portal-data-model.md) (portal-side identity model). Ships: - `Person` golden record + `User` portal-account overlay + `UserScope` Prisma models; - `PersonAndUserProvisioner` service called from `SessionEstablisher.establish` (blocking — lazy-creates `Person` + `User` at first OIDC callback); - `PERSON_SOURCES` closed-set catalogue + drift-gate extension; - `PrincipalBuilder.build(user, identity)` signature update + `ScopeResolver.resolve({ userId })` seam change — `Principal.user.{id, personId}` now carry real portal UUIDs, no longer the `entraOid` placeholder. No consumer for `UserScope` yet — `PrismaScopeResolver` lands in ADR-0026 PR 2. The `StubScopeResolver` continues to return `[{ kind: 'unrestricted' }]` for everyone. ## What lands | File | Change | | --- | --- | | `apps/portal-bff/prisma/schema.prisma` | **+3 models** in the `public` schema: `Person` (UUID PK + PII + nullable email indexed-not-unique + source catalogue + nullable externalId + back-ref to User), `User` (UUID PK + 1-to-1 personId FK + unique entraOid + tenantId + lastSignInAt + scopes[]), `UserScope` (UUID PK + userId FK with `onDelete: Cascade` + kind + opaque value with `@default("")` + source + nullable expiresAt + `@@unique([userId, kind, value])`). All comments explain the cross-references to ADR-0025 / ADR-0027 / ADR-0029. | | `apps/portal-bff/prisma/migrations/20260526210000_add_person_user_userscope/migration.sql` | **New** hand-written migration. DDL for the 3 tables, indexes (Person: source/externalId/email; User: unique personId + unique entraOid; UserScope: unique composite + plain userId), FKs with the correct `ON DELETE` actions (User.personId → RESTRICT; UserScope.userId → CASCADE — both Prisma defaults given the schema's `Delegation?` / explicit `onDelete: Cascade`). | | `apps/portal-bff/src/users/person-source.ts` + `.spec.ts` | **New** catalogue. `PERSON_SOURCES = ['self-signin', 'admin-ui', 'seed'] as const`, `PersonSource` type union, `isPersonSource` type guard. Spec follows the structure-kind shape (catalogue content, no duplicates, type guard true/false, narrowing test via `String()` to widen). | | `apps/portal-bff/src/users/person-and-user-provisioner.service.ts` + `.spec.ts` | **New** blocking provisioner. Fast path: `findUnique by entraOid` + `update lastSignInAt`. Cold path: nested `create` of Person + linked User in a single transaction. Race-condition handling: catches P2002 on `User.entraOid` and re-runs `ensureUser` (loser of a concurrent first-sign-in falls through to the now-warm fast path). Defense-in-depth `isPersonSource` check on the constant. Spec covers cold/warm/race/non-P2002-propagation paths + `splitDisplayName` cases (single token / trailing whitespace / empty / multi-word). | | `scripts/check-catalogue-drift.mjs` | Property-literal scanner generalised. Adds `extractPersonSources` + `findPersonSourceViolationsInFile` (property `source` instead of `kind`, otherwise identical to the structure-kind scanner). The two extractors share `extractAsConstArray(path, constName)` and the two property scanners share `findPropertyLiteralViolations(path, validValues, sourceText, opts)`. Error-message formatter unchanged. Closing hint extended to reference all three catalogue locations. | | `scripts/check-catalogue-drift.spec.mjs` | Fixture now writes a `person-source.ts` alongside `structure-kind.ts`. 7 new tests: extractPersonSources (2), findPersonSourceViolationsInFile (5: skip-no-import, no-violation, flag, non-literal, line/col). Aggregation test updated to assert decorator + Structure.kind + Person.source violations all surface together. **29 tests total, all passing.** | | `apps/portal-bff/src/auth/scope-resolver.ts` | `resolve(input: { entraOid })` → `resolve(input: { userId })`. Stub still ignores its argument; PR 2's `PrismaScopeResolver` will key queries on `User.id`. Comment block updated to reflect that ADR-0026 PR 1 is now landed (no longer "proposed"). | | `apps/portal-bff/src/auth/principal-builder.ts` | Signature: `build(user)` → `build(user, identity: { userId, personId })`. `Principal.user.id` / `Principal.user.personId` populated from `identity` instead of `user.oid`. Scope resolver called with `{ userId: identity.userId }`. Doc comment block updated to remove the "placeholder" caveat and document the new wiring. | | `apps/portal-bff/src/auth/principal-builder.spec.ts` | New `TEST_IDENTITY` constant. Every `builder.build(...)` call gets the second arg. New assertions on `principal.user.id` / `principal.user.personId` carrying the test identity. Edge-case test "asks the scope resolver to resolve by entraOid" renamed + retargeted to `{ userId }`. **All 19 persona tests + 5 edge cases pass.** | | `apps/portal-bff/src/auth/session-establisher.service.ts` | New constructor arg `personUserProvisioner: PersonAndUserProvisioner`. `establish()` calls `ensureUser({ oid, tenantId, displayName, email: user.username })` **before** `principalBuilder.build` so the identity is available. Comment block explains the Entra `preferred_username` → `Person.email` mapping and the blocking-vs-best-effort distinction with `UserDirectoryService.recordSignIn`. | | `apps/portal-bff/src/auth/session-establisher.service.spec.ts` | Fixture extended with `provisioner` mock + `PROVISIONED_IDENTITY` constant. `STUB_PRINCIPAL` now carries those UUIDs instead of `user.oid`. New tests: (1) provisioner is called with the right input shape; (2) provisioner runs **before** `principalBuilder.build` (`mock.invocationCallOrder` assertion); (3) provisioner failure propagates and nothing downstream runs (build / audit / directory). | | `apps/portal-bff/src/auth/auth.controller.spec.ts` | Provisioner mock added to the controller fixture (the controller's specs don't exercise provisioning themselves but `SessionEstablisher`'s constructor needs the arg). Principal stub's UUIDs aligned with the new provisioned shape. | | `apps/portal-bff/src/users/users.module.ts` | `PersonAndUserProvisioner` registered + exported alongside `UserDirectoryService`. `@Global` so the auth module's `SessionEstablisher` can inject both without re-routing the module graph. Comment block updated to document the blocking/best-effort distinction between the two. | ## Key choices - **Provisioner is blocking**, not best-effort. Distinct from `UserDirectoryService.recordSignIn` which is still best-effort (ADR-0020 admin-list cache, swallows its own errors). Both run from `SessionEstablisher.establish` per the new ordering: (1) provisioner — blocking, (2) build principal — uses identity, (3) save session, (4) cookie, (5) user-session index (best-effort), (6) audit (blocking ADR-0013), (7) UserDirectoryService.recordSignIn (best-effort), (8) log. A provisioner failure short-circuits the whole flow before any of (3)..(8) — the spec asserts this explicitly. - **No email-based dedup in v1.** `Person.email` is indexed (not unique). The provisioner keys ONLY on `entraOid`. ADR-0026 §"Why no email-based merging in v1" — two distinct humans genuinely share emails; ADR-0029's sync flow handles operator-confirmed reconciliation. - **Race-condition handling on first sign-in.** Two concurrent first-sign-ins for the same `entraOid` both fall through to `create`. The unique constraint on `User.entraOid` rejects the loser with P2002; the provisioner catches that specific code and re-runs `ensureUser` — fast path now warm. Pathological infinite-loop guarded by the warm-path behaviour on the second attempt. Spec covers the success retry + the non-P2002 propagation paths. - **ScopeResolver seam moved from `{ entraOid }` to `{ userId }`.** The stub doesn't care about its argument either way; the change is the seam for ADR-0026 PR 2's `PrismaScopeResolver`, which keys `userScope` queries on `User.id` (UUID). Doing the rename now keeps PR 2 to "swap the implementation" only. - **`PersonAndUserProvisioner.SELF_SIGNIN_SOURCE`** is a typed constant inside the class, not a magic string. Defense in depth: TS type union (compile-time) + drift gate (`source: 'self-signin'` literal is in a file importing `person-source.ts` — flagged if it ever drifts off-catalogue) + runtime `isPersonSource` check (error log + throw if the constant is mutated to an off-catalogue value). - **UserDirectoryService stays.** ADR-0020's admin-list cache is functionally redundant with Person + User now, but folding it would extend the PR scope (DTO + reader + admin UI + migration of existing rows). Out of scope here — flagged as a follow-up. ## Local verification - [x] `node scripts/check-catalogue-drift.mjs` — clean (`4 privileges, 24 roles, 7 structure kinds, 3 person sources`). - [x] `node --test scripts/check-catalogue-drift.spec.mjs` — **29 tests passing** (was 22 — +7 for PERSON_SOURCES). - [x] `pnpm exec nx lint portal-bff` — **0 errors**, 13 warnings (all pre-existing, none from this PR). - [x] `pnpm exec nx test portal-bff` (filtered to the 6 affected spec files) — **766 tests passing**. - [x] `pnpm exec prisma generate` — client regenerated with the 3 new models. ## Test plan — remaining (on a fresh dev DB) - [x] `./infra/local/dev.sh down -v && ./infra/local/dev.sh up` (wipe + reboot) then `cd apps/portal-bff && pnpm exec prisma migrate dev` — applies the new migration cleanly, no drift prompt. - [x] `pnpm exec prisma studio` — `persons` / `users` / `user_scopes` tables visible, all empty (no seed in this PR). - [x] Sign in via `apf-portal` against the test tenant — `users` table gets one row, `persons` table gets one row, `user_scopes` stays empty. Principal in the session carries the provisioned UUIDs (not the `entraOid`). - [x] **Review focus** — the provisioner's race-handling logic; the `Entra preferred_username → Person.email` mapping in `SessionEstablisher`; the ScopeResolver seam change rationale; the FK actions in the migration SQL (especially CASCADE on UserScope.userId vs RESTRICT on User.personId). ## What's next - **ADR-0026 PR 2** — `PrismaScopeResolver` replacing `StubScopeResolver` + `/admin/users/:id/scopes` admin-app screen + `prisma/seed.ts` populating the 19 test personas' `user_scopes` per `notes/test-tenant-role-assignments.md` (referencing this PR's `User.id` and ADR-0027 PR 1's `Structure.code` values). - **Future PR (out of this scope)** — fold `UserDirectoryEntry` into Person + User now that the latter exists. Touches AdminUsersReader, the DTO, the admin SPA, and a data migration for existing rows. Defer until ADR-0026 PR 2 stabilises.
julien added 1 commit 2026-05-26 13:55:43 +02:00
feat(users): add Person + User + UserScope + lazy provisioner (ADR-0026 PR 1)
CI / scan (pull_request) Successful in 5m32s
CI / commits (pull_request) Successful in 5m34s
CI / check (pull_request) Successful in 6m8s
CI / a11y (pull_request) Successful in 4m51s
CI / perf (pull_request) Successful in 9m33s
056848e502
Schema: Person golden record + User portal-account overlay (1-to-0-or-1)
+ UserScope (the table behind the ADR-0025 scope axis). All in the
public schema. UserScope.value is opaque (no FK to ADR-0027 tables -
historical scope rows survive structure decommissioning).

Migration: hand-written, follows the existing convention. FKs with
correct ON DELETE actions (RESTRICT on User.personId for the required
relation, CASCADE on UserScope.userId via explicit onDelete: Cascade
in the schema).

Catalogue: PERSON_SOURCES = [self-signin, admin-ui, seed] as const
under apps/portal-bff/src/users/person-source.ts. Defense in depth =
TS type union + drift gate scanner extension (property literal
"source: 'X'" in files importing person-source.ts).

PersonAndUserProvisioner: blocking lazy-create at first OIDC callback.
Fast path = findUnique by entraOid + update lastSignInAt. Cold path =
nested create of Person + User in one transaction. Race-condition
handling: catches P2002 on User.entraOid unique constraint and re-runs
ensureUser. Defense-in-depth isPersonSource check on the constant.

PrincipalBuilder signature: build(user, identity: { userId, personId }).
Principal.user.{id, personId} populated from real UUIDs. ScopeResolver
seam moved from { entraOid } to { userId } so PR 2's PrismaScopeResolver
can key queries on User.id.

SessionEstablisher: new constructor arg personUserProvisioner.
establish() calls ensureUser BEFORE principalBuilder.build so the
identity is available. Entra preferred_username (= AuthenticatedUser.
username) maps to Person.email per ADR-0026 lifecycle. Provisioner
failure short-circuits the whole flow before save / cookie / audit /
directory.

UserDirectoryService stays as the ADR-0020 admin-list cache - folding
it into Person+User is a follow-up after ADR-0026 PR 2 stabilises.

Local verification: drift gate clean (4 / 24 / 7 / 3), 29 drift-gate
spec tests passing, portal-bff lint 0 errors, 766 portal-bff specs
passing.
julien merged commit 24071a63ec into main 2026-05-26 13:57:38 +02:00
julien deleted branch feat/adr-0026-pr1-person-user-userscope 2026-05-26 13:57:40 +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#232