diff --git a/.changeset/33200-set-manager-scim-held-only.md b/.changeset/33200-set-manager-scim-held-only.md new file mode 100644 index 00000000000..1f04299abe4 --- /dev/null +++ b/.changeset/33200-set-manager-scim-held-only.md @@ -0,0 +1,20 @@ +--- +'@objectstack/plugin-auth': patch +'@objectstack/platform-objects': patch +'@objectstack/lint': patch +--- + +fix(plugin-auth): Set Manager refuses only a person a SCIM directory holds, so an admin can change the manager of someone who signs in through SSO + +Clause-②: yes (widening) +Metadata-protocol: none + +`POST /api/v1/auth/admin/set-user-manager` refused every user whose `sys_user.source` is `idp_provisioned` with `403 PERMISSION_DENIED`, saying a directory owns their manager. ADR-0135 D4 stamps that value on every sign-in through an identity provider by a person with no local password: the platform's own SSO on a hosted environment, and any social or enterprise OIDC provider. Those people have no directory behind them. So after their first sign-in, nobody could change their manager, and approvals routed to the manager could not follow a reorganisation. + +The endpoint now refuses only a person a SCIM directory holds: `source` is `idp_provisioned` and a SCIM connection has provisioned or linked them (a `sys_scim_subject` row). The answer is unchanged for them (`403 PERMISSION_DENIED`, `details.reason: 'idp_provisioned'`), and its message says to change the manager in the directory. Everyone else gets the answer a local user gets. The admin user import's `manager_id` column runs the same check, so an SSO-only row's manager link now lands. The self-assignment, cycle, depth and cross-organization refusals are unchanged. Nothing that was accepted before is refused now. + +`sys_user`'s **Set Manager** action is now offered to a platform admin on every user row. It used to be hidden on `idp_provisioned` rows. A SCIM-held row is refused by the endpoint, which names the directory. + +`os explain approval-approvers-may-resolve-empty` now says the admin operation refuses an identity a SCIM directory holds, and that an identity that only signs in through SSO is set like any other. + +The `idp_provisioned` stamp itself (ADR-0135 D4) and the password refusals are unchanged. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index df3315b41ca..041d5596a71 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -100,11 +100,13 @@ row's `manager` result: a link it cannot make never fails the user it imported. The column is also written by a seed, or by any other system-context write, which bypasses the managed-update whitelist. SCIM provisioning and directory sync can populate it too, but only through a provisioning path your own deployment supplies: this platform declares the SCIM -`manager` attribute without projecting it onto the column. Where an identity carries -`source: 'idp_provisioned'` the admin operation **refuses**, so that directory stays the one -surface that authors its manager. A user a SCIM connection provisions carries that value from its -creation unless it holds a local password, so for such a user the column is written only by that -deployment-supplied path, and a value the column already holds stays as it is. +`manager` attribute without projecting it onto the column. Where a SCIM directory holds an +identity (it carries `source: 'idp_provisioned'` and the directory has provisioned or linked it) +the admin operation **refuses**, the import's `manager_id` column included, so that directory +stays the one surface that authors its manager; for such a user the column is written only by that +deployment-supplied path, and a value the column already holds stays as it is. A person who only +signs in through SSO also carries `source: 'idp_provisioned'`, but no directory holds them: their +manager is set with **Set Manager** or the import like anyone else's. Setting the column is still something you have to *do*. Where `manager_id` is unset the rung expands to nobody, and under the default `onEmptyApprovers: 'admin_rescue'` the request opens on diff --git a/content/docs/capabilities/approvals.mdx b/content/docs/capabilities/approvals.mdx index 6ad9cc229bd..b994c4a5fdf 100644 --- a/content/docs/capabilities/approvals.mdx +++ b/content/docs/capabilities/approvals.mdx @@ -15,7 +15,8 @@ A specific person · everyone holding a position (e.g. sales managers) · the su **Routing to the submitter's manager needs each user's manager set.** This style resolves `sys_user.manager_id`, which is not a profile field: editing the user does not set it. A platform admin sets it one user at a time from **Setup → Users → ⋯ → Set Manager**, which calls -`POST /api/v1/auth/admin/set-user-manager`. For many users at once, provisioning fills it: the +`POST /api/v1/auth/admin/set-user-manager` — for anyone, people who sign in through SSO included, +except a person a SCIM directory holds, whose manager is changed in that directory. For many users at once, provisioning fills it: the admin bulk-import endpoint reads a `manager_id` column, and a seed, or a SCIM / directory-sync path your deployment supplies, can write it too. Until it is set, a manager-only approval step resolves to nobody and the node's `onEmptyApprovers` policy decides what happens — by default the diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index 69e5b794017..0ec63634653 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -1301,6 +1301,11 @@ sign-in through any other one leaves the person pending. Their positions, permis from the moment they are added, so seed data and approval flows can name them before they sign in. Off a managed environment both doors answer `409`. +Signing in does not lock the manager: a platform administrator still changes +it with **Set Manager** (`POST /api/v1/auth/admin/set-user-manager`). That +endpoint refuses only a person a SCIM directory holds, whose manager is changed +in the directory. + A host can be told about people as they come and go: the `environmentUserHost` option of the auth plugin is called after a person is added, and before a person is deactivated (`admin/ban-user`) or reactivated (`admin/unban-user`). diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 6ad0ac34bc1..baf57a7ab04 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -3336,9 +3336,10 @@ const MANAGER_ONLY_ROUTES = 'write, which bypasses the managed-update whitelist. SCIM provisioning and directory sync can ' + 'populate it too, but only through a provisioning path your own deployment supplies: this ' + 'platform declares the SCIM \'manager\' attribute without projecting it onto the column — and ' + - 'where an identity carries source \'idp_provisioned\' the admin operation refuses, the import\'s ' + + 'where a SCIM directory holds an identity the admin operation refuses, the import\'s ' + 'manager_id column included, leaving that directory the one surface that authors its ' + - 'manager. Or declare onEmptyApprovers: \'fallback\' on the node, with a ' + + 'manager. An identity that only signs in through SSO, with no SCIM directory behind it, is set ' + + 'through the admin operation like any other. Or declare onEmptyApprovers: \'fallback\' on the node, with a ' + 'fallbackApprovers list: an empty manager rung then opens the request on those people instead ' + 'of on the organization\'s administrators, which needs no write to the column at all.'; diff --git a/packages/lint/src/validate-approval-approvers.test.ts b/packages/lint/src/validate-approval-approvers.test.ts index d4db7b7d8c0..bfbf1c21e50 100644 --- a/packages/lint/src/validate-approval-approvers.test.ts +++ b/packages/lint/src/validate-approval-approvers.test.ts @@ -375,12 +375,18 @@ describe('unset-manager dead-end (#16748)', () => { // ⛔ And they must not be deleted: a deployment running a real directory // sync may well populate the column, and the defect was presenting all // three as equally available, never naming them at all. They now also take - // PRECEDENCE — the endpoint refuses an `idp_provisioned` identity, and so - // does the import's `manager_id` column, which runs the same derivation — + // PRECEDENCE — the endpoint refuses an identity a SCIM directory holds, and + // so does the import's `manager_id` column, which runs the same derivation — // so the hint must not read as "use the endpoint instead of your directory". expect(remedy).toContain('SCIM provisioning and directory sync can populate it'); - expect(remedy).toContain("source 'idp_provisioned' the admin operation refuses"); + expect(remedy).toContain('where a SCIM directory holds an identity the admin operation refuses'); expect(remedy).toContain("the import's manager_id column included"); + // ⛔ But only where a directory exists: the `idp_provisioned` mark alone + // also covers a person who only signs in through SSO, whose manager the + // endpoint sets (maintainer ruling record 6895645364). A remedy that sent + // that admin to a directory they do not have cannot be carried out. + expect(remedy).not.toContain("source 'idp_provisioned' the admin operation refuses"); + expect(remedy).toContain('only signs in through SSO'); }); it('the one-line `fix:` names the first route and the escape, and never the Console form', () => { diff --git a/packages/lint/src/validate-approval-approvers.ts b/packages/lint/src/validate-approval-approvers.ts index 524647463d5..88c6e9c4dff 100644 --- a/packages/lint/src/validate-approval-approvers.ts +++ b/packages/lint/src/validate-approval-approvers.ts @@ -144,8 +144,11 @@ const STAYS_LOCKED = ', and (lockRecord) the record stays locked'; * It reaches the column under a SYSTEM context — by context, ⛔ not by a * whitelist entry — which is why the whitelist reading above is unchanged. * It refuses self-assignment, a link that closes a cycle, a chain past its - * depth cap, a manager provably outside the user's organizations, and any - * identity whose `sys_user.source` is `idp_provisioned`. + * depth cap, a manager provably outside the user's organizations, and an + * identity a SCIM directory holds (`sys_user.source` `idp_provisioned` AND + * a `sys_scim_subject` row). An `idp_provisioned` identity with no SCIM + * subject — a person who only signs in through SSO — is set like any other + * (maintainer ruling record 6895645364). * - Seed, or any other system-context write — AVAILABLE HERE, unchanged. * Both write guards gate on `isUserContextWrite`, spelled identically in * each: `Boolean(userId) && isSystem !== true` (plugin-security @@ -179,7 +182,7 @@ const STAYS_LOCKED = ', and (lockRecord) the record stays locked'; * one may well populate the column through it — but named as something the * operator's own provisioning supplies, ⛔ never as something this repo gives * them. They also now have PRECEDENCE over the endpoint rather than merely - * sitting beside it: on an `idp_provisioned` identity the endpoint refuses, so + * sitting beside it: on an identity a SCIM directory holds the endpoint refuses, so * the directory is the one authoring surface for those rows. * * ⛔ WHAT DID NOT CHANGE — and why this rule is not deleted. The dead end the diff --git a/packages/platform-objects/src/identity/sys-user-set-manager-action.test.ts b/packages/platform-objects/src/identity/sys-user-set-manager-action.test.ts index 20dfa5af7a1..9d3a0efd015 100644 --- a/packages/platform-objects/src/identity/sys-user-set-manager-action.test.ts +++ b/packages/platform-objects/src/identity/sys-user-set-manager-action.test.ts @@ -15,20 +15,24 @@ * managed-update whitelist is `{name, image, locale}`, so a picker that * PATCHed `/api/v1/data/sys_user/:id` would be refused by the identity * write guard — correctly — and would read as a Console bug. - * 2. **The `visible` predicate carries the directory-sync term and NOT the - * self-service ownership term.** The three self-service identity actions - * on this object spell `record.source != "idp_provisioned"` as one half of - * `record.id == ctx.user.id && …`. Copying that predicate whole — the - * natural thing to do, and what a reader of the card would do — would hide - * an ADMIN action on someone else's row from every admin. The failure is - * silent and fail-closed (#8990): the button simply is not offered. + * 2. **The `visible` predicate reads NO record column — neither the + * self-service ownership term nor the `source` term.** The three + * self-service identity actions on this object spell + * `record.source != "idp_provisioned"` beside `record.id == ctx.user.id`. + * Copying either half — the natural thing to do — hides an ADMIN action + * from rows the endpoint accepts: the ownership half from every admin, + * the `source` half from every person who only signs in through SSO + * (ADR-0135 D4 stamps them `idp_provisioned` with no directory behind + * them; maintainer ruling record 6895645364, option A, has the endpoint + * refuse only an identity a SCIM directory holds). The failure is silent + * and fail-closed (#8990): the button simply is not offered. * 3. **No second copy of the server's refusals.** Self-assignment, cycle, - * depth, cross-organization and directory-owned identity are all enforced + * depth, cross-organization and SCIM-held identity are all enforced * at the write, in one derivation (`applyUserManagerLink`), which the bulk * importer already routes onto rather than re-deriving. A client-side * duplicate is the drift, not the safety net — so this file pins that the - * declaration reads exactly one record column and declares no predicate - * for any of the other four refusals. + * declaration reads no record column and declares no predicate for any + * of the five refusals. * * The sweep in `action-predicate-sparse-face.test.ts` already covers this * action's predicate for the sparse-face guard; that is deliberately not @@ -130,14 +134,17 @@ describe('#19249 — sys_user.set_user_manager posts the admin endpoint', () => it('⛔ declares no second copy of the server-side refusals', () => { // Every refusal is enforced at the write and surfaces from there. What // would go wrong quietly is a client-side re-derivation drifting from the - // endpoint's; so the predicate is pinned to the ONE column it reads, and - // the declaration to having no other gate at all. + // endpoint's; so the predicate is pinned to reading no record column at + // all, and the declaration to having no other gate. const visible = sourceOf(ACTION.visible); expect(visible).toBeDefined(); + // Positive control: the standing term really is there, so the empty column + // set below is a reading of the predicate, not of an absent one. + expect(visible).toContain('current_user.isPlatformAdmin == true'); const columns = new Set( [...visible!.matchAll(/record\.([a-z_][a-z0-9_]*)/gi)].map((m) => m[1]), ); - expect([...columns]).toEqual(['source']); + expect([...columns]).toEqual([]); expect(ACTION.disabled).toBeUndefined(); // The manager chain, the organization screen and the self-assignment check // are the endpoint's; none of them is expressible — or declared — here. @@ -148,15 +155,22 @@ describe('#19249 — sys_user.set_user_manager posts the admin endpoint', () => }); }); -describe('#19249 — the visible predicate: directory-sync term, NOT the self-service one', () => { +describe('the visible predicate: offered on every row, the SCIM-held refusal is the server\'s', () => { const visible = (): string => { const source = sourceOf(ACTION.visible); if (!source) throw new Error('set_user_manager has no CEL source'); return source; }; - it('is hidden for a directory-owned identity (the server answers 403 idp_provisioned)', () => { - expect(evaluate(visible(), { source: 'idp_provisioned' })).toBe(false); + it('⭐ is OFFERED on an idp_provisioned row — an SSO-only person\'s manager is set here', () => { + // The endpoint answers 200 for this row unless a SCIM directory holds it, + // and no column on the row says which; hiding the button here hid it from + // every person who ever signed in through SSO. + expect(evaluate(visible(), { id: 'someone_else', source: 'idp_provisioned' })).toBe(true); + }); + + it('is OFFERED on the sparse face too (no source column projected)', () => { + expect(evaluate(visible(), { id: 'someone_else' })).toBe(true); }); it('⭐ is OFFERED to an admin on someone else\'s env-native row', () => { @@ -165,13 +179,22 @@ describe('#19249 — the visible predicate: directory-sync term, NOT the self-se expect(evaluate(visible(), { id: 'someone_else', source: 'env_native' })).toBe(true); }); - it('carries the same directory-sync term the self-service actions spell', () => { - // Byte-identical term, so the two never drift into two spellings of one - // rule — while the ownership half they also carry stays out (asserted - // above by the offered-to-an-admin verdict). - expect(visible()).toContain('record.source != "idp_provisioned"'); + it('⛔ does NOT carry the self-service actions\' source term', () => { + // Positive control: the term is still spelled on the self-service side + // (password and identity edits stay hidden for a managed identity, ADR-0135 + // D4), so its absence here is a reading, not a rename. const selfService = actionsOf().find((a) => a.name === 'change_my_password'); expect(sourceOf(selfService?.visible)).toContain('record.source != "idp_provisioned"'); + expect(visible()).not.toContain('record.source'); + }); + + it('is still hidden from a caller without platform-admin standing', () => { + const member = { id: 'm_1', isPlatformAdmin: false, positions: [] as string[] }; + const r = celEngine.evaluate( + { dialect: 'cel', source: visible() }, + { record: { id: 'someone_else', source: 'idp_provisioned' }, extra: { current_user: member, user: member, ctx: { user: member }, os: { user: member }, features: {} } }, + ); + expect(r.ok && r.value).toBe(false); }); it('⛔ is NOT gated on features.admin, and that is deliberate', () => { diff --git a/packages/platform-objects/src/identity/sys-user.object.ts b/packages/platform-objects/src/identity/sys-user.object.ts index b7734b97cc1..ac2e7a9f4a3 100644 --- a/packages/platform-objects/src/identity/sys-user.object.ts +++ b/packages/platform-objects/src/identity/sys-user.object.ts @@ -675,23 +675,22 @@ export const SysUser = ObjectSchema.create({ recordIdParam: 'userId', successMessage: 'Manager updated', refreshAfter: true, - // Hidden for a directory-managed identity, whose manager the IdP owns: - // the endpoint's refusal 5 answers 403 / `idp_provisioned`, so the - // button would be an affordance the server side refuses by design. - // This carries the SAME `record.source` term the three self-service - // identity actions below carry — and only that term: this is an admin - // action on someone else's row, so their `record.id == ctx.user.id` - // half is deliberately NOT copied (it would hide the button from every - // admin). `has()` per operand for the sparse action face (#8990) — the - // rationale is on the self-service block below. + // Offered on every row, `idp_provisioned` ones included, and the + // endpoint refuses the one case it must. Its refusal 5 answers 403 / + // `idp_provisioned` only for an identity a SCIM directory HOLDS (a + // `sys_scim_subject` row, maintainer ruling record 6895645364, option + // A); a person who only signs in through SSO carries the same `source` + // with no directory behind them, and their manager is set here. No + // column on this row says "held by SCIM", so ⛔ a `record.source` term + // would hide the button from every SSO-only person — the defect this + // predicate used to carry — and a SCIM-held row is answered by the + // server's refusal, which names the directory to go to. // - // ANDed ahead of it, the platform-admin standing the door's gate judges - // (ADR-0068 D4, the admin block header above): without it the button - // was offered to every caller who could open a user row, and the door - // refused each one 403 `PERMISSION_DENIED`. One flat conjunction, the - // principal term first, the way the self-service predicates below lead - // with theirs. - visible: 'current_user.isPlatformAdmin == true && has(record.source) && record.source != "idp_provisioned"', + // The platform-admin standing the door's gate judges (ADR-0068 D4, the + // admin block header above): without it the button was offered to every + // caller who could open a user row, and the door refused each one 403 + // `PERMISSION_DENIED`. + visible: 'current_user.isPlatformAdmin == true', // The action collects a param, so its explanatory line rides // `description` and ⛔ never `confirmText` — pairing the two shows two // dialogs for one decision (#7278/#7309). diff --git a/packages/platform-objects/src/platform-objects.test.ts b/packages/platform-objects/src/platform-objects.test.ts index 29b8f99bcb3..d069e617eec 100644 --- a/packages/platform-objects/src/platform-objects.test.ts +++ b/packages/platform-objects/src/platform-objects.test.ts @@ -772,7 +772,7 @@ describe('feature-gate lowering matrix (#2874)', () => { // The rest of the platform-admin family. Three carry no feature gate, so // the authored predicate is served as written — no lowering — and is // pinned here anyway, beside add_member, so every member has its row. - ['SysUser', SysUser, 'set_user_manager', `${STANDING} && has(record.source) && record.source != "idp_provisioned"`], + ['SysUser', SysUser, 'set_user_manager', STANDING], ['SysSsoProvider', SysSsoProvider, 'register_sso_provider', STANDING], ['SysSsoProvider', SysSsoProvider, 'register_saml_provider', STANDING], ['SysSsoProvider', SysSsoProvider, 'request_domain_verification', STANDING], diff --git a/packages/plugins/plugin-auth/src/admin-import-users-manager-pass.test.ts b/packages/plugins/plugin-auth/src/admin-import-users-manager-pass.test.ts index e32d7bc5e7d..1f2ed9d3605 100644 --- a/packages/plugins/plugin-auth/src/admin-import-users-manager-pass.test.ts +++ b/packages/plugins/plugin-auth/src/admin-import-users-manager-pass.test.ts @@ -95,6 +95,8 @@ function matchesWhere(row: Row, where: Record): boolean { function makeHarness(opts: { seedUsers?: Row[]; seedMembers?: Row[]; + /** `sys_scim_subject` rows: a user named here is held by a SCIM directory. */ + seedScimSubjects?: Row[]; phoneEnabled?: boolean; emailAvailable?: boolean; smsInviteAvailable?: boolean; @@ -105,6 +107,7 @@ function makeHarness(opts: { const tables: Record = { sys_user: (opts.seedUsers ?? []).map((u) => ({ manager_id: null, source: 'env_native', ...u })), sys_member: [...(opts.seedMembers ?? [])], + sys_scim_subject: [...(opts.seedScimSubjects ?? [])], sys_audit_log: [], }; @@ -459,23 +462,46 @@ describe('import-users manager pass — the refusals are the DELEGATE\'s (#18028 expect(h.userBy('b@x.co')?.manager_id ?? null).toBeNull(); }); - it('directory-owned identity — an upsert row the IdP owns is refused', async () => { + it('SCIM-held identity — an upsert row a SCIM directory owns is refused', async () => { const h = makeHarness({ seedUsers: [ - { id: 'u_sso', email: 'sso@x.co', name: 'SSO', source: 'idp_provisioned' }, + { id: 'u_scim', email: 'scim@x.co', name: 'SCIM', source: 'idp_provisioned' }, { id: 'u_boss', email: 'boss@x.co', name: 'Boss' }, ], + seedScimSubjects: [{ id: 'sub_1', user_id: 'u_scim' }], }); const res = await runAdminImportUsers(h.deps, makeRequest({ passwordPolicy: 'none', mode: 'upsert', matchBy: 'email', format: 'json', - rows: [{ email: 'sso@x.co', name: 'SSO', manager_id: 'boss@x.co' }], + rows: [{ email: 'scim@x.co', name: 'SCIM', manager_id: 'boss@x.co' }], }), ACTOR); const data = payload(res); expect(data.rows[0].action).toBe('updated'); expect(data.rows[0].manager).toBe('idp_provisioned'); + expect(String(data.rows[0].error)).toContain('directory'); expect(data.summary.manager.refused).toBe(1); - expect(h.userBy('sso@x.co')?.manager_id ?? null).toBeNull(); + expect(h.userBy('scim@x.co')?.manager_id ?? null).toBeNull(); + }); + + it('⭐ SSO-only identity (idp_provisioned, no SCIM subject) — its manager link lands', async () => { + // ADR-0135 D4 stamps the mark on any SSO sign-in without a local password; + // with no directory behind it, the import links it like any other row. + const h = makeHarness({ + seedUsers: [ + { id: 'u_sso', email: 'sso@x.co', name: 'SSO', source: 'idp_provisioned' }, + { id: 'u_boss', email: 'boss@x.co', name: 'Boss' }, + ], + }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', mode: 'upsert', matchBy: 'email', format: 'json', + rows: [{ email: 'sso@x.co', name: 'SSO', manager_id: 'boss@x.co' }], + }), ACTOR); + + const data = payload(res); + expect(data.rows[0].action).toBe('updated'); + expect(data.rows[0].manager).toBe('linked'); + expect(data.summary.manager).toEqual({ linked: 1, unresolved: 0, refused: 0 }); + expect(h.userBy('sso@x.co')?.manager_id).toBe('u_boss'); }); it('cross-organization — the delegate\'s sys_member screen really runs', async () => { @@ -517,6 +543,8 @@ describe('import-users manager pass — the refusals are the DELEGATE\'s (#18028 // And none of the predicates' own machinery. expect(IMPORT_USERS_SOURCE).not.toContain('MAX_MANAGER_CHAIN_DEPTH'); expect(IMPORT_USERS_SOURCE).not.toContain('sys_member'); + expect(IMPORT_USERS_SOURCE).not.toContain('sys_scim_subject'); + expect(IMPORT_USERS_SOURCE).not.toContain('isHeldByScimDirectory'); }); }); diff --git a/packages/plugins/plugin-auth/src/admin-import-users.ts b/packages/plugins/plugin-auth/src/admin-import-users.ts index a7809b323f2..c02b51f7425 100644 --- a/packages/plugins/plugin-auth/src/admin-import-users.ts +++ b/packages/plugins/plugin-auth/src/admin-import-users.ts @@ -88,9 +88,11 @@ * returned, when every row in the batch exists. * - **Where the refusals come from.** `applyUserManagerLink` — the same * derivation `POST /admin/set-user-manager` runs, imported, ⛔ never copied. - * Self-assignment, cycle, depth cap, cross-organization and directory-owned - * identity are that function's to answer, and the refusal it returns is - * reported on the row rather than re-worded here. + * Self-assignment, cycle, depth cap, cross-organization and an identity a + * SCIM directory holds are that function's to answer, and the refusal it + * returns is reported on the row rather than re-worded here. An identity + * that only signs in through SSO (`idp_provisioned` with no directory + * behind it) is linked like any other row. * - **A manager problem never costs the row its identity.** The user is * created either way; `rows[].manager` carries the machine-readable outcome * in `rows[].delivery`'s shape and `rows[].error` carries the sentence. diff --git a/packages/plugins/plugin-auth/src/admin-set-user-manager.test.ts b/packages/plugins/plugin-auth/src/admin-set-user-manager.test.ts index e7e46cc916e..7eac2b65314 100644 --- a/packages/plugins/plugin-auth/src/admin-set-user-manager.test.ts +++ b/packages/plugins/plugin-auth/src/admin-set-user-manager.test.ts @@ -587,38 +587,112 @@ describe('set-user-manager — refusal 4: cross-organization', () => { }); }); -describe('set-user-manager — refusal 5: the directory owns this identity', () => { - const provisioned = () => ({ +describe('set-user-manager — refusal 5: a SCIM directory owns this identity', () => { + // Maintainer ruling record 6895645364, option A: "directory wins" applies + // where a directory actually exists. ADR-0135 D4 stamps `idp_provisioned` on + // EVERY federated link without a local password, so the mark alone also + // covers a person who only signs in through SSO (the platform's own, or a + // social / enterprise OIDC provider) with no directory behind them. The + // refusal reads the mark AND a `sys_scim_subject` row — the predicate + // `scim-sso-adoption.ts` judges "held by a SCIM directory" with. + const people = () => ({ sys_user: [ + // SCIM-held: the mark and a SCIM subject. + { id: 'u_scim', manager_id: 'u_old', source: 'idp_provisioned' }, + // SSO-only: the mark, no SCIM subject (a platform-SSO first sign-in). { id: 'u_sso', manager_id: 'u_old', source: 'idp_provisioned' }, + // SCIM-provisioned but holding a local password: D4 leaves it env_native. + { id: 'u_scim_pw', manager_id: null, source: 'env_native' }, { id: 'u_boss', manager_id: null, source: 'env_native' }, { id: 'u_old', manager_id: null, source: 'env_native' }, ] as Row[], + sys_scim_subject: [ + { id: 'sub_1', user_id: 'u_scim' }, + { id: 'sub_2', user_id: 'u_scim_pw' }, + ] as Row[], }); - it('refuses a SET on an idp_provisioned identity, naming the sync as the surface', async () => { - const engine = makeEngine(provisioned()); - const res = await runSetUserManager(deps(engine), ACTOR, post({ userId: 'u_sso', managerId: 'u_boss' })); + it('refuses a SET on a SCIM-held identity, naming the directory as the surface', async () => { + const engine = makeEngine(people()); + const res = await runSetUserManager(deps(engine), ACTOR, post({ userId: 'u_scim', managerId: 'u_boss' })); expect(res.status).toBe(403); expect(res.body.error?.code).toBe('PERMISSION_DENIED'); expect(res.body.error?.details?.reason).toBe('idp_provisioned'); expect(res.body.error?.message).toContain('directory'); expect(engine.updates).toEqual([]); + // The verdict was read from the SCIM subject table, for this user. + expect(engine.reads).toContainEqual({ object: 'sys_scim_subject', where: { user_id: 'u_scim' } }); }); - it('refuses the CLEAR too — a value the next sync reverts is the shape ADR-0049 refuses', async () => { - const engine = makeEngine(provisioned()); - const res = await runSetUserManager(deps(engine), ACTOR, post({ userId: 'u_sso', managerId: null })); + it('refuses the CLEAR too on a SCIM-held identity — both are writes that directory owns', async () => { + const engine = makeEngine(people()); + const res = await runSetUserManager(deps(engine), ACTOR, post({ userId: 'u_scim', managerId: null })); expect(res.status).toBe(403); expect(res.body.error?.details?.reason).toBe('idp_provisioned'); expect(engine.updates).toEqual([]); }); - it('an env_native identity is unaffected — the control for the screen above', async () => { - const engine = makeEngine(provisioned()); - const res = await runSetUserManager(deps(engine), ACTOR, post({ userId: 'u_old', managerId: 'u_boss' })); + it('⭐ an SSO-only identity (idp_provisioned, no SCIM subject) is SET like a local one', async () => { + const engine = makeEngine(people()); + const res = await runSetUserManager(deps(engine), ACTOR, post({ userId: 'u_sso', managerId: 'u_boss' })); + + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + expect(engine.updates).toHaveLength(1); + expect(engine.updates[0].object).toBe('sys_user'); + expect(engine.updates[0].data).toEqual({ id: 'u_sso', manager_id: 'u_boss' }); + }); + + it('⭐ an SSO-only identity can be CLEARED as well', async () => { + const engine = makeEngine(people()); + const res = await runSetUserManager(deps(engine), ACTOR, post({ userId: 'u_sso', managerId: null })); + expect(res.status).toBe(200); + expect(engine.updates.map((u) => u.data)).toEqual([{ id: 'u_sso', manager_id: null }]); + }); + + it('an SSO-only identity still meets the other refusals — self-assignment is refused as for anyone', async () => { + const engine = makeEngine(people()); + const res = await runSetUserManager(deps(engine), ACTOR, post({ userId: 'u_sso', managerId: 'u_sso' })); + + expect(res.status).toBe(400); + expect(res.body.error?.code).toBe('INVALID_FIELD'); + expect(res.body.error?.details?.reason).toBe('self_assignment'); + expect(engine.updates).toEqual([]); + }); + + it('an env_native identity is unaffected — even one that owns a SCIM subject (no served request becomes refused)', async () => { + const engine = makeEngine(people()); + const plain = await runSetUserManager(deps(engine), ACTOR, post({ userId: 'u_old', managerId: 'u_boss' })); + expect(plain.status).toBe(200); + const withPassword = await runSetUserManager(deps(engine), ACTOR, post({ userId: 'u_scim_pw', managerId: 'u_boss' })); + expect(withPassword.status).toBe(200); + expect(engine.updates.map((u) => u.data.id)).toEqual(['u_old', 'u_scim_pw']); + // The SCIM table is not even asked for an env_native row. + expect(engine.reads.some((r) => r.object === 'sys_scim_subject')).toBe(false); + }); + + it('a missing sys_scim_subject table means no directory: the SSO-only link is written', async () => { + const engine = makeEngine(people()); + const find = engine.find.bind(engine); + engine.find = async (object: string, query?: unknown) => { + if (object === 'sys_scim_subject') throw new Error('SQLITE_ERROR: no such table: sys_scim_subject'); + return find(object, query); + }; + const res = await runSetUserManager(deps(engine), ACTOR, post({ userId: 'u_sso', managerId: 'u_boss' })); + + expect(res.status).toBe(200); + expect(engine.updates.map((u) => u.data)).toEqual([{ id: 'u_sso', manager_id: 'u_boss' }]); + }); + + it('⛔ a FAILED SCIM-subject read is never read as "no directory" — it propagates and writes nothing', async () => { + const engine = makeEngine(people()); + engine.failReadsOn('sys_scim_subject'); + await expect( + runSetUserManager(deps(engine), ACTOR, post({ userId: 'u_sso', managerId: 'u_boss' })), + ).rejects.toThrow('read of sys_scim_subject failed'); + expect(engine.updates).toEqual([]); }); }); diff --git a/packages/plugins/plugin-auth/src/admin-set-user-manager.ts b/packages/plugins/plugin-auth/src/admin-set-user-manager.ts index 3c9eaf679ca..1af62837558 100644 --- a/packages/plugins/plugin-auth/src/admin-set-user-manager.ts +++ b/packages/plugins/plugin-auth/src/admin-set-user-manager.ts @@ -86,13 +86,22 @@ * halves are wanted: data drifts after a write, so the read-time screen * stays the last line, and the write-time refusal is the only one an * operator can act on at the moment they made the mistake. - * 5. **Directory-owned identity** — refused when the target is - * `source: 'idp_provisioned'`. The ruling picked "directory wins, per - * identity", keyed on the `sys_user.source` column the platform already - * stamps and already uses to hide three self-service identity actions. - * The rejected alternative was last-writer-wins, which stores a value the - * next sync silently reverts — a write that reports success and does not - * persist, which is exactly what ADR-0049 exists to refuse. + * 5. **Directory-owned identity** — refused when a SCIM directory holds the + * target: it reads `source: 'idp_provisioned'` AND owns a + * `sys_scim_subject` row ({@link isHeldByScimDirectory}, the one + * definition `scim-sso-adoption.ts` also judges adoption by). The ruling + * picked "directory wins, per identity"; the rejected alternative was + * last-writer-wins, which stores a value the next sync silently reverts — + * a write that reports success and does not persist, which is exactly + * what ADR-0049 exists to refuse. ⛔ The `source` mark ALONE is not a + * directory: ADR-0135 D4 stamps `idp_provisioned` on every federated link + * without a local password, so a person who only signs in through SSO + * (the platform's own, or a social or enterprise OIDC provider) carries it + * with no directory behind them, and their manager is set here like any + * other user's (maintainer ruling record 6895645364, option A: "directory + * wins" applies where a directory actually exists). The `source` term stays + * a conjunct, so a SCIM-provisioned user holding a local password — which + * D4 leaves `env_native` — keeps the answer it had. * * ## Why these `error.code` values and not dedicated ones * @@ -114,7 +123,7 @@ * | cycle | RESOURCE_CONFLICT | 409 | cycle | * | depth cap | VALUE_OUT_OF_RANGE | 400 | max_depth_exceeded | * | cross-organization | INVALID_REFERENCE | 400 | cross_organization | - * | directory-owned identity | PERMISSION_DENIED | 403 | idp_provisioned | + * | SCIM-held identity | PERMISSION_DENIED | 403 | idp_provisioned | * * Authorization is the caller's, not this module's: the mount runs the * ADR-0068 platform-admin gate (`judgePlatformAdmin`) and hands the actor in @@ -128,6 +137,8 @@ import { authSystemWriteContext } from './auth-actor-attribution.js'; import type { AdminActor, EndpointResult } from './admin-user-endpoints.js'; import { readJsonRequestBody } from './request-json-body.js'; +import { isHeldByScimDirectory } from './scim-sso-adoption.js'; +import { isMissingTableError } from '@objectstack/types'; /** * Hard cap on the reporting chain this endpoint will create, counted in links @@ -263,6 +274,23 @@ async function findUser( return row && row.id ? row : null; } +/** + * Is `userId` held by a SCIM directory? {@link isHeldByScimDirectory} answers, + * imported — ⛔ never a second copy of the predicate. A missing + * `sys_scim_subject` table means no SCIM directory has ever provisioned + * anyone here, so it answers "not held"; any other read failure propagates, + * and the mount answers it as a 500 that writes nothing — a directory that + * could not be asked is never read as absent. + */ +async function heldByScimDirectory(engine: SetUserManagerEngine, userId: string): Promise { + try { + return await isHeldByScimDirectory(engine, userId); + } catch (e) { + if (isMissingTableError(e, 'sys_scim_subject')) return false; + throw e; + } +} + /** * The organization ids an identity PROVABLY holds membership in. An empty * array means "no tenancy fact recorded", which is not the same as "member of @@ -509,16 +537,17 @@ export async function applyUserManagerLink( return deny(404, 'RESOURCE_NOT_FOUND', 'user_not_found', 'User not found'); } - // Refusal 5 — the directory owns this identity. Applied to the CLEAR as - // well as the set: both are writes the next sync would overwrite. - if (String(user.source ?? '') === 'idp_provisioned') { + // Refusal 5 — a SCIM directory owns this identity. Applied to the CLEAR as + // well as the set: both are writes that directory owns. The `source` mark + // is read first and alone is NOT enough (see refusal 5 above): an identity + // that only signs in through SSO carries it too, with no directory behind it. + if (String(user.source ?? '') === 'idp_provisioned' && await heldByScimDirectory(engine, userId)) { return deny( 403, 'PERMISSION_DENIED', 'idp_provisioned', - "This identity is provisioned by an external directory (sys_user.source is 'idp_provisioned'), " - + 'so its manager is maintained by that directory and a value written here would be ' - + 'reverted on the next sync. Set the manager in the directory instead.', + 'This identity is provisioned by a SCIM directory, so that directory owns its manager. ' + + 'Change the manager in your directory instead.', ); } diff --git a/packages/plugins/plugin-auth/src/demo-staff.test.ts b/packages/plugins/plugin-auth/src/demo-staff.test.ts index 8841dc92b2e..991ab741fe9 100644 --- a/packages/plugins/plugin-auth/src/demo-staff.test.ts +++ b/packages/plugins/plugin-auth/src/demo-staff.test.ts @@ -242,11 +242,12 @@ describe('provisioning — a failure after sign-up says the account exists', () * the cross-organization screen stays out of these cases, as it does for any * identity without one. */ -function managerEngine(users: Array>) { +function managerEngine(users: Array>, scimSubjects: Array> = []) { const updates: Array> = []; const engine: DemoStaffEngine = { async find(object, query) { - const matched = object === 'sys_user' ? selectRows(users, (query.where ?? {}) as Record) : []; + const rows = object === 'sys_user' ? users : object === 'sys_scim_subject' ? scimSubjects : null; + const matched = rows ? selectRows(rows, (query.where ?? {}) as Record) : []; return typeof query.limit === 'number' ? matched.slice(0, query.limit) : matched; }, async update(object, data, options) { @@ -392,13 +393,13 @@ describe('provisioning — each declared manager is linked once every entry has }); it('a link the set-manager write refuses is reported with its code and reason', async () => { - // A directory-owned identity: the set-manager write's refusal 5. The - // provisioning carries no copy of that rule; this is the shared one. + // An identity a SCIM directory holds: the set-manager write's refusal 5. + // The provisioning carries no copy of that rule; this is the shared one. const users: Array> = [ { id: 'u_c1', email: 'counsel1@legal.example', manager_id: null, source: 'idp_provisioned' }, { id: 'u_lead', email: 'lead@legal.example', manager_id: null }, ]; - const { engine, updates, signUp } = managerEngine(users); + const { engine, updates, signUp } = managerEngine(users, [{ id: 'sub_1', user_id: 'u_c1' }]); const outcome = await provisionDemoStaff(STAFF, deps(engine, signUp)); diff --git a/packages/plugins/plugin-auth/src/scim-sso-adoption.ts b/packages/plugins/plugin-auth/src/scim-sso-adoption.ts index 7be3a38c5fe..7b5d81b2479 100644 --- a/packages/plugins/plugin-auth/src/scim-sso-adoption.ts +++ b/packages/plugins/plugin-auth/src/scim-sso-adoption.ts @@ -121,6 +121,24 @@ const organizationKey = (value: unknown): string => (typeof value === 'string' ? /** sqlite answers a boolean as 0/1; anything but true is not verified. */ const isTrue = (value: unknown): boolean => value === true || value === 1; +/** + * Is this account held by a SCIM directory? It is when a `sys_scim_subject` + * row names it: the vendor writes one for every user a SCIM connection + * provisions or links, and never deletes it. Condition 2 of the rule above, + * and the one definition of "held by a SCIM directory" in this package — + * `admin-set-user-manager.ts` imports it for its directory refusal. Reads as + * the system; a read failure propagates to the caller. + */ +export async function isHeldByScimDirectory(engine: ScimSsoAdoptionEngine, userId: string): Promise { + const subjects = await engine.find('sys_scim_subject', { + where: { user_id: userId }, + fields: ['id'], + limit: 1, + context: SYSTEM_CTX, + }); + return subjects.length > 0; +} + // [#32975] The address's domain and a provider's domain list are read through // the ONE parse every rule that judges an address against that list shares // (`sso-account-at-proven-domain.ts`): an entry names the same domain here as @@ -164,13 +182,7 @@ export async function judgeScimSsoAdoption( if (linkedProviderIds.includes(LOCAL_PASSWORD_PROVIDER)) return { adopt: false, reason: 'holds_local_password' }; // 2. Not held by a SCIM directory. - const subjects = await engine.find('sys_scim_subject', { - where: { user_id: userId }, - fields: ['id'], - limit: 1, - context: SYSTEM_CTX, - }); - if (subjects.length > 0) return { adopt: false, reason: 'held_by_scim' }; + if (await isHeldByScimDirectory(engine, userId)) return { adopt: false, reason: 'held_by_scim' }; // 3. Linked to an SSO provider of the connection's organization. const federated = linkedProviderIds.filter((id) => id !== LOCAL_PASSWORD_PROVIDER);