feat(users): add Person + User + UserScope + lazy provisioner (ADR-0026 PR 1) #232
Reference in New Issue
Block a user
Delete Branch "feat/adr-0026-pr1-person-user-userscope"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
First implementation PR for ADR-0026 (portal-side identity model). Ships:
Persongolden record +Userportal-account overlay +UserScopePrisma models;PersonAndUserProvisionerservice called fromSessionEstablisher.establish(blocking — lazy-createsPerson+Userat first OIDC callback);PERSON_SOURCESclosed-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 theentraOidplaceholder.No consumer for
UserScopeyet —PrismaScopeResolverlands in ADR-0026 PR 2. TheStubScopeResolvercontinues to return[{ kind: 'unrestricted' }]for everyone.What lands
apps/portal-bff/prisma/schema.prismapublicschema: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 withonDelete: 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.sqlON DELETEactions (User.personId → RESTRICT; UserScope.userId → CASCADE — both Prisma defaults given the schema'sDelegation?/ explicitonDelete: Cascade).apps/portal-bff/src/users/person-source.ts+.spec.tsPERSON_SOURCES = ['self-signin', 'admin-ui', 'seed'] as const,PersonSourcetype union,isPersonSourcetype guard. Spec follows the structure-kind shape (catalogue content, no duplicates, type guard true/false, narrowing test viaString()to widen).apps/portal-bff/src/users/person-and-user-provisioner.service.ts+.spec.tsfindUnique by entraOid+update lastSignInAt. Cold path: nestedcreateof Person + linked User in a single transaction. Race-condition handling: catches P2002 onUser.entraOidand re-runsensureUser(loser of a concurrent first-sign-in falls through to the now-warm fast path). Defense-in-depthisPersonSourcecheck on the constant. Spec covers cold/warm/race/non-P2002-propagation paths +splitDisplayNamecases (single token / trailing whitespace / empty / multi-word).scripts/check-catalogue-drift.mjsextractPersonSources+findPersonSourceViolationsInFile(propertysourceinstead ofkind, otherwise identical to the structure-kind scanner). The two extractors shareextractAsConstArray(path, constName)and the two property scanners sharefindPropertyLiteralViolations(path, validValues, sourceText, opts). Error-message formatter unchanged. Closing hint extended to reference all three catalogue locations.scripts/check-catalogue-drift.spec.mjsperson-source.tsalongsidestructure-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.tsresolve(input: { entraOid })→resolve(input: { userId }). Stub still ignores its argument; PR 2'sPrismaScopeResolverwill key queries onUser.id. Comment block updated to reflect that ADR-0026 PR 1 is now landed (no longer "proposed").apps/portal-bff/src/auth/principal-builder.tsbuild(user)→build(user, identity: { userId, personId }).Principal.user.id/Principal.user.personIdpopulated fromidentityinstead ofuser.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.tsTEST_IDENTITYconstant. Everybuilder.build(...)call gets the second arg. New assertions onprincipal.user.id/principal.user.personIdcarrying 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.tspersonUserProvisioner: PersonAndUserProvisioner.establish()callsensureUser({ oid, tenantId, displayName, email: user.username })beforeprincipalBuilder.buildso the identity is available. Comment block explains the Entrapreferred_username→Person.emailmapping and the blocking-vs-best-effort distinction withUserDirectoryService.recordSignIn.apps/portal-bff/src/auth/session-establisher.service.spec.tsprovisionermock +PROVISIONED_IDENTITYconstant.STUB_PRINCIPALnow carries those UUIDs instead ofuser.oid. New tests: (1) provisioner is called with the right input shape; (2) provisioner runs beforeprincipalBuilder.build(mock.invocationCallOrderassertion); (3) provisioner failure propagates and nothing downstream runs (build / audit / directory).apps/portal-bff/src/auth/auth.controller.spec.tsSessionEstablisher's constructor needs the arg). Principal stub's UUIDs aligned with the new provisioned shape.apps/portal-bff/src/users/users.module.tsPersonAndUserProvisionerregistered + exported alongsideUserDirectoryService.@Globalso the auth module'sSessionEstablishercan inject both without re-routing the module graph. Comment block updated to document the blocking/best-effort distinction between the two.Key choices
UserDirectoryService.recordSignInwhich is still best-effort (ADR-0020 admin-list cache, swallows its own errors). Both run fromSessionEstablisher.establishper 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.Person.emailis indexed (not unique). The provisioner keys ONLY onentraOid. ADR-0026 §"Why no email-based merging in v1" — two distinct humans genuinely share emails; ADR-0029's sync flow handles operator-confirmed reconciliation.entraOidboth fall through tocreate. The unique constraint onUser.entraOidrejects the loser with P2002; the provisioner catches that specific code and re-runsensureUser— 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.{ entraOid }to{ userId }. The stub doesn't care about its argument either way; the change is the seam for ADR-0026 PR 2'sPrismaScopeResolver, which keysuserScopequeries onUser.id(UUID). Doing the rename now keeps PR 2 to "swap the implementation" only.PersonAndUserProvisioner.SELF_SIGNIN_SOURCEis 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 importingperson-source.ts— flagged if it ever drifts off-catalogue) + runtimeisPersonSourcecheck (error log + throw if the constant is mutated to an off-catalogue value).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.mjs— 29 tests passing (was 22 — +7 for PERSON_SOURCES).pnpm exec nx lint portal-bff— 0 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) thencd apps/portal-bff && pnpm exec prisma migrate dev— applies the new migration cleanly, no drift prompt.pnpm exec prisma studio—persons/users/user_scopestables visible, all empty (no seed in this PR).apf-portalagainst the test tenant —userstable gets one row,personstable gets one row,user_scopesstays empty. Principal in the session carries the provisioned UUIDs (not theentraOid).Entra preferred_username → Person.emailmapping inSessionEstablisher; 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
PrismaScopeResolverreplacingStubScopeResolver+/admin/users/:id/scopesadmin-app screen +prisma/seed.tspopulating the 19 test personas'user_scopespernotes/test-tenant-role-assignments.md(referencing this PR'sUser.idand ADR-0027 PR 1'sStructure.codevalues).UserDirectoryEntryinto 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.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.