feat(users): add Person + User + UserScope + lazy provisioner (ADR-0026 PR 1) (#232)
## 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)
- [ ] `./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 studio` — `persons` / `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 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.
---------
Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #232
This commit was merged in pull request #232.
This commit is contained in:
@@ -15,7 +15,9 @@ import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
extractCatalogues,
|
||||
extractPersonSources,
|
||||
extractStructureKinds,
|
||||
findPersonSourceViolationsInFile,
|
||||
findStructureKindViolationsInFile,
|
||||
findViolationsInFile,
|
||||
scanWorkspace,
|
||||
@@ -59,6 +61,17 @@ function makeFixture({ files }) {
|
||||
export type StructureKind = (typeof STRUCTURE_KINDS)[number];
|
||||
`,
|
||||
);
|
||||
mkdirSync(join(root, 'apps/portal-bff/src/users'), { recursive: true });
|
||||
writeFileSync(
|
||||
join(root, 'apps/portal-bff/src/users/person-source.ts'),
|
||||
`export const PERSON_SOURCES = [
|
||||
'self-signin',
|
||||
'admin-ui',
|
||||
'seed',
|
||||
] as const;
|
||||
export type PersonSource = (typeof PERSON_SOURCES)[number];
|
||||
`,
|
||||
);
|
||||
for (const [relativePath, contents] of Object.entries(files)) {
|
||||
const full = join(root, relativePath);
|
||||
mkdirSync(join(full, '..'), { recursive: true });
|
||||
@@ -262,6 +275,91 @@ describe('findStructureKindViolationsInFile', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractPersonSources', () => {
|
||||
it('reads the PERSON_SOURCES catalogue from person-source.ts', () => {
|
||||
const root = makeFixture({ files: {} });
|
||||
const sources = extractPersonSources(join(root, 'apps/portal-bff/src/users/person-source.ts'));
|
||||
assert.deepEqual([...sources].sort(), ['admin-ui', 'seed', 'self-signin']);
|
||||
});
|
||||
|
||||
it('throws when the constant is missing', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'drift-fixture-'));
|
||||
mkdirSync(join(root, 'apps/portal-bff/src/users'), { recursive: true });
|
||||
writeFileSync(
|
||||
join(root, 'apps/portal-bff/src/users/person-source.ts'),
|
||||
`export const NOT_PERSON_SOURCES = ['foo'] as const;\n`,
|
||||
);
|
||||
assert.throws(
|
||||
() => extractPersonSources(join(root, 'apps/portal-bff/src/users/person-source.ts')),
|
||||
/PERSON_SOURCES/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findPersonSourceViolationsInFile', () => {
|
||||
const validSources = new Set(['self-signin', 'admin-ui', 'seed']);
|
||||
|
||||
it('skips files that do not import person-source (would false-positive)', () => {
|
||||
// `source: 'X'` is an extremely common pattern (event sources, log
|
||||
// sources, etc.). Without the import filter, every such literal
|
||||
// would be flagged.
|
||||
const text = `
|
||||
const evt = { source: 'logger', message: 'hello' };
|
||||
`;
|
||||
const violations = findPersonSourceViolationsInFile('virtual.ts', validSources, text);
|
||||
assert.equal(violations.length, 0);
|
||||
});
|
||||
|
||||
it('returns no violations when every source literal is in the catalogue', () => {
|
||||
const text = `
|
||||
import type { PersonSource } from '../users/person-source';
|
||||
const a = { source: 'self-signin' as PersonSource };
|
||||
const b = { source: 'seed' as PersonSource };
|
||||
`;
|
||||
const violations = findPersonSourceViolationsInFile('virtual.ts', validSources, text);
|
||||
assert.equal(violations.length, 0);
|
||||
});
|
||||
|
||||
it('flags every source literal not in the catalogue', () => {
|
||||
const text = `
|
||||
import { PERSON_SOURCES } from '../users/person-source';
|
||||
const a = { source: 'self-signin' };
|
||||
const b = { source: 'pleiades' };
|
||||
const c = { source: 'rogue-source' };
|
||||
`;
|
||||
const violations = findPersonSourceViolationsInFile('virtual.ts', validSources, text);
|
||||
assert.equal(violations.length, 2);
|
||||
const values = violations.map((v) => v.value).sort();
|
||||
assert.deepEqual(values, ['pleiades', 'rogue-source']);
|
||||
assert.equal(violations[0].callee, 'Person.source');
|
||||
assert.equal(violations[0].catalogue, 'PERSON_SOURCES');
|
||||
});
|
||||
|
||||
it('skips non-literal initialisers (variable indirection)', () => {
|
||||
const text = `
|
||||
import { PERSON_SOURCES } from '../users/person-source';
|
||||
const s = 'something';
|
||||
const a = { source: s };
|
||||
`;
|
||||
const violations = findPersonSourceViolationsInFile('virtual.ts', validSources, text);
|
||||
assert.equal(violations.length, 0);
|
||||
});
|
||||
|
||||
it('reports line and column of the offending literal', () => {
|
||||
const text = [
|
||||
`import { PERSON_SOURCES } from '../users/person-source';`,
|
||||
`const x = {`,
|
||||
` source: 'rogue-source',`,
|
||||
`};`,
|
||||
].join('\n');
|
||||
const violations = findPersonSourceViolationsInFile('virtual.ts', validSources, text);
|
||||
assert.equal(violations.length, 1);
|
||||
assert.equal(violations[0].line, 3);
|
||||
// 'rogue-source' literal starts at column 11 (0-indexed 10, +1 in the report).
|
||||
assert.equal(violations[0].column, 11);
|
||||
});
|
||||
});
|
||||
|
||||
describe('scanWorkspace', () => {
|
||||
it('returns 0 violations on a clean fixture', () => {
|
||||
const root = makeFixture({
|
||||
@@ -333,25 +431,28 @@ describe('scanWorkspace', () => {
|
||||
assert.equal(violations.length, 1);
|
||||
});
|
||||
|
||||
it('aggregates decorator + Structure.kind violations together', () => {
|
||||
it('aggregates decorator + Structure.kind + Person.source violations together', () => {
|
||||
const root = makeFixture({
|
||||
files: {
|
||||
'apps/portal-bff/src/foo.ts': `
|
||||
import { STRUCTURE_KINDS } from './structures/structure-kind';
|
||||
import { PERSON_SOURCES } from './users/person-source';
|
||||
@RequirePrivilege('Portal.Ghost') class Bad {}
|
||||
const s = { kind: 'phantom_kind' };
|
||||
const p = { source: 'rogue-source' };
|
||||
`,
|
||||
},
|
||||
});
|
||||
const { violations } = scanWorkspace(root);
|
||||
assert.equal(violations.length, 2);
|
||||
assert.equal(violations.length, 3);
|
||||
const values = violations.map((v) => v.value).sort();
|
||||
assert.deepEqual(values, ['Portal.Ghost', 'phantom_kind']);
|
||||
assert.deepEqual(values, ['Portal.Ghost', 'phantom_kind', 'rogue-source']);
|
||||
});
|
||||
|
||||
it('returns the structureKinds set alongside catalogues', () => {
|
||||
it('returns the structureKinds and personSources sets alongside catalogues', () => {
|
||||
const root = makeFixture({ files: {} });
|
||||
const { structureKinds } = scanWorkspace(root);
|
||||
const { structureKinds, personSources } = scanWorkspace(root);
|
||||
assert.deepEqual([...structureKinds].sort(), ['antenne', 'medico_social', 'siege']);
|
||||
assert.deepEqual([...personSources].sort(), ['admin-ui', 'seed', 'self-signin']);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user