From 96f3de597be9ccb888539276563e4eff98ad1a0f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:24:08 +0000 Subject: [PATCH 01/20] feat(plugin-auth): project the SCIM enterprise manager onto sys_user.manager_id Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../plugin-auth/src/admin-set-user-manager.ts | 174 +++++++++------ .../src/auth-manager-plugin-list.ts | 13 +- .../src/scim-manager-projection.ts | 210 ++++++++++++++++++ 3 files changed, 322 insertions(+), 75 deletions(-) create mode 100644 packages/plugins/plugin-auth/src/scim-manager-projection.ts 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 1af62837558..8f0b4f57905 100644 --- a/packages/plugins/plugin-auth/src/admin-set-user-manager.ts +++ b/packages/plugins/plugin-auth/src/admin-set-user-manager.ts @@ -448,6 +448,104 @@ async function deepestSubordinateChain( return { kind: 'ok', depth }; } +/** + * Refusals 1 to 4 — self-assignment, the proposed manager's existence, + * cross-organization, cycle and depth — judged for ONE proposed link + * `userId -> managerId`, without writing anything. + * + * Split out of {@link applyUserManagerLink} for the one caller that must not + * run refusal 5: the SCIM manager projection (`scim-manager-projection.ts`). + * There the writer IS the directory that holds the identity, so "change it in + * your directory" would refuse the directory itself; every other refusal + * applies to it unchanged, and this is where it gets them. ⛔ Never a second + * copy of these predicates on that path. + * + * Answers `null` when the link may be written, or the refusal that stops it. + * The caller owns authorization AND the write. + */ +export async function screenUserManagerLink( + deps: SetUserManagerDeps, + engine: SetUserManagerEngine, + userId: string, + managerId: string, +): Promise { + // Refusal 1 — self-assignment. + if (managerId === userId) { + return deny( + 400, + 'INVALID_FIELD', + 'self_assignment', + 'A user cannot be their own manager: an approval routed to the manager rung would resolve ' + + 'to the submitter, which is the approval this tier exists to prevent.', + ); + } + + const manager = await findUser(engine, managerId); + if (!manager) { + return deny( + 400, + 'INVALID_REFERENCE', + 'manager_not_found', + 'The proposed manager does not exist', + ); + } + + // Refusal 4 — cross-organization. + const screen = await screenCrossOrganization(deps, engine, userId, managerId); + if (screen.outside) { + return deny( + 400, + 'INVALID_REFERENCE', + 'cross_organization', + `The proposed manager holds membership in ${screen.managerOrgs.length} organization(s), ` + + `none of them an organization this user belongs to. Routing approvals to him would put ` + + `approval authority over the record outside its tenant. Grant him a membership in one ` + + `of this user's organizations, or pick a manager inside them.`, + ); + } + + // Refusals 2 and 3 — cycle and depth, in one walk. + const walk = await walkChain(engine, managerId, userId); + if (walk.kind === 'cycle') { + return deny( + 409, + 'RESOURCE_CONFLICT', + 'cycle', + 'That link would close a loop in the reporting chain: this user already appears above the ' + + 'proposed manager, so the chain would never reach a top. Clear the intermediate link ' + + 'first, then set this one.', + ); + } + if (walk.kind === 'existing_loop') { + return deny( + 409, + 'RESOURCE_CONFLICT', + 'cycle', + `The proposed manager's own reporting chain already contains a loop (it revisits user ` + + `'${walk.repeated}'), so attaching this user beneath it would produce a chain with no ` + + `top. Repair that loop first.`, + ); + } + // The upper half fits; the lower half must fit in what is left of the cap. + const below = walk.kind === 'too_deep' + ? walk + : await deepestSubordinateChain(engine, userId, MAX_MANAGER_CHAIN_DEPTH - walk.links); + if (below.kind === 'too_deep') { + return deny( + 400, + 'VALUE_OUT_OF_RANGE', + 'max_depth_exceeded', + `That link would make this user's reporting chain longer than the maximum of ` + + `${MAX_MANAGER_CHAIN_DEPTH} links. The hierarchy scopes that walk this chain are ` + + `bounded, so a longer chain is not resolved in full. The count runs from the deepest ` + + `existing report below this user, through this user, to the top above the proposed ` + + `manager. Shorten the chain above the proposed manager, or the chain of reports below ` + + `this user, first.`, + ); + } + return null; +} + /** * `POST /api/v1/auth/admin/set-user-manager` — the caller is ALREADY gated by * the mount's ADR-0068 platform-admin check, and `actor` is that judged admin. @@ -552,80 +650,8 @@ export async function applyUserManagerLink( } if (managerId !== null) { - // Refusal 1 — self-assignment. - if (managerId === userId) { - return deny( - 400, - 'INVALID_FIELD', - 'self_assignment', - 'A user cannot be their own manager: an approval routed to the manager rung would resolve ' - + 'to the submitter, which is the approval this tier exists to prevent.', - ); - } - - const manager = await findUser(engine, managerId); - if (!manager) { - return deny( - 400, - 'INVALID_REFERENCE', - 'manager_not_found', - 'The proposed manager does not exist', - ); - } - - // Refusal 4 — cross-organization. - const screen = await screenCrossOrganization(deps, engine, userId, managerId); - if (screen.outside) { - return deny( - 400, - 'INVALID_REFERENCE', - 'cross_organization', - `The proposed manager holds membership in ${screen.managerOrgs.length} organization(s), ` - + `none of them an organization this user belongs to. Routing approvals to him would put ` - + `approval authority over the record outside its tenant. Grant him a membership in one ` - + `of this user's organizations, or pick a manager inside them.`, - ); - } - - // Refusals 2 and 3 — cycle and depth, in one walk. - const walk = await walkChain(engine, managerId, userId); - if (walk.kind === 'cycle') { - return deny( - 409, - 'RESOURCE_CONFLICT', - 'cycle', - 'That link would close a loop in the reporting chain: this user already appears above the ' - + 'proposed manager, so the chain would never reach a top. Clear the intermediate link ' - + 'first, then set this one.', - ); - } - if (walk.kind === 'existing_loop') { - return deny( - 409, - 'RESOURCE_CONFLICT', - 'cycle', - `The proposed manager's own reporting chain already contains a loop (it revisits user ` - + `'${walk.repeated}'), so attaching this user beneath it would produce a chain with no ` - + `top. Repair that loop first.`, - ); - } - // The upper half fits; the lower half must fit in what is left of the cap. - const below = walk.kind === 'too_deep' - ? walk - : await deepestSubordinateChain(engine, userId, MAX_MANAGER_CHAIN_DEPTH - walk.links); - if (below.kind === 'too_deep') { - return deny( - 400, - 'VALUE_OUT_OF_RANGE', - 'max_depth_exceeded', - `That link would make this user's reporting chain longer than the maximum of ` - + `${MAX_MANAGER_CHAIN_DEPTH} links. The hierarchy scopes that walk this chain are ` - + `bounded, so a longer chain is not resolved in full. The count runs from the deepest ` - + `existing report below this user, through this user, to the top above the proposed ` - + `manager. Shorten the chain above the proposed manager, or the chain of reports below ` - + `this user, first.`, - ); - } + const screened = await screenUserManagerLink(deps, engine, userId, managerId); + if (screened) return screened; } // The write. `authSystemWriteContext()` builds both halves together: diff --git a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts index 9761d0ccf1a..1b10a868b91 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts @@ -844,6 +844,7 @@ export async function buildPluginList(this: PluginListHost): Promise { await import('./scim-connection-service.js'); const { createScimGroupProjection } = await import('./scim-group-projection.js'); const { createScimSsoAdoptionResolver } = await import('./scim-sso-adoption.js'); + const { projectScimManager } = await import('./scim-manager-projection.js'); const secret = this.resolveAuthSecret(); // [#32120] One stamper for this manager's SCIM plugin, so its // per-credential minute claims are shared by every request it verifies. @@ -909,7 +910,17 @@ export async function buildPluginList(this: PluginListHost): Promise { getEngine: () => this.getDataEngine() as never, readConnection: () => scimRequestScope.getStore(), }), - reconcileUser: (state, context) => this.reconcileScimUserLifecycle(state, context), + // The Enterprise `manager` attribute onto `sys_user.manager_id`, + // after the lifecycle reconcile and in the same transaction, through + // the admin endpoint's own refusals. See `scim-manager-projection.ts`. + reconcileUser: async (state, context) => { + await this.reconcileScimUserLifecycle(state, context); + await projectScimManager( + { getDataEngine: () => this.getDataEngine() as never, logger: this.config.logger as never }, + state, + context, + ); + }, }, // [ADR-0134 D4, filled for permission sets] A pushed group grants the // permission sets its `sys_idp_group_mapping` rows name, inside the diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.ts new file mode 100644 index 00000000000..725be2dedbc --- /dev/null +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.ts @@ -0,0 +1,210 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The SCIM Enterprise User `manager` attribute, projected onto + * `sys_user.manager_id`. PACKAGE-INTERNAL. + * + * ## The gap this closes + * + * `admin-set-user-manager` refuses an identity a SCIM directory holds ("change + * it in your directory"; maintainer ruling record 6895645364, option A), and + * until this module no code carried the directory's own answer to the column: + * `@better-auth/scim` validates and stores + * `urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:manager` and + * echoes it back, but writes nothing of it onto the user. So for a SCIM-held + * user neither side could set the manager, and the approvals `manager` rung + * and the `own_and_reports` scope (ADR-0057) read a column nobody could write. + * + * ## The seam, and why it is this one + * + * The vendor hands the host three callbacks inside its SCIM transaction, and + * none receives the resource: `identity.resolveUser` sees it on a create only + * and runs BEFORE the transaction; `projection.reconcileUser` and + * `identity.reconcileUser` see the user's state. So the projection reads what + * the vendor has just stored — the profile source's `scimUser` row, whose + * `serializedAttributes` hold the canonical attributes the request left — on + * `identity.reconcileUser`, which the vendor calls after every user create, + * replace, patch, reprovision and delete. It runs after the lifecycle + * reconcile (`reconcileScimUserLifecycle`, the ADR-0135 D4 stamp, untouched), + * through the data engine, whose writes join the SCIM request's transaction + * (`scimRequestScope`), so a refusal rolls the whole SCIM mutation back and + * the identity provider reads a SCIM error with nothing written. + * + * ## When it projects, and when it does not + * + * - Only inside an authenticated SCIM protocol request, and only for the + * connection that request verified as. The vendor also calls this callback + * while it decommissions a connection or replays a provisioning domain; a + * decommission must never be refused over an org-chart reference, so those + * runs project nothing. + * - Only from the user's PROFILE source (the vendor's `profileSourceId`, the + * same rule that decides whose name and email the user carries), and only + * when that source belongs to the request's connection. + * - Only on an active state. A deprovision is never refused over the manager; + * a user re-activated later projects the manager its source then holds. + * - Only when the manager CHANGES. A stored reference that resolves to the + * manager the user already has is not judged again, so an unrelated PATCH is + * never refused over a chain other links have since reshaped. + * + * ## What `manager.value` is matched against + * + * The manager's SCIM resource `id` — RFC 7643 §4.3 defines `manager.value` as + * "the id of the SCIM resource representing the User's manager" — among the + * Users the SAME connection provisioned (a resource id means something only to + * the connection that issued it, which is also how `GET /Users/{id}` scopes + * it). A `$ref` alone is read the same way, by its final `/Users/{id}` path + * segment. ⛔ Never the `externalId`, the `userName` or an email as a second + * dialect: one reading, so a reference either names a User or is refused. + * + * ## The refusals + * + * A reference that names no User this connection provisioned is refused — + * never dropped, so the directory learns its reference did not land. Every + * other refusal is the admin endpoint's own, from + * {@link screenUserManagerLink} (self-assignment, cycle, depth cap, + * cross-organization), imported: one derivation, never a copy. Each is a SCIM + * error in RFC 7644 §3.12 shape: status 400, `scimType: invalidValue` — the + * vendor's own answer to a value it refuses — and the refusal's sentence as + * `detail`. The refusal ledger (`scim-refusal-audit.ts`) records it like any + * other SCIM refusal. A cleared or absent attribute clears the column. + */ + +import type { SCIMIdentityState, SCIMTransactionContext } from '@better-auth/scim'; +import { authSystemWriteContext } from './auth-actor-attribution.js'; +import { screenUserManagerLink, type SetUserManagerDeps } from './admin-set-user-manager.js'; +import { scimRequestConnectionId } from './scim-connection-service.js'; + +/** The SCIM Enterprise User extension the attribute lives in. */ +export const SCIM_ENTERPRISE_USER_SCHEMA = 'urn:ietf:params:scim:schemas:extension:enterprise:2.0:User'; + +const SCIM_ERROR_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:Error'; + +const SYSTEM_READ_CTX = { isSystem: true, positions: [], permissions: [] } as const; + +/** The vendor-side `scimUser` row fields this module reads. */ +interface ScimUserRow { + id?: unknown; + userId?: unknown; + connectionId?: unknown; + serializedAttributes?: unknown; +} + +/** What the stored attributes say about the manager. */ +export type ScimManagerReference = + | { kind: 'none' } + | { kind: 'id'; id: string } + | { kind: 'unreadable'; ref: string }; + +/** + * The manager reference in a `scimUser` row's stored canonical attributes: + * `enterprise.manager.value`, else the final `/Users/{id}` segment of + * `enterprise.manager.$ref`. A row stored before the vendor kept attributes, + * or one with no manager, names none. + */ +export function readScimManagerReference(serializedAttributes: unknown): ScimManagerReference { + if (typeof serializedAttributes !== 'string' || serializedAttributes === '') return { kind: 'none' }; + // The vendor validated this payload before storing it and validates it again + // on every read, so a parse failure here is the vendor's state, not input — + // it propagates, and the vendor answers it as a SCIM 500 that writes nothing. + const attributes = JSON.parse(serializedAttributes) as { enterprise?: { manager?: { value?: unknown; $ref?: unknown } } }; + const manager = attributes?.enterprise?.manager; + if (!manager || typeof manager !== 'object') return { kind: 'none' }; + if (typeof manager.value === 'string' && manager.value !== '') return { kind: 'id', id: manager.value }; + if (typeof manager.$ref === 'string' && manager.$ref !== '') { + const match = /\/Users\/([^/?#]+)\/?$/.exec(manager.$ref); + return match ? { kind: 'id', id: decodeURIComponent(match[1]) } : { kind: 'unreadable', ref: manager.$ref }; + } + return { kind: 'none' }; +} + +/** A SCIM 400 `invalidValue` error, built the way the vendor builds its own. */ +async function scimInvalidValue(detail: string): Promise { + const { APIError } = await import('better-auth/api'); + const error = new APIError('BAD_REQUEST', { + schemas: [SCIM_ERROR_SCHEMA], + status: '400', + scimType: 'invalidValue', + detail, + } as never); + error.message = detail; + return error; +} + +const text = (v: unknown): string => (typeof v === 'string' ? v : v == null ? '' : String(v)); + +/** The admin endpoint's own dependencies: the engine, and its degradation channel. */ +export type ScimManagerProjectionDeps = SetUserManagerDeps; + +/** + * Project the profile source's `manager` onto `sys_user.manager_id` for the + * user in `state`, inside the SCIM transaction `context` belongs to. Resolves + * when the column already agrees or was written; throws the SCIM error the + * identity provider reads when the reference is refused. + */ +export async function projectScimManager( + deps: ScimManagerProjectionDeps, + state: SCIMIdentityState, + context: SCIMTransactionContext, +): Promise { + const connectionId = scimRequestConnectionId(); + if (!connectionId || !state.active || !state.profileSourceId) return; + + const db = context.database; + const source = await db.findOne({ + model: 'scimUser', + where: [{ field: 'id', value: state.profileSourceId }], + }); + if (!source || text(source.connectionId) !== connectionId) return; + + const reference = readScimManagerReference(source.serializedAttributes); + if (reference.kind === 'unreadable') { + throw await scimInvalidValue( + `${SCIM_ENTERPRISE_USER_SCHEMA}:manager names no User: its $ref '${reference.ref}' does not end in ` + + `/Users/{id}, and it carries no value. Send the manager's SCIM resource id as manager.value.`, + ); + } + + let managerId: string | null = null; + if (reference.kind === 'id') { + const managerSource = await db.findOne({ + model: 'scimUser', + where: [ + { field: 'id', value: reference.id }, + { field: 'connectionId', value: connectionId }, + ], + }); + if (!managerSource || !text(managerSource.userId)) { + throw await scimInvalidValue( + `${SCIM_ENTERPRISE_USER_SCHEMA}:manager.value '${reference.id}' names no User this connection ` + + `provisioned. manager.value is the manager's SCIM resource id (the id this service returned when ` + + `the manager was created), not an externalId, userName or email. Provision the manager first, or ` + + `send the right id; nothing of this request was written.`, + ); + } + managerId = text(managerSource.userId); + } + + const engine = deps.getDataEngine(); + if (!engine) { + throw new Error( + `[auth] SCIM manager projection: no data engine to write sys_user.manager_id for user '${state.userId}'`, + ); + } + const rows = await engine.find('sys_user', { + where: { id: state.userId }, + fields: ['id', 'manager_id'], + limit: 1, + context: SYSTEM_READ_CTX, + }); + const current = text((Array.isArray(rows) ? (rows[0] as { manager_id?: unknown } | undefined) : undefined)?.manager_id); + if (current === (managerId ?? '')) return; + + if (managerId !== null) { + const refusal = await screenUserManagerLink(deps, engine, state.userId, managerId); + if (refusal) throw await scimInvalidValue(refusal.message); + } + + // Attributed to the connection (`svc:scim:CONNECTION_ID`) inside a SCIM + // request, and joined to its transaction. + await engine.update('sys_user', { id: state.userId, manager_id: managerId }, { context: await authSystemWriteContext() }); +} From 2f59626c40c173b09619948fcaf1985cfcfe18c4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:36:13 +0000 Subject: [PATCH 02/20] docs(lint): grade SCIM as a route that populates sys_user.manager_id Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- packages/lint/src/rule-explanations.ts | 16 +- .../src/validate-approval-approvers.test.ts | 7 +- .../lint/src/validate-approval-approvers.ts | 28 +- .../src/scim-manager-projection.test.ts | 340 ++++++++++++++++++ 4 files changed, 371 insertions(+), 20 deletions(-) create mode 100644 packages/plugins/plugin-auth/src/scim-manager-projection.test.ts diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index baf57a7ab04..4779814fe44 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -3333,13 +3333,15 @@ const MANAGER_ONLY_ROUTES = 'an existing user — and links each row once every row in the file exists, through those same ' + 'refusals; a link it cannot make is reported on that row\'s manager result and 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 — and ' + - '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. 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 ' + + 'write, which bypasses the managed-update whitelist. SCIM provisioning populates it too: the ' + + 'Enterprise User \'manager\' attribute, whose value is the manager\'s SCIM resource id, is ' + + 'written onto the column on every SCIM create, replace and patch, through those same refusals, ' + + 'and an id that names no user the connection provisioned is refused — and 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. Any other directory sync ' + + 'populates it only through a provisioning path your own deployment supplies. 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 bfbf1c21e50..ac6abb4f683 100644 --- a/packages/lint/src/validate-approval-approvers.test.ts +++ b/packages/lint/src/validate-approval-approvers.test.ts @@ -370,7 +370,10 @@ describe('unset-manager dead-end (#16748)', () => { // ⛔ The one that is NOT this repo's to offer must be marked as the // deployment's own, and the hint must say WHY rather than merely hedging. expect(remedy).toContain('a provisioning path your own deployment supplies'); - expect(remedy).toContain("declares the SCIM 'manager' attribute without projecting it"); + // SCIM is no longer among them: its `manager` attribute is projected onto + // the column (plugin-auth `scim-manager-projection.ts`). + expect(remedy).not.toContain('without projecting it'); + expect(remedy).toContain("Enterprise User 'manager' attribute, whose value is the manager's SCIM resource id"); // ⛔ And they must not be deleted: a deployment running a real directory // sync may well populate the column, and the defect was presenting all @@ -378,7 +381,7 @@ describe('unset-manager dead-end (#16748)', () => { // 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('SCIM provisioning populates it too'); 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 diff --git a/packages/lint/src/validate-approval-approvers.ts b/packages/lint/src/validate-approval-approvers.ts index 88c6e9c4dff..26cacdfc61d 100644 --- a/packages/lint/src/validate-approval-approvers.ts +++ b/packages/lint/src/validate-approval-approvers.ts @@ -155,11 +155,17 @@ const STAYS_LOCKED = ', and (lockRecord) the record stays locked'; * `system-write-guard.ts`, plugin-auth `identity-write-guard.ts`). A * system-context write therefore bypasses the managed-update whitelist by * construction. - * - SCIM — NOT here, re-measured and unchanged. The Enterprise `manager` - * attribute IS declared (`scim.zod.ts`), but no non-test file under - * `packages/plugins` or `packages/runtime` projects it onto the column: - * measured 0, against a control (`SysScimGroup`) the same scan does find, - * so the scan discriminates. + * - SCIM — AVAILABLE HERE, and the grade this block used to give it ("NOT + * here, 0 projection sites") went stale when the projection landed. + * plugin-auth `scim-manager-projection.ts` carries the Enterprise User + * `manager.value` — the manager's SCIM resource id among the Users the + * same connection provisioned (RFC 7643 §4.3) — onto the column on every + * SCIM create, replace and patch, inside the SCIM transaction, through + * the endpoint's own refusals (`screenUserManagerLink`: self-assignment, + * cycle, depth cap, cross-organization); a reference naming no User is a + * SCIM 400 `invalidValue`, never dropped, and a cleared or absent + * attribute clears the column. Measured by + * `scim-manager-projection.test.ts`, end to end through the vendor. * - Admin bulk import — AVAILABLE HERE, and the grade this block used to * give it ("NOT here") went stale when the import tier admitted the column. * `POST /api/v1/auth/admin/import-users` (`admin-import-users.ts`) reads a @@ -178,12 +184,12 @@ const STAYS_LOCKED = ', and (lockRecord) the record stays locked'; * It is the route to name for a whole file; a remedy that said otherwise * sent the author away from a supported path. * - * ⇒ SCIM and directory sync stay NAMED, because a deployment running a real - * 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 identity a SCIM directory holds the endpoint refuses, so - * the directory is the one authoring surface for those rows. + * ⇒ SCIM is NAMED as a route this repo gives, with PRECEDENCE over the + * endpoint rather than beside it: on an identity a SCIM directory holds the + * endpoint refuses, so the directory's `manager` attribute is the one + * authoring surface for those rows. Any other directory sync stays named as + * something the operator's own provisioning supplies, ⛔ never as something + * this repo gives them. * * ⛔ WHAT DID NOT CHANGE — and why this rule is not deleted. The dead end the * finding reports SURVIVES the write surface: a static check still cannot read diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts new file mode 100644 index 00000000000..0b74552c8a0 --- /dev/null +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts @@ -0,0 +1,340 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The SCIM Enterprise `manager` attribute lands on `sys_user.manager_id`, + * end to end through `@better-auth/scim` (`scim-manager-projection.ts`). + * + * Every case drives `AuthManager.handleRequest()` with a real SCIM bearer on a + * real `ObjectQL` over better-sqlite3, because what the projection does is + * only half the behaviour: the vendor's transaction decides whether a refused + * reference leaves anything behind, and its after-hook decides the error body + * the identity provider reads. Each refusal is a single-cause fixture, and + * each asserts the SCIM error AND that nothing changed. + */ + +import { describe, it, expect, afterEach, afterAll } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ADMIN_FULL_ACCESS } from '@objectstack/spec/identity'; +import { AuthManager } from './auth-manager.js'; +import { authIdentityObjects } from './manifest.js'; +import { createTenancyService } from './tenancy-service.js'; +import { mintScimConnectionCredential } from './scim-connection-service.js'; +import { registerLastAdminGuard, type LastAdminGuardEngine } from './last-admin-guard.js'; +import { registerIdentityWriteGuard, registerManagedUpdateWhitelist } from './identity-write-guard.js'; +import { SYS_USER_PROFILE_EDIT_FIELDS } from './sys-user-writable-fields.js'; +import { MAX_MANAGER_CHAIN_DEPTH } from './admin-set-user-manager.js'; +import { readScimManagerReference, SCIM_ENTERPRISE_USER_SCHEMA } from './scim-manager-projection.js'; +import { bindTestSecurityCatalog } from './__tests__/security-catalog.testkit.js'; +import { sqliteEnginePool, type BootedSqliteEngine } from './__tests__/sqlite-engine-pool.testkit.js'; +// Clocked windows measure behaviour, never loading (AGENTS.md, Build & Test). +import 'better-auth'; +import 'better-auth/api'; +import 'better-auth/db'; +import 'better-auth/plugins'; +import 'better-auth/plugins/admin'; +import 'better-auth/plugins/bearer'; +import 'better-auth/plugins/organization'; +import 'better-auth/plugins/organization/access'; +import '@better-auth/core/context'; +import '@better-auth/core/error'; +import '@better-auth/oauth-provider'; +import '@better-auth/scim'; + +const BASE = 'http://localhost:3000'; +const AUTH = `${BASE}/api/v1/auth`; +const SECRET = 'test-secret-at-least-32-chars-long-scim-mgr'; + +const USER_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:User'; +const PATCH_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:PatchOp'; +const ERROR_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:Error'; + +const SYSTEM = { context: { isSystem: true } } as const; +const ORG = 'org_acme_scim_mgr'; +const OTHER_ORG = 'org_other_scim_mgr'; +const CONNECTION = 'entra-scim-mgr'; +const OTHER_CONNECTION = 'okta-scim-mgr'; +const DEFAULT_ORG = 'org_default'; + +async function bootEngine(): Promise { + const engine = new ObjectQL(); + const driver = new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: ':memory:' }, + useNullAsDefault: true, + }); + engine.registerDriver(driver, true); + await engine.init(); + for (const object of authIdentityObjects) { + engine.registry.registerObject(object as never, '@objectstack/plugin-auth'); + } + await engine.syncSchemas(); + await engine.insert('sys_organization', { id: DEFAULT_ORG, name: 'Default Organization', slug: 'default' }, SYSTEM); + bindTestSecurityCatalog(engine, { permissions: [{ name: ADMIN_FULL_ACCESS }] }); + registerManagedUpdateWhitelist('sys_user', SYS_USER_PROFILE_EDIT_FIELDS); + registerIdentityWriteGuard(engine, { packageId: 'test.identity-write-guard' }); + registerLastAdminGuard(engine as unknown as LastAdminGuardEngine, { packageId: 'test.last-admin-guard' }); + return { engine, driver }; +} + +const enginePool = sqliteEnginePool(bootEngine, { keepBootOrganizations: true }); +afterEach(enginePool.release); +afterAll(enginePool.destroy); + +interface Harness { + engine: ObjectQL; + token: string; + otherToken: string; + send: (request: Request) => Promise; +} + +async function boot(): Promise { + const engine = await enginePool.take(); + const manager = new AuthManager({ + secret: SECRET, + baseUrl: BASE, + dataEngine: engine as never, + getTenancy: () => createTenancyService({ requested: 'isolated', probeIsolation: () => true }), + plugins: { scim: true, organization: true }, + } as never); + const { token } = await mintScimConnectionCredential(engine as never, SECRET, { + connectionId: CONNECTION, + organizationId: ORG, + }); + const { token: otherToken } = await mintScimConnectionCredential(engine as never, SECRET, { + connectionId: OTHER_CONNECTION, + organizationId: ORG, + }); + return { engine, token, otherToken, send: (request) => manager.handleRequest(request) }; +} + +function scimRequest(token: string, method: string, path: string, body?: unknown): Request { + return new Request(`${AUTH}/scim/v2${path}`, { + method, + headers: { + origin: BASE, + authorization: `Bearer ${token}`, + ...(body !== undefined ? { 'content-type': 'application/scim+json' } : {}), + }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }); +} + +type Manager = { value?: string; $ref?: string }; + +/** A create in Entra ID's shape, with the Enterprise extension when a manager is given. */ +function userBody(local: string, manager?: Manager) { + const email = `${local}@acme.com`; + return { + schemas: manager ? [USER_SCHEMA, SCIM_ENTERPRISE_USER_SCHEMA] : [USER_SCHEMA], + userName: email, + externalId: `ext-${local}`, + name: { givenName: local, familyName: 'Test' }, + displayName: `${local} Test`, + emails: [{ value: email, type: 'work', primary: true }], + active: true, + ...(manager ? { [SCIM_ENTERPRISE_USER_SCHEMA]: { manager } } : {}), + }; +} + +interface Provisioned { + scimId: string; + userId: string; +} + +async function provision(h: Harness, local: string, manager?: Manager, token = h.token): Promise { + const res = await h.send(scimRequest(token, 'POST', '/Users', userBody(local, manager))); + expect(res.status, `create ${local} failed: ${await res.clone().text()}`).toBe(201); + const { id } = (await res.json()) as { id: string }; + return { scimId: id, userId: await userIdOf(h, `${local}@acme.com`) }; +} + +async function userIdOf(h: Harness, email: string): Promise { + const rows = (await h.engine.find('sys_user', { where: { email }, fields: ['id'] }, SYSTEM)) as Array<{ id: string }>; + expect(rows).toHaveLength(1); + return rows[0].id; +} + +async function managerOf(h: Harness, userId: string): Promise { + const row = (await h.engine.findOne('sys_user', { where: { id: userId }, fields: ['manager_id'] }, SYSTEM)) as { + manager_id?: string | null; + }; + return row?.manager_id ?? null; +} + +function patch(operations: unknown[]) { + return { schemas: [PATCH_SCHEMA], Operations: operations }; +} + +/** RFC 7644 §3.12: the error the identity provider reads, 400 `invalidValue`. */ +async function expectInvalidValue(res: Response, detail: RegExp): Promise { + const text = await res.text(); + expect(res.status, `expected 400 invalidValue, got ${res.status} ${text}`).toBe(400); + const body = JSON.parse(text) as { schemas?: string[]; status?: string; scimType?: string; detail?: string }; + expect(body.schemas).toEqual([ERROR_SCHEMA]); + expect(body.status).toBe('400'); + expect(body.scimType).toBe('invalidValue'); + expect(body.detail).toMatch(detail); +} + +describe('SCIM manager projection: the directory sets, changes and clears sys_user.manager_id', () => { + it('a create carrying manager.value (the manager\'s SCIM id) links the user to that manager', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const emp = await provision(h, 'emp', { value: boss.scimId }); + expect(await managerOf(h, emp.userId)).toBe(boss.userId); + }); + + it('a $ref alone is read by its /Users/{id} segment', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const emp = await provision(h, 'emp', { $ref: `${AUTH}/scim/v2/Users/${boss.scimId}` }); + expect(await managerOf(h, emp.userId)).toBe(boss.userId); + }); + + it('a replace changes the manager, and a replace without the attribute clears it', async () => { + const h = await boot(); + const first = await provision(h, 'first'); + const second = await provision(h, 'second'); + const emp = await provision(h, 'emp', { value: first.scimId }); + + const changed = await h.send(scimRequest(h.token, 'PUT', `/Users/${emp.scimId}`, userBody('emp', { value: second.scimId }))); + expect(changed.status, await changed.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBe(second.userId); + + const cleared = await h.send(scimRequest(h.token, 'PUT', `/Users/${emp.scimId}`, userBody('emp'))); + expect(cleared.status, await cleared.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBeNull(); + }); + + it('a PATCH replace sets it, and a PATCH remove clears it', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const emp = await provision(h, 'emp'); + expect(await managerOf(h, emp.userId)).toBeNull(); + + const set = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: boss.scimId } }, + ]))); + expect(set.status, await set.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBe(boss.userId); + + const removed = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'remove', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager` }, + ]))); + expect(removed.status, await removed.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBeNull(); + }); + + it('a deprovision is never refused over a manager reference that no longer resolves', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const emp = await provision(h, 'emp', { value: boss.scimId }); + const gone = await h.send(scimRequest(h.token, 'DELETE', `/Users/${boss.scimId}`)); + expect(gone.status, await gone.clone().text()).toBe(204); + + const deactivated = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: 'active', value: false }, + ]))); + expect(deactivated.status, await deactivated.clone().text()).toBe(200); + }); +}); + +describe('SCIM manager projection: a reference that names no known User is refused, never dropped', () => { + it('an unknown manager.value refuses the create, and nothing of it is written', async () => { + const h = await boot(); + const res = await h.send(scimRequest(h.token, 'POST', '/Users', userBody('emp', { value: 'no-such-scim-id' }))); + await expectInvalidValue(res, /names no User this connection provisioned/); + expect(await h.engine.find('sys_user', { where: { email: 'emp@acme.com' }, fields: ['id'] }, SYSTEM)).toEqual([]); + expect(await h.engine.find('sys_scim_user', { where: { user_name: 'emp@acme.com' }, fields: ['id'] }, SYSTEM)).toEqual([]); + }); + + it('the manager\'s externalId is not a SCIM resource id, so it is refused too', async () => { + const h = await boot(); + await provision(h, 'boss'); + const res = await h.send(scimRequest(h.token, 'POST', '/Users', userBody('emp', { value: 'ext-boss' }))); + await expectInvalidValue(res, /names no User this connection provisioned/); + }); + + it('another connection\'s resource id is refused: an id means something only to the connection that issued it', async () => { + const h = await boot(); + const boss = await provision(h, 'boss', undefined, h.otherToken); + const res = await h.send(scimRequest(h.token, 'POST', '/Users', userBody('emp', { value: boss.scimId }))); + await expectInvalidValue(res, /names no User this connection provisioned/); + }); + + it('a PATCH to an unknown manager keeps the manager the user had', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const emp = await provision(h, 'emp', { value: boss.scimId }); + const res = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: 'no-such-scim-id' } }, + ]))); + await expectInvalidValue(res, /names no User this connection provisioned/); + expect(await managerOf(h, emp.userId)).toBe(boss.userId); + }); +}); + +describe('SCIM manager projection: the admin endpoint\'s four refusals, answered as SCIM errors', () => { + it('self-assignment', async () => { + const h = await boot(); + const emp = await provision(h, 'emp'); + const res = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: emp.scimId } }, + ]))); + await expectInvalidValue(res, /cannot be their own manager/); + expect(await managerOf(h, emp.userId)).toBeNull(); + }); + + it('a cycle', async () => { + const h = await boot(); + const a = await provision(h, 'a'); + const b = await provision(h, 'b', { value: a.scimId }); + const res = await h.send(scimRequest(h.token, 'PATCH', `/Users/${a.scimId}`, patch([ + { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: b.scimId } }, + ]))); + await expectInvalidValue(res, /close a loop/); + expect(await managerOf(h, a.userId)).toBeNull(); + expect(await managerOf(h, b.userId)).toBe(a.userId); + }); + + it('the depth cap', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + // MAX_MANAGER_CHAIN_DEPTH links already run above the boss, so one more edge is past the cap. + let below = boss.userId; + for (let i = 0; i < MAX_MANAGER_CHAIN_DEPTH; i += 1) { + const id = `usr_chain_${i}`; + await h.engine.insert('sys_user', { id, email: `chain${i}@acme.com`, name: `Chain ${i}`, email_verified: true }, SYSTEM); + await h.engine.update('sys_user', { id: below, manager_id: id }, SYSTEM); + below = id; + } + const res = await h.send(scimRequest(h.token, 'POST', '/Users', userBody('emp', { value: boss.scimId }))); + await expectInvalidValue(res, new RegExp(`maximum of ${MAX_MANAGER_CHAIN_DEPTH} links`)); + expect(await h.engine.find('sys_user', { where: { email: 'emp@acme.com' }, fields: ['id'] }, SYSTEM)).toEqual([]); + }); + + it('a manager provably outside the user\'s organizations', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const emp = await provision(h, 'emp'); + await h.engine.insert('sys_member', { id: 'mem_emp', user_id: emp.userId, organization_id: ORG, role: 'member' }, SYSTEM); + await h.engine.insert('sys_member', { id: 'mem_boss', user_id: boss.userId, organization_id: OTHER_ORG, role: 'member' }, SYSTEM); + const res = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: boss.scimId } }, + ]))); + await expectInvalidValue(res, /none of them an organization this user belongs to/); + expect(await managerOf(h, emp.userId)).toBeNull(); + }); +}); + +describe('readScimManagerReference', () => { + it('reads value first, then the $ref segment, and names an unreadable $ref', () => { + const attrs = (manager: unknown) => JSON.stringify({ enterprise: { manager } }); + expect(readScimManagerReference(undefined)).toEqual({ kind: 'none' }); + expect(readScimManagerReference(JSON.stringify({ schemas: [USER_SCHEMA] }))).toEqual({ kind: 'none' }); + expect(readScimManagerReference(attrs({ value: 'v1', $ref: 'https://x/Users/r1' }))).toEqual({ kind: 'id', id: 'v1' }); + expect(readScimManagerReference(attrs({ $ref: 'https://x/scim/v2/Users/r%201' }))).toEqual({ kind: 'id', id: 'r 1' }); + expect(readScimManagerReference(attrs({ $ref: 'https://x/people/r1' }))).toEqual({ kind: 'unreadable', ref: 'https://x/people/r1' }); + }); +}); From 22baa5ef290fe84c81252da3c6a7085c63be4dda Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:38:03 +0000 Subject: [PATCH 03/20] test(plugin-auth): pin the SCIM manager projection end to end Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../src/scim-manager-projection.test.ts | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts index 0b74552c8a0..5e011904829 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts @@ -56,6 +56,33 @@ const CONNECTION = 'entra-scim-mgr'; const OTHER_CONNECTION = 'okta-scim-mgr'; const DEFAULT_ORG = 'org_default'; +// The grant tables a SCIM deployment registers beside the identity objects; +// the last-administrator guard reads them on every user update. +const sysPermissionSet = { + name: 'sys_permission_set', + label: 'Permission Set', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + name: { name: 'name', type: 'text' as const }, + label: { name: 'label', type: 'text' as const }, + active: { name: 'active', type: 'boolean' as const }, + }, +}; + +const sysUserPermissionSet = { + name: 'sys_user_permission_set', + label: 'User Permission Set', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + user_id: { name: 'user_id', type: 'text' as const }, + permission_set_id: { name: 'permission_set_id', type: 'text' as const }, + permission_set: { name: 'permission_set', type: 'text' as const }, + organization_id: { name: 'organization_id', type: 'text' as const }, + valid_from: { name: 'valid_from', type: 'datetime' as const }, + valid_until: { name: 'valid_until', type: 'datetime' as const }, + }, +}; + async function bootEngine(): Promise { const engine = new ObjectQL(); const driver = new SqlDriver({ @@ -65,7 +92,7 @@ async function bootEngine(): Promise { }); engine.registerDriver(driver, true); await engine.init(); - for (const object of authIdentityObjects) { + for (const object of [...authIdentityObjects, sysPermissionSet, sysUserPermissionSet]) { engine.registry.registerObject(object as never, '@objectstack/plugin-auth'); } await engine.syncSchemas(); From df5795f00c47e5928956acf26a989fd020f76070 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:40:35 +0000 Subject: [PATCH 04/20] test(plugin-auth): pin that an unchanged SCIM manager is not judged again Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../src/scim-manager-projection.test.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts index 5e011904829..40d6fd1cc6f 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts @@ -253,6 +253,24 @@ describe('SCIM manager projection: the directory sets, changes and clears sys_us expect(await managerOf(h, emp.userId)).toBeNull(); }); + it('an unchanged manager is not judged again: a PATCH elsewhere is served though the chain above grew past the cap', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const emp = await provision(h, 'emp', { value: boss.scimId }); + let below = boss.userId; + for (let i = 0; i < MAX_MANAGER_CHAIN_DEPTH; i += 1) { + const id = `usr_above_${i}`; + await h.engine.insert('sys_user', { id, email: `above${i}@acme.com`, name: `Above ${i}`, email_verified: true }, SYSTEM); + await h.engine.update('sys_user', { id: below, manager_id: id }, SYSTEM); + below = id; + } + const renamed = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: 'displayName', value: 'Emp Renamed' }, + ]))); + expect(renamed.status, await renamed.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBe(boss.userId); + }); + it('a deprovision is never refused over a manager reference that no longer resolves', async () => { const h = await boot(); const boss = await provision(h, 'boss'); From 6b34a6b4e82c69ee0c96781ac09a27142ab1e4b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:42:21 +0000 Subject: [PATCH 05/20] chore: changesets for the SCIM manager projection Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .changeset/33918-lint-scim-manager-route.md | 10 ++++++++++ .changeset/33918-scim-manager-projection.md | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 .changeset/33918-lint-scim-manager-route.md create mode 100644 .changeset/33918-scim-manager-projection.md diff --git a/.changeset/33918-lint-scim-manager-route.md b/.changeset/33918-lint-scim-manager-route.md new file mode 100644 index 00000000000..7ba7913840f --- /dev/null +++ b/.changeset/33918-lint-scim-manager-route.md @@ -0,0 +1,10 @@ +--- +'@objectstack/lint': patch +--- + +docs(lint): `os explain approval-approvers-may-resolve-empty` names SCIM as a route that populates `sys_user.manager_id` + +Clause-②: yes (widening). A SCIM request whose `manager` is ignored today starts writing `manager_id`. A manager value naming no known user is answered as a SCIM error. The dev measures this again before the PR, including whether any request served today becomes refused. +Metadata-protocol: none + +The `manager` arm's remedy said the platform declares the SCIM `manager` attribute without projecting it onto the column. plugin-auth now projects it, so the remedy says that the Enterprise User `manager` attribute, whose value is the manager's SCIM resource id, is written onto the column on every SCIM create, replace and patch through the admin operation's refusals, and that an id naming no user the connection provisioned is refused. Any other directory sync is still named as something your own deployment supplies. diff --git a/.changeset/33918-scim-manager-projection.md b/.changeset/33918-scim-manager-projection.md new file mode 100644 index 00000000000..2c0714d8bf9 --- /dev/null +++ b/.changeset/33918-scim-manager-projection.md @@ -0,0 +1,18 @@ +--- +'@objectstack/plugin-auth': patch +--- + +feat(plugin-auth): a SCIM directory sets, changes and clears a user's manager through the Enterprise User `manager` attribute + +Clause-②: yes (widening). A SCIM request whose `manager` is ignored today starts writing `manager_id`. A manager value naming no known user is answered as a SCIM error. The dev measures this again before the PR, including whether any request served today becomes refused. +Metadata-protocol: none + +`POST /api/v1/auth/admin/set-user-manager` refuses a person a SCIM directory holds and says to change the manager in the directory, but nothing carried the directory's answer to `sys_user.manager_id`: `@better-auth/scim` stored and echoed `urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:manager` and wrote nothing of it onto the user. So a SCIM-held user's manager could not change from either side, and approvals routed to the manager could not follow a reorganisation. + +A SCIM create, replace or patch now projects `manager.value` onto `sys_user.manager_id`, inside the SCIM transaction. `manager.value` is the manager's SCIM resource `id` (RFC 7643 §4.3), looked up among the Users the same connection provisioned; a `$ref` alone is read by its final `/Users/{id}` segment. The link goes through the admin endpoint's own refusals: self-assignment, a cycle, the 20-link depth cap and a manager provably outside the user's organizations. A reference that names no User the connection provisioned is refused too. Each refusal is a SCIM `400` with `scimType: invalidValue`, and nothing of the request is written. Removing the attribute (a PATCH `remove`, or a replace without it) clears `manager_id`. + +The projection follows the user's profile source (the one whose name and email the user carries), runs only on an active user, and judges a manager only when it changes, so a deprovision or an unrelated update is never refused over the org chart. + +Requests accepted before and refused now: a create, replace or patch whose `manager.value` is not the SCIM id of a User this connection provisioned (an `externalId`, an email, a value from another connection, or a manager not provisioned yet), and one whose manager would be the user themself, close a cycle, pass the depth cap or cross an organization. They used to answer `201`/`200` and leave `manager_id` untouched. + +The `idp_provisioned` stamp (ADR-0135 D4) is unchanged. From a5f9766a3aac1f7f619b99b7f740b87bda8e4e8a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:57:34 +0000 Subject: [PATCH 06/20] fix(plugin-auth): carry the refusal's ADR-0112 code on the SCIM manager error Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../src/scim-manager-projection.test.ts | 21 ++++++++++--------- .../src/scim-manager-projection.ts | 19 ++++++++++++----- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts index 40d6fd1cc6f..60001d7d5e4 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts @@ -194,13 +194,14 @@ function patch(operations: unknown[]) { } /** RFC 7644 §3.12: the error the identity provider reads, 400 `invalidValue`. */ -async function expectInvalidValue(res: Response, detail: RegExp): Promise { +async function expectInvalidValue(res: Response, code: string, detail: RegExp): Promise { const text = await res.text(); expect(res.status, `expected 400 invalidValue, got ${res.status} ${text}`).toBe(400); - const body = JSON.parse(text) as { schemas?: string[]; status?: string; scimType?: string; detail?: string }; + const body = JSON.parse(text) as { schemas?: string[]; status?: string; scimType?: string; code?: string; detail?: string }; expect(body.schemas).toEqual([ERROR_SCHEMA]); expect(body.status).toBe('400'); expect(body.scimType).toBe('invalidValue'); + expect(body.code).toBe(code); expect(body.detail).toMatch(detail); } @@ -289,7 +290,7 @@ describe('SCIM manager projection: a reference that names no known User is refus it('an unknown manager.value refuses the create, and nothing of it is written', async () => { const h = await boot(); const res = await h.send(scimRequest(h.token, 'POST', '/Users', userBody('emp', { value: 'no-such-scim-id' }))); - await expectInvalidValue(res, /names no User this connection provisioned/); + await expectInvalidValue(res, 'INVALID_REFERENCE', /names no User this connection provisioned/); expect(await h.engine.find('sys_user', { where: { email: 'emp@acme.com' }, fields: ['id'] }, SYSTEM)).toEqual([]); expect(await h.engine.find('sys_scim_user', { where: { user_name: 'emp@acme.com' }, fields: ['id'] }, SYSTEM)).toEqual([]); }); @@ -298,14 +299,14 @@ describe('SCIM manager projection: a reference that names no known User is refus const h = await boot(); await provision(h, 'boss'); const res = await h.send(scimRequest(h.token, 'POST', '/Users', userBody('emp', { value: 'ext-boss' }))); - await expectInvalidValue(res, /names no User this connection provisioned/); + await expectInvalidValue(res, 'INVALID_REFERENCE', /names no User this connection provisioned/); }); it('another connection\'s resource id is refused: an id means something only to the connection that issued it', async () => { const h = await boot(); const boss = await provision(h, 'boss', undefined, h.otherToken); const res = await h.send(scimRequest(h.token, 'POST', '/Users', userBody('emp', { value: boss.scimId }))); - await expectInvalidValue(res, /names no User this connection provisioned/); + await expectInvalidValue(res, 'INVALID_REFERENCE', /names no User this connection provisioned/); }); it('a PATCH to an unknown manager keeps the manager the user had', async () => { @@ -315,7 +316,7 @@ describe('SCIM manager projection: a reference that names no known User is refus const res = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: 'no-such-scim-id' } }, ]))); - await expectInvalidValue(res, /names no User this connection provisioned/); + await expectInvalidValue(res, 'INVALID_REFERENCE', /names no User this connection provisioned/); expect(await managerOf(h, emp.userId)).toBe(boss.userId); }); }); @@ -327,7 +328,7 @@ describe('SCIM manager projection: the admin endpoint\'s four refusals, answered const res = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: emp.scimId } }, ]))); - await expectInvalidValue(res, /cannot be their own manager/); + await expectInvalidValue(res, 'INVALID_FIELD', /cannot be their own manager/); expect(await managerOf(h, emp.userId)).toBeNull(); }); @@ -338,7 +339,7 @@ describe('SCIM manager projection: the admin endpoint\'s four refusals, answered const res = await h.send(scimRequest(h.token, 'PATCH', `/Users/${a.scimId}`, patch([ { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: b.scimId } }, ]))); - await expectInvalidValue(res, /close a loop/); + await expectInvalidValue(res, 'RESOURCE_CONFLICT', /close a loop/); expect(await managerOf(h, a.userId)).toBeNull(); expect(await managerOf(h, b.userId)).toBe(a.userId); }); @@ -355,7 +356,7 @@ describe('SCIM manager projection: the admin endpoint\'s four refusals, answered below = id; } const res = await h.send(scimRequest(h.token, 'POST', '/Users', userBody('emp', { value: boss.scimId }))); - await expectInvalidValue(res, new RegExp(`maximum of ${MAX_MANAGER_CHAIN_DEPTH} links`)); + await expectInvalidValue(res, 'VALUE_OUT_OF_RANGE', new RegExp(`maximum of ${MAX_MANAGER_CHAIN_DEPTH} links`)); expect(await h.engine.find('sys_user', { where: { email: 'emp@acme.com' }, fields: ['id'] }, SYSTEM)).toEqual([]); }); @@ -368,7 +369,7 @@ describe('SCIM manager projection: the admin endpoint\'s four refusals, answered const res = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: boss.scimId } }, ]))); - await expectInvalidValue(res, /none of them an organization this user belongs to/); + await expectInvalidValue(res, 'INVALID_REFERENCE', /none of them an organization this user belongs to/); expect(await managerOf(h, emp.userId)).toBeNull(); }); }); diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.ts index 725be2dedbc..292d416e4e3 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.ts @@ -64,8 +64,8 @@ * {@link screenUserManagerLink} (self-assignment, cycle, depth cap, * cross-organization), imported: one derivation, never a copy. Each is a SCIM * error in RFC 7644 §3.12 shape: status 400, `scimType: invalidValue` — the - * vendor's own answer to a value it refuses — and the refusal's sentence as - * `detail`. The refusal ledger (`scim-refusal-audit.ts`) records it like any + * vendor's own answer to a value it refuses — the refusal's sentence as + * `detail`, and the admin endpoint's ADR-0112 `code` for the same refusal. The refusal ledger (`scim-refusal-audit.ts`) records it like any * other SCIM refusal. A cleared or absent attribute clears the column. */ @@ -117,13 +117,20 @@ export function readScimManagerReference(serializedAttributes: unknown): ScimMan return { kind: 'none' }; } -/** A SCIM 400 `invalidValue` error, built the way the vendor builds its own. */ -async function scimInvalidValue(detail: string): Promise { +/** + * A SCIM 400 `invalidValue` error, in the body the vendor builds its own in + * (RFC 7644 §3.12), plus the ADR-0112 `code` of the refusal it carries — the + * admin endpoint's code for the same refusal — which the refusal ledger + * records beside the `scimType`. A body already in SCIM shape passes the + * vendor's after-hook unchanged. + */ +async function scimInvalidValue(code: string, detail: string): Promise { const { APIError } = await import('better-auth/api'); const error = new APIError('BAD_REQUEST', { schemas: [SCIM_ERROR_SCHEMA], status: '400', scimType: 'invalidValue', + code, detail, } as never); error.message = detail; @@ -159,6 +166,7 @@ export async function projectScimManager( const reference = readScimManagerReference(source.serializedAttributes); if (reference.kind === 'unreadable') { throw await scimInvalidValue( + 'INVALID_REFERENCE', `${SCIM_ENTERPRISE_USER_SCHEMA}:manager names no User: its $ref '${reference.ref}' does not end in ` + `/Users/{id}, and it carries no value. Send the manager's SCIM resource id as manager.value.`, ); @@ -175,6 +183,7 @@ export async function projectScimManager( }); if (!managerSource || !text(managerSource.userId)) { throw await scimInvalidValue( + 'INVALID_REFERENCE', `${SCIM_ENTERPRISE_USER_SCHEMA}:manager.value '${reference.id}' names no User this connection ` + `provisioned. manager.value is the manager's SCIM resource id (the id this service returned when ` + `the manager was created), not an externalId, userName or email. Provision the manager first, or ` @@ -201,7 +210,7 @@ export async function projectScimManager( if (managerId !== null) { const refusal = await screenUserManagerLink(deps, engine, state.userId, managerId); - if (refusal) throw await scimInvalidValue(refusal.message); + if (refusal) throw await scimInvalidValue(refusal.code, refusal.message); } // Attributed to the connection (`svc:scim:CONNECTION_ID`) inside a SCIM From 64633dbd45fd2009d32b4c770efa7fb423c62e9e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 02:00:48 +0000 Subject: [PATCH 07/20] fix(plugin-auth): keep the SCIM error body a literal the code pin reads Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- packages/plugins/plugin-auth/src/scim-manager-projection.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.ts index 292d416e4e3..2717b555ae0 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.ts @@ -132,7 +132,7 @@ async function scimInvalidValue(code: string, detail: string): Promise { scimType: 'invalidValue', code, detail, - } as never); + }); error.message = detail; return error; } From bec3326d5fec0554c455badbaabe535c27bc8e61 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 02:39:47 +0000 Subject: [PATCH 08/20] refactor(plugin-auth): one shared write of sys_user.manager_id for the admin door and the SCIM projection Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../plugin-auth/src/admin-set-user-manager.ts | 27 ++++++++++++++----- .../src/scim-manager-projection.ts | 5 ++-- 2 files changed, 22 insertions(+), 10 deletions(-) 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 8f0b4f57905..ead97d8e17b 100644 --- a/packages/plugins/plugin-auth/src/admin-set-user-manager.ts +++ b/packages/plugins/plugin-auth/src/admin-set-user-manager.ts @@ -654,13 +654,26 @@ export async function applyUserManagerLink( if (screened) return screened; } - // The write. `authSystemWriteContext()` builds both halves together: - // `isSystem: true` is the AUTHORIZATION half that carries this past the - // ADR-0092 identity write guard without any whitelist entry, and - // `attributedUserId` is the ATTRIBUTION half, so the row records the admin - // who made the change rather than the system. + await writeUserManagerLink(engine, userId, managerId); + return null; +} + +/** + * The one write of `sys_user.manager_id`, shared by every caller that has + * already judged the link: {@link applyUserManagerLink} and the SCIM manager + * projection (`scim-manager-projection.ts`). + * + * `authSystemWriteContext()` builds both halves together: `isSystem: true` is + * the AUTHORIZATION half that carries this past the ADR-0092 identity write + * guard without any whitelist entry, and `attributedUserId` is the ATTRIBUTION + * half, so the row records the admin who made the change (or, inside a SCIM + * request, the connection) rather than the system. + */ +export async function writeUserManagerLink( + engine: SetUserManagerEngine, + userId: string, + managerId: string | null, +): Promise { const context = await authSystemWriteContext(); await engine.update('sys_user', { id: userId, manager_id: managerId }, { context }); - - return null; } diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.ts index 2717b555ae0..ed576f45bba 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.ts @@ -70,8 +70,7 @@ */ import type { SCIMIdentityState, SCIMTransactionContext } from '@better-auth/scim'; -import { authSystemWriteContext } from './auth-actor-attribution.js'; -import { screenUserManagerLink, type SetUserManagerDeps } from './admin-set-user-manager.js'; +import { screenUserManagerLink, writeUserManagerLink, type SetUserManagerDeps } from './admin-set-user-manager.js'; import { scimRequestConnectionId } from './scim-connection-service.js'; /** The SCIM Enterprise User extension the attribute lives in. */ @@ -215,5 +214,5 @@ export async function projectScimManager( // Attributed to the connection (`svc:scim:CONNECTION_ID`) inside a SCIM // request, and joined to its transaction. - await engine.update('sys_user', { id: state.userId, manager_id: managerId }, { context: await authSystemWriteContext() }); + await writeUserManagerLink(engine, state.userId, managerId); } From 585cf6ead0b19b941abed5ec9d2851c681a16917 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:09:12 +0000 Subject: [PATCH 09/20] feat(plugin-auth)!: serve an unresolvable SCIM manager reference, project only on directory-owned identities and on writes that name the attribute An unresolvable manager reference (unknown id, externalId-style value, another connection's id, unreadable $ref) no longer refuses the SCIM user write: the write lands, manager_id stays, and one bounded operator warn names the connection. The four structural refusals stay SCIM 400 invalidValue. A write that does not name the attribute leaves manager_id alone, and the projection writes only on identities the directory owns, read through the one predicate the admin endpoint's directory refusal reads. Lint explanation, docs and changesets follow the rule; both changesets declare the narrowing. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .changeset/33918-lint-scim-manager-route.md | 10 +- .changeset/33918-scim-manager-projection.md | 23 +- content/docs/automation/approvals.mdx | 18 +- content/docs/capabilities/approvals.mdx | 5 +- packages/lint/src/rule-explanations.ts | 14 +- .../src/validate-approval-approvers.test.ts | 2 +- .../lint/src/validate-approval-approvers.ts | 20 +- .../plugin-auth/src/admin-set-user-manager.ts | 25 +- .../src/auth-manager-plugin-list.ts | 12 +- .../src/auth-manager-request-routing.ts | 7 + .../src/scim-connection-service.ts | 10 + .../src/scim-manager-projection.test.ts | 280 +++++++++++++-- .../src/scim-manager-projection.ts | 323 ++++++++++++------ 13 files changed, 592 insertions(+), 157 deletions(-) diff --git a/.changeset/33918-lint-scim-manager-route.md b/.changeset/33918-lint-scim-manager-route.md index 7ba7913840f..809f4db94d5 100644 --- a/.changeset/33918-lint-scim-manager-route.md +++ b/.changeset/33918-lint-scim-manager-route.md @@ -2,9 +2,13 @@ '@objectstack/lint': patch --- -docs(lint): `os explain approval-approvers-may-resolve-empty` names SCIM as a route that populates `sys_user.manager_id` +docs(lint)!: `os explain approval-approvers-may-resolve-empty` names SCIM as a route that populates `sys_user.manager_id` -Clause-②: yes (widening). A SCIM request whose `manager` is ignored today starts writing `manager_id`. A manager value naming no known user is answered as a SCIM error. The dev measures this again before the PR, including whether any request served today becomes refused. +Clause-②: yes (narrowing) Metadata-protocol: none -The `manager` arm's remedy said the platform declares the SCIM `manager` attribute without projecting it onto the column. plugin-auth now projects it, so the remedy says that the Enterprise User `manager` attribute, whose value is the manager's SCIM resource id, is written onto the column on every SCIM create, replace and patch through the admin operation's refusals, and that an id naming no user the connection provisioned is refused. Any other directory sync is still named as something your own deployment supplies. + + +**BREAKING** in the behaviour this text now describes, not in the lint package: a SCIM user write whose named manager would make the user their own manager, close a cycle, run past the depth cap or cross an organization boundary was served before and is now refused with SCIM `400 invalidValue` (plugin-auth's note has the details). The lint rule and its findings are unchanged. + +The `manager` arm's remedy said the platform declares the SCIM `manager` attribute without projecting it onto the column. plugin-auth now projects it, so the remedy says that the Enterprise User `manager` attribute, whose value is the manager's SCIM resource id, is written onto the column for an active user a SCIM directory holds, from the connection that provisioned that user's profile, on a create, replace or patch that names the attribute, through the admin operation's refusals. A write that does not name it leaves the column as it is, and an id naming no user the connection provisioned is served with the column unchanged. Any other directory sync is still named as something your own deployment supplies. diff --git a/.changeset/33918-scim-manager-projection.md b/.changeset/33918-scim-manager-projection.md index 2c0714d8bf9..39d7ed6d741 100644 --- a/.changeset/33918-scim-manager-projection.md +++ b/.changeset/33918-scim-manager-projection.md @@ -2,17 +2,28 @@ '@objectstack/plugin-auth': patch --- -feat(plugin-auth): a SCIM directory sets, changes and clears a user's manager through the Enterprise User `manager` attribute +feat(plugin-auth)!: a SCIM directory sets, changes and clears a user's manager through the Enterprise User `manager` attribute -Clause-②: yes (widening). A SCIM request whose `manager` is ignored today starts writing `manager_id`. A manager value naming no known user is answered as a SCIM error. The dev measures this again before the PR, including whether any request served today becomes refused. +Clause-②: yes (narrowing) Metadata-protocol: none -`POST /api/v1/auth/admin/set-user-manager` refuses a person a SCIM directory holds and says to change the manager in the directory, but nothing carried the directory's answer to `sys_user.manager_id`: `@better-auth/scim` stored and echoed `urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:manager` and wrote nothing of it onto the user. So a SCIM-held user's manager could not change from either side, and approvals routed to the manager could not follow a reorganisation. + -A SCIM create, replace or patch now projects `manager.value` onto `sys_user.manager_id`, inside the SCIM transaction. `manager.value` is the manager's SCIM resource `id` (RFC 7643 §4.3), looked up among the Users the same connection provisioned; a `$ref` alone is read by its final `/Users/{id}` segment. The link goes through the admin endpoint's own refusals: self-assignment, a cycle, the 20-link depth cap and a manager provably outside the user's organizations. A reference that names no User the connection provisioned is refused too. Each refusal is a SCIM `400` with `scimType: invalidValue`, and nothing of the request is written. Removing the attribute (a PATCH `remove`, or a replace without it) clears `manager_id`. +**BREAKING** for a SCIM identity provider that sends a manager the admin endpoint would refuse. A SCIM create, replace or patch that names the Enterprise User `manager` attribute, for an active user the directory holds, whose manager resolves to a User the same connection provisioned, and where that link would make the user their own manager, close a cycle, run past the 20-link depth cap, or cross an organization boundary, used to answer `201` / `200` and leave `manager_id` untouched. It now answers SCIM `400` with `scimType: invalidValue` and the admin endpoint's reason, and nothing of the request is written. Those four are the only requests served before and refused now. Remedy: correct the manager in the directory. -The projection follows the user's profile source (the one whose name and email the user carries), runs only on an active user, and judges a manager only when it changes, so a deprovision or an unrelated update is never refused over the org chart. +**The gap.** `POST /api/v1/auth/admin/set-user-manager` refuses a person a SCIM directory holds and says to change the manager in the directory, but nothing carried the directory's answer to `sys_user.manager_id`: `@better-auth/scim` stored and echoed `urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:manager` and wrote nothing of it onto the user. So a SCIM-held user's manager could not change from either side, and approvals routed to the manager could not follow a reorganisation. -Requests accepted before and refused now: a create, replace or patch whose `manager.value` is not the SCIM id of a User this connection provisioned (an `externalId`, an email, a value from another connection, or a manager not provisioned yet), and one whose manager would be the user themself, close a cycle, pass the depth cap or cross an organization. They used to answer `201`/`200` and leave `manager_id` untouched. +**The rule.** A SCIM user write that names the attribute now projects `manager.value` onto `sys_user.manager_id`, inside the SCIM transaction. `manager.value` is the manager's SCIM resource `id` (RFC 7643 §4.3), looked up among the Users the same connection provisioned; a `$ref` alone is read by its final `/Users/{id}` segment. The link goes through the admin endpoint's own refusals, above. + +- **Silence is not a clear.** A create or PATCH that does not name the attribute leaves `manager_id` as it is. An explicit PATCH `remove`, or a replace without the attribute, clears it. +- **One owner per identity.** The projection writes only on an identity whose manager the directory owns, which is exactly the set the admin endpoint refuses (one shared predicate). On any other identity, for example one holding a local password, the admin endpoint owns the column and the projection writes nothing. +- **A reference that names no User is served.** An unknown id, an `externalId` or email, another connection's id, or a `$ref` with no readable `/Users/{id}` segment does not fail the write: the user is saved, `manager_id` stays as it was, and the server logs one operator warning per connection per window, with the count it held back. +- **An unchanged manager is not judged again**, so a write is never refused over a chain other links have since reshaped, and a report whose manager was deleted keeps working. + +**Where it does not project, and why.** + +- Outside an authenticated SCIM request: the vendor also runs this step while it decommissions a connection or replays a provisioning domain. Neither is a write the directory made, and a decommission must never be refused over an org-chart reference. +- When the user's profile source belongs to another connection: that connection authors the user's name and email, so its manager is the one that counts, not this request's. +- For an inactive user: a deprovision is never refused over the org chart. A manager named while the user is inactive is not applied on re-activation alone; it lands on the next active write that names it. The `idp_provisioned` stamp (ADR-0135 D4) is unchanged. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 041d5596a71..80399ddcb05 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -98,13 +98,17 @@ file exists, through the same refusals as the endpoint above, and reports each o 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 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 +managed-update whitelist. SCIM provisioning populates it too: the Enterprise User `manager` +attribute, whose `value` is the manager's SCIM resource `id`, is written onto the column on a SCIM +create, replace or patch that names the attribute, through the same refusals (each answered as a +SCIM `400 invalidValue`). It is written only for an active user the directory holds, and only from +the connection that provisioned that user's profile. A write that does not name the attribute +leaves the column as it is; removing the attribute, or a replace without it, clears the column. An +id that names no user the connection provisioned does not fail the write: the user is saved, the +column stays as it was, and the server logs a warning for the operator. 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. +Any other directory sync writes it only through a path your own deployment supplies. 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. diff --git a/content/docs/capabilities/approvals.mdx b/content/docs/capabilities/approvals.mdx index b994c4a5fdf..c0e96d3d4c3 100644 --- a/content/docs/capabilities/approvals.mdx +++ b/content/docs/capabilities/approvals.mdx @@ -17,8 +17,9 @@ A specific person · everyone holding a position (e.g. sales managers) · the su admin sets it one user at a time from **Setup → Users → ⋯ → Set Manager**, which calls `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 +admin bulk-import endpoint reads a `manager_id` column, SCIM provisioning writes it from the +Enterprise User `manager` attribute, and a seed, or a 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 request opens and waits for an administrator. The details, and the fallback that needs no manager data at all, are in [Automation → Approvals](/docs/automation/approvals). diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 7d1cef535d5..70af38684e6 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -3333,12 +3333,14 @@ const MANAGER_ONLY_ROUTES = 'an existing user — and links each row once every row in the file exists, through those same ' + 'refusals; a link it cannot make is reported on that row\'s manager result and 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 populates it too: the ' + - 'Enterprise User \'manager\' attribute, whose value is the manager\'s SCIM resource id, is ' + - 'written onto the column on every SCIM create, replace and patch, through those same refusals, ' + - 'and an id that names no user the connection provisioned is refused — and 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. Any other directory sync ' + + 'write, which bypasses the managed-update whitelist. SCIM provisioning populates it too, for an ' + + 'active user a SCIM directory holds and only from the connection that provisioned that user\'s ' + + 'profile: the Enterprise User \'manager\' attribute, whose value is the manager\'s SCIM resource ' + + 'id, is written onto the column on a SCIM create, replace or patch that names the attribute, ' + + 'through those same refusals. A write that does not name it leaves the column as it is, and an ' + + 'id that names no user the connection provisioned is served and leaves the column unchanged. ' + + 'Where a SCIM directory holds an identity, the admin operation refuses it, the import\'s ' + + 'manager_id column included, leaving that directory the one surface that authors its manager. Any other directory sync ' + 'populates it only through a provisioning path your own deployment supplies. 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 ' + diff --git a/packages/lint/src/validate-approval-approvers.test.ts b/packages/lint/src/validate-approval-approvers.test.ts index ac6abb4f683..dc2dccf57ef 100644 --- a/packages/lint/src/validate-approval-approvers.test.ts +++ b/packages/lint/src/validate-approval-approvers.test.ts @@ -382,7 +382,7 @@ describe('unset-manager dead-end (#16748)', () => { // 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 populates it too'); - expect(remedy).toContain('where a SCIM directory holds an identity the admin operation refuses'); + expect(remedy).toContain('Where a SCIM directory holds an identity, the admin operation refuses it'); 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 diff --git a/packages/lint/src/validate-approval-approvers.ts b/packages/lint/src/validate-approval-approvers.ts index 26cacdfc61d..fe4a764969e 100644 --- a/packages/lint/src/validate-approval-approvers.ts +++ b/packages/lint/src/validate-approval-approvers.ts @@ -159,13 +159,19 @@ const STAYS_LOCKED = ', and (lockRecord) the record stays locked'; * here, 0 projection sites") went stale when the projection landed. * plugin-auth `scim-manager-projection.ts` carries the Enterprise User * `manager.value` — the manager's SCIM resource id among the Users the - * same connection provisioned (RFC 7643 §4.3) — onto the column on every - * SCIM create, replace and patch, inside the SCIM transaction, through - * the endpoint's own refusals (`screenUserManagerLink`: self-assignment, - * cycle, depth cap, cross-organization); a reference naming no User is a - * SCIM 400 `invalidValue`, never dropped, and a cleared or absent - * attribute clears the column. Measured by - * `scim-manager-projection.test.ts`, end to end through the vendor. + * same connection provisioned (RFC 7643 §4.3) — onto the column, inside + * the SCIM transaction, through the endpoint's own refusals + * (`screenUserManagerLink`: self-assignment, cycle, depth cap, + * cross-organization, each a SCIM 400 `invalidValue`). It runs only for + * an ACTIVE user whose manager the directory owns (the one predicate the + * endpoint's directory refusal reads), only from the connection that + * holds that user's profile source, and only on a create, replace or + * patch that NAMES the attribute: a write that does not name it leaves + * the column as it is, and an explicit remove (or a replace without it) + * clears it. A reference naming no User is served with the column left + * unchanged and a bounded operator warn (maintainer ruling record + * 6909383114). Measured by `scim-manager-projection.test.ts`, end to end + * through the vendor. * - Admin bulk import — AVAILABLE HERE, and the grade this block used to * give it ("NOT here") went stale when the import tier admitted the column. * `POST /api/v1/auth/admin/import-users` (`admin-import-users.ts`) reads a 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 ead97d8e17b..6de502c7052 100644 --- a/packages/plugins/plugin-auth/src/admin-set-user-manager.ts +++ b/packages/plugins/plugin-auth/src/admin-set-user-manager.ts @@ -291,6 +291,25 @@ async function heldByScimDirectory(engine: SetUserManagerEngine, userId: string) } } +/** + * WHO OWNS `sys_user.manager_id` for this identity — the one predicate both + * doors read (seat ruling 6907953084 on the L2 review, item b): a SCIM + * directory owns it when the identity reads `source: 'idp_provisioned'` AND + * a SCIM directory holds it ({@link isHeldByScimDirectory}). There the admin + * endpoint refuses (refusal 5) and the SCIM manager projection writes; + * everywhere else the admin endpoint writes and the projection writes + * nothing. One predicate, so neither door overwrites the other. + */ +async function directoryOwnsManagerOf(engine: SetUserManagerEngine, user: UserRow): Promise { + return String(user.source ?? '') === 'idp_provisioned' && await heldByScimDirectory(engine, String(user.id)); +} + +/** {@link directoryOwnsManagerOf}, by id: `false` for a user that does not exist. */ +export async function directoryOwnsUserManager(engine: SetUserManagerEngine, userId: string): Promise { + const user = await findUser(engine, userId); + return user ? directoryOwnsManagerOf(engine, user) : false; +} + /** * 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 @@ -449,8 +468,8 @@ async function deepestSubordinateChain( } /** - * Refusals 1 to 4 — self-assignment, the proposed manager's existence, - * cross-organization, cycle and depth — judged for ONE proposed link + * Refusals 1 to 4 — self-assignment, cross-organization, cycle and depth, + * plus the proposed manager's existence — judged for ONE proposed link * `userId -> managerId`, without writing anything. * * Split out of {@link applyUserManagerLink} for the one caller that must not @@ -639,7 +658,7 @@ export async function applyUserManagerLink( // 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)) { + if (await directoryOwnsManagerOf(engine, user)) { return deny( 403, 'PERMISSION_DENIED', diff --git a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts index 1167b335003..382f9719da4 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts @@ -847,7 +847,11 @@ export async function buildPluginList(this: PluginListHost): Promise { await import('./scim-connection-service.js'); const { createScimGroupProjection } = await import('./scim-group-projection.js'); const { createScimSsoAdoptionResolver } = await import('./scim-sso-adoption.js'); - const { projectScimManager } = await import('./scim-manager-projection.js'); + const { createScimManagerProjection } = await import('./scim-manager-projection.js'); + const projectScimManager = createScimManagerProjection({ + getDataEngine: () => this.getDataEngine() as never, + logger: this.config.logger as never, + }); const secret = this.resolveAuthSecret(); // [#32120] One stamper for this manager's SCIM plugin, so its // per-credential minute claims are shared by every request it verifies. @@ -918,11 +922,7 @@ export async function buildPluginList(this: PluginListHost): Promise { // the admin endpoint's own refusals. See `scim-manager-projection.ts`. reconcileUser: async (state, context) => { await this.reconcileScimUserLifecycle(state, context); - await projectScimManager( - { getDataEngine: () => this.getDataEngine() as never, logger: this.config.logger as never }, - state, - context, - ); + await projectScimManager(state, context); }, }, // [ADR-0134 D4, filled for permission sets] A pushed group grants the diff --git a/packages/plugins/plugin-auth/src/auth-manager-request-routing.ts b/packages/plugins/plugin-auth/src/auth-manager-request-routing.ts index 944e5a37b0b..96d96fe86da 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-request-routing.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-request-routing.ts @@ -286,6 +286,13 @@ export async function handleRequest(this: Pick => { const { scimRequestScope } = await import('./scim-connection-service.js'); const scope: ScimRequestScope = { scim: true }; + // Whether this user write names the Enterprise `manager` attribute, + // read off a clone before the vendor consumes the body: the manager + // projection writes only on a write that names it + // (`scim-manager-projection.ts`). + const { scimUserManagerIntentOf } = await import('./scim-manager-projection.js'); + const userManagerIntent = await scimUserManagerIntentOf(request, endpointPath); + if (userManagerIntent) scope.userManagerIntent = userManagerIntent; let scimResponse = await scimRequestScope.run(scope, runHandler); if (scimResponse.status === 409) { const { translateScimConflictDetail } = await import('./scim-conflict-detail.js'); diff --git a/packages/plugins/plugin-auth/src/scim-connection-service.ts b/packages/plugins/plugin-auth/src/scim-connection-service.ts index 5ef542e3ef2..f4a77d4db8f 100644 --- a/packages/plugins/plugin-auth/src/scim-connection-service.ts +++ b/packages/plugins/plugin-auth/src/scim-connection-service.ts @@ -119,6 +119,16 @@ export interface ScimRequestScope { * none or the row names no organization. */ organizationId?: string; + /** + * Whether this request NAMES the Enterprise User `manager` attribute, read + * off the request before the vendor runs (`scimUserManagerIntent`, + * `scim-manager-projection.ts`): `named` for a create or PATCH that carries + * or removes it and for every replace (a replace without it is a clear), + * `silent` for any other user write. The projection writes nothing on a + * silent one (seat ruling 6907953084 on the L2 review, item a). Absent + * outside a user create, replace or patch. + */ + userManagerIntent?: 'named' | 'silent'; } /** Is the current async chain inside an authenticated SCIM protocol request? */ diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts index 60001d7d5e4..5972eff1b5a 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts @@ -9,10 +9,14 @@ * only half the behaviour: the vendor's transaction decides whether a refused * reference leaves anything behind, and its after-hook decides the error body * the identity provider reads. Each refusal is a single-cause fixture, and - * each asserts the SCIM error AND that nothing changed. + * each asserts the SCIM error AND that nothing changed. An unresolvable + * reference is served (maintainer ruling record 6909383114): each shape + * asserts the write landed, the column did not move, and the operator warn. + * The two doors (this projection and the admin endpoint) read one ownership + * predicate (seat ruling record 6907953084), pinned from both sides. */ -import { describe, it, expect, afterEach, afterAll } from 'vitest'; +import { describe, it, expect, afterEach, afterAll, vi } from 'vitest'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { ADMIN_FULL_ACCESS } from '@objectstack/spec/identity'; @@ -23,8 +27,14 @@ import { mintScimConnectionCredential } from './scim-connection-service.js'; import { registerLastAdminGuard, type LastAdminGuardEngine } from './last-admin-guard.js'; import { registerIdentityWriteGuard, registerManagedUpdateWhitelist } from './identity-write-guard.js'; import { SYS_USER_PROFILE_EDIT_FIELDS } from './sys-user-writable-fields.js'; -import { MAX_MANAGER_CHAIN_DEPTH } from './admin-set-user-manager.js'; -import { readScimManagerReference, SCIM_ENTERPRISE_USER_SCHEMA } from './scim-manager-projection.js'; +import { MAX_MANAGER_CHAIN_DEPTH, applyUserManagerLink, directoryOwnsUserManager } from './admin-set-user-manager.js'; +import { + createScimManagerProjection, + readScimManagerReference, + scimBodyNamesManager, + SCIM_ENTERPRISE_USER_SCHEMA, +} from './scim-manager-projection.js'; +import { scimRequestScope } from './scim-connection-service.js'; import { bindTestSecurityCatalog } from './__tests__/security-catalog.testkit.js'; import { sqliteEnginePool, type BootedSqliteEngine } from './__tests__/sqlite-engine-pool.testkit.js'; // Clocked windows measure behaviour, never loading (AGENTS.md, Build & Test). @@ -113,14 +123,18 @@ interface Harness { token: string; otherToken: string; send: (request: Request) => Promise; + /** The operator warns the projection said about an unresolvable reference. */ + unresolvedWarns: () => string[]; } async function boot(): Promise { const engine = await enginePool.take(); + const warn = vi.fn(); const manager = new AuthManager({ secret: SECRET, baseUrl: BASE, dataEngine: engine as never, + logger: { info: vi.fn(), warn, error: vi.fn(), debug: vi.fn() }, getTenancy: () => createTenancyService({ requested: 'isolated', probeIsolation: () => true }), plugins: { scim: true, organization: true }, } as never); @@ -132,7 +146,10 @@ async function boot(): Promise { connectionId: OTHER_CONNECTION, organizationId: ORG, }); - return { engine, token, otherToken, send: (request) => manager.handleRequest(request) }; + const unresolvedWarns = () => warn.mock.calls + .map(([message]) => String(message)) + .filter((message) => message.includes('manager reference that names no User')); + return { engine, token, otherToken, send: (request) => manager.handleRequest(request), unresolvedWarns }; } function scimRequest(token: string, method: string, path: string, body?: unknown): Request { @@ -189,6 +206,19 @@ async function managerOf(h: Harness, userId: string): Promise { return row?.manager_id ?? null; } +/** The admin endpoint's door, on the harness engine. */ +function adminSetManager(h: Harness, userId: string, managerId: string | null) { + return applyUserManagerLink({ getDataEngine: () => h.engine as never }, userId, managerId); +} + +/** A local password: D4 keeps the user `env_native`, so no directory holds its manager. */ +async function giveLocalPassword(h: Harness, userId: string): Promise { + await h.engine.insert('sys_account', { + id: `acc_cred_${userId}`, provider_id: 'credential', account_id: userId, user_id: userId, + }, SYSTEM); + await h.engine.update('sys_user', { id: userId, source: 'env_native' }, SYSTEM); +} + function patch(operations: unknown[]) { return { schemas: [PATCH_SCHEMA], Operations: operations }; } @@ -286,39 +316,220 @@ describe('SCIM manager projection: the directory sets, changes and clears sys_us }); }); -describe('SCIM manager projection: a reference that names no known User is refused, never dropped', () => { - it('an unknown manager.value refuses the create, and nothing of it is written', async () => { +describe('SCIM manager projection: a reference that names no User is served, and the column stays', () => { + it('an unknown manager.value: the create lands, manager_id stays empty, and the operator is told', async () => { const h = await boot(); - const res = await h.send(scimRequest(h.token, 'POST', '/Users', userBody('emp', { value: 'no-such-scim-id' }))); - await expectInvalidValue(res, 'INVALID_REFERENCE', /names no User this connection provisioned/); - expect(await h.engine.find('sys_user', { where: { email: 'emp@acme.com' }, fields: ['id'] }, SYSTEM)).toEqual([]); - expect(await h.engine.find('sys_scim_user', { where: { user_name: 'emp@acme.com' }, fields: ['id'] }, SYSTEM)).toEqual([]); + const emp = await provision(h, 'emp', { value: 'no-such-scim-id' }); + expect(await managerOf(h, emp.userId)).toBeNull(); + const warns = h.unresolvedWarns(); + expect(warns).toHaveLength(1); + expect(warns[0]).toContain(`'${CONNECTION}'`); }); - it('the manager\'s externalId is not a SCIM resource id, so it is refused too', async () => { + it('the manager\'s externalId is not a SCIM resource id: served, nothing linked', async () => { const h = await boot(); await provision(h, 'boss'); - const res = await h.send(scimRequest(h.token, 'POST', '/Users', userBody('emp', { value: 'ext-boss' }))); - await expectInvalidValue(res, 'INVALID_REFERENCE', /names no User this connection provisioned/); + const emp = await provision(h, 'emp', { value: 'ext-boss' }); + expect(await managerOf(h, emp.userId)).toBeNull(); + expect(h.unresolvedWarns()).toHaveLength(1); }); - it('another connection\'s resource id is refused: an id means something only to the connection that issued it', async () => { + it('another connection\'s resource id means nothing to this one: served, nothing linked', async () => { const h = await boot(); const boss = await provision(h, 'boss', undefined, h.otherToken); - const res = await h.send(scimRequest(h.token, 'POST', '/Users', userBody('emp', { value: boss.scimId }))); - await expectInvalidValue(res, 'INVALID_REFERENCE', /names no User this connection provisioned/); + const emp = await provision(h, 'emp', { value: boss.scimId }); + expect(await managerOf(h, emp.userId)).toBeNull(); + expect(h.unresolvedWarns()).toHaveLength(1); + }); + + it('a $ref with no /Users/{id} segment, or one that does not decode, is served (not a 500)', async () => { + const h = await boot(); + const a = await provision(h, 'a', { $ref: 'https://idp.example/people/r1' }); + const b = await provision(h, 'b', { $ref: `${AUTH}/scim/v2/Users/%E0%A4%A` }); + expect(await managerOf(h, a.userId)).toBeNull(); + expect(await managerOf(h, b.userId)).toBeNull(); }); - it('a PATCH to an unknown manager keeps the manager the user had', async () => { + it('a PATCH to an unknown manager is served and keeps the manager the user had', async () => { const h = await boot(); const boss = await provision(h, 'boss'); const emp = await provision(h, 'emp', { value: boss.scimId }); const res = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: 'no-such-scim-id' } }, + { op: 'replace', path: 'displayName', value: 'Emp Renamed' }, + ]))); + expect(res.status, await res.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBe(boss.userId); + const rows = (await h.engine.find('sys_user', { where: { id: emp.userId }, fields: ['name'] }, SYSTEM)) as Array<{ name?: string }>; + expect(rows[0]?.name).toBe('Emp Renamed'); + }); + + it('the operator warn is bounded per connection: a second unresolvable write in the window says nothing', async () => { + const h = await boot(); + await provision(h, 'a', { value: 'no-such-1' }); + await provision(h, 'b', { value: 'no-such-2' }); + await provision(h, 'c', { value: 'no-such-3' }); + expect(h.unresolvedWarns()).toHaveLength(1); + }); + + it('a report whose manager was deleted keeps working: a write that names no manager, and a replace re-sending the dangling one', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const emp = await provision(h, 'emp', { value: boss.scimId }); + const gone = await h.send(scimRequest(h.token, 'DELETE', `/Users/${boss.scimId}`)); + expect(gone.status, await gone.clone().text()).toBe(204); + const before = await managerOf(h, emp.userId); + + const renamed = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: 'displayName', value: 'Emp Renamed' }, + ]))); + expect(renamed.status, await renamed.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBe(before); + expect(h.unresolvedWarns()).toHaveLength(0); + + const replaced = await h.send(scimRequest(h.token, 'PUT', `/Users/${emp.scimId}`, userBody('emp', { value: boss.scimId }))); + expect(replaced.status, await replaced.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBe(before); + expect(h.unresolvedWarns()).toHaveLength(1); + }); +}); + +describe('SCIM manager projection: silence is not a clear, and one predicate decides which door owns the column', () => { + it('a write that does not name manager keeps a value the admin route set; an explicit remove clears it', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const emp = await provision(h, 'emp'); + // Set through the admin route while the user held a local password … + await giveLocalPassword(h, emp.userId); + expect(await adminSetManager(h, emp.userId, boss.userId)).toBeNull(); + // … then the password went and the directory holds the identity again. + await h.engine.delete('sys_account', { where: { id: `acc_cred_${emp.userId}` }, ...SYSTEM }); + await h.engine.update('sys_user', { id: emp.userId, source: 'idp_provisioned' }, SYSTEM); + expect(await directoryOwnsUserManager(h.engine as never, emp.userId)).toBe(true); + + const renamed = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: 'displayName', value: 'Emp Renamed' }, + ]))); + expect(renamed.status, await renamed.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBe(boss.userId); + + const removed = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'remove', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager` }, + ]))); + expect(removed.status, await removed.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBeNull(); + }); + + it('on an identity the directory does not hold, the projection writes nothing and the admin route owns the column', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const other = await provision(h, 'other'); + const emp = await provision(h, 'emp'); + await giveLocalPassword(h, emp.userId); + expect(await directoryOwnsUserManager(h.engine as never, emp.userId)).toBe(false); + + const named = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: boss.scimId } }, + ]))); + expect(named.status, await named.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBeNull(); + + expect(await adminSetManager(h, emp.userId, other.userId)).toBeNull(); + const replaced = await h.send(scimRequest(h.token, 'PUT', `/Users/${emp.scimId}`, userBody('emp'))); + expect(replaced.status, await replaced.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBe(other.userId); + }); + + it('on an identity the directory holds, the admin route refuses and the projection writes', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const emp = await provision(h, 'emp'); + expect(await directoryOwnsUserManager(h.engine as never, emp.userId)).toBe(true); + + const refused = await adminSetManager(h, emp.userId, boss.userId); + expect(refused?.status).toBe(403); + expect(refused?.body.error?.details?.reason).toBe('idp_provisioned'); + expect(await managerOf(h, emp.userId)).toBeNull(); + + const named = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: boss.scimId } }, + ]))); + expect(named.status, await named.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBe(boss.userId); + }); +}); + +describe('SCIM manager projection: the cases it does not project', () => { + it('an inactive user: a manager named while inactive is not written, re-activation alone does not apply it, the next naming write does', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const emp = await provision(h, 'emp'); + const deactivated = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: 'active', value: false }, + { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: boss.scimId } }, + ]))); + expect(deactivated.status, await deactivated.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBeNull(); + + const reactivated = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: 'active', value: true }, ]))); - await expectInvalidValue(res, 'INVALID_REFERENCE', /names no User this connection provisioned/); + expect(reactivated.status, await reactivated.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBeNull(); + + const named = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: boss.scimId } }, + ]))); + expect(named.status, await named.clone().text()).toBe(200); expect(await managerOf(h, emp.userId)).toBe(boss.userId); }); + + // The two branches below have no public door that reaches them in one + // request (a connection decommission, a provisioning-domain replay, a user + // two connections share), so they drive the callback itself; each carries + // its control leg, where the same call goes on to read the engine. + const state = { userId: 'usr_emp', active: true, profileSourceId: 'src_emp', sources: [] } as never; + const contextFor = (connectionId: string) => { + const findOne = vi.fn(async () => ({ id: 'src_emp', userId: 'usr_emp', connectionId, serializedAttributes: '' })); + return { findOne, context: { database: { findOne } } as never }; + }; + const noEngine = () => { + const getDataEngine = vi.fn(() => undefined); + return { getDataEngine, project: createScimManagerProjection({ getDataEngine }) }; + }; + + it('outside a SCIM request (a decommission or a domain replay): nothing is read or written', async () => { + const { getDataEngine, project } = noEngine(); + const { findOne, context } = contextFor(CONNECTION); + await expect(project(state, context)).resolves.toBeUndefined(); + expect(findOne).not.toHaveBeenCalled(); + expect(getDataEngine).not.toHaveBeenCalled(); + + // Control: the same call inside a SCIM request that names the manager reaches the engine. + await expect(scimRequestScope.run( + { scim: true, connectionId: CONNECTION, userManagerIntent: 'named' }, + () => project(state, context), + )).rejects.toThrow(/no data engine/); + expect(getDataEngine).toHaveBeenCalledTimes(1); + }); + + it('a profile source another connection owns: that connection authors this user\'s profile, so nothing is written', async () => { + const { getDataEngine, project } = noEngine(); + const { findOne, context } = contextFor(OTHER_CONNECTION); + await expect(scimRequestScope.run( + { scim: true, connectionId: CONNECTION, userManagerIntent: 'named' }, + () => project(state, context), + )).resolves.toBeUndefined(); + expect(findOne).toHaveBeenCalledTimes(1); + expect(getDataEngine).not.toHaveBeenCalled(); + + // Control: the profile source's own connection reaches the engine. + await expect(scimRequestScope.run( + { scim: true, connectionId: OTHER_CONNECTION, userManagerIntent: 'named' }, + () => project(state, context), + )).rejects.toThrow(/no data engine/); + expect(getDataEngine).toHaveBeenCalledTimes(1); + }); }); describe('SCIM manager projection: the admin endpoint\'s four refusals, answered as SCIM errors', () => { @@ -375,12 +586,39 @@ describe('SCIM manager projection: the admin endpoint\'s four refusals, answered }); describe('readScimManagerReference', () => { - it('reads value first, then the $ref segment, and names an unreadable $ref', () => { + it('reads value first, then the $ref segment; a $ref with no segment, or one that does not decode, is unreadable', () => { const attrs = (manager: unknown) => JSON.stringify({ enterprise: { manager } }); expect(readScimManagerReference(undefined)).toEqual({ kind: 'none' }); expect(readScimManagerReference(JSON.stringify({ schemas: [USER_SCHEMA] }))).toEqual({ kind: 'none' }); expect(readScimManagerReference(attrs({ value: 'v1', $ref: 'https://x/Users/r1' }))).toEqual({ kind: 'id', id: 'v1' }); expect(readScimManagerReference(attrs({ $ref: 'https://x/scim/v2/Users/r%201' }))).toEqual({ kind: 'id', id: 'r 1' }); - expect(readScimManagerReference(attrs({ $ref: 'https://x/people/r1' }))).toEqual({ kind: 'unreadable', ref: 'https://x/people/r1' }); + expect(readScimManagerReference(attrs({ $ref: 'https://x/people/r1' }))).toEqual({ kind: 'unreadable' }); + expect(readScimManagerReference(attrs({ $ref: 'https://x/scim/v2/Users/%E0%A4%A' }))).toEqual({ kind: 'unreadable' }); + }); +}); + +describe('scimBodyNamesManager', () => { + const ENT = SCIM_ENTERPRISE_USER_SCHEMA; + const ops = (...operations: unknown[]) => ({ schemas: [PATCH_SCHEMA], Operations: operations }); + + it('a replace always names it, since a replace without the attribute is a clear', () => { + expect(scimBodyNamesManager('replace', {})).toBe(true); + }); + + it('a create names it only when it carries it', () => { + expect(scimBodyNamesManager('create', userBody('emp'))).toBe(false); + expect(scimBodyNamesManager('create', userBody('emp', { value: 'm1' }))).toBe(true); + }); + + it('a PATCH names it when an operation addresses or carries it, matched case-insensitively', () => { + expect(scimBodyNamesManager('patch', ops({ op: 'replace', path: 'displayName', value: 'x' }))).toBe(false); + expect(scimBodyNamesManager('patch', ops({ op: 'replace', path: 'active', value: false }))).toBe(false); + expect(scimBodyNamesManager('patch', ops({ op: 'remove', path: `${ENT}:manager` }))).toBe(true); + expect(scimBodyNamesManager('patch', ops({ op: 'Replace', path: `${ENT.toUpperCase()}:Manager.value`, value: 'm1' }))).toBe(true); + expect(scimBodyNamesManager('patch', ops({ op: 'replace', path: 'manager', value: { value: 'm1' } }))).toBe(true); + expect(scimBodyNamesManager('patch', ops({ op: 'remove', path: ENT }))).toBe(true); + expect(scimBodyNamesManager('patch', ops({ op: 'replace', path: ENT, value: { department: 'x' } }))).toBe(false); + expect(scimBodyNamesManager('patch', ops({ op: 'replace', value: { [ENT]: { manager: { value: 'm1' } } } }))).toBe(true); + expect(scimBodyNamesManager('patch', ops({ op: 'replace', value: { displayName: 'x' } }))).toBe(false); }); }); diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.ts index ed576f45bba..cf4cc869a79 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.ts @@ -30,21 +30,33 @@ * (`scimRequestScope`), so a refusal rolls the whole SCIM mutation back and * the identity provider reads a SCIM error with nothing written. * - * ## When it projects, and when it does not + * ## When it writes, and why each other case writes nothing * - * - Only inside an authenticated SCIM protocol request, and only for the - * connection that request verified as. The vendor also calls this callback - * while it decommissions a connection or replays a provisioning domain; a - * decommission must never be refused over an org-chart reference, so those - * runs project nothing. + * - Only on a write that NAMES the attribute ({@link scimUserManagerIntentOf}, + * read off the request before the vendor runs): a create or PATCH that + * carries or removes it, and every replace, since a replace without it is a + * clear. A write that does not name it leaves `manager_id` as it is: silence + * is not a clear (seat ruling 6907953084, item a). + * - Only on an identity the directory OWNS the manager of — the exact set the + * admin endpoint refuses, read through the one predicate both doors share, + * `directoryOwnsUserManager` (seat ruling 6907953084, item b). On any other + * identity the admin endpoint owns the column and the projection writes + * nothing, so neither door overwrites the other. + * - Only inside an authenticated SCIM protocol request, for the connection it + * verified as. The vendor also calls this callback while it decommissions a + * connection or replays a provisioning domain; neither is a write the + * directory made, and a decommission must never be refused over an + * org-chart reference. * - Only from the user's PROFILE source (the vendor's `profileSourceId`, the * same rule that decides whose name and email the user carries), and only - * when that source belongs to the request's connection. - * - Only on an active state. A deprovision is never refused over the manager; - * a user re-activated later projects the manager its source then holds. - * - Only when the manager CHANGES. A stored reference that resolves to the - * manager the user already has is not judged again, so an unrelated PATCH is - * never refused over a chain other links have since reshaped. + * when it belongs to the request's connection: another connection's request + * does not author this user's profile, so its manager is not this user's. + * - Only on an active state: a deprovision is never refused over the org + * chart. A manager named while the user is inactive stays in the + * directory's resource and lands on the next active write that names it. + * - Only when the manager CHANGES: a reference that resolves to the manager + * the user already has is not judged again, so a write is never refused + * over a chain other links have since reshaped. * * ## What `manager.value` is matched against * @@ -52,26 +64,37 @@ * "the id of the SCIM resource representing the User's manager" — among the * Users the SAME connection provisioned (a resource id means something only to * the connection that issued it, which is also how `GET /Users/{id}` scopes - * it). A `$ref` alone is read the same way, by its final `/Users/{id}` path - * segment. ⛔ Never the `externalId`, the `userName` or an email as a second - * dialect: one reading, so a reference either names a User or is refused. + * it). A `$ref` alone is read by its final `/Users/{id}` path segment. ⛔ Never + * the `externalId`, the `userName` or an email as a second dialect. * - * ## The refusals + * ## A reference that names no User is served; a structural one is refused * - * A reference that names no User this connection provisioned is refused — - * never dropped, so the directory learns its reference did not land. Every - * other refusal is the admin endpoint's own, from - * {@link screenUserManagerLink} (self-assignment, cycle, depth cap, - * cross-organization), imported: one derivation, never a copy. Each is a SCIM - * error in RFC 7644 §3.12 shape: status 400, `scimType: invalidValue` — the - * vendor's own answer to a value it refuses — the refusal's sentence as - * `detail`, and the admin endpoint's ADR-0112 `code` for the same refusal. The refusal ledger (`scim-refusal-audit.ts`) records it like any - * other SCIM refusal. A cleared or absent attribute clears the column. + * Maintainer ruling record 6909383114: a reference that cannot be resolved — + * an unknown id, an `externalId`-style value, another connection's id, a + * `$ref` with no readable `/Users/{id}` segment — does not refuse the user + * write. The write lands, `manager_id` stays as it was, and an operator warn + * names the connection, bounded per connection + * ({@link SCIM_MANAGER_UNRESOLVED_WARNS_PER_WINDOW} per window, with the count + * it dropped). The check runs after the unchanged-manager short-circuit, and a + * write that does not name the attribute never reaches it, so a report whose + * manager was deleted keeps working. The four structural refusals are the + * admin endpoint's own, from {@link screenUserManagerLink} (self-assignment, + * cycle, depth cap, cross-organization), imported: one derivation, never a + * copy. Each is a SCIM error in RFC 7644 §3.12 shape: status 400, + * `scimType: invalidValue`, the refusal's sentence as `detail`, and the admin + * endpoint's ADR-0112 `code` for the same refusal. The refusal ledger + * (`scim-refusal-audit.ts`) records it like any other SCIM refusal. */ import type { SCIMIdentityState, SCIMTransactionContext } from '@better-auth/scim'; -import { screenUserManagerLink, writeUserManagerLink, type SetUserManagerDeps } from './admin-set-user-manager.js'; -import { scimRequestConnectionId } from './scim-connection-service.js'; +import { + directoryOwnsUserManager, + screenUserManagerLink, + writeUserManagerLink, + type SetUserManagerDeps, +} from './admin-set-user-manager.js'; +import { scimRequestScope } from './scim-connection-service.js'; +import { ScimRefusalAuditBound } from './scim-refusal-audit.js'; /** The SCIM Enterprise User extension the attribute lives in. */ export const SCIM_ENTERPRISE_USER_SCHEMA = 'urn:ietf:params:scim:schemas:extension:enterprise:2.0:User'; @@ -80,6 +103,9 @@ const SCIM_ERROR_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:Error'; const SYSTEM_READ_CTX = { isSystem: true, positions: [], permissions: [] } as const; +/** Operator warns one connection gets per 10-minute window for unresolvable references. */ +export const SCIM_MANAGER_UNRESOLVED_WARNS_PER_WINDOW = 1; + /** The vendor-side `scimUser` row fields this module reads. */ interface ScimUserRow { id?: unknown; @@ -88,17 +114,108 @@ interface ScimUserRow { serializedAttributes?: unknown; } +// --------------------------------------------------------------------------- +// Does the request NAME the attribute? Read before the vendor runs. +// --------------------------------------------------------------------------- + +const ENTERPRISE_LOWER = SCIM_ENTERPRISE_USER_SCHEMA.toLowerCase(); +const MANAGER_PATH_LOWER = `${ENTERPRISE_LOWER}:manager`; + +const isRecord = (v: unknown): v is Record => typeof v === 'object' && v !== null && !Array.isArray(v); + +/** The value under `key` in `obj`, matched case-insensitively (SCIM attribute names are). */ +function keyed(obj: Record, key: string): { found: boolean; value?: unknown } { + for (const [k, v] of Object.entries(obj)) if (k.toLowerCase() === key) return { found: true, value: v }; + return { found: false }; +} + +/** Does a resource-shaped object (a create body, a pathless PATCH value) carry the attribute? */ +function objectNamesManager(obj: Record): boolean { + if (keyed(obj, MANAGER_PATH_LOWER).found || keyed(obj, 'manager').found) return true; + const extension = keyed(obj, ENTERPRISE_LOWER); + return extension.found && isRecord(extension.value) && keyed(extension.value, 'manager').found; +} + +/** Does one PATCH path address the attribute (or the extension holding it)? */ +function pathNamesManager(path: string, op: string, value: unknown): boolean { + const p = path.trim().toLowerCase(); + if (p === 'manager' || p.startsWith('manager.') || p === MANAGER_PATH_LOWER || p.startsWith(`${MANAGER_PATH_LOWER}.`)) { + return true; + } + // The whole extension: removing it removes the manager; replacing it names + // the manager only when the new value carries one. + if (p === ENTERPRISE_LOWER) return op === 'remove' || (isRecord(value) && keyed(value, 'manager').found); + return false; +} + +/** + * Whether a SCIM user write NAMES the Enterprise `manager` attribute, from its + * kind and parsed body: a create that carries it, a PATCH with an operation + * that addresses or carries it, and every replace (a replace without it is a + * clear). + */ +export function scimBodyNamesManager(kind: 'create' | 'replace' | 'patch', body: unknown): boolean { + if (kind === 'replace') return true; + if (!isRecord(body)) return false; + if (kind === 'create') return objectNamesManager(body); + const operations = keyed(body, 'operations').value; + if (!Array.isArray(operations)) return false; + return operations.some((operation) => { + if (!isRecord(operation)) return false; + const op = String(keyed(operation, 'op').value ?? '').toLowerCase(); + const path = keyed(operation, 'path').value; + const value = keyed(operation, 'value').value; + if (typeof path === 'string' && path.trim() !== '') return pathNamesManager(path, op, value); + return isRecord(value) && objectNamesManager(value); + }); +} + +/** + * The manager intent of one SCIM request, for `ScimRequestScope.userManagerIntent`: + * `named` / `silent` for a user create, replace or patch, `undefined` for any + * other request. The body is read from a clone, so the vendor still reads its + * own; a body that does not parse is `silent`, and the vendor refuses it. + */ +export async function scimUserManagerIntentOf( + request: Request, + endpointPath: string | undefined, +): Promise<'named' | 'silent' | undefined> { + const path = endpointPath ?? ''; + const method = request.method.toUpperCase(); + const kind = method === 'POST' && /^\/scim\/v2\/Users\/?$/.test(path) + ? 'create' + : method === 'PUT' && /^\/scim\/v2\/Users\/[^/]+$/.test(path) + ? 'replace' + : method === 'PATCH' && /^\/scim\/v2\/Users\/[^/]+$/.test(path) + ? 'patch' + : undefined; + if (!kind) return undefined; + if (kind === 'replace') return 'named'; + let body: unknown; + try { + body = JSON.parse(await request.clone().text()); + } catch { + return 'silent'; + } + return scimBodyNamesManager(kind, body) ? 'named' : 'silent'; +} + +// --------------------------------------------------------------------------- +// The reference the stored attributes carry +// --------------------------------------------------------------------------- + /** What the stored attributes say about the manager. */ export type ScimManagerReference = | { kind: 'none' } | { kind: 'id'; id: string } - | { kind: 'unreadable'; ref: string }; + | { kind: 'unreadable' }; /** * The manager reference in a `scimUser` row's stored canonical attributes: * `enterprise.manager.value`, else the final `/Users/{id}` segment of * `enterprise.manager.$ref`. A row stored before the vendor kept attributes, - * or one with no manager, names none. + * or one with no manager, names none; a `$ref` with no readable segment + * (none, or one that does not decode) is unreadable. */ export function readScimManagerReference(serializedAttributes: unknown): ScimManagerReference { if (typeof serializedAttributes !== 'string' || serializedAttributes === '') return { kind: 'none' }; @@ -111,7 +228,12 @@ export function readScimManagerReference(serializedAttributes: unknown): ScimMan if (typeof manager.value === 'string' && manager.value !== '') return { kind: 'id', id: manager.value }; if (typeof manager.$ref === 'string' && manager.$ref !== '') { const match = /\/Users\/([^/?#]+)\/?$/.exec(manager.$ref); - return match ? { kind: 'id', id: decodeURIComponent(match[1]) } : { kind: 'unreadable', ref: manager.$ref }; + if (!match) return { kind: 'unreadable' }; + try { + return { kind: 'id', id: decodeURIComponent(match[1]) }; + } catch { + return { kind: 'unreadable' }; + } } return { kind: 'none' }; } @@ -138,81 +260,92 @@ async function scimInvalidValue(code: string, detail: string): Promise { const text = (v: unknown): string => (typeof v === 'string' ? v : v == null ? '' : String(v)); -/** The admin endpoint's own dependencies: the engine, and its degradation channel. */ -export type ScimManagerProjectionDeps = SetUserManagerDeps; +/** The admin endpoint's own dependencies (the engine), plus the operator channel. */ +export interface ScimManagerProjectionDeps extends SetUserManagerDeps { + /** Overrides the warn bound's clock and window, for tests. */ + warnBound?: ScimRefusalAuditBound; +} + +/** The `identity.reconcileUser` half that projects the manager. */ +export type ScimManagerProjection = (state: SCIMIdentityState, context: SCIMTransactionContext) => Promise; /** - * Project the profile source's `manager` onto `sys_user.manager_id` for the - * user in `state`, inside the SCIM transaction `context` belongs to. Resolves - * when the column already agrees or was written; throws the SCIM error the - * identity provider reads when the reference is refused. + * Build the projection, with its own per-connection bound on the operator + * warn for an unresolvable reference. */ -export async function projectScimManager( - deps: ScimManagerProjectionDeps, - state: SCIMIdentityState, - context: SCIMTransactionContext, -): Promise { - const connectionId = scimRequestConnectionId(); - if (!connectionId || !state.active || !state.profileSourceId) return; - - const db = context.database; - const source = await db.findOne({ - model: 'scimUser', - where: [{ field: 'id', value: state.profileSourceId }], - }); - if (!source || text(source.connectionId) !== connectionId) return; - - const reference = readScimManagerReference(source.serializedAttributes); - if (reference.kind === 'unreadable') { - throw await scimInvalidValue( - 'INVALID_REFERENCE', - `${SCIM_ENTERPRISE_USER_SCHEMA}:manager names no User: its $ref '${reference.ref}' does not end in ` - + `/Users/{id}, and it carries no value. Send the manager's SCIM resource id as manager.value.`, +export function createScimManagerProjection(deps: ScimManagerProjectionDeps): ScimManagerProjection { + const bound = deps.warnBound ?? new ScimRefusalAuditBound({ rowsPerKey: SCIM_MANAGER_UNRESOLVED_WARNS_PER_WINDOW }); + + const warnUnresolved = (connectionId: string, userId: string): void => { + const admitted = bound.admit(connectionId); + if (!admitted) return; + deps.logger?.warn( + `[auth] SCIM connection '${connectionId}' sent an Enterprise User manager reference that names no User ` + + `it provisioned (user '${userId}'): the user write was served and sys_user.manager_id was left as it ` + + 'was. manager.value must be the manager\'s SCIM resource id, the id this service returned when the ' + + 'manager was created. Fix the identity provider\'s manager mapping, or provision the manager first. ' + + `Said once per connection per window${admitted.suppressed > 0 ? `; ${admitted.suppressed} more since the last notice` : ''}.`, + { connectionId, userId, suppressed: admitted.suppressed }, ); - } + }; - let managerId: string | null = null; - if (reference.kind === 'id') { - const managerSource = await db.findOne({ + return async (state, context) => { + const scope = scimRequestScope.getStore(); + const connectionId = scope?.scim === true ? scope.connectionId : undefined; + if (!connectionId || scope?.userManagerIntent !== 'named') return; + if (!state.active || !state.profileSourceId) return; + + const db = context.database; + const source = await db.findOne({ model: 'scimUser', - where: [ - { field: 'id', value: reference.id }, - { field: 'connectionId', value: connectionId }, - ], + where: [{ field: 'id', value: state.profileSourceId }], }); - if (!managerSource || !text(managerSource.userId)) { - throw await scimInvalidValue( - 'INVALID_REFERENCE', - `${SCIM_ENTERPRISE_USER_SCHEMA}:manager.value '${reference.id}' names no User this connection ` - + `provisioned. manager.value is the manager's SCIM resource id (the id this service returned when ` - + `the manager was created), not an externalId, userName or email. Provision the manager first, or ` - + `send the right id; nothing of this request was written.`, + if (!source || text(source.connectionId) !== connectionId) return; + + const engine = deps.getDataEngine(); + if (!engine) { + throw new Error( + `[auth] SCIM manager projection: no data engine to write sys_user.manager_id for user '${state.userId}'`, ); } - managerId = text(managerSource.userId); - } + // The one ownership predicate the admin endpoint's refusal 5 reads. + if (!(await directoryOwnsUserManager(engine, state.userId))) return; - const engine = deps.getDataEngine(); - if (!engine) { - throw new Error( - `[auth] SCIM manager projection: no data engine to write sys_user.manager_id for user '${state.userId}'`, - ); - } - const rows = await engine.find('sys_user', { - where: { id: state.userId }, - fields: ['id', 'manager_id'], - limit: 1, - context: SYSTEM_READ_CTX, - }); - const current = text((Array.isArray(rows) ? (rows[0] as { manager_id?: unknown } | undefined) : undefined)?.manager_id); - if (current === (managerId ?? '')) return; + const reference = readScimManagerReference(source.serializedAttributes); + let managerId: string | null | undefined = null; // `undefined` = unresolvable + if (reference.kind === 'unreadable') { + managerId = undefined; + } else if (reference.kind === 'id') { + const managerSource = await db.findOne({ + model: 'scimUser', + where: [ + { field: 'id', value: reference.id }, + { field: 'connectionId', value: connectionId }, + ], + }); + managerId = managerSource && text(managerSource.userId) ? text(managerSource.userId) : undefined; + } - if (managerId !== null) { - const refusal = await screenUserManagerLink(deps, engine, state.userId, managerId); - if (refusal) throw await scimInvalidValue(refusal.code, refusal.message); - } + const rows = await engine.find('sys_user', { + where: { id: state.userId }, + fields: ['id', 'manager_id'], + limit: 1, + context: SYSTEM_READ_CTX, + }); + const current = text((Array.isArray(rows) ? (rows[0] as { manager_id?: unknown } | undefined) : undefined)?.manager_id); + if (managerId !== undefined && current === (managerId ?? '')) return; + if (managerId === undefined) { + warnUnresolved(connectionId, state.userId); + return; + } + + if (managerId !== null) { + const refusal = await screenUserManagerLink(deps, engine, state.userId, managerId); + if (refusal) throw await scimInvalidValue(refusal.code, refusal.message); + } - // Attributed to the connection (`svc:scim:CONNECTION_ID`) inside a SCIM - // request, and joined to its transaction. - await writeUserManagerLink(engine, state.userId, managerId); + // Attributed to the connection (`svc:scim:CONNECTION_ID`) inside a SCIM + // request, and joined to its transaction. + await writeUserManagerLink(engine, state.userId, managerId); + }; } From e6199798ddeac807c142a48c13b74bf5120cbaaf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:39:59 +0000 Subject: [PATCH 10/20] test(plugin-auth): read the admin route's refusal by its own fields Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../plugins/plugin-auth/src/scim-manager-projection.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts index 5972eff1b5a..d3447d1e1a7 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts @@ -448,7 +448,8 @@ describe('SCIM manager projection: silence is not a clear, and one predicate dec const refused = await adminSetManager(h, emp.userId, boss.userId); expect(refused?.status).toBe(403); - expect(refused?.body.error?.details?.reason).toBe('idp_provisioned'); + expect(refused?.code).toBe('PERMISSION_DENIED'); + expect(refused?.reason).toBe('idp_provisioned'); expect(await managerOf(h, emp.userId)).toBeNull(); const named = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ From 345781c4c9679995bf8cad9676c6e7a560c51627 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 08:26:58 +0000 Subject: [PATCH 11/20] test(plugin-auth): clear and re-apply a manager through a replace, which the vendor always calls back on Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .changeset/33918-scim-manager-projection.md | 2 +- .../src/scim-manager-projection.test.ts | 21 ++++++++++--------- .../src/scim-manager-projection.ts | 6 +++++- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/.changeset/33918-scim-manager-projection.md b/.changeset/33918-scim-manager-projection.md index 39d7ed6d741..9b601294bb9 100644 --- a/.changeset/33918-scim-manager-projection.md +++ b/.changeset/33918-scim-manager-projection.md @@ -24,6 +24,6 @@ Metadata-protocol: none - Outside an authenticated SCIM request: the vendor also runs this step while it decommissions a connection or replays a provisioning domain. Neither is a write the directory made, and a decommission must never be refused over an org-chart reference. - When the user's profile source belongs to another connection: that connection authors the user's name and email, so its manager is the one that counts, not this request's. -- For an inactive user: a deprovision is never refused over the org chart. A manager named while the user is inactive is not applied on re-activation alone; it lands on the next active write that names it. +- For an inactive user: a deprovision is never refused over the org chart. A manager named while the user is inactive is not applied on re-activation alone; it lands on the next replace, or on a patch that changes it. (`@better-auth/scim` calls the host only when a PATCH changes what it stores, so a patch that re-sends the same value, or removes an attribute the directory never sent, writes nothing; a replace always reaches the projection.) The `idp_provisioned` stamp (ADR-0135 D4) is unchanged. diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts index d3447d1e1a7..2000f3569f0 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts @@ -395,7 +395,7 @@ describe('SCIM manager projection: a reference that names no User is served, and }); describe('SCIM manager projection: silence is not a clear, and one predicate decides which door owns the column', () => { - it('a write that does not name manager keeps a value the admin route set; an explicit remove clears it', async () => { + it('a write that does not name manager keeps a value the admin route set; a replace without it clears it', async () => { const h = await boot(); const boss = await provision(h, 'boss'); const emp = await provision(h, 'emp'); @@ -413,10 +413,11 @@ describe('SCIM manager projection: silence is not a clear, and one predicate dec expect(renamed.status, await renamed.clone().text()).toBe(200); expect(await managerOf(h, emp.userId)).toBe(boss.userId); - const removed = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ - { op: 'remove', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager` }, - ]))); - expect(removed.status, await removed.clone().text()).toBe(200); + // The explicit PATCH remove is pinned above, on a manager the directory + // set: a remove of an attribute the directory's resource never carried + // changes nothing the vendor stores, and it answers without calling back. + const cleared = await h.send(scimRequest(h.token, 'PUT', `/Users/${emp.scimId}`, userBody('emp'))); + expect(cleared.status, await cleared.clone().text()).toBe(200); expect(await managerOf(h, emp.userId)).toBeNull(); }); @@ -461,7 +462,7 @@ describe('SCIM manager projection: silence is not a clear, and one predicate dec }); describe('SCIM manager projection: the cases it does not project', () => { - it('an inactive user: a manager named while inactive is not written, re-activation alone does not apply it, the next naming write does', async () => { + it('an inactive user: a manager named while inactive is not written, re-activation alone does not apply it, the next replace does', async () => { const h = await boot(); const boss = await provision(h, 'boss'); const emp = await provision(h, 'emp'); @@ -478,10 +479,10 @@ describe('SCIM manager projection: the cases it does not project', () => { expect(reactivated.status, await reactivated.clone().text()).toBe(200); expect(await managerOf(h, emp.userId)).toBeNull(); - const named = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ - { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: boss.scimId } }, - ]))); - expect(named.status, await named.clone().text()).toBe(200); + // A PATCH re-sending the same value changes nothing the vendor stores, so + // it answers without calling back; a replace always calls back. + const replaced = await h.send(scimRequest(h.token, 'PUT', `/Users/${emp.scimId}`, userBody('emp', { value: boss.scimId }))); + expect(replaced.status, await replaced.clone().text()).toBe(200); expect(await managerOf(h, emp.userId)).toBe(boss.userId); }); diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.ts index cf4cc869a79..6eed8efac8e 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.ts @@ -53,7 +53,11 @@ * does not author this user's profile, so its manager is not this user's. * - Only on an active state: a deprovision is never refused over the org * chart. A manager named while the user is inactive stays in the - * directory's resource and lands on the next active write that names it. + * directory's resource and is not applied on re-activation alone; it lands + * on the next replace, or on a patch that changes it. (The vendor calls + * back only when a PATCH changes what it stores, so a patch re-sending the + * same value, or removing an attribute the resource never carried, reaches + * no host code; a replace always calls back.) * - Only when the manager CHANGES: a reference that resolves to the manager * the user already has is not judged again, so a write is never refused * over a chain other links have since reshaped. From 165b161ff506f27229b52dc0c23762b0c40109a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:19:55 +0000 Subject: [PATCH 12/20] feat(plugin-auth,plugin-audit): an unresolvable SCIM manager reference leaves one bounded scim_manager_unresolved row The served write's operator warn and the ledger row share one admission, so rows follow the warn's rate (one per connection per window) and carry its dropped count. The projection notes the event on the request scope; the SCIM arm hands it to the audit slot after the response, outside the vendor's transaction, only for an answer below 400. The row names the connection, the user's record and the reference capped at 256 characters, nothing else. Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .../sys-audit-log-action-labels.test.ts | 2 + .../sys-audit-log-retired-actions.test.ts | 7 + .../src/objects/sys-audit-log.object.ts | 16 ++ .../src/scim-refusal-audit.test.ts | 103 +++++++++++ .../plugin-audit/src/scim-refusal-audit.ts | 165 +++++++++++++++++- .../src/auth-manager-request-routing.ts | 7 + .../src/scim-connection-service.ts | 21 +++ .../src/scim-manager-projection.test.ts | 121 ++++++++++++- .../src/scim-manager-projection.ts | 95 +++++++++- 9 files changed, 517 insertions(+), 20 deletions(-) diff --git a/packages/plugins/plugin-audit/src/objects/sys-audit-log-action-labels.test.ts b/packages/plugins/plugin-audit/src/objects/sys-audit-log-action-labels.test.ts index af94bb790e1..d68fef6a413 100644 --- a/packages/plugins/plugin-audit/src/objects/sys-audit-log-action-labels.test.ts +++ b/packages/plugins/plugin-audit/src/objects/sys-audit-log-action-labels.test.ts @@ -43,6 +43,8 @@ describe('sys_audit_log.action option labels', () => { 'audit_signing_key_change', // A new value, added writer-first; no existing value moved. 'dataset_query', + // #33918: a new value, added writer-first; no existing value moved. + 'scim_manager_unresolved', ]); }); diff --git a/packages/plugins/plugin-audit/src/objects/sys-audit-log-retired-actions.test.ts b/packages/plugins/plugin-audit/src/objects/sys-audit-log-retired-actions.test.ts index e4bba748850..c40c22aa80e 100644 --- a/packages/plugins/plugin-audit/src/objects/sys-audit-log-retired-actions.test.ts +++ b/packages/plugins/plugin-audit/src/objects/sys-audit-log-retired-actions.test.ts @@ -143,6 +143,13 @@ const ACTIONS_WITH_WRITERS: ReadonlyArray = {}): ScimRefusalAud const metadataOf = (row: Record): Record => JSON.parse(String(row.metadata)); +/** [#33918] A served write whose manager reference named no User, as plugin-auth hands it. */ +function unresolved(overrides: Partial = {}): ScimManagerUnresolvedAuditEvent { + return { + connectionId: 'okta-33918', + organizationId: 'org_33918', + userId: 'usr_emp_33918', + referenceKind: 'id', + reference: 'no-such-scim-id', + ...overrides, + }; +} + describe('[#31829] the SCIM refusal writer on the real `audit` slot', () => { let kernel: ObjectKernel; let engine: ObjectQL; @@ -148,6 +164,34 @@ describe('[#31829] the SCIM refusal writer on the real `audit` slot', () => { }); }); + it('[#33918] an unresolvable manager reference writes ONE row on the user\'s record, naming the connection and the reference', async () => { + const at = async () => (await engine.find(LEDGER, { + where: { action: SCIM_MANAGER_UNRESOLVED_AUDIT_ACTION }, + context: SYS, + })) as Array>; + const before = (await at()).length; + await audit.recordScimManagerUnresolved(unresolved({ suppressed: 4 })); + const after = await at(); + expect(after).toHaveLength(before + 1); + const row = after.at(-1)!; + expect(row).toMatchObject({ + action: 'scim_manager_unresolved', + user_id: null, + actor: 'svc:scim:okta-33918', + object_name: 'sys_user', + record_id: 'usr_emp_33918', + tenant_id: 'org_33918', + }); + expect(row.old_value ?? null).toBeNull(); + expect(row.new_value ?? null).toBeNull(); + expect(metadataOf(row)).toEqual({ + scim_connection_id: 'okta-33918', + reference_kind: 'id', + manager_reference: 'no-such-scim-id', + suppressed: 4, + }); + }); + it('an event that is not a refusal (no status of 400 or above) writes nothing', async () => { const before = (await rows()).length; await audit.recordScimRefusal(refusal({ status: 201 })); @@ -239,3 +283,62 @@ describe('[#31829] the writer never changes the SCIM answer', () => { expect(debug).toHaveBeenCalledTimes(1); }); }); + +describe('[#33918] the scim_manager_unresolved row is bounded to the reference', () => { + const all = () => true; + + it('the reference is capped, and the row says it was', () => { + const long = 'r'.repeat(SCIM_MANAGER_REFERENCE_LIMIT + 1); + const meta = metadataOf(buildScimManagerUnresolvedAuditRow(unresolved({ reference: long }), all)!); + expect(meta.manager_reference).toBe(long.slice(0, SCIM_MANAGER_REFERENCE_LIMIT)); + expect(meta.manager_reference_truncated).toBe(true); + const exact = metadataOf(buildScimManagerUnresolvedAuditRow(unresolved({ reference: long.slice(1) }), all)!); + expect(exact).not.toHaveProperty('manager_reference_truncated'); + }); + + it('fields the event type does not declare never reach the row', () => { + const row = buildScimManagerUnresolvedAuditRow( + { ...unresolved(), body: { userName: 'alice@example.com' }, email: 'alice@example.com', bearer: 'oss_scim_SECRET' } as any, + all, + )!; + const stored = JSON.stringify(row); + for (const value of ['alice@example.com', 'oss_scim_', 'SECRET']) { + expect(stored.includes(value), `the row carries ${value}: ${stored}`).toBe(false); + } + }); + + it('an event that cannot name its connection, its user or its reference writes nothing', () => { + expect(buildScimManagerUnresolvedAuditRow(unresolved({ connectionId: 'okta 33918; drop' }), all)).toBeNull(); + expect(buildScimManagerUnresolvedAuditRow(unresolved({ userId: '' }), all)).toBeNull(); + expect(buildScimManagerUnresolvedAuditRow(unresolved({ referenceKind: 'email' as any }), all)).toBeNull(); + expect(buildScimManagerUnresolvedAuditRow(unresolved({ reference: '' }), all)).toBeNull(); + expect(buildScimManagerUnresolvedAuditRow(undefined as any, all)).toBeNull(); + }); + + it('a malformed organization is not stamped, and a ledger without `actor` gets no `actor` key', () => { + expect(buildScimManagerUnresolvedAuditRow(unresolved({ organizationId: 'org 33918; drop' }), all)) + .toMatchObject({ tenant_id: null, actor: 'svc:scim:okta-33918' }); + expect(buildScimManagerUnresolvedAuditRow(unresolved(), (_o, field) => field !== 'actor')).not.toHaveProperty('actor'); + }); + + it('a refused insert is reported at error once per cause, apart from the refusal rows, and never thrown', async () => { + const error = vi.fn(); + const debug = vi.fn(); + const failing = { + insert: async () => { + throw Object.assign(new Error('disk full'), { code: 'SQLITE_FULL' }); + }, + getSchema: () => undefined, + } as any; + const writer = createScimRefusalAuditWriter({ getEngine: () => failing, logger: { error, debug, warn: vi.fn() } }); + + await expect(writer.recordScimManagerUnresolved(unresolved())).resolves.toBeUndefined(); + await expect(writer.recordScimManagerUnresolved(unresolved())).resolves.toBeUndefined(); + await expect(writer.recordScimRefusal(refusal())).resolves.toBeUndefined(); + + expect(error).toHaveBeenCalledTimes(2); + expect(String(error.mock.calls[0]?.[0])).toContain('scim_manager_unresolved'); + expect(String(error.mock.calls[1]?.[0])).toContain('scim_refused'); + expect(debug).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/plugins/plugin-audit/src/scim-refusal-audit.ts b/packages/plugins/plugin-audit/src/scim-refusal-audit.ts index a74f361db91..219312d6f97 100644 --- a/packages/plugins/plugin-audit/src/scim-refusal-audit.ts +++ b/packages/plugins/plugin-audit/src/scim-refusal-audit.ts @@ -51,6 +51,35 @@ * attribute value, the resource id or the error's `detail` text. The event * has no field for any of them, and every field it has is re-checked against * a bounded token shape here before it reaches the row. + * + * ## [#33918] `scim_manager_unresolved`: a served write whose manager names no User + * + * The second row this writer emits, on the same slot and through the same + * write. plugin-auth projects the SCIM Enterprise User `manager` attribute + * onto `sys_user.manager_id` (`scim-manager-projection.ts` there); a + * reference that names no User the connection provisioned does not refuse + * the write (maintainer ruling record 6909383114): the write is served, + * `manager_id` stays as it was, and the event is recorded with one operator + * warn and one row. plugin-auth hands the event over only for a request it + * answered below 400, after the response, and only when the warn's own bound + * (one per connection per window) admitted it, so the rows follow the warn's + * rate and carry its dropped count as `suppressed`. + * + * - `action: 'scim_manager_unresolved'`; `actor` `svc:scim:CONNECTION_ID`; + * `user_id` null (an identity provider acted, no human); + * - `object_name: 'sys_user'`, `record_id`: the user the write was about, so + * the row sits on that user's ledger history and is served under that + * record's read gate; + * - `tenant_id`: the connection's organization, as for `scim_refused`; + * - `metadata`: `scim_connection_id`, `reference_kind` (`id`, the value + * looked up, or `unreadable`, a `$ref` with no readable `/Users/{id}` + * segment), `manager_reference` (the reference as the directory sent it, + * at most {@link SCIM_MANAGER_REFERENCE_LIMIT} characters, with + * `manager_reference_truncated` when it was longer) and `suppressed`. + * + * ⛔ Nothing else of the request or of the user: no body, no name, no email, + * no other attribute. The reference is the one value recorded, and it is + * bounded here as well as at the door. */ import type { IDataEngine } from '@objectstack/spec/contracts'; @@ -66,6 +95,12 @@ import { SCIM_CONNECTION_ID_KEY, SCIM_SERVICE_PRINCIPAL_PREFIX } from './scim-co /** The `sys_audit_log.action` value this writer emits. */ export const SCIM_REFUSED_AUDIT_ACTION = 'scim_refused' as const; +/** [#33918] The `sys_audit_log.action` value of a served write whose manager reference named no User. */ +export const SCIM_MANAGER_UNRESOLVED_AUDIT_ACTION = 'scim_manager_unresolved' as const; + +/** [#33918] The most characters of a manager reference a row records. */ +export const SCIM_MANAGER_REFERENCE_LIMIT = 256; + /** `metadata.scim_connection_id` of a refusal whose bearer verified as no connection. */ export const UNKNOWN_SCIM_CONNECTION = 'unknown'; @@ -96,6 +131,25 @@ export interface ScimRefusalAuditEvent { suppressed?: number; } +/** + * [#33918] One served SCIM user write whose Enterprise `manager` reference + * named no User the connection provisioned. + */ +export interface ScimManagerUnresolvedAuditEvent { + /** The connection that sent the write. */ + connectionId: string; + /** The connection's organization; the row's `tenant_id`. */ + organizationId?: string; + /** The `sys_user` id the write was about. */ + userId: string; + /** `id`: a value that named no User; `unreadable`: a `$ref` with no readable `/Users/{id}` segment. */ + referenceKind: 'id' | 'unreadable'; + /** The reference as the directory sent it; recorded up to {@link SCIM_MANAGER_REFERENCE_LIMIT} characters. */ + reference: string; + /** Unresolvable references of the same connection the bound dropped since its last row. */ + suppressed?: number; +} + /** What {@link createScimRefusalAuditWriter} adds to the `audit` slot. */ export interface ScimRefusalAuditWriter { /** @@ -104,6 +158,11 @@ export interface ScimRefusalAuditWriter { * cause. */ recordScimRefusal(event: ScimRefusalAuditEvent): Promise; + /** + * [#33918] Record one served SCIM write whose manager reference named no + * User. Never throws, and reports a lost row loudly, once per cause. + */ + recordScimManagerUnresolved(event: ScimManagerUnresolvedAuditEvent): Promise; } export interface ScimRefusalAuditWriterOptions { @@ -205,6 +264,56 @@ export function buildScimRefusalAuditRow( return row; } +/** A `sys_user` id the row records as its `record_id`. */ +const USER_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,254}$/; + +/** The reference kinds. */ +const REFERENCE_KINDS: ReadonlySet = new Set(['id', 'unreadable']); + +/** + * [#33918] The ledger row of one served SCIM write whose manager reference + * named no User, or `null` for an event that cannot name its connection, its + * user or its reference. Exported for the writer's tests. + */ +export function buildScimManagerUnresolvedAuditRow( + event: ScimManagerUnresolvedAuditEvent, + objectHasField: (objectName: string, field: string) => boolean, +): Record | null { + const connectionId = token(event?.connectionId, CONNECTION_ID); + const userId = token(event?.userId, USER_ID); + const kind = event?.referenceKind; + if (!connectionId || !userId || typeof kind !== 'string' || !REFERENCE_KINDS.has(kind)) return null; + if (typeof event.reference !== 'string' || event.reference === '') return null; + const organizationId = token(event.organizationId, CONNECTION_ID); + const truncated = event.reference.length > SCIM_MANAGER_REFERENCE_LIMIT; + const metadata: Record = { + [SCIM_CONNECTION_ID_KEY]: connectionId, + reference_kind: kind, + manager_reference: truncated ? event.reference.slice(0, SCIM_MANAGER_REFERENCE_LIMIT) : event.reference, + }; + if (truncated) metadata.manager_reference_truncated = true; + const suppressed = event.suppressed; + if (typeof suppressed === 'number' && Number.isInteger(suppressed) && suppressed > 0) { + metadata.suppressed = suppressed; + } + const row: Record = { + action: SCIM_MANAGER_UNRESOLVED_AUDIT_ACTION, + // An identity provider acted, no human. + user_id: null, + // The user the write was about: the row sits on that record's history. + object_name: 'sys_user', + record_id: userId, + old_value: null, + new_value: null, + ip_address: null, + user_agent: null, + tenant_id: organizationId ?? null, + metadata: safeStringify(metadata), + }; + if (objectHasField('sys_audit_log', 'actor')) row.actor = `${SCIM_SERVICE_PRINCIPAL_PREFIX}${connectionId}`; + return row; +} + /** Create the SCIM refusal writer for the `audit` service slot. */ export function createScimRefusalAuditWriter(opts: ScimRefusalAuditWriterOptions): ScimRefusalAuditWriter { const { getEngine, logger } = opts; @@ -218,21 +327,32 @@ export function createScimRefusalAuditWriter(opts: ScimRefusalAuditWriterOptions * the status and the cause; never the event's connection or address. */ const reportedCauses = new Set(); - const reportWriteFailure = (status: unknown, err: unknown): void => { + const reportWriteFailure = (status: unknown, err: unknown, row: 'refusal' | 'manager' = 'refusal'): void => { const detail = String((err as any)?.message ?? err); try { - const cause = auditFailureCauseKey('sys_audit_log', err); + const cause = `${row}:${auditFailureCauseKey('sys_audit_log', err)}`; if (reportedCauses.has(cause)) { - logger?.debug?.('SCIM refusal audit write failed (already reported)', { status, err: detail, cause }); + logger?.debug?.( + row === 'refusal' + ? 'SCIM refusal audit write failed (already reported)' + : 'SCIM manager reference audit write failed (already reported)', + { status, err: detail, cause }, + ); return; } reportedCauses.add(cause); const message = - `SCIM refusal audit write FAILED (${auditFailureCauseSummary(err, detail)}) — the compliance trail is ` + - 'now INCOMPLETE. The identity provider was answered its refusal exactly as it would have been without ' + - 'the ledger, so nothing downstream looks broken; only the `sys_audit_log` row recording WHICH ' + - 'connection was refused, and why, never landed, and nothing retries it. A SCIM console or SIEM feed ' + - 'reading `scim_refused` rows keeps showing a connection with no errors. Every later refusal failing ' + + (row === 'refusal' + ? `SCIM refusal audit write FAILED (${auditFailureCauseSummary(err, detail)}) — the compliance trail is ` + + 'now INCOMPLETE. The identity provider was answered its refusal exactly as it would have been without ' + + 'the ledger, so nothing downstream looks broken; only the `sys_audit_log` row recording WHICH ' + + 'connection was refused, and why, never landed, and nothing retries it. A SCIM console or SIEM feed ' + + 'reading `scim_refused` rows keeps showing a connection with no errors. Every later refusal failing ' + : `SCIM manager reference audit write FAILED (${auditFailureCauseSummary(err, detail)}) — the ` + + 'compliance trail is now INCOMPLETE. The user write was served and its operator warn was logged, so ' + + 'nothing downstream looks broken; only the `sys_audit_log` row recording that the connection sent a ' + + 'manager reference naming no User never landed, and nothing retries it. A console reading ' + + '`scim_manager_unresolved` rows shows no such reference. Every later row failing ') + 'THIS WAY loses its row the same way (this CAUSE is reported ONCE — raise the log level to `debug` to ' + 'see the rest; a DIFFERENT cause gets its own `error` line). ' + (isMissingTableError(err, 'sys_audit_log') @@ -242,7 +362,9 @@ export function createScimRefusalAuditWriter(opts: ScimRefusalAuditWriterOptions 'one the table was created in. Set `OS_TELEMETRY_DB=0` to keep every lifecycle-classed object on ' + 'the primary datasource.' : 'Fix: resolve the driver fault quoted at the head of this line on the connection this write ran ' + - 'on — every refused SCIM request that hits it loses its row until it is resolved.'); + (row === 'refusal' + ? 'on — every refused SCIM request that hits it loses its row until it is resolved.' + : 'on — every unresolvable SCIM manager reference that hits it loses its row until it is resolved.')); if (logger?.error) { logger.error(message, err instanceof Error ? err : new Error(detail), { status }); } else { @@ -289,5 +411,30 @@ export function createScimRefusalAuditWriter(opts: ScimRefusalAuditWriterOptions reportWriteFailure(event.status, err); } }, + + async recordScimManagerUnresolved(event: ScimManagerUnresolvedAuditEvent): Promise { + if (!event) return; + const engine = getEngine(); + if (!engine) return; + if (probe === undefined || probedEngine !== engine) { + probe = createFieldPresenceProbe(engine); + probedEngine = engine; + } + let row: Record | null; + try { + row = buildScimManagerUnresolvedAuditRow(event, probe); + } catch (err) { + reportWriteFailure(undefined, err, 'manager'); + return; + } + if (!row) return; + try { + await persistScimRefusalAuditRow(engine, row); + } catch (err) { + // The same durability degradation as a lost refusal row: the write + // was served, the system looks normal, and the row is absent. + reportWriteFailure(undefined, err, 'manager'); + } + }, }; } diff --git a/packages/plugins/plugin-auth/src/auth-manager-request-routing.ts b/packages/plugins/plugin-auth/src/auth-manager-request-routing.ts index 96d96fe86da..6c06f106006 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-request-routing.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-request-routing.ts @@ -298,6 +298,13 @@ export async function handleRequest(this: Pick= 400) { const { observeScimRefusal, scimRefusalConnectionResolver } = await import('./scim-refusal-audit.js'); observeScimRefusal( diff --git a/packages/plugins/plugin-auth/src/scim-connection-service.ts b/packages/plugins/plugin-auth/src/scim-connection-service.ts index f4a77d4db8f..08f8531f7ba 100644 --- a/packages/plugins/plugin-auth/src/scim-connection-service.ts +++ b/packages/plugins/plugin-auth/src/scim-connection-service.ts @@ -129,6 +129,27 @@ export interface ScimRequestScope { * outside a user create, replace or patch. */ userManagerIntent?: 'named' | 'silent'; + /** + * [#33918] A manager reference this request's write could not resolve, set by + * the manager projection only when its operator warn's bound admitted the + * event. Read after the vendor answers: a request served below 400 hands it + * to the `audit` slot as one `scim_manager_unresolved` row + * (`observeScimManagerUnresolved`, `scim-manager-projection.ts`); a refused + * one wrote nothing, so it records nothing. + */ + userManagerUnresolved?: ScimManagerUnresolvedNote; +} + +/** [#33918] What the manager projection noted of an unresolvable reference; never the request body. */ +export interface ScimManagerUnresolvedNote { + /** The `sys_user` id the write was about. */ + userId: string; + /** `id`: a value that named no User; `unreadable`: a `$ref` with no readable `/Users/{id}` segment. */ + referenceKind: 'id' | 'unreadable'; + /** The reference as the directory sent it, already capped. */ + reference: string; + /** Unresolvable references of the connection the warn's bound dropped since its last notice. */ + suppressed: number; } /** Is the current async chain inside an authenticated SCIM protocol request? */ diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts index 2000f3569f0..7cecef7cce2 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts @@ -13,7 +13,10 @@ * reference is served (maintainer ruling record 6909383114): each shape * asserts the write landed, the column did not move, and the operator warn. * The two doors (this projection and the admin endpoint) read one ownership - * predicate (seat ruling record 6907953084), pinned from both sides. + * predicate (seat ruling record 6907953084), pinned from both sides. The + * ledger half of the ruling, one bounded `scim_manager_unresolved` event per + * admitted warn, is pinned on the `audit` slot the door hands it to; the row + * the writer builds from it is pinned in plugin-audit's `scim-refusal-audit.test.ts`. */ import { describe, it, expect, afterEach, afterAll, vi } from 'vitest'; @@ -125,15 +128,20 @@ interface Harness { send: (request: Request) => Promise; /** The operator warns the projection said about an unresolvable reference. */ unresolvedWarns: () => string[]; + /** The `scim_manager_unresolved` events handed to the `audit` slot, after the responses settle. */ + unresolvedEvents: () => Promise>>; } async function boot(): Promise { const engine = await enginePool.take(); const warn = vi.fn(); + const recordScimManagerUnresolved = vi.fn(async () => undefined); + const auditSink = { recordAuthEvent: vi.fn(async () => undefined), recordScimManagerUnresolved }; const manager = new AuthManager({ secret: SECRET, baseUrl: BASE, dataEngine: engine as never, + getAuditSink: () => auditSink, logger: { info: vi.fn(), warn, error: vi.fn(), debug: vi.fn() }, getTenancy: () => createTenancyService({ requested: 'isolated', probeIsolation: () => true }), plugins: { scim: true, organization: true }, @@ -149,7 +157,13 @@ async function boot(): Promise { const unresolvedWarns = () => warn.mock.calls .map(([message]) => String(message)) .filter((message) => message.includes('manager reference that names no User')); - return { engine, token, otherToken, send: (request) => manager.handleRequest(request), unresolvedWarns }; + const unresolvedEvents = async () => { + // The hand-off runs after the response (`setImmediate`); let it run. + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); + return recordScimManagerUnresolved.mock.calls.map((call) => (call as unknown[])[0] as Record); + }; + return { engine, token, otherToken, send: (request) => manager.handleRequest(request), unresolvedWarns, unresolvedEvents }; } function scimRequest(token: string, method: string, path: string, body?: unknown): Request { @@ -394,6 +408,103 @@ describe('SCIM manager projection: a reference that names no User is served, and }); }); +describe('[#33918] SCIM manager projection: an unresolvable reference leaves one bounded audit row per warn', () => { + afterEach(() => vi.restoreAllMocks()); + + it('a served write hands the slot ONE event: the connection, its organization, the user and the reference, nothing else', async () => { + const h = await boot(); + const emp = await provision(h, 'emp', { value: 'no-such-scim-id' }); + expect(await h.unresolvedEvents()).toEqual([ + { connectionId: CONNECTION, organizationId: ORG, userId: emp.userId, referenceKind: 'id', reference: 'no-such-scim-id' }, + ]); + }); + + it('an unreadable $ref is recorded as such, with the $ref as the directory sent it', async () => { + const h = await boot(); + const emp = await provision(h, 'emp', { $ref: 'https://idp.example/people/r1' }); + expect(await h.unresolvedEvents()).toEqual([ + { connectionId: CONNECTION, organizationId: ORG, userId: emp.userId, referenceKind: 'unreadable', reference: 'https://idp.example/people/r1' }, + ]); + }); + + it('the reference is capped, and nothing of the body rides with it', async () => { + const h = await boot(); + const long = `r${'x'.repeat(400)}`; + await provision(h, 'emp', { value: long }); + const [event] = await h.unresolvedEvents(); + expect(String(event?.reference)).toBe(long.slice(0, 257)); + const carried = JSON.stringify(event); + for (const value of ['emp@acme.com', 'ext-emp', 'emp Test', 'givenName']) { + expect(carried.includes(value), `the event carries ${value}: ${carried}`).toBe(false); + } + }); + + it('rows follow the warn\'s rate: one per connection per window, and the next carries the dropped count', async () => { + const h = await boot(); + await provision(h, 'a', { value: 'no-such-1' }); + await provision(h, 'b', { value: 'no-such-2' }); + await provision(h, 'c', { value: 'no-such-3' }); + expect(await h.unresolvedEvents()).toHaveLength(1); + expect(h.unresolvedWarns()).toHaveLength(1); + + const later = Date.now() + 11 * 60_000; + vi.spyOn(Date, 'now').mockReturnValue(later); + const d = await provision(h, 'd', { value: 'no-such-4' }); + const events = await h.unresolvedEvents(); + expect(events).toHaveLength(2); + expect(events[1]).toEqual({ + connectionId: CONNECTION, organizationId: ORG, userId: d.userId, referenceKind: 'id', reference: 'no-such-4', suppressed: 2, + }); + expect(h.unresolvedWarns()).toHaveLength(2); + }); + + it('no row on the served-unchanged paths: a resolved manager re-sent, a write that names none, a dangling one left alone', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const emp = await provision(h, 'emp', { value: boss.scimId }); + const resent = await h.send(scimRequest(h.token, 'PUT', `/Users/${emp.scimId}`, userBody('emp', { value: boss.scimId }))); + expect(resent.status, await resent.clone().text()).toBe(200); + const gone = await h.send(scimRequest(h.token, 'DELETE', `/Users/${boss.scimId}`)); + expect(gone.status, await gone.clone().text()).toBe(204); + const renamed = await h.send(scimRequest(h.token, 'PATCH', `/Users/${emp.scimId}`, patch([ + { op: 'replace', path: 'displayName', value: 'Emp Renamed' }, + ]))); + expect(renamed.status, await renamed.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBe(boss.userId); + expect(await h.unresolvedEvents()).toEqual([]); + }); + + it('no row on the structural refusals: the write was refused and rolled back', async () => { + const h = await boot(); + const a = await provision(h, 'a'); + const b = await provision(h, 'b', { value: a.scimId }); + const self = await h.send(scimRequest(h.token, 'PATCH', `/Users/${a.scimId}`, patch([ + { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: a.scimId } }, + ]))); + await expectInvalidValue(self, 'INVALID_FIELD', /cannot be their own manager/); + const cycle = await h.send(scimRequest(h.token, 'PATCH', `/Users/${a.scimId}`, patch([ + { op: 'replace', path: `${SCIM_ENTERPRISE_USER_SCHEMA}:manager`, value: { value: b.scimId } }, + ]))); + await expectInvalidValue(cycle, 'RESOURCE_CONFLICT', /close a loop/); + expect(await h.unresolvedEvents()).toEqual([]); + }); + + it('a request refused after the warn admitted its reference records nothing', async () => { + const recordScimManagerUnresolved = vi.fn(async () => undefined); + const { observeScimManagerUnresolved } = await import('./scim-manager-projection.js'); + const note = { userId: 'usr_emp', referenceKind: 'id' as const, reference: 'no-such', suppressed: 0 }; + observeScimManagerUnresolved({ recordScimManagerUnresolved } as never, 409, { connectionId: CONNECTION, userManagerUnresolved: note }); + observeScimManagerUnresolved({ recordScimManagerUnresolved } as never, 500, { connectionId: CONNECTION, userManagerUnresolved: note }); + await new Promise((resolve) => setImmediate(resolve)); + expect(recordScimManagerUnresolved).not.toHaveBeenCalled(); + + // Control: the same note on a served answer is handed over. + observeScimManagerUnresolved({ recordScimManagerUnresolved } as never, 200, { connectionId: CONNECTION, userManagerUnresolved: note }); + await new Promise((resolve) => setImmediate(resolve)); + expect(recordScimManagerUnresolved).toHaveBeenCalledTimes(1); + }); +}); + describe('SCIM manager projection: silence is not a clear, and one predicate decides which door owns the column', () => { it('a write that does not name manager keeps a value the admin route set; a replace without it clears it', async () => { const h = await boot(); @@ -594,8 +705,10 @@ describe('readScimManagerReference', () => { expect(readScimManagerReference(JSON.stringify({ schemas: [USER_SCHEMA] }))).toEqual({ kind: 'none' }); expect(readScimManagerReference(attrs({ value: 'v1', $ref: 'https://x/Users/r1' }))).toEqual({ kind: 'id', id: 'v1' }); expect(readScimManagerReference(attrs({ $ref: 'https://x/scim/v2/Users/r%201' }))).toEqual({ kind: 'id', id: 'r 1' }); - expect(readScimManagerReference(attrs({ $ref: 'https://x/people/r1' }))).toEqual({ kind: 'unreadable' }); - expect(readScimManagerReference(attrs({ $ref: 'https://x/scim/v2/Users/%E0%A4%A' }))).toEqual({ kind: 'unreadable' }); + expect(readScimManagerReference(attrs({ $ref: 'https://x/people/r1' }))) + .toEqual({ kind: 'unreadable', ref: 'https://x/people/r1' }); + expect(readScimManagerReference(attrs({ $ref: 'https://x/scim/v2/Users/%E0%A4%A' }))) + .toEqual({ kind: 'unreadable', ref: 'https://x/scim/v2/Users/%E0%A4%A' }); }); }); diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.ts index 6eed8efac8e..5fb79d9448e 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.ts @@ -79,7 +79,16 @@ * write. The write lands, `manager_id` stays as it was, and an operator warn * names the connection, bounded per connection * ({@link SCIM_MANAGER_UNRESOLVED_WARNS_PER_WINDOW} per window, with the count - * it dropped). The check runs after the unchanged-manager short-circuit, and a + * it dropped). The same admission records the event once in the compliance + * ledger: the projection notes it on the request's scope, and + * {@link observeScimManagerUnresolved} hands it to the `audit` slot's + * `recordScimManagerUnresolved` after the response, outside the SCIM + * transaction, and only for a request answered below 400 — one + * `scim_manager_unresolved` row per warn, carrying the warn's dropped count, + * the user's id and the reference capped at + * {@link SCIM_MANAGER_REFERENCE_AUDIT_LIMIT} characters, and nothing else of + * the request. No `audit` slot, or one without the member: no row, and the + * answer is the same. The check runs after the unchanged-manager short-circuit, and a * write that does not name the attribute never reaches it, so a report whose * manager was deleted keeps working. The four structural refusals are the * admin endpoint's own, from {@link screenUserManagerLink} (self-assignment, @@ -97,7 +106,9 @@ import { writeUserManagerLink, type SetUserManagerDeps, } from './admin-set-user-manager.js'; -import { scimRequestScope } from './scim-connection-service.js'; +import type { AuthEventAuditSurface } from './auth-session-audit.js'; +import { runAfterResponse } from './run-after-response.js'; +import { scimRequestScope, type ScimManagerUnresolvedNote, type ScimRequestScope } from './scim-connection-service.js'; import { ScimRefusalAuditBound } from './scim-refusal-audit.js'; /** The SCIM Enterprise User extension the attribute lives in. */ @@ -110,6 +121,9 @@ const SYSTEM_READ_CTX = { isSystem: true, positions: [], permissions: [] } as co /** Operator warns one connection gets per 10-minute window for unresolvable references. */ export const SCIM_MANAGER_UNRESOLVED_WARNS_PER_WINDOW = 1; +/** The most characters of an unresolvable reference handed to the ledger. */ +export const SCIM_MANAGER_REFERENCE_AUDIT_LIMIT = 256; + /** The vendor-side `scimUser` row fields this module reads. */ interface ScimUserRow { id?: unknown; @@ -212,7 +226,7 @@ export async function scimUserManagerIntentOf( export type ScimManagerReference = | { kind: 'none' } | { kind: 'id'; id: string } - | { kind: 'unreadable' }; + | { kind: 'unreadable'; ref: string }; /** * The manager reference in a `scimUser` row's stored canonical attributes: @@ -232,11 +246,11 @@ export function readScimManagerReference(serializedAttributes: unknown): ScimMan if (typeof manager.value === 'string' && manager.value !== '') return { kind: 'id', id: manager.value }; if (typeof manager.$ref === 'string' && manager.$ref !== '') { const match = /\/Users\/([^/?#]+)\/?$/.exec(manager.$ref); - if (!match) return { kind: 'unreadable' }; + if (!match) return { kind: 'unreadable', ref: manager.$ref }; try { return { kind: 'id', id: decodeURIComponent(match[1]) }; } catch { - return { kind: 'unreadable' }; + return { kind: 'unreadable', ref: manager.$ref }; } } return { kind: 'none' }; @@ -280,9 +294,23 @@ export type ScimManagerProjection = (state: SCIMIdentityState, context: SCIMTran export function createScimManagerProjection(deps: ScimManagerProjectionDeps): ScimManagerProjection { const bound = deps.warnBound ?? new ScimRefusalAuditBound({ rowsPerKey: SCIM_MANAGER_UNRESOLVED_WARNS_PER_WINDOW }); - const warnUnresolved = (connectionId: string, userId: string): void => { + const warnUnresolved = ( + scope: ScimRequestScope, + connectionId: string, + userId: string, + reference: Exclude, + ): void => { const admitted = bound.admit(connectionId); if (!admitted) return; + // The ledger row rides the same admission, so it follows the warn's rate. + const raw = reference.kind === 'id' ? reference.id : reference.ref; + scope.userManagerUnresolved = { + userId, + referenceKind: reference.kind, + // One character past the cap survives, so the writer can say the row's copy was truncated. + reference: raw.slice(0, SCIM_MANAGER_REFERENCE_AUDIT_LIMIT + 1), + suppressed: admitted.suppressed, + }; deps.logger?.warn( `[auth] SCIM connection '${connectionId}' sent an Enterprise User manager reference that names no User ` + `it provisioned (user '${userId}'): the user write was served and sys_user.manager_id was left as it ` @@ -339,7 +367,7 @@ export function createScimManagerProjection(deps: ScimManagerProjectionDeps): Sc const current = text((Array.isArray(rows) ? (rows[0] as { manager_id?: unknown } | undefined) : undefined)?.manager_id); if (managerId !== undefined && current === (managerId ?? '')) return; if (managerId === undefined) { - warnUnresolved(connectionId, state.userId); + warnUnresolved(scope, connectionId, state.userId, reference as Exclude); return; } @@ -353,3 +381,56 @@ export function createScimManagerProjection(deps: ScimManagerProjectionDeps): Sc await writeUserManagerLink(engine, state.userId, managerId); }; } + +// --------------------------------------------------------------------------- +// The ledger row of an unresolvable reference, after the response +// --------------------------------------------------------------------------- + +/** The `audit` slot member this module hands its event to, declared locally (`AuthEventAuditSurface` note). */ +interface ScimManagerUnresolvedAuditSurface { + recordScimManagerUnresolved?(event: { + connectionId: string; + organizationId?: string; + userId: string; + referenceKind: 'id' | 'unreadable'; + reference: string; + suppressed?: number; + }): Promise; +} + +/** + * Hand the request's noted unresolvable reference, if any, to the sink's + * `recordScimManagerUnresolved`, after the response. Only a request answered + * below 400 records one: a refused request rolled its write back. Called by + * `handleRequest` outside `scimRequestScope`, so the row is never written + * inside the vendor's transaction. Never throws, and never delays or changes + * the answer. + */ +export function observeScimManagerUnresolved( + sink: AuthEventAuditSurface | undefined, + status: number, + scope: Pick, +): void { + try { + const note: ScimManagerUnresolvedNote | undefined = scope.userManagerUnresolved; + if (!note || status >= 400 || !scope.connectionId) return; + const writer = (sink as ScimManagerUnresolvedAuditSurface | undefined)?.recordScimManagerUnresolved; + if (typeof writer !== 'function') return; + const event = { + connectionId: scope.connectionId, + ...(scope.organizationId ? { organizationId: scope.organizationId } : {}), + userId: note.userId, + referenceKind: note.referenceKind, + reference: note.reference, + ...(note.suppressed > 0 ? { suppressed: note.suppressed } : {}), + }; + runAfterResponse( + () => writer.call(sink, event), + () => { + /* the writer reports its own lost rows; the SCIM answer is already given */ + }, + ); + } catch { + /* bookkeeping never changes a SCIM answer */ + } +} From 4958560ca27a75e38e941cbb59df866768b387e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:21:00 +0000 Subject: [PATCH 13/20] chore: changesets for the scim_manager_unresolved audit row Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .changeset/33918-scim-manager-projection.md | 2 +- .../33918-scim-manager-unresolved-audit.md | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 .changeset/33918-scim-manager-unresolved-audit.md diff --git a/.changeset/33918-scim-manager-projection.md b/.changeset/33918-scim-manager-projection.md index 9b601294bb9..6527ba0a890 100644 --- a/.changeset/33918-scim-manager-projection.md +++ b/.changeset/33918-scim-manager-projection.md @@ -17,7 +17,7 @@ Metadata-protocol: none - **Silence is not a clear.** A create or PATCH that does not name the attribute leaves `manager_id` as it is. An explicit PATCH `remove`, or a replace without the attribute, clears it. - **One owner per identity.** The projection writes only on an identity whose manager the directory owns, which is exactly the set the admin endpoint refuses (one shared predicate). On any other identity, for example one holding a local password, the admin endpoint owns the column and the projection writes nothing. -- **A reference that names no User is served.** An unknown id, an `externalId` or email, another connection's id, or a `$ref` with no readable `/Users/{id}` segment does not fail the write: the user is saved, `manager_id` stays as it was, and the server logs one operator warning per connection per window, with the count it held back. +- **A reference that names no User is served.** An unknown id, an `externalId` or email, another connection's id, or a `$ref` with no readable `/Users/{id}` segment does not fail the write: the user is saved, `manager_id` stays as it was, and the event is recorded with one operator warning and one `scim_manager_unresolved` audit row (when `@objectstack/plugin-audit` is installed), both once per connection per window, carrying the count held back. The row names the connection, the user and the reference, cut to 256 characters, and nothing else from the request; a request that is refused writes none. - **An unchanged manager is not judged again**, so a write is never refused over a chain other links have since reshaped, and a report whose manager was deleted keeps working. **Where it does not project, and why.** diff --git a/.changeset/33918-scim-manager-unresolved-audit.md b/.changeset/33918-scim-manager-unresolved-audit.md new file mode 100644 index 00000000000..98573ad7d4e --- /dev/null +++ b/.changeset/33918-scim-manager-unresolved-audit.md @@ -0,0 +1,20 @@ +--- +'@objectstack/plugin-audit': patch +--- + +feat(plugin-audit)!: `sys_audit_log` records a SCIM user write whose Enterprise `manager` reference names no user, as one bounded `scim_manager_unresolved` row + +Clause-②: yes (narrowing) +Metadata-protocol: none + + + +**BREAKING** in the SCIM behaviour this row belongs to, not in this package: plugin-auth now refuses with SCIM `400 invalidValue` a manager link the admin endpoint would refuse (self, cycle, depth cap, cross-organization); plugin-auth's note has the details. Nothing this package already wrote or read changes. + +**The new row.** `sys_audit_log.action` gains `scim_manager_unresolved` (label "SCIM Manager Unresolved"), written by the SCIM writer on the `audit` slot (`recordScimManagerUnresolved`, beside `recordScimRefusal`, through the same insert). plugin-auth hands it one event when a SCIM user write it served named an Enterprise User `manager` whose reference resolves to no user that connection provisioned: the write is saved, `manager_id` is left as it was, and the event is recorded with one operator warning and this row. + +- **Bounded rate.** The row and the warning share one admission: one per SCIM connection per 10-minute window. The next row carries the number held back in between as `metadata.suppressed`. +- **Bounded content.** `actor` is the connection's service principal (`svc:scim:CONNECTION_ID`), `object_name` / `record_id` the `sys_user` the write was about, `tenant_id` the connection's organization, and `metadata` holds `scim_connection_id`, `reference_kind` (`id` or `unreadable`) and `manager_reference`, the reference as the directory sent it, cut to 256 characters (`manager_reference_truncated: true` when it was longer). Nothing else from the request or the user is recorded. +- **Only served writes.** A refused request writes no such row (its `scim_refused` row is unchanged), and the row is written after the response, outside the SCIM transaction. + +Find them in the Audit Log under the "SCIM Manager Unresolved" action, or on the user's own audit history. From 94c33dc5e0f86666086baea0f1a491be93a226fc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:24:52 +0000 Subject: [PATCH 14/20] docs(approvals): an unresolvable SCIM manager reference also leaves a scim_manager_unresolved audit row Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- content/docs/automation/approvals.mdx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 80399ddcb05..da6d41b8396 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -105,7 +105,9 @@ SCIM `400 invalidValue`). It is written only for an active user the directory ho the connection that provisioned that user's profile. A write that does not name the attribute leaves the column as it is; removing the attribute, or a replace without it, clears the column. An id that names no user the connection provisioned does not fail the write: the user is saved, the -column stays as it was, and the server logs a warning for the operator. Where a SCIM directory holds an identity (it carries `source: 'idp_provisioned'` and +column stays as it was, and the server logs a warning for the operator and records a +`scim_manager_unresolved` row in the audit log, naming the connection, the user and the reference, once per +connection per ten minutes. 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. Any other directory sync writes it only through a path your own deployment supplies. A person who only From fa75b59c2b8d50954c040ed346595b6ba65722d1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:30:05 +0000 Subject: [PATCH 15/20] fix(plugin-auth): stamp each SCIM manager refusal code as a literal, so the dispatcher error vocabulary reads them Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .../src/scim-manager-projection.ts | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.ts index 5fb79d9448e..c80568c5aa2 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.ts @@ -105,6 +105,7 @@ import { screenUserManagerLink, writeUserManagerLink, type SetUserManagerDeps, + type SetUserManagerRefusal, } from './admin-set-user-manager.js'; import type { AuthEventAuditSurface } from './auth-session-audit.js'; import { runAfterResponse } from './run-after-response.js'; @@ -276,6 +277,31 @@ async function scimInvalidValue(code: string, detail: string): Promise { return error; } +/** + * The SCIM error for one of the admin endpoint's structural refusals. Switched + * on the refusal's OWN code, so nothing is re-derived here; each code is + * spelled as a literal at its stamp, so `check:dispatcher-error-vocabulary` + * reads exactly which codes this door answers. A code the screen does not + * stamp today has no SCIM mapping and fails loudly (the vendor answers a 500 + * and writes nothing) rather than being answered under another code. + */ +async function scimRefusalError(refusal: SetUserManagerRefusal): Promise { + switch (refusal.code) { + case 'INVALID_FIELD': + return scimInvalidValue('INVALID_FIELD', refusal.message); + case 'INVALID_REFERENCE': + return scimInvalidValue('INVALID_REFERENCE', refusal.message); + case 'RESOURCE_CONFLICT': + return scimInvalidValue('RESOURCE_CONFLICT', refusal.message); + case 'VALUE_OUT_OF_RANGE': + return scimInvalidValue('VALUE_OUT_OF_RANGE', refusal.message); + default: + return new Error( + `[auth] SCIM manager projection: the manager refusal code '${refusal.code}' has no SCIM mapping`, + ); + } +} + const text = (v: unknown): string => (typeof v === 'string' ? v : v == null ? '' : String(v)); /** The admin endpoint's own dependencies (the engine), plus the operator channel. */ @@ -373,7 +399,7 @@ export function createScimManagerProjection(deps: ScimManagerProjectionDeps): Sc if (managerId !== null) { const refusal = await screenUserManagerLink(deps, engine, state.userId, managerId); - if (refusal) throw await scimInvalidValue(refusal.code, refusal.message); + if (refusal) throw await scimRefusalError(refusal); } // Attributed to the connection (`svc:scim:CONNECTION_ID`) inside a SCIM From c659399a70d6088ff7408a00448fde3c7cc1eb74 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:42:37 +0000 Subject: [PATCH 16/20] i18n(plugin-audit): label scim_manager_unresolved in every shipped locale Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .../plugin-audit/src/translations/ar.objects.generated.ts | 3 ++- .../plugin-audit/src/translations/de.objects.generated.ts | 3 ++- .../plugin-audit/src/translations/en.objects.generated.ts | 3 ++- .../plugin-audit/src/translations/es-ES.objects.generated.ts | 3 ++- .../plugin-audit/src/translations/fr.objects.generated.ts | 3 ++- .../plugin-audit/src/translations/ja-JP.objects.generated.ts | 3 ++- .../plugin-audit/src/translations/ko.objects.generated.ts | 3 ++- .../plugin-audit/src/translations/pt-BR.objects.generated.ts | 3 ++- .../plugin-audit/src/translations/ru.objects.generated.ts | 3 ++- .../plugin-audit/src/translations/zh-CN.objects.generated.ts | 3 ++- .../plugin-audit/src/translations/zh-Hant.objects.generated.ts | 3 ++- 11 files changed, 22 insertions(+), 11 deletions(-) diff --git a/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts index ceedc232385..ab632fbc530 100644 --- a/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts @@ -45,7 +45,8 @@ export const arObjects: NonNullable = { credential_use: "استخدام بيانات الاعتماد", scim_refused: "رفض طلب SCIM", audit_signing_key_change: "تغيير مفتاح توقيع التدقيق", - dataset_query: "استعلام مجموعة بيانات" + dataset_query: "استعلام مجموعة بيانات", + scim_manager_unresolved: "تعذّر تحديد مدير SCIM" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts index 7d435e5a744..4f22461c266 100644 --- a/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts @@ -45,7 +45,8 @@ export const deObjects: NonNullable = { credential_use: "Verwendung von Anmeldedaten", scim_refused: "SCIM-Anfrage abgelehnt", audit_signing_key_change: "Änderung des Audit-Signaturschlüssels", - dataset_query: "Dataset-Abfrage" + dataset_query: "Dataset-Abfrage", + scim_manager_unresolved: "SCIM-Vorgesetzter nicht auflösbar" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts index bbf8b7dc2e7..2ed5a9678dd 100644 --- a/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts @@ -45,7 +45,8 @@ export const enObjects: NonNullable = { credential_use: "Credential Use", scim_refused: "SCIM Refused", audit_signing_key_change: "Audit Signing Key Change", - dataset_query: "Dataset Query" + dataset_query: "Dataset Query", + scim_manager_unresolved: "SCIM Manager Unresolved" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts index d311895d0d9..1cd3f1437ac 100644 --- a/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts @@ -45,7 +45,8 @@ export const esESObjects: NonNullable = { credential_use: "Uso de credencial", scim_refused: "Solicitud SCIM rechazada", audit_signing_key_change: "Cambio de clave de firma de auditoría", - dataset_query: "Consulta de conjunto de datos" + dataset_query: "Consulta de conjunto de datos", + scim_manager_unresolved: "Responsable SCIM no resuelto" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts index 3fc0bb1b903..f00c368739c 100644 --- a/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts @@ -45,7 +45,8 @@ export const frObjects: NonNullable = { credential_use: "Utilisation d’identifiants", scim_refused: "Requête SCIM refusée", audit_signing_key_change: "Changement de clé de signature d’audit", - dataset_query: "Requête de jeu de données" + dataset_query: "Requête de jeu de données", + scim_manager_unresolved: "Responsable SCIM non résolu" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts index 2d4ffd6603a..7f6b8eb56e7 100644 --- a/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts @@ -45,7 +45,8 @@ export const jaJPObjects: NonNullable = { credential_use: "資格情報の使用", scim_refused: "SCIM 要求の拒否", audit_signing_key_change: "監査署名キーの変更", - dataset_query: "データセットクエリ" + dataset_query: "データセットクエリ", + scim_manager_unresolved: "SCIM マネージャーの未解決" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts index 991b0e31b2c..9fc133a53dc 100644 --- a/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts @@ -45,7 +45,8 @@ export const koObjects: NonNullable = { credential_use: "자격 증명 사용", scim_refused: "SCIM 요청 거부", audit_signing_key_change: "감사 서명 키 변경", - dataset_query: "데이터 세트 쿼리" + dataset_query: "데이터 세트 쿼리", + scim_manager_unresolved: "SCIM 관리자 확인 불가" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts index a8355497d3e..6b2fb8c0032 100644 --- a/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts @@ -45,7 +45,8 @@ export const ptBRObjects: NonNullable = { credential_use: "Uso de credencial", scim_refused: "Solicitação SCIM recusada", audit_signing_key_change: "Alteração da chave de assinatura de auditoria", - dataset_query: "Consulta de conjunto de dados" + dataset_query: "Consulta de conjunto de dados", + scim_manager_unresolved: "Gestor SCIM não resolvido" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts index b4815144258..a8b4a78a9de 100644 --- a/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts @@ -45,7 +45,8 @@ export const ruObjects: NonNullable = { credential_use: "Использование учётных данных", scim_refused: "Запрос SCIM отклонён", audit_signing_key_change: "Изменение ключа подписи аудита", - dataset_query: "Запрос к набору данных" + dataset_query: "Запрос к набору данных", + scim_manager_unresolved: "Руководитель SCIM не найден" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts index 51d8c96b13e..694ccef42f8 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts @@ -45,7 +45,8 @@ export const zhCNObjects: NonNullable = { credential_use: "凭据使用", scim_refused: "SCIM 请求被拒", audit_signing_key_change: "审计签名密钥变更", - dataset_query: "数据集查询" + dataset_query: "数据集查询", + scim_manager_unresolved: "SCIM 上级无法解析" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts index 8d317587bae..c5ea7f54e81 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts @@ -45,7 +45,8 @@ export const zhHantObjects: NonNullable = { credential_use: "憑證使用", scim_refused: "SCIM 請求遭拒", audit_signing_key_change: "稽核簽章金鑰變更", - dataset_query: "資料集查詢" + dataset_query: "資料集查詢", + scim_manager_unresolved: "SCIM 上級無法解析" } }, user_id: { From 50a7e17b563ea5edfe54d2e816d55c0fe4a049cd Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:47:04 +0000 Subject: [PATCH 17/20] test(plugin-auth): reach the door's reference cap through a long $ref, the attribute the vendor lets past 256 characters Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .../plugins/plugin-auth/src/scim-manager-projection.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts index 7cecef7cce2..a349586ad04 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts @@ -429,8 +429,10 @@ describe('[#33918] SCIM manager projection: an unresolvable reference leaves one it('the reference is capped, and nothing of the body rides with it', async () => { const h = await boot(); - const long = `r${'x'.repeat(400)}`; - await provision(h, 'emp', { value: long }); + // The vendor caps `manager.value` at 256 characters but a `$ref` at 2048, + // so a long unreadable `$ref` is what reaches the door's cap. + const long = `https://idp.example/people/${'x'.repeat(400)}`; + await provision(h, 'emp', { $ref: long }); const [event] = await h.unresolvedEvents(); expect(String(event?.reference)).toBe(long.slice(0, 257)); const carried = JSON.stringify(event); From dcf1984e5f6515d69bb3c4fe36664501d815e57d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:00:58 +0000 Subject: [PATCH 18/20] test(plugin-auth): a manager.value past 256 characters is the vendor's refusal, with no audit row Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .../plugin-auth/src/scim-manager-projection.test.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts index a349586ad04..d2f06479732 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts @@ -441,6 +441,17 @@ describe('[#33918] SCIM manager projection: an unresolvable reference leaves one } }); + it('a manager.value past 256 characters is the vendor\'s 400: nothing written, no row', async () => { + const h = await boot(); + const res = await h.send(scimRequest(h.token, 'POST', '/Users', userBody('emp', { value: 'v'.repeat(257) }))); + const text = await res.text(); + expect(res.status, text).toBe(400); + expect((JSON.parse(text) as { scimType?: string }).scimType).toBe('invalidValue'); + expect(await h.engine.find('sys_user', { where: { email: 'emp@acme.com' }, fields: ['id'] }, SYSTEM)).toEqual([]); + expect(await h.unresolvedEvents()).toEqual([]); + expect(h.unresolvedWarns()).toHaveLength(0); + }); + it('rows follow the warn\'s rate: one per connection per window, and the next carries the dropped count', async () => { const h = await boot(); await provision(h, 'a', { value: 'no-such-1' }); From 4c0b0ffd9bd0fc0b3d508e26f2e36ccc9609d1e7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:06:42 +0000 Subject: [PATCH 19/20] test(plugin-auth): pin the unchanged-manager short-circuit on a replace, the write that names the manager Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .../plugins/plugin-auth/src/scim-manager-projection.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts index d2f06479732..c19df09017d 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts @@ -314,6 +314,12 @@ describe('SCIM manager projection: the directory sets, changes and clears sys_us ]))); expect(renamed.status, await renamed.clone().text()).toBe(200); expect(await managerOf(h, emp.userId)).toBe(boss.userId); + + // A replace NAMES the manager, so it reaches the projection: the same + // manager is not judged again, though linking it afresh would be past the cap. + const resent = await h.send(scimRequest(h.token, 'PUT', `/Users/${emp.scimId}`, userBody('emp', { value: boss.scimId }))); + expect(resent.status, await resent.clone().text()).toBe(200); + expect(await managerOf(h, emp.userId)).toBe(boss.userId); }); it('a deprovision is never refused over a manager reference that no longer resolves', async () => { From 317c495572e4351db852b1e1e26183ac04a68f36 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 12:39:02 +0000 Subject: [PATCH 20/20] fix(plugin-auth): serve a manager reference whose platform user is gone, like any reference that names no User A connection's own SCIM User whose sys_user no longer exists screened as manager_not_found and answered SCIM 400. Per maintainer ruling 6909383114 it names no User: the write is served, manager_id is unchanged, and it gets the bounded warn and scim_manager_unresolved row. Only the four structural refusals answer 400. The ownership predicate now answers with the user's row, so the projection reads sys_user once per write instead of twice. Changesets: the upgrade note on replace-syncing providers that map no manager, and the note that the warn's admission runs inside the SCIM transaction. Lint and approvals docs say "no existing user". Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .changeset/33918-lint-scim-manager-route.md | 2 +- .changeset/33918-scim-manager-projection.md | 4 ++- .../33918-scim-manager-unresolved-audit.md | 2 +- content/docs/automation/approvals.mdx | 2 +- packages/lint/src/rule-explanations.ts | 2 +- .../plugin-auth/src/admin-set-user-manager.ts | 16 +++++++-- .../src/scim-manager-projection.test.ts | 35 +++++++++++++++++++ .../src/scim-manager-projection.ts | 31 ++++++++-------- 8 files changed, 73 insertions(+), 21 deletions(-) diff --git a/.changeset/33918-lint-scim-manager-route.md b/.changeset/33918-lint-scim-manager-route.md index 809f4db94d5..e1cc94d6eb6 100644 --- a/.changeset/33918-lint-scim-manager-route.md +++ b/.changeset/33918-lint-scim-manager-route.md @@ -11,4 +11,4 @@ Metadata-protocol: none **BREAKING** in the behaviour this text now describes, not in the lint package: a SCIM user write whose named manager would make the user their own manager, close a cycle, run past the depth cap or cross an organization boundary was served before and is now refused with SCIM `400 invalidValue` (plugin-auth's note has the details). The lint rule and its findings are unchanged. -The `manager` arm's remedy said the platform declares the SCIM `manager` attribute without projecting it onto the column. plugin-auth now projects it, so the remedy says that the Enterprise User `manager` attribute, whose value is the manager's SCIM resource id, is written onto the column for an active user a SCIM directory holds, from the connection that provisioned that user's profile, on a create, replace or patch that names the attribute, through the admin operation's refusals. A write that does not name it leaves the column as it is, and an id naming no user the connection provisioned is served with the column unchanged. Any other directory sync is still named as something your own deployment supplies. +The `manager` arm's remedy said the platform declares the SCIM `manager` attribute without projecting it onto the column. plugin-auth now projects it, so the remedy says that the Enterprise User `manager` attribute, whose value is the manager's SCIM resource id, is written onto the column for an active user a SCIM directory holds, from the connection that provisioned that user's profile, on a create, replace or patch that names the attribute, through the admin operation's refusals. A write that does not name it leaves the column as it is, and an id naming no existing user the connection provisioned is served with the column unchanged. Any other directory sync is still named as something your own deployment supplies. diff --git a/.changeset/33918-scim-manager-projection.md b/.changeset/33918-scim-manager-projection.md index 6527ba0a890..53aeabf2ddf 100644 --- a/.changeset/33918-scim-manager-projection.md +++ b/.changeset/33918-scim-manager-projection.md @@ -11,13 +11,15 @@ Metadata-protocol: none **BREAKING** for a SCIM identity provider that sends a manager the admin endpoint would refuse. A SCIM create, replace or patch that names the Enterprise User `manager` attribute, for an active user the directory holds, whose manager resolves to a User the same connection provisioned, and where that link would make the user their own manager, close a cycle, run past the 20-link depth cap, or cross an organization boundary, used to answer `201` / `200` and leave `manager_id` untouched. It now answers SCIM `400` with `scimType: invalidValue` and the admin endpoint's reason, and nothing of the request is written. Those four are the only requests served before and refused now. Remedy: correct the manager in the directory. +**On upgrade.** An identity provider that syncs by replace and maps no manager clears, on its next sync, a `manager_id` set earlier for a user the directory holds, because a replace without the attribute is a clear. Map the manager attribute in the identity provider before upgrading if those values should stay. + **The gap.** `POST /api/v1/auth/admin/set-user-manager` refuses a person a SCIM directory holds and says to change the manager in the directory, but nothing carried the directory's answer to `sys_user.manager_id`: `@better-auth/scim` stored and echoed `urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:manager` and wrote nothing of it onto the user. So a SCIM-held user's manager could not change from either side, and approvals routed to the manager could not follow a reorganisation. **The rule.** A SCIM user write that names the attribute now projects `manager.value` onto `sys_user.manager_id`, inside the SCIM transaction. `manager.value` is the manager's SCIM resource `id` (RFC 7643 §4.3), looked up among the Users the same connection provisioned; a `$ref` alone is read by its final `/Users/{id}` segment. The link goes through the admin endpoint's own refusals, above. - **Silence is not a clear.** A create or PATCH that does not name the attribute leaves `manager_id` as it is. An explicit PATCH `remove`, or a replace without the attribute, clears it. - **One owner per identity.** The projection writes only on an identity whose manager the directory owns, which is exactly the set the admin endpoint refuses (one shared predicate). On any other identity, for example one holding a local password, the admin endpoint owns the column and the projection writes nothing. -- **A reference that names no User is served.** An unknown id, an `externalId` or email, another connection's id, or a `$ref` with no readable `/Users/{id}` segment does not fail the write: the user is saved, `manager_id` stays as it was, and the event is recorded with one operator warning and one `scim_manager_unresolved` audit row (when `@objectstack/plugin-audit` is installed), both once per connection per window, carrying the count held back. The row names the connection, the user and the reference, cut to 256 characters, and nothing else from the request; a request that is refused writes none. +- **A reference that names no User is served.** An unknown id, an `externalId` or email, another connection's id, a `$ref` with no readable `/Users/{id}` segment, or a User of this connection whose platform user no longer exists does not fail the write: the user is saved, `manager_id` stays as it was, and the event is recorded with one operator warning and one `scim_manager_unresolved` audit row (when `@objectstack/plugin-audit` is installed), both once per connection per window, carrying the count held back. The row names the connection, the user and the reference, cut to 256 characters, and nothing else from the request; a request that is refused writes none. - **An unchanged manager is not judged again**, so a write is never refused over a chain other links have since reshaped, and a report whose manager was deleted keeps working. **Where it does not project, and why.** diff --git a/.changeset/33918-scim-manager-unresolved-audit.md b/.changeset/33918-scim-manager-unresolved-audit.md index 98573ad7d4e..0f2f7f0e538 100644 --- a/.changeset/33918-scim-manager-unresolved-audit.md +++ b/.changeset/33918-scim-manager-unresolved-audit.md @@ -13,7 +13,7 @@ Metadata-protocol: none **The new row.** `sys_audit_log.action` gains `scim_manager_unresolved` (label "SCIM Manager Unresolved"), written by the SCIM writer on the `audit` slot (`recordScimManagerUnresolved`, beside `recordScimRefusal`, through the same insert). plugin-auth hands it one event when a SCIM user write it served named an Enterprise User `manager` whose reference resolves to no user that connection provisioned: the write is saved, `manager_id` is left as it was, and the event is recorded with one operator warning and this row. -- **Bounded rate.** The row and the warning share one admission: one per SCIM connection per 10-minute window. The next row carries the number held back in between as `metadata.suppressed`. +- **Bounded rate.** The row and the warning share one admission: one per SCIM connection per 10-minute window. The next row carries the number held back in between as `metadata.suppressed`. The admission happens inside the SCIM transaction, before the answer is known: a request refused after its reference was admitted still logs the warning and spends the window, so the next served unresolvable reference in that window is counted only in `suppressed`. - **Bounded content.** `actor` is the connection's service principal (`svc:scim:CONNECTION_ID`), `object_name` / `record_id` the `sys_user` the write was about, `tenant_id` the connection's organization, and `metadata` holds `scim_connection_id`, `reference_kind` (`id` or `unreadable`) and `manager_reference`, the reference as the directory sent it, cut to 256 characters (`manager_reference_truncated: true` when it was longer). Nothing else from the request or the user is recorded. - **Only served writes.** A refused request writes no such row (its `scim_refused` row is unchanged), and the row is written after the response, outside the SCIM transaction. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index da6d41b8396..716f173b37e 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -104,7 +104,7 @@ create, replace or patch that names the attribute, through the same refusals (ea SCIM `400 invalidValue`). It is written only for an active user the directory holds, and only from the connection that provisioned that user's profile. A write that does not name the attribute leaves the column as it is; removing the attribute, or a replace without it, clears the column. An -id that names no user the connection provisioned does not fail the write: the user is saved, the +id that names no existing user the connection provisioned does not fail the write: the user is saved, the column stays as it was, and the server logs a warning for the operator and records a `scim_manager_unresolved` row in the audit log, naming the connection, the user and the reference, once per connection per ten minutes. Where a SCIM directory holds an identity (it carries `source: 'idp_provisioned'` and diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 70af38684e6..e3c6829f5f2 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -3338,7 +3338,7 @@ const MANAGER_ONLY_ROUTES = 'profile: the Enterprise User \'manager\' attribute, whose value is the manager\'s SCIM resource ' + 'id, is written onto the column on a SCIM create, replace or patch that names the attribute, ' + 'through those same refusals. A write that does not name it leaves the column as it is, and an ' + - 'id that names no user the connection provisioned is served and leaves the column unchanged. ' + + 'id that names no existing user the connection provisioned is served and leaves the column unchanged. ' + 'Where a SCIM directory holds an identity, the admin operation refuses it, the import\'s ' + 'manager_id column included, leaving that directory the one surface that authors its manager. Any other directory sync ' + 'populates it only through a provisioning path your own deployment supplies. An identity that ' + 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 6de502c7052..80c2b9c0c5b 100644 --- a/packages/plugins/plugin-auth/src/admin-set-user-manager.ts +++ b/packages/plugins/plugin-auth/src/admin-set-user-manager.ts @@ -304,10 +304,22 @@ async function directoryOwnsManagerOf(engine: SetUserManagerEngine, user: UserRo return String(user.source ?? '') === 'idp_provisioned' && await heldByScimDirectory(engine, String(user.id)); } +/** + * {@link directoryOwnsManagerOf}, by id, answering with the user's row (its + * `manager_id` included) when the directory owns it and `null` otherwise, a + * user that does not exist among them: the predicate and the column in one read. + */ +export async function directoryOwnedUser( + engine: SetUserManagerEngine, + userId: string, +): Promise<{ readonly manager_id?: unknown } | null> { + const user = await findUser(engine, userId); + return user && await directoryOwnsManagerOf(engine, user) ? user : null; +} + /** {@link directoryOwnsManagerOf}, by id: `false` for a user that does not exist. */ export async function directoryOwnsUserManager(engine: SetUserManagerEngine, userId: string): Promise { - const user = await findUser(engine, userId); - return user ? directoryOwnsManagerOf(engine, user) : false; + return (await directoryOwnedUser(engine, userId)) !== null; } /** diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts index c19df09017d..fb01a0fba62 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.test.ts @@ -477,6 +477,41 @@ describe('[#33918] SCIM manager projection: an unresolvable reference leaves one expect(h.unresolvedWarns()).toHaveLength(2); }); + it('a connection\'s own User whose platform user is gone names no User: a create and a replace are served, one warn and one row each', async () => { + const h = await boot(); + const boss = await provision(h, 'boss'); + const ex = await provision(h, 'ex'); + const emp2 = await provision(h, 'emp2', { value: ex.scimId }); + expect(await managerOf(h, emp2.userId)).toBe(ex.userId); + // The vendor's scimUser row stays and its sys_user goes: removed at the + // driver, past the engine's restrict, the way an out-of-band delete lands. + const driver = (h.engine as unknown as { getDriver: (object: string) => { delete: (object: string, id: string) => Promise } }) + .getDriver('sys_user'); + await driver.delete('sys_user', boss.userId); + expect(await h.engine.find('sys_user', { where: { id: boss.userId }, fields: ['id'] }, SYSTEM), 'the boss row is gone').toEqual([]); + + const res = await h.send(scimRequest(h.token, 'POST', '/Users', userBody('emp1', { value: boss.scimId }))); + expect(res.status, await res.clone().text()).toBe(201); + const emp1 = await userIdOf(h, 'emp1@acme.com'); + expect(await managerOf(h, emp1)).toBeNull(); + expect(h.unresolvedWarns()).toHaveLength(1); + expect(await h.unresolvedEvents()).toEqual([ + { connectionId: CONNECTION, organizationId: ORG, userId: emp1, referenceKind: 'id', reference: boss.scimId }, + ]); + + // A fresh window, so the replace's warn and row are its own. + vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 11 * 60_000); + const replaced = await h.send(scimRequest(h.token, 'PUT', `/Users/${emp2.scimId}`, userBody('emp2', { value: boss.scimId }))); + expect(replaced.status, await replaced.clone().text()).toBe(200); + expect(await managerOf(h, emp2.userId)).toBe(ex.userId); + expect(h.unresolvedWarns()).toHaveLength(2); + const events = await h.unresolvedEvents(); + expect(events).toHaveLength(2); + expect(events[1]).toEqual({ + connectionId: CONNECTION, organizationId: ORG, userId: emp2.userId, referenceKind: 'id', reference: boss.scimId, + }); + }); + it('no row on the served-unchanged paths: a resolved manager re-sent, a write that names none, a dangling one left alone', async () => { const h = await boot(); const boss = await provision(h, 'boss'); diff --git a/packages/plugins/plugin-auth/src/scim-manager-projection.ts b/packages/plugins/plugin-auth/src/scim-manager-projection.ts index c80568c5aa2..bf9ad15a509 100644 --- a/packages/plugins/plugin-auth/src/scim-manager-projection.ts +++ b/packages/plugins/plugin-auth/src/scim-manager-projection.ts @@ -75,7 +75,8 @@ * * Maintainer ruling record 6909383114: a reference that cannot be resolved — * an unknown id, an `externalId`-style value, another connection's id, a - * `$ref` with no readable `/Users/{id}` segment — does not refuse the user + * `$ref` with no readable `/Users/{id}` segment, this connection's own User + * whose platform user no longer exists — does not refuse the user * write. The write lands, `manager_id` stays as it was, and an operator warn * names the connection, bounded per connection * ({@link SCIM_MANAGER_UNRESOLVED_WARNS_PER_WINDOW} per window, with the count @@ -101,7 +102,7 @@ import type { SCIMIdentityState, SCIMTransactionContext } from '@better-auth/scim'; import { - directoryOwnsUserManager, + directoryOwnedUser, screenUserManagerLink, writeUserManagerLink, type SetUserManagerDeps, @@ -117,8 +118,6 @@ export const SCIM_ENTERPRISE_USER_SCHEMA = 'urn:ietf:params:scim:schemas:extensi const SCIM_ERROR_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:Error'; -const SYSTEM_READ_CTX = { isSystem: true, positions: [], permissions: [] } as const; - /** Operator warns one connection gets per 10-minute window for unresolvable references. */ export const SCIM_MANAGER_UNRESOLVED_WARNS_PER_WINDOW = 1; @@ -366,8 +365,10 @@ export function createScimManagerProjection(deps: ScimManagerProjectionDeps): Sc `[auth] SCIM manager projection: no data engine to write sys_user.manager_id for user '${state.userId}'`, ); } - // The one ownership predicate the admin endpoint's refusal 5 reads. - if (!(await directoryOwnsUserManager(engine, state.userId))) return; + // The one ownership predicate the admin endpoint's refusal 5 reads; the + // row it answers with carries the column's current value. + const owned = await directoryOwnedUser(engine, state.userId); + if (!owned) return; const reference = readScimManagerReference(source.serializedAttributes); let managerId: string | null | undefined = null; // `undefined` = unresolvable @@ -384,21 +385,23 @@ export function createScimManagerProjection(deps: ScimManagerProjectionDeps): Sc managerId = managerSource && text(managerSource.userId) ? text(managerSource.userId) : undefined; } - const rows = await engine.find('sys_user', { - where: { id: state.userId }, - fields: ['id', 'manager_id'], - limit: 1, - context: SYSTEM_READ_CTX, - }); - const current = text((Array.isArray(rows) ? (rows[0] as { manager_id?: unknown } | undefined) : undefined)?.manager_id); + const current = text(owned.manager_id); if (managerId !== undefined && current === (managerId ?? '')) return; + const named = reference as Exclude; if (managerId === undefined) { - warnUnresolved(scope, connectionId, state.userId, reference as Exclude); + warnUnresolved(scope, connectionId, state.userId, named); return; } if (managerId !== null) { const refusal = await screenUserManagerLink(deps, engine, state.userId, managerId); + // A connection's own SCIM row whose user no longer exists names no User + // either: served, like any unresolvable reference (ruling 6909383114). + // Only the four structural refusals answer 400. + if (refusal?.reason === 'manager_not_found') { + warnUnresolved(scope, connectionId, state.userId, named); + return; + } if (refusal) throw await scimRefusalError(refusal); }