From 87aac9842300c4b184adab17bbec79fb4f401df6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 18:07:03 +0000 Subject: [PATCH 1/5] wip(plugin-auth): SSO group claim projects the IdP group mapping (WIP) Claude-Session: https://claude.ai/code/session_01ADHkmNwrm1hJ9e7eLARM7n Co-authored-by: Claude --- .../identity/sys-idp-group-mapping.object.ts | 26 +- .../src/auth-manager-plugin-list.ts | 16 + .../plugins/plugin-auth/src/auth-plugin.ts | 6 +- .../plugin-auth/src/auth-route-ledger.ts | 4 +- .../src/idp-group-mapping-admin.ts | 215 +++++++++-- .../plugin-auth/src/scim-group-projection.ts | 140 ++++++-- .../plugin-auth/src/sso-group-projection.ts | 119 ++++++ .../src/sso-oidc-refusal-cause.test.ts | 339 +++++++++++++++++- 8 files changed, 783 insertions(+), 82 deletions(-) create mode 100644 packages/plugins/plugin-auth/src/sso-group-projection.ts diff --git a/packages/platform-objects/src/identity/sys-idp-group-mapping.object.ts b/packages/platform-objects/src/identity/sys-idp-group-mapping.object.ts index 68d5aa11f8f..61bb76ccfde 100644 --- a/packages/platform-objects/src/identity/sys-idp-group-mapping.object.ts +++ b/packages/platform-objects/src/identity/sys-idp-group-mapping.object.ts @@ -6,11 +6,12 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; * sys_idp_group_mapping — which permission set an identity provider's group * grants (ADR-0134 D4's group seam, filled for permission sets only). * - * One row says: a member of THIS group, pushed by THIS source, holds THIS - * permission set in THIS organization. The source is a SCIM connection today + * One row says: a member of THIS group, sent by THIS source, holds THIS + * permission set in THIS organization. The source is a SCIM connection * (`source_kind: 'scim'`, `source_id` = the connection id the bearer verifies - * as); the kind column is there so an SSO provider's group claim can name its - * provider the same way later, without a second mapping model. + * as) or an SSO provider whose sign-in carries the user's groups as a claim + * (`source_kind: 'sso'`, `source_id` = the provider id): one mapping model for + * both, never a second one. * * Who writes it: the platform administrator, through plugin-auth's * `/admin/scim/set-group-mapping` and `/admin/scim/delete-group-mapping` @@ -23,8 +24,10 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; * administrator standing. * * Who reads it: the SCIM `projection` (`scim-group-projection.ts`) when a - * group's membership changes. A group is matched by its `externalId` when the - * row names one, else by its `displayName`; the row names exactly one. + * group's membership changes, and the SSO sign-in (`sso-group-projection.ts`) + * on every sign-in through the provider. A group is matched by its + * `externalId` (for SSO: a claim value equal to it) when the row names one, + * else by its `displayName`; the row names exactly one. * * @namespace sys */ @@ -68,16 +71,19 @@ export const SysIdpGroupMapping = ObjectSchema.create({ label: 'Source Kind', required: true, defaultValue: 'scim', - description: 'What pushes the group: a SCIM connection.', + description: 'What sends the group: a SCIM connection, or an SSO provider at sign-in.', group: 'Source', - options: [{ value: 'scim', label: 'SCIM Connection' }], + options: [ + { value: 'scim', label: 'SCIM Connection' }, + { value: 'sso', label: 'SSO Provider' }, + ], }), source_id: Field.text({ label: 'Source ID', required: true, maxLength: 255, - description: 'The SCIM connection ID the group arrives through, e.g. "okta-prod".', + description: 'The SCIM connection ID or the SSO provider ID the group arrives through, e.g. "okta-prod".', group: 'Source', }), @@ -109,7 +115,7 @@ export const SysIdpGroupMapping = ObjectSchema.create({ label: 'Organization', required: false, maxLength: 255, - description: 'The organization the grant is made in: the organization that owns the SCIM connection.', + description: 'The organization the grant is made in: the organization that owns the SCIM connection or the SSO provider.', group: 'Grant', }), 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 84421974707..79e27783189 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts @@ -770,11 +770,27 @@ export async function buildPluginList(this: PluginListHost): Promise { // OFF by default, so the vendor's own register / update-provider doors // write them. `saml` hands the vendor its one IdP-initiated option as a // getter that answers the ACS request's own provider. + // + // IdP group → permission set (the same ruling, item 3; `sso-group-projection.ts`): + // every sign-in's group claim (`userInfo.groups`, filled by the provider's own + // `mapping.extraFields.groups`) is matched against the provider's + // `sys_idp_group_mapping` rows, the SCIM half's one model, and only ordinary + // permission sets inside the organization boundary are granted. On EVERY + // sign-in, so the grants follow the IdP's groups; a failure is logged and + // never fails the sign-in. + const { createSsoGroupProvisioner } = await import('./sso-group-projection.js'); return sso({ organizationProvisioning: { defaultRole: 'member' }, ...(enabled.ssoDomainVerification ? { domainVerification: { enabled: true } } : {}), saml: ssoSamlOptions(), schema: { ssoProvider: { additionalFields: SSO_PROVIDER_SIGN_IN_FIELDS } }, + provisionUser: createSsoGroupProvisioner({ + getEngine: () => this.getDataEngine(), + boundary: async () => (await this.config.organizationBoundary?.().catch(() => undefined)) ?? undefined, + warn: (message) => this.config.logger?.warn?.(message), + error: (message) => this.config.logger?.error?.(message), + }), + provisionUserOnEveryLogin: true, }); }); } diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 368a3c7e342..f07a8d91623 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -4251,14 +4251,16 @@ export class AuthPlugin implements Plugin { }); // [ADR-0134 D4, filled for permission sets] The identity-provider group - // mapping door: which ordinary permission set a SCIM connection's group - // grants. The same gate as the credential door above, then the save + // mapping door: which ordinary permission set a SCIM connection's group, + // or an SSO provider's sign-in group claim (ruling record 6718355623, + // item 3: the same mapping, no second model), grants. The same gate as the credential door above, then the save // refuses any set outside the organization boundary (judged by the // `security` service), so an IdP group never confers administrator // standing. See `idp-group-mapping-admin.ts`. const groupMappingDeps = (actor: PlatformAdminActor): import('./idp-group-mapping-admin.js').IdpGroupMappingAdminDeps => ({ getDataEngine: () => this.authManager!.getDataEngine(), isScimEnabled: () => this.authManager!.isScimWired(), + isSsoEnabled: () => this.authManager!.isSsoWired(), boundary: () => this.authManager!.organizationBoundaryJudge(), reconcile: (domain) => this.authManager!.reconcileScimProjectionDomain(domain), attributed: (fn) => runAttributedToUser(actor, fn), diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.ts index beb48032ed3..fec1c735afa 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.ts @@ -254,8 +254,8 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [ // #16678 note below. { route: 'POST /api/v1/auth/admin/scim/mint-credential', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', requires: 'scim', note: 'no SDK method builds this URL — an operator script or the identity-provider setup posts it; mints the bearer a SCIM connection authenticates with (scim-connection-service.ts) and answers the plaintext once, Cache-Control: no-store — only its keyed one-way digest is stored, and nothing logs it; refused 503 SERVICE_UNAVAILABLE while SCIM is off; one sys_audit_log row per mint naming the admin and the connection, never the credential; platform-admin gated (ADR-0068), ADR-0134' }, { route: 'POST /api/v1/auth/admin/scim/revoke-credential', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — an operator script posts it with the credentialId the mint answered; switches that credential row inactive, so the SCIM verifier refuses its bearer from the next request on (rotation is a second mint for the same connection, then this); 404 for an unknown credential, 409 when already revoked; one sys_audit_log row per revoke naming the admin and the connection; served whether or not SCIM is on; platform-admin gated (ADR-0068), ADR-0134' }, - { route: 'POST /api/v1/auth/admin/scim/set-group-mapping', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', requires: 'scim', note: 'no SDK method builds this URL — an operator script posts it; saves one sys_idp_group_mapping row (a SCIM connection group, by externalId or displayName, to one permission set in the connection organization) and re-projects the connection so current members gain it; refused 400 VALIDATION_FAILED on permissionSet for any set outside the organization boundary (administrator sets, agent ceilings, superuser wildcards, adminScope, non-organization capabilities), judged by the security service; a re-save of the same group and set is idempotent in the connection organization, and refused 409 RESOURCE_CONFLICT naming the old mapping when that row lives in another organization (delete it first); 503 while SCIM or the security service is absent; one sys_audit_log row per save; platform-admin gated (ADR-0068), ADR-0134 D4' }, - { route: 'POST /api/v1/auth/admin/scim/delete-group-mapping', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — an operator script posts it with the mappingId the save answered; deletes that sys_idp_group_mapping row and re-projects the connection so the grants it made go (with SCIM off nothing is re-projected and those grants stay until removed by hand; the answer says reprojected: false); 404 for an unknown mapping; one sys_audit_log row per delete; platform-admin gated (ADR-0068), ADR-0134 D4' }, + { route: 'POST /api/v1/auth/admin/scim/set-group-mapping', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — an operator script posts it; saves one sys_idp_group_mapping row (a group, by externalId or displayName, to one permission set) for a SCIM connection (connectionId: in the connection organization, re-projected at once so current members gain it) or an SSO provider (providerId: in the provider organization, applied at each member next sign-in through that provider, from the userInfo.groups the provider mapping.extraFields fills; the answer says reprojected: false); exactly one of connectionId / providerId; refused 400 VALIDATION_FAILED on permissionSet for any set outside the organization boundary (administrator sets, agent ceilings, superuser wildcards, adminScope, non-organization capabilities), judged by the security service; a re-save of the same group and set is idempotent in the connection organization, and refused 409 RESOURCE_CONFLICT naming the old mapping when that row lives in another organization (delete it first); 503 while SCIM (connectionId), SSO (providerId) or the security service is absent; one sys_audit_log row per save; platform-admin gated (ADR-0068), ADR-0134 D4' }, + { route: 'POST /api/v1/auth/admin/scim/delete-group-mapping', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — an operator script posts it with the mappingId the save answered; deletes that sys_idp_group_mapping row; a SCIM mapping re-projects the connection so the grants it made go (with SCIM off nothing is re-projected and those grants stay until removed by hand; the answer says reprojected: false), an SSO mapping removes at once the grants its provider projected for that set in that organization unless another of the provider mappings still names it (then each member next sign-in decides); 404 for an unknown mapping; one sys_audit_log row per delete; platform-admin gated (ADR-0068), ADR-0134 D4' }, { route: 'POST /api/v1/auth/admin/sso/register', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', requires: 'sso', note: 'no SDK method builds this URL — the sys_sso_provider register action posts flat form fields; ObjectStack bridge re-dispatching into @better-auth/sso /sso/register, platform-admin gated ahead of the delegation (ADR-0068 D4), so registering an identity provider never rests on the vendor\'s own check alone. Distinct path from the vendor\'s own /sso/register, which the catch-all serves' }, { route: 'POST /api/v1/auth/admin/sso/register-saml', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', requires: 'sso', note: 'no SDK method builds this URL — the sys_sso_provider register_saml_provider action posts flat fields the bridge reshapes into better-auth\'s nested samlConfig; platform-admin gated ahead of the delegation (ADR-0068 D4), ADR-0069 P3' }, { route: 'POST /api/v1/auth/admin/sso/request-domain-verification', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', requires: 'sso', note: 'no SDK method builds this URL — the sys_sso_provider action posts it and renders the returned DNS TXT record; ObjectStack bridge over @better-auth/sso, additionally gated on the opt-in ssoDomainVerification switch (OS_SSO_DOMAIN_VERIFICATION) — off means the inner endpoint 404s, the mount itself is unconditional; platform-admin gated (ADR-0068 D4), ADR-0135 D6' }, diff --git a/packages/plugins/plugin-auth/src/idp-group-mapping-admin.ts b/packages/plugins/plugin-auth/src/idp-group-mapping-admin.ts index db80bd9cd4f..18a164a70a2 100644 --- a/packages/plugins/plugin-auth/src/idp-group-mapping-admin.ts +++ b/packages/plugins/plugin-auth/src/idp-group-mapping-admin.ts @@ -6,6 +6,14 @@ * `POST /api/v1/auth/admin/scim/delete-group-mapping` (ADR-0134 D4's group * seam, filled for ordinary permission sets). * + * ## Two sources, one door + * + * A mapping's group arrives either through a SCIM connection (`connectionId`) + * or as an SSO provider's sign-in claim (`providerId`; maintainer ruling A, + * record 6718355623, item 3: the same mapping object, no second model). A save + * names exactly one. Everything below holds for both; where they differ it + * says so. + * * ## Who may use it * * The platform administrator only, the same population that mints the SCIM @@ -31,7 +39,9 @@ * rows' `organization_id`), never a value the caller names. A connection with a * credential that names no organization, or with credentials in two, is refused * (`rule_violation` on `connectionId`): a mapping always names exactly one - * organization, so the projection never writes an organization-less grant. + * organization, so the projection never writes an organization-less grant. For + * an SSO provider it is the provider row's `organization_id`, and a provider + * that names none is refused the same way (`rule_violation` on `providerId`). * * ## After a save or delete * @@ -40,6 +50,14 @@ * set now rather than at their next SCIM change. A failed re-projection does * not undo the saved row; the answer says so, and the next SCIM change of each * member applies it. + * + * An SSO provider pushes nothing between sign-ins, so who is in a group is only + * known at a member's sign-in: a save applies at each member's next sign-in + * (the answer says `reprojected: false`). A delete removes at once the grants + * that provider projected for the mapping's set in its organization, unless + * another of the provider's mappings still names that set there (then each + * member's next sign-in decides); `reconciledUsers` counts the users whose + * grant went. */ import type { IDataEngine } from '@objectstack/spec/contracts'; @@ -47,9 +65,13 @@ import { withSystemContext } from './objectql-adapter.js'; import type { PlatformAdminActor } from './platform-admin-gate.js'; import { readJsonRequestBody } from './request-json-body.js'; import { SCIM_CREDENTIAL_OBJECT, scimCredentialIsLive } from './scim-connection-service.js'; +import { SSO_PROVIDER_OBJECT } from './sso-client-secret.js'; import { IDP_GROUP_MAPPING_OBJECT, SCIM_MAPPING_SOURCE_KIND, + SSO_MAPPING_SOURCE_KIND, + ssoGroupProjectionReason, + type IdpGroupMappingSourceKind, type OrganizationBoundaryJudge, } from './scim-group-projection.js'; @@ -59,7 +81,8 @@ export const IDP_GROUP_MAPPING_DELETE_PATH = '/admin/scim/delete-group-mapping'; const SYSTEM_CTX = { isSystem: true } as const; const MAX_TEXT = 255; const MAX_SET_NAME = 100; -const SET_BODY_KEYS = new Set(['connectionId', 'groupExternalId', 'groupDisplayName', 'permissionSet']); +const SET_BODY_KEYS = new Set(['connectionId', 'providerId', 'groupExternalId', 'groupDisplayName', 'permissionSet']); +const GRANT_OBJECT = 'sys_user_permission_set'; interface FieldRefusal { field: string; @@ -77,6 +100,8 @@ export interface IdpGroupMappingAdminResult { export interface IdpGroupMappingAdminDeps { getDataEngine: () => IDataEngine | null | undefined; isScimEnabled: () => boolean; + /** Is the SSO plugin wired? Absent reads as no: an SSO mapping is then refused 503. */ + isSsoEnabled?: () => boolean; /** The `security` service's boundary predicate, resolved per call. */ boundary: () => Promise; /** Re-project one provisioning domain (`AuthManager.reconcileScimProjectionDomain`). */ @@ -154,7 +179,7 @@ async function readConnection( async function writeMappingAudit( deps: IdpGroupMappingAdminDeps, engine: IDataEngine, - entry: { action: 'create' | 'delete'; actor: PlatformAdminActor; mappingId: string; event: string; connectionId: string; permissionSet: string }, + entry: { action: 'create' | 'delete'; actor: PlatformAdminActor; mappingId: string; event: string; source: MappingSource; permissionSet: string }, ): Promise { if (!registered(engine, 'sys_audit_log')) return; // plugin-audit uninstalled: a declared skip try { @@ -168,7 +193,7 @@ async function writeMappingAudit( record_id: entry.mappingId, metadata: JSON.stringify({ event: entry.event, - connectionId: entry.connectionId, + ...(entry.source.kind === SSO_MAPPING_SOURCE_KIND ? { providerId: entry.source.id } : { connectionId: entry.source.id }), permissionSet: entry.permissionSet, ...(entry.actor.impersonatedBy ? { impersonated_by: entry.actor.impersonatedBy } : {}), }), @@ -177,8 +202,8 @@ async function writeMappingAudit( ); } catch (error) { deps.logger?.warn( - `[AuthPlugin] the sys_audit_log row for IdP group mapping ${entry.mappingId} (${entry.event}, connection ` - + `'${entry.connectionId}') was NOT written — the change itself SUCCEEDED and nothing retries the row. ` + `[AuthPlugin] the sys_audit_log row for IdP group mapping ${entry.mappingId} (${entry.event}, ${sourceWord(entry.source)} ` + + `'${entry.source.id}') was NOT written — the change itself SUCCEEDED and nothing retries the row. ` + 'Remedy: restore write access to sys_audit_log, then treat this line as the audit record. ' + `Cause: ${(error as Error)?.message ?? String(error)}`, ); @@ -201,7 +226,84 @@ async function reproject(deps: IdpGroupMappingAdminDeps, connectionId: string, d } } -/** `POST /admin/scim/set-group-mapping` — save one group → permission-set mapping for a SCIM connection. */ +/** Where a mapping's group arrives from. */ +interface MappingSource { + kind: IdpGroupMappingSourceKind; + id: string; +} + +/** How a message names a source. */ +function sourceWord(source: MappingSource): string { + return source.kind === SSO_MAPPING_SOURCE_KIND ? 'SSO provider' : 'SCIM connection'; +} + +/** The answer's member naming the source: `providerId` for an SSO provider, `connectionId` for a SCIM connection. */ +function sourceMember(source: MappingSource): Record { + return source.kind === SSO_MAPPING_SOURCE_KIND ? { providerId: source.id } : { connectionId: source.id }; +} + +/** The organization that owns an SSO provider: its row's `organization_id`. */ +async function readSsoProviderOrganization( + engine: IDataEngine, + providerId: string, +): Promise<{ found: false } | { found: true; organizationId: string }> { + const row = (await engine.findOne( + SSO_PROVIDER_OBJECT, + { where: { provider_id: providerId }, fields: ['organization_id'] }, + { context: SYSTEM_CTX } as never, + )) as Record | null; + return row ? { found: true, organizationId: text(row.organization_id) } : { found: false }; +} + +/** + * Remove the grants an SSO provider projected for (`permissionSet`, `organizationId`), + * unless another of its mappings still names that set there. Each removal goes + * through the engine, so its write guards judge it; a failure is reported, + * never thrown (the row change stands). + */ +async function revokeSsoProjectedGrants( + deps: IdpGroupMappingAdminDeps, + engine: IDataEngine, + providerId: string, + permissionSet: string, + organizationId: string, +): Promise> { + try { + const remaining = await engine.find( + IDP_GROUP_MAPPING_OBJECT, + { where: { source_kind: SSO_MAPPING_SOURCE_KIND, source_id: providerId, permission_set: permissionSet } }, + { context: SYSTEM_CTX } as never, + ); + const stillNamed = (Array.isArray(remaining) ? (remaining as Record[]) : []).some( + (r) => text(r.organization_id) === organizationId, + ); + if (stillNamed || !registered(engine, GRANT_OBJECT)) return { reprojected: false, reconciledUsers: 0 }; + const grants = await engine.find( + GRANT_OBJECT, + { + where: { reason: ssoGroupProjectionReason(providerId), permission_set: permissionSet, organization_id: organizationId }, + fields: ['id', 'user_id'], + }, + { context: SYSTEM_CTX } as never, + ); + const writer: IDataEngine = withSystemContext(engine); + const users = new Set(); + for (const grant of Array.isArray(grants) ? (grants as Record[]) : []) { + await writer.delete(GRANT_OBJECT, { where: { id: text(grant.id) } }); + users.add(text(grant.user_id)); + } + return { reprojected: true, reconciledUsers: users.size }; + } catch (error) { + deps.logger?.error( + `[AuthPlugin] IdP group mapping for SSO provider '${providerId}' was DELETED, but removing the grants of ` + + `'${permissionSet}' it projected FAILED, so those users keep the set until their next sign-in through that ` + + `provider. Remedy: remove the grants by hand, or have each user sign in again. Cause: ${(error as Error)?.message ?? String(error)}`, + ); + return { reprojected: false, reconciledUsers: 0 }; + } +} + +/** `POST /admin/scim/set-group-mapping` — save one group → permission-set mapping for a SCIM connection or an SSO provider. */ export async function runSetIdpGroupMapping( deps: IdpGroupMappingAdminDeps, actor: PlatformAdminActor, @@ -214,44 +316,69 @@ export async function runSetIdpGroupMapping( const refusals: FieldRefusal[] = []; for (const key of Object.keys(body)) { if (!SET_BODY_KEYS.has(key)) { - refusals.push({ field: key, code: 'unknown_field', message: `${key} is not a field of a group mapping (connectionId, groupExternalId, groupDisplayName, permissionSet).` }); + refusals.push({ field: key, code: 'unknown_field', message: `${key} is not a field of a group mapping (connectionId, providerId, groupExternalId, groupDisplayName, permissionSet).` }); } } const connectionId = readText(body, 'connectionId', MAX_TEXT, refusals); + const providerId = readText(body, 'providerId', MAX_TEXT, refusals); const groupExternalId = readText(body, 'groupExternalId', MAX_TEXT, refusals); const groupDisplayName = readText(body, 'groupDisplayName', MAX_TEXT, refusals); const permissionSet = readText(body, 'permissionSet', MAX_SET_NAME, refusals); - if (!connectionId) refusals.push({ field: 'connectionId', code: 'required', message: 'connectionId is required: the SCIM connection the group arrives through.' }); + if (!connectionId && !providerId) { + refusals.push({ field: 'connectionId', code: 'required', message: 'connectionId is required: the SCIM connection the group arrives through (or providerId: the SSO provider whose sign-in carries it).' }); + } else if (connectionId && providerId) { + refusals.push({ field: 'providerId', code: 'rule_violation', message: 'Name the source by connectionId (a SCIM connection) or by providerId (an SSO provider), not both.' }); + } if (!permissionSet) refusals.push({ field: 'permissionSet', code: 'required', message: 'permissionSet is required: the permission set a member of the group is granted.' }); if (!groupExternalId && !groupDisplayName) { refusals.push({ field: 'groupExternalId', code: 'required', message: 'Name the group by groupExternalId or by groupDisplayName.' }); } else if (groupExternalId && groupDisplayName) { refusals.push({ field: 'groupDisplayName', code: 'rule_violation', message: 'Name the group by groupExternalId or by groupDisplayName, not both.' }); } - if (refusals.length > 0 || !connectionId || !permissionSet) return refuseFields(refusals); + if (refusals.length > 0 || !permissionSet) return refuseFields(refusals); + const source: MappingSource = providerId + ? { kind: SSO_MAPPING_SOURCE_KIND, id: providerId } + : { kind: SCIM_MAPPING_SOURCE_KIND, id: connectionId! }; - if (!deps.isScimEnabled()) { + if (source.kind === SCIM_MAPPING_SOURCE_KIND && !deps.isScimEnabled()) { return fail(503, 'SERVICE_UNAVAILABLE', 'SCIM provisioning is not enabled on this deployment, so no group can arrive to be mapped. Enable it (OS_SCIM_ENABLED=true, or plugins.scim) and save again.'); } + if (source.kind === SSO_MAPPING_SOURCE_KIND && !deps.isSsoEnabled?.()) { + return fail(503, 'SERVICE_UNAVAILABLE', 'SSO is not enabled on this deployment, so no sign-in can carry a group to be mapped. Enable it (OS_SSO_ENABLED=true, or plugins.sso) and save again.'); + } const engine = deps.getDataEngine(); if (!engine || !registered(engine, IDP_GROUP_MAPPING_OBJECT)) { return fail(503, 'SERVICE_UNAVAILABLE', 'The data engine or the sys_idp_group_mapping object is unavailable.'); } - const connection = await readConnection(engine, connectionId); - if (!connection.found) { - return refuseFields([{ field: 'connectionId', code: 'reference_not_found', message: `No SCIM connection '${connectionId}' exists: mint its credential first.` }]); - } - if (connection.organizations.length === 0) { - return refuseFields([{ field: 'connectionId', code: 'rule_violation', message: `SCIM connection '${connectionId}' has no live credential (every one is revoked or expired), so no organization owns it. Mint a credential for it first.` }]); - } - if (connection.organizations.includes('')) { - return refuseFields([{ field: 'connectionId', code: 'rule_violation', message: `SCIM connection '${connectionId}' has a credential owned by no organization, so a grant it makes would belong to no organization. Mint the connection's credential in an organization first.` }]); - } - if (connection.organizations.length > 1) { - return refuseFields([{ field: 'connectionId', code: 'rule_violation', message: `SCIM connection '${connectionId}' has credentials owned by more than one organization, so the organization a grant belongs to is ambiguous. Revoke the stray credentials first.` }]); + let organizationId: string; + let domains: string[] = []; + if (source.kind === SSO_MAPPING_SOURCE_KIND) { + const provider = await readSsoProviderOrganization(engine, source.id); + if (!provider.found) { + return refuseFields([{ field: 'providerId', code: 'reference_not_found', message: `No SSO provider '${source.id}' exists: register it first.` }]); + } + if (!provider.organizationId) { + return refuseFields([{ field: 'providerId', code: 'rule_violation', message: `SSO provider '${source.id}' belongs to no organization, so a grant its sign-in makes would belong to no organization. Register the provider in an organization first.` }]); + } + organizationId = provider.organizationId; + } else { + const connection = await readConnection(engine, source.id); + if (!connection.found) { + return refuseFields([{ field: 'connectionId', code: 'reference_not_found', message: `No SCIM connection '${source.id}' exists: mint its credential first.` }]); + } + if (connection.organizations.length === 0) { + return refuseFields([{ field: 'connectionId', code: 'rule_violation', message: `SCIM connection '${source.id}' has no live credential (every one is revoked or expired), so no organization owns it. Mint a credential for it first.` }]); + } + if (connection.organizations.includes('')) { + return refuseFields([{ field: 'connectionId', code: 'rule_violation', message: `SCIM connection '${source.id}' has a credential owned by no organization, so a grant it makes would belong to no organization. Mint the connection's credential in an organization first.` }]); + } + if (connection.organizations.length > 1) { + return refuseFields([{ field: 'connectionId', code: 'rule_violation', message: `SCIM connection '${source.id}' has credentials owned by more than one organization, so the organization a grant belongs to is ambiguous. Revoke the stray credentials first.` }]); + } + organizationId = connection.organizations[0]; + domains = connection.domains; } - const organizationId = connection.organizations[0]; const judge = await deps.boundary(); if (!judge) { @@ -267,29 +394,30 @@ export async function runSetIdpGroupMapping( } const row = { - source_kind: SCIM_MAPPING_SOURCE_KIND, - source_id: connectionId, + source_kind: source.kind, + source_id: source.id, ...(groupExternalId ? { group_external_id: groupExternalId } : { group_display_name: groupDisplayName }), permission_set: permissionSet, organization_id: organizationId, }; const sameRows = await engine.find( IDP_GROUP_MAPPING_OBJECT, - { where: { source_kind: SCIM_MAPPING_SOURCE_KIND, source_id: connectionId, permission_set: permissionSet } }, + { where: { source_kind: source.kind, source_id: source.id, permission_set: permissionSet } }, { context: SYSTEM_CTX } as never, ); const sameKey = (Array.isArray(sameRows) ? (sameRows as Record[]) : []).filter( (r) => text(r.group_external_id) === (groupExternalId ?? '') && text(r.group_display_name) === (groupExternalId ? '' : groupDisplayName ?? ''), ); - // A same-key row saved while another organization owned the connection is - // not this mapping: its row and its grants stay in that organization. Never + // A same-key row saved while another organization owned the source is not + // this mapping: its row and its grants stay in that organization. Never // answer an organization the row does not carry, and never write a twin. const elsewhere = sameKey.find((r) => text(r.organization_id) !== organizationId); if (elsewhere) { + const owner = source.kind === SSO_MAPPING_SOURCE_KIND ? 'provider' : 'connection'; return fail( 409, 'RESOURCE_CONFLICT', - `IdP group mapping '${text(elsewhere.id)}' already maps this group to '${permissionSet}' for SCIM connection '${connectionId}' in organization '${text(elsewhere.organization_id)}', but the connection now belongs to organization '${organizationId}'. Delete mapping '${text(elsewhere.id)}' first (POST /admin/scim/delete-group-mapping), then save again.`, + `IdP group mapping '${text(elsewhere.id)}' already maps this group to '${permissionSet}' for ${sourceWord(source)} '${source.id}' in organization '${text(elsewhere.organization_id)}', but the ${owner} now belongs to organization '${organizationId}'. Delete mapping '${text(elsewhere.id)}' first (POST /admin/scim/delete-group-mapping), then save again.`, ); } const existing = sameKey.find((r) => text(r.organization_id) === organizationId); @@ -300,14 +428,17 @@ export async function runSetIdpGroupMapping( const writer: IDataEngine = withSystemContext(engine); const inserted = (await deps.attributed(() => writer.insert(IDP_GROUP_MAPPING_OBJECT, row))) as Record; mappingId = text(inserted?.id); - await writeMappingAudit(deps, engine, { action: 'create', actor, mappingId, event: 'idp_group_mapping_saved', connectionId, permissionSet }); + await writeMappingAudit(deps, engine, { action: 'create', actor, mappingId, event: 'idp_group_mapping_saved', source, permissionSet }); } - const applied = await deps.attributed(() => reproject(deps, connectionId, connection.domains)); + // An SSO provider pushes nothing between sign-ins: the mapping applies at each member's next sign-in. + const applied = source.kind === SSO_MAPPING_SOURCE_KIND + ? { reprojected: false, reconciledUsers: 0 } + : await deps.attributed(() => reproject(deps, source.id, domains)); return { status: 200, body: { success: true, - data: { mappingId, created: !existing, connectionId, permissionSet, organizationId: organizationId || null, ...applied }, + data: { mappingId, created: !existing, ...sourceMember(source), permissionSet, organizationId: organizationId || null, ...applied }, }, }; } @@ -334,12 +465,20 @@ export async function runDeleteIdpGroupMapping( { context: SYSTEM_CTX } as never, )) as Record | null; if (!row) return fail(404, 'RESOURCE_NOT_FOUND', `No IdP group mapping '${mappingId}' exists`); - const connectionId = text(row.source_id); + const source: MappingSource = { + kind: text(row.source_kind) === SSO_MAPPING_SOURCE_KIND ? SSO_MAPPING_SOURCE_KIND : SCIM_MAPPING_SOURCE_KIND, + id: text(row.source_id), + }; const permissionSet = text(row.permission_set); const writer: IDataEngine = withSystemContext(engine); await deps.attributed(() => writer.delete(IDP_GROUP_MAPPING_OBJECT, { where: { id: mappingId } })); - await writeMappingAudit(deps, engine, { action: 'delete', actor, mappingId, event: 'idp_group_mapping_deleted', connectionId, permissionSet }); - const connection = deps.isScimEnabled() ? await readConnection(engine, connectionId) : ({ found: false } as const); - const applied = connection.found ? await deps.attributed(() => reproject(deps, connectionId, connection.domains)) : { reprojected: false, reconciledUsers: 0 }; - return { status: 200, body: { success: true, data: { mappingId, connectionId, permissionSet, deleted: true, ...applied } } }; + await writeMappingAudit(deps, engine, { action: 'delete', actor, mappingId, event: 'idp_group_mapping_deleted', source, permissionSet }); + let applied: Record; + if (source.kind === SSO_MAPPING_SOURCE_KIND) { + applied = await deps.attributed(() => revokeSsoProjectedGrants(deps, engine, source.id, permissionSet, text(row.organization_id))); + } else { + const connection = deps.isScimEnabled() ? await readConnection(engine, source.id) : ({ found: false } as const); + applied = connection.found ? await deps.attributed(() => reproject(deps, source.id, connection.domains)) : { reprojected: false, reconciledUsers: 0 }; + } + return { status: 200, body: { success: true, data: { mappingId, ...sourceMember(source), permissionSet, deleted: true, ...applied } } }; } diff --git a/packages/plugins/plugin-auth/src/scim-group-projection.ts b/packages/plugins/plugin-auth/src/scim-group-projection.ts index b250fa574b5..29f3f1cfd35 100644 --- a/packages/plugins/plugin-auth/src/scim-group-projection.ts +++ b/packages/plugins/plugin-auth/src/scim-group-projection.ts @@ -49,6 +49,15 @@ * vendor's `APIError` with its own status (`withValidationErrorMapping`): the * vendor passes an `APIError` through to the identity provider and turns any * other throw into a SCIM 500, which an IdP retries forever. + * + * ## One model, two sources + * + * An SSO provider's group claim reads the same `sys_idp_group_mapping` rows + * (`source_kind: 'sso'`, `source_id` = the provider id) through the same + * matcher, the same admission ({@link createMappingAdmission}) and the same + * reconcile ({@link reconcileMappedGrants}), with a marker of its own; see + * `sso-group-projection.ts`. Each source removes only the grants carrying its + * own marker, so neither ever takes away a grant the other made. */ import type { IDataEngine } from '@objectstack/core'; @@ -64,6 +73,12 @@ const GRANT_OBJECT = 'sys_user_permission_set'; /** The `source_kind` of a mapping row pushed by a SCIM connection. */ export const SCIM_MAPPING_SOURCE_KIND = 'scim'; +/** The `source_kind` of a mapping row whose group arrives as an SSO provider's sign-in claim. */ +export const SSO_MAPPING_SOURCE_KIND = 'sso'; + +/** What sends a mapped group: a SCIM connection, or an SSO provider at sign-in. */ +export type IdpGroupMappingSourceKind = typeof SCIM_MAPPING_SOURCE_KIND | typeof SSO_MAPPING_SOURCE_KIND; + /** The machine prefix of every grant the projection writes. */ export const SCIM_GROUP_PROJECTION_REASON_PREFIX = 'scim-group-projection'; @@ -72,6 +87,14 @@ export function scimGroupProjectionReason(provisioningDomainId: string): string return `${SCIM_GROUP_PROJECTION_REASON_PREFIX}: provisioning domain '${provisioningDomainId}'`; } +/** The machine prefix of every grant an SSO provider's group claim projects. */ +export const SSO_GROUP_PROJECTION_REASON_PREFIX = 'sso-group-projection'; + +/** The `reason` an SSO-projected grant carries: the marker plus the provider whose sign-in projected it. */ +export function ssoGroupProjectionReason(providerId: string): string { + return `${SSO_GROUP_PROJECTION_REASON_PREFIX}: provider '${providerId}'`; +} + /** The security service member that judges a set against the organization boundary. */ export interface OrganizationBoundaryJudge { organizationBoundaryFailure(setName: string): Promise; @@ -104,16 +127,24 @@ function rowsOf(result: unknown): Record[] { return Array.isArray(result) ? (result as Record[]) : []; } -/** The mapping rows of one SCIM connection. */ -async function connectionMappings(engine: IDataEngine, connectionId: string): Promise { +/** The mapping rows of one source: a SCIM connection, or an SSO provider. */ +export async function sourceMappings( + engine: IDataEngine, + kind: IdpGroupMappingSourceKind, + sourceId: string, +): Promise { if (!registered(engine, IDP_GROUP_MAPPING_OBJECT)) return []; return rowsOf( await withSystemContext(engine).find(IDP_GROUP_MAPPING_OBJECT, { - where: { source_kind: SCIM_MAPPING_SOURCE_KIND, source_id: connectionId }, + where: { source_kind: kind, source_id: sourceId }, }), ); } +/** The mapping rows of one SCIM connection. */ +const connectionMappings = (engine: IDataEngine, connectionId: string) => + sourceMappings(engine, SCIM_MAPPING_SOURCE_KIND, connectionId); + /** Does mapping `row` name `group`? By external id when the row names one, else by display name. */ export function mappingMatchesGroup(row: MappingRow, group: { externalId?: string; displayName: string }): boolean { const externalId = text(row.group_external_id); @@ -122,28 +153,34 @@ export function mappingMatchesGroup(row: MappingRow, group: { externalId?: strin return displayName !== '' && displayName === group.displayName; } -/** Build the `projection` member of `scim({ … })`. */ -export function createScimGroupProjection(deps: ScimGroupProjectionDeps): SCIMProjection { - const warned = new Set(); - const engineOrThrow = (): IDataEngine => { - const engine = deps.getEngine(); - if (!engine) throw new Error('[auth] SCIM group projection: no data engine to read mappings or write grants through'); - return engine; - }; +/** How a refusal names a mapping's source, per kind. */ +const SOURCE_WORDS: Record = { + scim: { label: 'SCIM', source: 'connection', owner: 'the connection\'s credential belongs to an organization' }, + sso: { label: 'SSO', source: 'provider', owner: 'the provider belongs to an organization' }, +}; - /** - * May mapping `row` grant now? Only a row that names an organization and a set - * still inside the organization boundary. Asked by `roles.exists` AND again by - * `reconcileUser` before every insert, so the boundary holds on any vendor - * path, whether or not it consulted `exists` first. A refusal grants nothing - * and is warned once per mapping. - */ - const admits = async (row: MappingRow): Promise => { +/** The admission both sources ask before a mapping may grant: see {@link createMappingAdmission}. */ +export type MappingAdmission = (row: MappingRow) => Promise; + +/** + * May mapping `row` grant now? Only a row that names an organization and a set + * still inside the organization boundary, judged by the `security` service's + * own predicate; with no such service, nothing is shown inside the boundary and + * nothing is granted (fail closed). A refusal grants nothing and is warned once + * per mapping. + */ +export function createMappingAdmission( + deps: Pick, + kind: IdpGroupMappingSourceKind, +): MappingAdmission { + const warned = new Set(); + const words = SOURCE_WORDS[kind]; + return async (row) => { const mappingId = text(row.id); let refusal: string | null; if (!text(row.organization_id)) { refusal = 'it names no organization, so its grant would belong to no organization. Delete the mapping and ' - + 'save it again once the connection\'s credential belongs to an organization'; + + `save it again once ${words.owner}`; } else { const judge = await deps.boundary(); const failure = judge @@ -156,10 +193,26 @@ export function createScimGroupProjection(deps: ScimGroupProjectionDeps): SCIMPr if (refusal === null) return true; if (!warned.has(mappingId)) { warned.add(mappingId); - deps.warn(`[auth] SCIM group mapping ${mappingId} (connection '${text(row.source_id)}') grants nothing: ${refusal}.`); + deps.warn(`[auth] ${words.label} group mapping ${mappingId} (${words.source} '${text(row.source_id)}') grants nothing: ${refusal}.`); } return false; }; +} + +/** Build the `projection` member of `scim({ … })`. */ +export function createScimGroupProjection(deps: ScimGroupProjectionDeps): SCIMProjection { + const engineOrThrow = (): IDataEngine => { + const engine = deps.getEngine(); + if (!engine) throw new Error('[auth] SCIM group projection: no data engine to read mappings or write grants through'); + return engine; + }; + + /** + * Asked by `roles.exists` AND again by `reconcileUser` before every insert, + * so the boundary holds on any vendor path, whether or not it consulted + * `exists` first. + */ + const admits = createMappingAdmission(deps, SCIM_MAPPING_SOURCE_KIND); return { roles: { @@ -179,22 +232,51 @@ export function createScimGroupProjection(deps: ScimGroupProjectionDeps): SCIMPr /** * Make the user's projected grants for this provisioning domain equal the - * vendor's desired set. Reads first, then inserts, then deletes; every write - * joins the SCIM request's transaction. A mapping `admits` refuses (no - * organization, or a set outside the organization boundary) is not desired, - * so its grant is not written, and one this projection made earlier is removed. + * vendor's desired set: {@link reconcileMappedGrants} with this domain's marker. */ export async function reconcileProjectedGrants( engine: IDataEngine, state: SCIMProjectedUserState, - admits: (row: MappingRow) => Promise, + admits: MappingAdmission, +): Promise { + await reconcileMappedGrants( + engine, + { + userId: state.userId, + reason: scimGroupProjectionReason(state.provisioningDomainId), + mappingIds: state.grants.map((grant) => grant.role), + }, + admits, + ); +} + +/** One user's desired mapped grants from one source, and the marker that source's grants carry. */ +export interface MappedGrantState { + userId: string; + /** The `reason` every grant this source writes carries; only rows carrying it are ever removed. */ + reason: string; + /** The `sys_idp_group_mapping` ids the user's current groups match. */ + mappingIds: readonly string[]; +} + +/** + * Make the user's grants carrying `state.reason` equal the sets the matched + * mappings name. Reads first, then inserts, then deletes. A mapping `admits` + * refuses (no organization, or a set outside the organization boundary) is not + * desired, so its grant is not written, and one this source made earlier is + * removed. Inside a SCIM request every write joins its transaction. + */ +export async function reconcileMappedGrants( + engine: IDataEngine, + state: MappedGrantState, + admits: MappingAdmission, ): Promise { - const reason = scimGroupProjectionReason(state.provisioningDomainId); - const mappingIds = [...new Set(state.grants.map((grant) => grant.role))]; + const reason = state.reason; + const mappingIds = [...new Set(state.mappingIds)]; const grantTable = registered(engine, GRANT_OBJECT); if (!grantTable) { if (mappingIds.length === 0) return; // nothing desired, nothing of ours can exist - throw new Error(`[auth] SCIM group projection: ${GRANT_OBJECT} is not registered, so mapped permission sets cannot be granted`); + throw new Error(`[auth] IdP group projection: ${GRANT_OBJECT} is not registered, so mapped permission sets cannot be granted`); } const reader = withSystemContext(engine); const writer = withValidationErrorMapping(withSystemContext(engine) as unknown as Record) as unknown as IDataEngine; diff --git a/packages/plugins/plugin-auth/src/sso-group-projection.ts b/packages/plugins/plugin-auth/src/sso-group-projection.ts new file mode 100644 index 00000000000..f758540b80d --- /dev/null +++ b/packages/plugins/plugin-auth/src/sso-group-projection.ts @@ -0,0 +1,119 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The SSO half of the identity-provider group mapping: an SSO sign-in's group + * claim grants the ordinary permission sets its `sys_idp_group_mapping` rows + * name (maintainer ruling A on the Enterprise SSO operator knobs, record + * 6718355623: item 3 follows the SCIM mapping's ruled model, the same mapping + * object, no second model). + * + * ## Where the groups come from + * + * `@better-auth/sso` (1.7.12) builds each sign-in's `userInfo` from the + * provider's own `mapping.extraFields` (OIDC: the userinfo response or the ID + * token; SAML: the assertion's attributes). A provider whose mapping names + * `extraFields: { groups: CLAIM }` therefore hands this module + * `userInfo.groups` ({@link SSO_GROUPS_USER_INFO_KEY}): a string or a list of + * strings. No new provider setting: the claim is configured where every other + * claim of that provider is. + * + * ## What a sign-in does with them + * + * The vendor calls `provisionUser` after the account is linked and the + * session row exists; with `provisionUserOnEveryLogin` it does so on every + * sign-in, not only the first, so the grants follow the IdP's groups at each + * sign-in. Each claim value is matched against the provider's mapping rows + * (`source_kind: 'sso'`, `source_id` = the provider id) by the SCIM half's own + * matcher: a row naming a `group_external_id` matches a value equal to it + * (Entra ID sends group object ids), a row naming a `group_display_name` + * matches a value equal to that (Okta sends group names). + * + * The matched rows go through the SCIM half's admission and reconcile + * (`scim-group-projection.ts`): a row that names no organization, or whose set + * the `security` service does not show inside the organization boundary, is + * not granted (fail closed with no security service). Every grant carries + * {@link ssoGroupProjectionReason} for its provider, and reconcile removes only + * rows carrying that exact marker, so a grant made by hand or by SCIM is never + * touched. A sign-in whose claim is absent desires no set: the grants this + * provider projected earlier are removed, nothing else is written, and a user + * with none signs in exactly as before. + * + * Every write goes through the ObjectQL engine with the system context the + * other sign-in writes carry, so the engine's own write guards judge it: the + * break-glass last-administrator guard refuses a removal it refuses anywhere + * else. + * + * ## When it fails + * + * A failure never fails the sign-in: the IdP has authenticated the user, and a + * refused sign-in would turn a last-administrator guard refusal into the + * lockout that guard exists to prevent. It is logged at `error`, once per + * sign-in, because the user is now signed in with grants that do not follow + * the IdP's groups while nothing looks wrong. + */ + +import type { IDataEngine } from '@objectstack/core'; +import { + SSO_MAPPING_SOURCE_KIND, + createMappingAdmission, + mappingMatchesGroup, + reconcileMappedGrants, + sourceMappings, + ssoGroupProjectionReason, + type OrganizationBoundaryJudge, +} from './scim-group-projection.js'; + +/** The `userInfo` member a provider's `mapping.extraFields` fills with the user's groups. */ +export const SSO_GROUPS_USER_INFO_KEY = 'groups'; + +export interface SsoGroupProjectionDeps { + getEngine: () => IDataEngine | null | undefined; + /** Resolved per call: the security plugin starts after this one. */ + boundary: () => Promise; + warn: (message: string) => void; + error: (message: string) => void; +} + +/** What the vendor hands `provisionUser` (the members this module reads). */ +export interface SsoProvisionUserInput { + user: { id?: unknown }; + userInfo: Record; + provider: { providerId?: unknown }; +} + +/** + * The user's groups from a sign-in's `userInfo`: a single string or a list of + * strings, trimmed, blanks dropped. Anything else, or no member, is no groups. + */ +export function readSsoGroupClaim(userInfo: Record | null | undefined): string[] { + const raw = userInfo?.[SSO_GROUPS_USER_INFO_KEY]; + const values = typeof raw === 'string' ? [raw] : Array.isArray(raw) ? raw : []; + return [...new Set(values.filter((v): v is string => typeof v === 'string').map((v) => v.trim()).filter(Boolean))]; +} + +/** Build the `provisionUser` member of `sso({ … })`. */ +export function createSsoGroupProvisioner(deps: SsoGroupProjectionDeps): (input: SsoProvisionUserInput) => Promise { + const admits = createMappingAdmission(deps, SSO_MAPPING_SOURCE_KIND); + return async ({ user, userInfo, provider }) => { + const providerId = typeof provider?.providerId === 'string' ? provider.providerId : ''; + const userId = typeof user?.id === 'string' ? user.id : ''; + if (!providerId || !userId) return; + try { + const engine = deps.getEngine(); + if (!engine) throw new Error('no data engine to read mappings or write grants through'); + const groups = readSsoGroupClaim(userInfo); + const rows = await sourceMappings(engine, SSO_MAPPING_SOURCE_KIND, providerId); + const mappingIds = rows + .filter((row) => groups.some((group) => mappingMatchesGroup(row, { externalId: group, displayName: group }))) + .map((row) => String(row.id)); + await reconcileMappedGrants(engine, { userId, reason: ssoGroupProjectionReason(providerId), mappingIds }, admits); + } catch (error) { + deps.error( + `[auth] SSO sign-in through provider '${providerId}' SUCCEEDED, but applying the provider's IdP group mappings ` + + `to user ${userId} FAILED, so their permission sets still reflect their previous sign-in and do not follow ` + + 'the identity provider\'s groups. Remedy: fix the cause; the next sign-in applies the mappings again. ' + + `Cause: ${(error as Error)?.message ?? String(error)}`, + ); + } + }; +} diff --git a/packages/plugins/plugin-auth/src/sso-oidc-refusal-cause.test.ts b/packages/plugins/plugin-auth/src/sso-oidc-refusal-cause.test.ts index 7d084ef3500..54ba309cd05 100644 --- a/packages/plugins/plugin-auth/src/sso-oidc-refusal-cause.test.ts +++ b/packages/plugins/plugin-auth/src/sso-oidc-refusal-cause.test.ts @@ -22,11 +22,21 @@ * `token_not_verified`, and every per-cause assertion fails. */ -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { SignJWT, exportJWK, generateKeyPair, type JWK } from 'jose'; import { AuthManager } from './auth-manager'; import { createMemoryEngine } from './impersonation-bearer-rotation.test'; import { inviteForAudienceGate } from './audience-gate-test-support'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SecurityPlugin } from '@objectstack/plugin-security'; +import { ADMIN_FULL_ACCESS } from '@objectstack/spec/identity'; +import { authIdentityObjects } from './manifest.js'; +import { registerLastAdminGuard, type LastAdminGuardEngine } from './last-admin-guard.js'; +import { runDeleteIdpGroupMapping, runSetIdpGroupMapping, type IdpGroupMappingAdminDeps } from './idp-group-mapping-admin.js'; +import type { OrganizationBoundaryJudge } from './scim-group-projection.js'; +import { bindTestSecurityCatalog } from './__tests__/security-catalog.testkit.js'; +import { sqliteEnginePool, type BootedSqliteEngine } from './__tests__/sqlite-engine-pool.testkit.js'; import { SSO_OIDC_REFUSAL_CAUSES, SSO_OIDC_UNCLASSIFIED_REFUSAL, @@ -91,6 +101,8 @@ interface TokenShape { kid?: string; signWith?: 'current' | 'other'; email?: string; + /** Further claims the IdP asserts (e.g. `groups`). */ + claims?: Record; } async function idToken(shape: TokenShape = {}): Promise { @@ -99,6 +111,7 @@ async function idToken(shape: TokenShape = {}): Promise { email: shape.email ?? EMAIL, email_verified: true, name: 'Mia Chen', + ...shape.claims, }; if (shape.azp) claims.azp = shape.azp; const jwt = new SignJWT(claims) @@ -500,3 +513,327 @@ describe('invite_only refuses an unknown OIDC user unless the provider allows JI expect(cookiesOf(res)).toMatch(/session_token=/); }); }); + +// ── 4. IdP group → permission set at sign-in ──────────────────────────────── +// +// Ruling A on the Enterprise SSO knobs (record 6718355623), item 3: an SSO +// provider's group claim grants the ordinary permission set a +// `sys_idp_group_mapping` row names, the same mapping model as SCIM. The +// sign-in is the real one above (`/sign-in/sso` → stubbed IdP → callback), on a +// real ObjectQL engine over better-sqlite3 with the break-glass guard +// registered as `auth-plugin.ts` registers it; the mapping is saved through +// the platform-admin door's own function and judged by plugin-security's REAL +// `organizationBoundaryFailure`. + +const GROUP_ORG = 'org_acme_sso'; +const DEFAULT_ORG = 'org_default'; +const SALES = 'sales_reader'; +/** Outside the boundary by condition (c): a capability no catalog entry declares `scope: 'org'`. */ +const PLATFORM_OPS = 'platform_ops'; +/** The marker every grant this provider's sign-ins project carries (its wire value, pinned literally). */ +const SSO_MARKER = `sso-group-projection: provider '${PROVIDER_ID}'`; +const SYSTEM = { context: { isSystem: true } } as const; +const PLATFORM_ADMIN = { id: 'usr_platform_admin' }; + +/** The grant table, down to the columns the projection and the guard read. */ +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: { name: 'permission_set', type: 'text' as const }, + organization_id: { name: 'organization_id', type: 'text' as const }, + reason: { name: 'reason', type: 'text' as const }, + valid_from: { name: 'valid_from', type: 'datetime' as const }, + valid_until: { name: 'valid_until', type: 'datetime' as const }, + }, +}; + +const groupEnginePool = sqliteEnginePool(bootGroupEngine, { keepBootOrganizations: true }); +afterEach(groupEnginePool.release); +afterAll(groupEnginePool.destroy); + +async function bootGroupEngine(): 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, sysUserPermissionSet]) { + 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); + await engine.insert('sys_organization', { id: GROUP_ORG, name: 'Acme', slug: 'acme' }, SYSTEM); + // [ADR-0131 D3/D4] `admin_full_access` is a catalog definition the guard resolves a grant's set name to. + bindTestSecurityCatalog(engine, { permissions: [{ name: ADMIN_FULL_ACCESS }] }); + registerLastAdminGuard(engine as unknown as LastAdminGuardEngine, { packageId: 'test.last-admin-guard' }); + return { engine, driver }; +} + +/** The catalog the security service judges against; a case may redefine a set after its mapping is saved. */ +let groupCatalog: Array> = []; + +/** The `security` service plugin-security registers, over a catalog bound to a stub engine. */ +async function boundaryJudge(): Promise { + groupCatalog = [{ name: SALES }, { name: ADMIN_FULL_ACCESS }, { name: PLATFORM_OPS, systemPermissions: ['manage_platform_settings'] }]; + const ql = bindTestSecurityCatalog({ registerMiddleware: vi.fn(), getSchema: () => undefined }, () => ({ permissions: groupCatalog })); + const services: Record = { + manifest: { register: vi.fn() }, + objectql: ql, + metadata: { get: async () => undefined, list: async () => [] }, + }; + const registerService = vi.fn(); + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin(); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + const svc = registerService.mock.calls.find((c: unknown[]) => c[0] === 'security')?.[1] as Partial; + expect(typeof svc?.organizationBoundaryFailure, 'the security service serves organizationBoundaryFailure').toBe('function'); + return svc as OrganizationBoundaryJudge; +} + +interface GroupRp { + manager: AuthManager; + engine: ObjectQL; + door: IdpGroupMappingAdminDeps; + warn: ReturnType; + error: ReturnType; +} + +/** + * A relying party whose provider belongs to `GROUP_ORG` and maps the `groups` + * claim through its own `mapping.extraFields`, JIT on. `judge: false` composes + * no security service (the boundary seam is absent). + */ +async function makeGroupRp(opts: { judge?: boolean; provider?: Record } = {}): Promise { + const engine = await groupEnginePool.take(); + const judge = opts.judge === false ? undefined : await boundaryJudge(); + const warn = vi.fn(); + const error = vi.fn(); + const manager = new AuthManager({ + secret: SECRET, + baseUrl: BASE, + dataEngine: engine, + trustedOrigins: [BASE, IDP], + plugins: { sso: true, organization: true }, + logger: { warn, error, info: vi.fn() }, + organizationBoundary: async () => judge, + } as unknown as ConstructorParameters[0]); + // Stored the way an un-migrated row is (cleartext secret in the blob), so the + // callback reads it back without a crypto provider. + await engine.insert('sys_sso_provider', { + provider_id: PROVIDER_ID, + issuer: IDP, + domain: 'acme.com', + organization_id: GROUP_ORG, + allow_jit: true, + oidc_config: JSON.stringify({ + issuer: IDP, + clientId: CLIENT_ID, + clientSecret: CLIENT_SECRET, + authorizationEndpoint: `${IDP}/authorize`, + tokenEndpoint: `${IDP}/token`, + jwksEndpoint: `${IDP}/jwks`, + discoveryEndpoint: `${IDP}/.well-known/openid-configuration`, + pkce: true, + scopes: ['openid', 'email', 'profile'], + mapping: { email: 'email', name: 'name', extraFields: { groups: 'groups' } }, + }), + ...opts.provider, + }, SYSTEM); + await engine.insert('sys_user', { id: 'usr_admin', email: 'admin@acme.com', name: 'Admin', email_verified: true }, SYSTEM); + const door: IdpGroupMappingAdminDeps = { + getDataEngine: () => manager.getDataEngine() as never, + isScimEnabled: () => manager.isScimWired(), + isSsoEnabled: () => manager.isSsoWired(), + boundary: () => manager.organizationBoundaryJudge(), + reconcile: (domain) => manager.reconcileScimProjectionDomain(domain), + attributed: (fn) => fn(), + logger: { warn, error }, + } as IdpGroupMappingAdminDeps; + return { manager, engine, door, warn, error }; +} + +function saveGroupMapping(rp: GroupRp, body: Record) { + return runSetIdpGroupMapping( + rp.door, + PLATFORM_ADMIN, + new Request(`${AUTH}/admin/scim/set-group-mapping`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }), + ); +} + +function deleteGroupMapping(rp: GroupRp, mappingId: string) { + return runDeleteIdpGroupMapping( + rp.door, + PLATFORM_ADMIN, + new Request(`${AUTH}/admin/scim/delete-group-mapping`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ mappingId }) }), + ); +} + +function savedMappingId(saved: Awaited>): string { + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + if (!saved.body.success) throw new Error('the mapping save was refused'); + return String(saved.body.data.mappingId); +} + +/** Sign Mia in through the IdP with the given claims; answers the callback and Mia's user id. */ +async function signInWithClaims(rp: GroupRp, claims?: Record): Promise<{ res: Response; userId: string }> { + const res = await signInThroughIdp(rp as unknown as Rp, await idToken({ claims })); + expect(res.status).toBe(302); + expect(res.headers.get('location'), `the sign-in did not land: ${res.headers.get('location')}`).toBe(AFTER); + expect(cookiesOf(res)).toMatch(/session_token=[^;]/); + const user = (await rp.engine.findOne('sys_user', { where: { email: EMAIL }, fields: ['id'] }, SYSTEM)) as { id: string } | null; + expect(user, 'the sign-in landed a sys_user row').toBeTruthy(); + return { res, userId: String(user!.id) }; +} + +async function grantsOf(rp: GroupRp, userId: string): Promise> { + const rows = (await rp.engine.find('sys_user_permission_set', { where: { user_id: userId } }, SYSTEM)) as Array>; + return rows + .map((r) => ({ permission_set: String(r.permission_set), organization_id: (r.organization_id as string) ?? null, reason: (r.reason as string) ?? null })) + .sort((a, b) => a.permission_set.localeCompare(b.permission_set)); +} + +/** Every grant-table write the engine is asked for. */ +function observeGrantWrites(rp: GroupRp): string[] { + const writes: string[] = []; + const engine = rp.engine as unknown as Record unknown>; + for (const op of ['insert', 'update', 'delete'] as const) { + const original = engine[op].bind(rp.engine); + vi.spyOn(engine, op).mockImplementation(async (object: unknown, ...rest: unknown[]) => { + if (object === 'sys_user_permission_set') writes.push(op); + return original(object, ...rest); + }); + } + return writes; +} + +const projectedSales = { permission_set: SALES, organization_id: GROUP_ORG, reason: SSO_MARKER }; + +describe('an SSO sign-in grants the permission set its IdP group is mapped to', () => { + afterEach(() => vi.restoreAllMocks()); + + it('a mapped group grants the set in the provider\'s organization, by display name and by external id', async () => { + const rp = await makeGroupRp(); + savedMappingId(await saveGroupMapping(rp, { providerId: PROVIDER_ID, groupDisplayName: 'Acme Sales', permissionSet: SALES })); + const { userId } = await signInWithClaims(rp, { groups: ['Acme Everyone', 'Acme Sales'] }); + expect(await grantsOf(rp, userId)).toEqual([projectedSales]); + + // Entra ID sends group object ids: a mapping by external id matches the same claim. + const other = await makeGroupRp(); + savedMappingId(await saveGroupMapping(other, { providerId: PROVIDER_ID, groupExternalId: '6f1b2c3d-sales', permissionSet: SALES })); + const signedIn = await signInWithClaims(other, { groups: '6f1b2c3d-sales' }); + expect(await grantsOf(other, signedIn.userId)).toEqual([projectedSales]); + expect(rp.error).not.toHaveBeenCalled(); + }); + + it('leaving the group revokes the projected grant at the next sign-in; a grant made by hand stays', async () => { + const rp = await makeGroupRp(); + savedMappingId(await saveGroupMapping(rp, { providerId: PROVIDER_ID, groupDisplayName: 'Acme Sales', permissionSet: SALES })); + const { userId } = await signInWithClaims(rp, { groups: ['Acme Sales'] }); + expect(await grantsOf(rp, userId)).toEqual([projectedSales]); + await rp.engine.insert('sys_user_permission_set', { user_id: userId, permission_set: 'support_agent', organization_id: GROUP_ORG }, SYSTEM); + + await signInWithClaims(rp, { groups: ['Acme Everyone'] }); + expect(await grantsOf(rp, userId)).toEqual([{ permission_set: 'support_agent', organization_id: GROUP_ORG, reason: null }]); + }); + + it('CONTROL: an unmapped group grants nothing', async () => { + const rp = await makeGroupRp(); + savedMappingId(await saveGroupMapping(rp, { providerId: PROVIDER_ID, groupDisplayName: 'Acme Sales', permissionSet: SALES })); + const { userId } = await signInWithClaims(rp, { groups: ['Acme Marketing'] }); + expect(await grantsOf(rp, userId)).toEqual([]); + }); + + it('CONTROL: a sign-in with no groups claim behaves as before — signed in, nothing written to the grant table, nothing logged', async () => { + const rp = await makeGroupRp(); + savedMappingId(await saveGroupMapping(rp, { providerId: PROVIDER_ID, groupDisplayName: 'Acme Sales', permissionSet: SALES })); + const writes = observeGrantWrites(rp); + const { userId } = await signInWithClaims(rp); + expect(writes).toEqual([]); + expect(await grantsOf(rp, userId)).toEqual([]); + expect(rp.error).not.toHaveBeenCalled(); + expect(rp.warn).not.toHaveBeenCalled(); + }); + + it('a mapping naming an administrator set, or a set outside the organization boundary, is refused at save and stores nothing', async () => { + const rp = await makeGroupRp(); + for (const set of [ADMIN_FULL_ACCESS, PLATFORM_OPS]) { + const saved = await saveGroupMapping(rp, { providerId: PROVIDER_ID, groupDisplayName: 'Acme Admins', permissionSet: set }); + expect(saved.status).toBe(400); + expect(saved.body).toMatchObject({ success: false, error: { code: 'VALIDATION_FAILED', fields: [{ field: 'permissionSet', code: 'rule_violation' }] } }); + } + expect(await rp.engine.find('sys_idp_group_mapping', {}, SYSTEM)).toEqual([]); + }); + + it('a set redefined outside the boundary after its mapping was saved grants nothing at sign-in', async () => { + const rp = await makeGroupRp(); + savedMappingId(await saveGroupMapping(rp, { providerId: PROVIDER_ID, groupDisplayName: 'Acme Sales', permissionSet: SALES })); + groupCatalog = groupCatalog.map((p) => (p.name === SALES ? { ...p, adminScope: { businessUnits: ['*'] } } : p)); + const { userId } = await signInWithClaims(rp, { groups: ['Acme Sales'] }); + expect(await grantsOf(rp, userId)).toEqual([]); + expect(String(rp.warn.mock.calls.map((c) => c[0]))).toMatch(/SSO group mapping .* grants nothing/); + }); + + it('with no security service composed, a save is refused 503 and a stored mapping grants nothing at sign-in (fail closed)', async () => { + const rp = await makeGroupRp({ judge: false }); + const saved = await saveGroupMapping(rp, { providerId: PROVIDER_ID, groupDisplayName: 'Acme Sales', permissionSet: SALES }); + expect(saved.status).toBe(503); + expect(await rp.engine.find('sys_idp_group_mapping', {}, SYSTEM)).toEqual([]); + + await rp.engine.insert('sys_idp_group_mapping', { + source_kind: 'sso', source_id: PROVIDER_ID, group_display_name: 'Acme Sales', permission_set: SALES, organization_id: GROUP_ORG, + }, SYSTEM); + const { userId } = await signInWithClaims(rp, { groups: ['Acme Sales'] }); + expect(await grantsOf(rp, userId)).toEqual([]); + }); + + it('the break-glass guard still refuses through the sign-in: the last administrator\'s grant is not removed, and the sign-in still lands', async () => { + const rp = await makeGroupRp(); + // Mia already exists and is the only administrator, through a grant carrying this provider's marker. + await rp.engine.delete('sys_user', { where: { id: 'usr_admin' } }, SYSTEM as never); + await rp.engine.insert('sys_user', { id: 'usr_mia', email: EMAIL, name: 'Mia Chen', email_verified: true }, SYSTEM); + await rp.engine.insert('sys_user_permission_set', { + user_id: 'usr_mia', permission_set: ADMIN_FULL_ACCESS, organization_id: DEFAULT_ORG, reason: SSO_MARKER, + }, SYSTEM); + + const { userId } = await signInWithClaims(rp, { groups: [] }); + expect(userId).toBe('usr_mia'); + expect(await grantsOf(rp, userId)).toEqual([{ permission_set: ADMIN_FULL_ACCESS, organization_id: DEFAULT_ORG, reason: SSO_MARKER }]); + expect(rp.error).toHaveBeenCalledTimes(1); + expect(String(rp.error.mock.calls[0][0])).toMatch(/applying the provider's IdP group mappings .* FAILED/); + }); + + it('deleting the mapping removes the grants it projected at once', async () => { + const rp = await makeGroupRp(); + const mappingId = savedMappingId(await saveGroupMapping(rp, { providerId: PROVIDER_ID, groupDisplayName: 'Acme Sales', permissionSet: SALES })); + const { userId } = await signInWithClaims(rp, { groups: ['Acme Sales'] }); + expect(await grantsOf(rp, userId)).toEqual([projectedSales]); + + const deleted = await deleteGroupMapping(rp, mappingId); + expect(deleted.status, JSON.stringify(deleted.body)).toBe(200); + expect(deleted.body).toMatchObject({ success: true, data: { providerId: PROVIDER_ID, deleted: true, reprojected: true, reconciledUsers: 1 } }); + expect(await grantsOf(rp, userId)).toEqual([]); + }); + + it('the door names exactly one source, and an SSO source must be a provider in an organization', async () => { + const rp = await makeGroupRp(); + const both = await saveGroupMapping(rp, { connectionId: 'okta-prod', providerId: PROVIDER_ID, groupDisplayName: 'Acme Sales', permissionSet: SALES }); + expect(both.status).toBe(400); + expect(both.body).toMatchObject({ error: { code: 'VALIDATION_FAILED', fields: [{ field: 'providerId', code: 'rule_violation' }] } }); + const unknown = await saveGroupMapping(rp, { providerId: 'nobody', groupDisplayName: 'Acme Sales', permissionSet: SALES }); + expect(unknown.body).toMatchObject({ error: { code: 'VALIDATION_FAILED', fields: [{ field: 'providerId', code: 'reference_not_found' }] } }); + await rp.engine.update('sys_sso_provider', { organization_id: null }, { where: { provider_id: PROVIDER_ID }, multi: true, context: { isSystem: true } } as never); + const orphan = await saveGroupMapping(rp, { providerId: PROVIDER_ID, groupDisplayName: 'Acme Sales', permissionSet: SALES }); + expect(orphan.body).toMatchObject({ error: { code: 'VALIDATION_FAILED', fields: [{ field: 'providerId', code: 'rule_violation' }] } }); + expect(await rp.engine.find('sys_idp_group_mapping', {}, SYSTEM)).toEqual([]); + }); +}); From d87fee184cd5eb155c263ee88d93734c07f17b24 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 18:12:17 +0000 Subject: [PATCH 2/5] test(plugin-auth): the break-glass pin signs the administrator in through the provider first Claude-Session: https://claude.ai/code/session_01ADHkmNwrm1hJ9e7eLARM7n Co-authored-by: Claude --- .../plugin-auth/src/sso-oidc-refusal-cause.test.ts | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/packages/plugins/plugin-auth/src/sso-oidc-refusal-cause.test.ts b/packages/plugins/plugin-auth/src/sso-oidc-refusal-cause.test.ts index 54ba309cd05..4f3a66cd7b8 100644 --- a/packages/plugins/plugin-auth/src/sso-oidc-refusal-cause.test.ts +++ b/packages/plugins/plugin-auth/src/sso-oidc-refusal-cause.test.ts @@ -798,15 +798,14 @@ describe('an SSO sign-in grants the permission set its IdP group is mapped to', it('the break-glass guard still refuses through the sign-in: the last administrator\'s grant is not removed, and the sign-in still lands', async () => { const rp = await makeGroupRp(); - // Mia already exists and is the only administrator, through a grant carrying this provider's marker. - await rp.engine.delete('sys_user', { where: { id: 'usr_admin' } }, SYSTEM as never); - await rp.engine.insert('sys_user', { id: 'usr_mia', email: EMAIL, name: 'Mia Chen', email_verified: true }, SYSTEM); + // Mia is the only administrator, through a grant carrying this provider's marker + // (a row the projection would remove: no mapping names it). + const { userId } = await signInWithClaims(rp, { groups: [] }); await rp.engine.insert('sys_user_permission_set', { - user_id: 'usr_mia', permission_set: ADMIN_FULL_ACCESS, organization_id: DEFAULT_ORG, reason: SSO_MARKER, + user_id: userId, permission_set: ADMIN_FULL_ACCESS, organization_id: DEFAULT_ORG, reason: SSO_MARKER, }, SYSTEM); - const { userId } = await signInWithClaims(rp, { groups: [] }); - expect(userId).toBe('usr_mia'); + await signInWithClaims(rp, { groups: [] }); expect(await grantsOf(rp, userId)).toEqual([{ permission_set: ADMIN_FULL_ACCESS, organization_id: DEFAULT_ORG, reason: SSO_MARKER }]); expect(rp.error).toHaveBeenCalledTimes(1); expect(String(rp.error.mock.calls[0][0])).toMatch(/applying the provider's IdP group mappings .* FAILED/); From de80434cb64ca32c6e7f190970fb9b0b4b30daee Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 18:21:17 +0000 Subject: [PATCH 3/5] feat(platform-objects): sys_idp_group_mapping names an SSO provider source; translations; changeset Claude-Session: https://claude.ai/code/session_01ADHkmNwrm1hJ9e7eLARM7n Co-authored-by: Claude --- .../30967-sso-group-permission-set-mapping.md | 16 ++++++++++++++++ .../apps/translations/ar.objects.generated.ts | 9 +++++---- .../apps/translations/de.objects.generated.ts | 9 +++++---- .../apps/translations/en.objects.generated.ts | 9 +++++---- .../apps/translations/es-ES.objects.generated.ts | 9 +++++---- .../apps/translations/fr.objects.generated.ts | 9 +++++---- .../apps/translations/ja-JP.objects.generated.ts | 9 +++++---- .../apps/translations/pt-BR.objects.generated.ts | 9 +++++---- .../apps/translations/ru.objects.generated.ts | 9 +++++---- .../apps/translations/zh-CN.objects.generated.ts | 9 +++++---- .../translations/zh-Hant.objects.generated.ts | 9 +++++---- 11 files changed, 66 insertions(+), 40 deletions(-) create mode 100644 .changeset/30967-sso-group-permission-set-mapping.md diff --git a/.changeset/30967-sso-group-permission-set-mapping.md b/.changeset/30967-sso-group-permission-set-mapping.md new file mode 100644 index 00000000000..2c85e341efe --- /dev/null +++ b/.changeset/30967-sso-group-permission-set-mapping.md @@ -0,0 +1,16 @@ +--- +'@objectstack/plugin-auth': patch +'@objectstack/platform-objects': patch +--- + +feat(plugin-auth): an SSO sign-in grants the ordinary permission set its IdP group is mapped to + +Clause-②: yes (widening) +Metadata-protocol: none + +An enterprise SSO provider (OIDC or SAML, through `@better-auth/sso`) can now drive what its users may do from the groups the identity provider sends at sign-in, through the same `sys_idp_group_mapping` mappings a SCIM connection uses. There is no second mapping model. + +- **Where the groups come from.** Set the provider's own claim mapping to fill `groups`: `mapping.extraFields: { groups: 'groups' }` for an OIDC claim named `groups`, or the attribute name an IdP uses for SAML (for example Entra ID's groups claim URI). The value may be one string or a list of strings. A provider whose mapping fills no `groups` behaves as before. +- **Saving a mapping.** `POST /api/v1/auth/admin/scim/set-group-mapping` now also takes `providerId` in place of `connectionId` (exactly one of the two; both is `400 VALIDATION_FAILED` on `providerId`). The grant's organization is the provider's own `organization_id`; a provider that names none, or an unknown provider, is refused `400 VALIDATION_FAILED` on `providerId`. With SSO off the save is refused `503`. The same platform-admin gate and the same organization-boundary judgement apply: administrator sets and every set outside the organization boundary are refused, and without a security service the save is refused `503`. The row is stored with `source_kind: 'sso'` (a new option on `sys_idp_group_mapping.source_kind`) and `source_id` = the provider id. +- **At each sign-in.** Every sign-in through the provider matches each group value against the provider's mappings (by `groupExternalId` when the mapping names one, which suits Entra ID's group object ids, else by exact `groupDisplayName`) and makes the user's grants follow them: a mapped group grants its set in the provider's organization, and a group the user has left loses the set at their next sign-in. A sign-in with no groups removes the grants that provider made earlier. The boundary is asked again before every grant, so a set that becomes an administrator set after its mapping was saved grants nothing, and with no security service nothing is granted. Only grants the provider made (their `reason` names the provider) are ever removed: a grant made by hand, or by SCIM, is never touched. Every write goes through the engine, so the break-glass last-administrator guard still refuses what it refuses elsewhere. If applying the mappings fails, the sign-in still succeeds and the failure is logged at `error`. +- **Deleting a mapping.** `POST /api/v1/auth/admin/scim/delete-group-mapping` removes an SSO mapping and, at once, the grants its provider made of that set in that organization, unless another of the provider's mappings still names that set (then each user's next sign-in decides). diff --git a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts index 5fd88ba5227..076bf77b8fb 100644 --- a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts @@ -2659,14 +2659,15 @@ export const arObjects: NonNullable = { }, source_kind: { label: "نوع المصدر", - help: "ما يرسل المجموعة: اتصال SCIM.", + help: "ما يرسل المجموعة: اتصال SCIM، أو مزوّد SSO عند تسجيل الدخول.", options: { - scim: "اتصال SCIM" + scim: "اتصال SCIM", + sso: "مزوّد SSO" } }, source_id: { label: "معرّف المصدر", - help: "معرّف اتصال SCIM الذي تصل عبره المجموعة، مثل \"okta-prod\"." + help: "معرّف اتصال SCIM أو معرّف مزوّد SSO الذي تصل عبره المجموعة، مثل \"okta-prod\"." }, group_external_id: { label: "المعرّف الخارجي للمجموعة", @@ -2682,7 +2683,7 @@ export const arObjects: NonNullable = { }, organization_id: { label: "المؤسسة", - help: "المؤسسة التي يتم المنح فيها: المؤسسة المالكة لاتصال SCIM." + help: "المؤسسة التي يتم المنح فيها: المؤسسة المالكة لاتصال SCIM أو لمزوّد SSO." }, created_at: { label: "تاريخ الإنشاء" diff --git a/packages/platform-objects/src/apps/translations/de.objects.generated.ts b/packages/platform-objects/src/apps/translations/de.objects.generated.ts index 034ba9390fc..c4b7befff7e 100644 --- a/packages/platform-objects/src/apps/translations/de.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.objects.generated.ts @@ -2659,14 +2659,15 @@ export const deObjects: NonNullable = { }, source_kind: { label: "Quellart", - help: "Was die Gruppe überträgt: eine SCIM-Verbindung.", + help: "Was die Gruppe überträgt: eine SCIM-Verbindung oder ein SSO-Anbieter bei der Anmeldung.", options: { - scim: "SCIM-Verbindung" + scim: "SCIM-Verbindung", + sso: "SSO-Anbieter" } }, source_id: { label: "Quell-ID", - help: "Die ID der SCIM-Verbindung, über die die Gruppe eintrifft, z. B. \"okta-prod\"." + help: "Die ID der SCIM-Verbindung oder des SSO-Anbieters, über die die Gruppe eintrifft, z. B. \"okta-prod\"." }, group_external_id: { label: "Externe Gruppen-ID", @@ -2682,7 +2683,7 @@ export const deObjects: NonNullable = { }, organization_id: { label: "Organisation", - help: "Die Organisation, in der die Berechtigung erteilt wird: die Organisation, der die SCIM-Verbindung gehört." + help: "Die Organisation, in der die Berechtigung erteilt wird: die Organisation, der die SCIM-Verbindung oder der SSO-Anbieter gehört." }, created_at: { label: "Erstellt am" diff --git a/packages/platform-objects/src/apps/translations/en.objects.generated.ts b/packages/platform-objects/src/apps/translations/en.objects.generated.ts index 38a9468edc9..435c4e0817e 100644 --- a/packages/platform-objects/src/apps/translations/en.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.objects.generated.ts @@ -2659,14 +2659,15 @@ export const enObjects: NonNullable = { }, source_kind: { label: "Source Kind", - help: "What pushes the group: a SCIM connection.", + help: "What sends the group: a SCIM connection, or an SSO provider at sign-in.", options: { - scim: "SCIM Connection" + scim: "SCIM Connection", + sso: "SSO Provider" } }, source_id: { label: "Source ID", - help: "The SCIM connection ID the group arrives through, e.g. \"okta-prod\"." + help: "The SCIM connection ID or the SSO provider ID the group arrives through, e.g. \"okta-prod\"." }, group_external_id: { label: "Group External ID", @@ -2682,7 +2683,7 @@ export const enObjects: NonNullable = { }, organization_id: { label: "Organization", - help: "The organization the grant is made in: the organization that owns the SCIM connection." + help: "The organization the grant is made in: the organization that owns the SCIM connection or the SSO provider." }, created_at: { label: "Created At" diff --git a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts index 8bcb22f987b..81083d7f034 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts @@ -2659,14 +2659,15 @@ export const esESObjects: NonNullable = { }, source_kind: { label: "Tipo de origen", - help: "Qué envía el grupo: una conexión SCIM.", + help: "Qué envía el grupo: una conexión SCIM o un proveedor SSO al iniciar sesión.", options: { - scim: "Conexión SCIM" + scim: "Conexión SCIM", + sso: "Proveedor SSO" } }, source_id: { label: "ID de origen", - help: "El ID de la conexión SCIM por la que llega el grupo, p. ej. \"okta-prod\"." + help: "El ID de la conexión SCIM o del proveedor SSO por el que llega el grupo, p. ej. \"okta-prod\"." }, group_external_id: { label: "ID externo del grupo", @@ -2682,7 +2683,7 @@ export const esESObjects: NonNullable = { }, organization_id: { label: "Organización", - help: "La organización en la que se concede: la organización propietaria de la conexión SCIM." + help: "La organización en la que se concede: la organización propietaria de la conexión SCIM o del proveedor SSO." }, created_at: { label: "Creado el" diff --git a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts index 950cb454acc..828f29ac65f 100644 --- a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts @@ -2659,14 +2659,15 @@ export const frObjects: NonNullable = { }, source_kind: { label: "Type de source", - help: "Ce qui envoie le groupe : une connexion SCIM.", + help: "Ce qui envoie le groupe : une connexion SCIM, ou un fournisseur SSO à la connexion.", options: { - scim: "Connexion SCIM" + scim: "Connexion SCIM", + sso: "Fournisseur SSO" } }, source_id: { label: "ID de source", - help: "L’ID de la connexion SCIM par laquelle le groupe arrive, p. ex. \"okta-prod\"." + help: "L’ID de la connexion SCIM ou du fournisseur SSO par lequel le groupe arrive, p. ex. \"okta-prod\"." }, group_external_id: { label: "ID externe du groupe", @@ -2682,7 +2683,7 @@ export const frObjects: NonNullable = { }, organization_id: { label: "Organisation", - help: "L’organisation dans laquelle l’attribution est faite : celle qui possède la connexion SCIM." + help: "L’organisation dans laquelle l’attribution est faite : celle qui possède la connexion SCIM ou le fournisseur SSO." }, created_at: { label: "Créé le" diff --git a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts index 1077e497e8b..520c61ce59f 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts @@ -2659,14 +2659,15 @@ export const jaJPObjects: NonNullable = { }, source_kind: { label: "ソース種別", - help: "グループを送信するもの:SCIM 接続。", + help: "グループを送信するもの:SCIM 接続、またはサインイン時の SSO プロバイダー。", options: { - scim: "SCIM 接続" + scim: "SCIM 接続", + sso: "SSO プロバイダー" } }, source_id: { label: "ソース ID", - help: "グループが届く SCIM 接続の ID(例:\"okta-prod\")。" + help: "グループが届く SCIM 接続の ID または SSO プロバイダーの ID(例:\"okta-prod\")。" }, group_external_id: { label: "グループ外部 ID", @@ -2682,7 +2683,7 @@ export const jaJPObjects: NonNullable = { }, organization_id: { label: "組織", - help: "付与が行われる組織:SCIM 接続を所有する組織。" + help: "付与が行われる組織:SCIM 接続または SSO プロバイダーを所有する組織。" }, created_at: { label: "作成日時" diff --git a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts index ee2112422d2..52c9f07b4aa 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts @@ -2659,14 +2659,15 @@ export const ptBRObjects: NonNullable = { }, source_kind: { label: "Tipo de origem", - help: "O que envia o grupo: uma conexão SCIM.", + help: "O que envia o grupo: uma conexão SCIM ou um provedor SSO no login.", options: { - scim: "Conexão SCIM" + scim: "Conexão SCIM", + sso: "Provedor SSO" } }, source_id: { label: "ID de origem", - help: "O ID da conexão SCIM pela qual o grupo chega, por exemplo \"okta-prod\"." + help: "O ID da conexão SCIM ou do provedor SSO pelo qual o grupo chega, por exemplo \"okta-prod\"." }, group_external_id: { label: "ID externo do grupo", @@ -2682,7 +2683,7 @@ export const ptBRObjects: NonNullable = { }, organization_id: { label: "Organização", - help: "A organização em que a concessão é feita: a organização proprietária da conexão SCIM." + help: "A organização em que a concessão é feita: a organização proprietária da conexão SCIM ou do provedor SSO." }, created_at: { label: "Criado em" diff --git a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts index e47f5df005e..9992291530a 100644 --- a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts @@ -2659,14 +2659,15 @@ export const ruObjects: NonNullable = { }, source_kind: { label: "Тип источника", - help: "Что передаёт группу: подключение SCIM.", + help: "Что передаёт группу: подключение SCIM или поставщик SSO при входе.", options: { - scim: "Подключение SCIM" + scim: "Подключение SCIM", + sso: "Поставщик SSO" } }, source_id: { label: "ID источника", - help: "ID подключения SCIM, через которое приходит группа, например \"okta-prod\"." + help: "ID подключения SCIM или поставщика SSO, через которое приходит группа, например \"okta-prod\"." }, group_external_id: { label: "Внешний ID группы", @@ -2682,7 +2683,7 @@ export const ruObjects: NonNullable = { }, organization_id: { label: "Организация", - help: "Организация, в которой выдаётся разрешение: организация, которой принадлежит подключение SCIM." + help: "Организация, в которой выдаётся разрешение: организация, которой принадлежит подключение SCIM или поставщик SSO." }, created_at: { label: "Создано" diff --git a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts index c273eda04c0..73823e00fc9 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts @@ -2659,14 +2659,15 @@ export const zhCNObjects: NonNullable = { }, source_kind: { label: "来源类型", - help: "推送该组的来源:SCIM 连接。", + help: "发送该组的来源:SCIM 连接,或登录时的 SSO 提供方。", options: { - scim: "SCIM 连接" + scim: "SCIM 连接", + sso: "SSO 提供方" } }, source_id: { label: "来源 ID", - help: "该组经由的 SCIM 连接 ID,例如 \"okta-prod\"。" + help: "该组经由的 SCIM 连接 ID 或 SSO 提供方 ID,例如 \"okta-prod\"。" }, group_external_id: { label: "组外部 ID", @@ -2682,7 +2683,7 @@ export const zhCNObjects: NonNullable = { }, organization_id: { label: "组织", - help: "授权所在的组织:拥有该 SCIM 连接的组织。" + help: "授权所在的组织:拥有该 SCIM 连接或 SSO 提供方的组织。" }, created_at: { label: "创建时间" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts index 00dbcc055c6..d308d108200 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts @@ -2659,14 +2659,15 @@ export const zhHantObjects: NonNullable = { }, source_kind: { label: "來源類型", - help: "推送該群組的來源:SCIM 連線。", + help: "傳送該群組的來源:SCIM 連線,或登入時的 SSO 提供者。", options: { - scim: "SCIM 連線" + scim: "SCIM 連線", + sso: "SSO 提供者" } }, source_id: { label: "來源 ID", - help: "該群組經由的 SCIM 連線 ID,例如 \"okta-prod\"。" + help: "該群組經由的 SCIM 連線 ID 或 SSO 提供者 ID,例如 \"okta-prod\"。" }, group_external_id: { label: "群組外部 ID", @@ -2682,7 +2683,7 @@ export const zhHantObjects: NonNullable = { }, organization_id: { label: "組織", - help: "授權所在的組織:擁有該 SCIM 連線的組織。" + help: "授權所在的組織:擁有該 SCIM 連線或 SSO 提供者的組織。" }, created_at: { label: "建立時間" From 3682cd753cf1474b235e0077fabb3aa4ca6246f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 18:23:13 +0000 Subject: [PATCH 4/5] fix(plugin-auth): the SSO group projection logs a failure on the host logger's error channel Claude-Session: https://claude.ai/code/session_01ADHkmNwrm1hJ9e7eLARM7n Co-authored-by: Claude --- .../plugins/plugin-auth/src/auth-manager-plugin-list.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) 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 79e27783189..03216f2516f 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts @@ -788,7 +788,14 @@ export async function buildPluginList(this: PluginListHost): Promise { getEngine: () => this.getDataEngine(), boundary: async () => (await this.config.organizationBoundary?.().catch(() => undefined)) ?? undefined, warn: (message) => this.config.logger?.warn?.(message), - error: (message) => this.config.logger?.error?.(message), + // The host logger carries `error` though the config type names only + // `info`/`warn` (as `logAfterResponseSendFailure` reads it); with none, + // the console's error stream, never a lower level. + error: (message) => { + const sink = this.config.logger as { error?: (msg: string) => void } | undefined; + if (typeof sink?.error === 'function') sink.error(message); + else console.error(message); + }, }), provisionUserOnEveryLogin: true, }); From 70db6d0601c6ca0f3d64750fcd93c9ce95b87a19 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 19:02:16 +0000 Subject: [PATCH 5/5] fix(plugin-auth): the SSO delete-revoke names the grant's organization as its tenant The grant removal on deleting an SSO group mapping now carries the system context with the grant's organization as tenant, as the sign-in's own grant writes do. The tenant-audit census and its page are recounted for the new write site. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmNwrm1hJ9e7eLARM7n --- .../docs/permissions/tenant-audit-census.mdx | 34 +++++++++---------- ...08-tenant-audit-write-call-sites.counts.md | 17 +++++----- .../src/idp-group-mapping-admin.ts | 3 +- 3 files changed, 28 insertions(+), 26 deletions(-) diff --git a/content/docs/permissions/tenant-audit-census.mdx b/content/docs/permissions/tenant-audit-census.mdx index 5e5303df990..5498944713a 100644 --- a/content/docs/permissions/tenant-audit-census.mdx +++ b/content/docs/permissions/tenant-audit-census.mdx @@ -132,7 +132,7 @@ are reported as `undecidable` rather than assumed either way. The same holds twice over for the context. An options argument spelled as a literal can be read; one spelled `options`, `{ ...opts }`, or handed through a -forwarding shim cannot, and **57 of the 275 sites are spelled that way**. A +forwarding shim cannot, and **57 of the 276 sites are spelled that way**. A context resolved from an inline literal or a local `const` can be tested for `isSystem`; one arriving from a helper call cannot. @@ -197,10 +197,10 @@ reproduce them. Where it disagrees, it disagrees on the page: | carried figure | where it survives | this census | | :--- | :--- | ---: | -| 175 write call sites | quoted in the merged changeset | **275** | +| 175 write call sites | quoted in the merged changeset | **276** | | 24 carrying no tenant context | quoted in the merged changeset | **3** provable and tenancy-enabled; **30** more whose options argument is unreadable | -| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **195 of 275** decidable, **80** undecidable | -| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 152 decidably elevated, 0 decidably not, 113 undecidable | +| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **196 of 276** decidable, **80** undecidable | +| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 153 decidably elevated, 0 decidably not, 113 undecidable | | 141 and 132, two independent re-derivations | the card that filed this work | — | **The differences are not reconciled, and deliberately so.** The old census's @@ -211,17 +211,17 @@ at any commit. Two structural facts do plausibly widen this reading against any hand or regex one, and both are counted in the generated tables below: the 62 sites reached -through an erased (`any`) receiver, and the 71 that name their object through a +through an erased (`any`) receiver, and the 72 that name their object through a `const` rather than inline. An instrument that read either the way a person does would report a smaller number and would not say so. The fourth row is the one worth flagging to anyone citing it. **The 135 / 77% figure has no surviving corroboration anywhere in the tree.** This census reads -152 of 275 (55%) as decidably elevated, with 113 more whose elevation is a +153 of 276 (55%) as decidably elevated, with 113 more whose elevation is a run-time fact — so the claim is neither confirmed nor refuted, and the honest answer is that a static reading cannot settle it. -⇒ **Cite `3 / 275`, and say what it is**: the sites whose options argument was +⇒ **Cite `3 / 276`, and say what it is**: the sites whose options argument was READ and holds no tenant context, against a decidably tenancy-enabled object. That is the control's provable yield surface. ⛔ Do not cite it as "the sites without tenant context" — **30 further sites** have an options argument this @@ -233,29 +233,29 @@ cannot read, and they are neither in nor out. | what | count | | :--- | ---: | -| write call sites on the application surface | **275** | -| …whose object name is statically decidable | 195 | +| write call sites on the application surface | **276** | +| …whose object name is statically decidable | 196 | | …whose object name is chosen at run time | 80 | -| …against an object with tenancy ENABLED | 189 | +| …against an object with tenancy ENABLED | 190 | | …against an object that declares tenancy off | 6 | -| threading a tenant context | 208 | +| threading a tenant context | 209 | | PROVABLY carrying none (options read, no context key) | **10** | | …of those, against a decidably tenancy-enabled object | **3** | | options argument UNREADABLE — may or may not carry one | 57 | | …of those, against a decidably tenancy-enabled object | 30 | -| threading a decidably ELEVATED (`isSystem`) context | 152 | +| threading a decidably ELEVATED (`isSystem`) context | 153 | | threading a context that is decidably NOT elevated | 0 | | threading a context whose elevation is a run-time fact | 113 | | how the instrument reached the site | count | | :--- | ---: | -| receiver carried a readable engine type | 213 | +| receiver carried a readable engine type | 214 | | receiver erased, placed by the object NAME | 52 | | receiver erased, placed by an `object: string` PARAMETER | 5 | | receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 | | object name spelled inline | 124 | -| object name spelled through a `const` | 71 | +| object name spelled through a `const` | 72 | | object name is an `object: string` parameter | 7 | | object name is some other run-time expression | 73 | @@ -307,12 +307,12 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-08 at `fe3aea79c`. +Measured on 2026-11-08 at `da13e5987`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1063 | -| engine-shaped types recognised | 114 | +| tracked non-test sources scanned | 1068 | +| engine-shaped types recognised | 115 | | declared objects in the registry | 132 | | same-named calls subtracted as non-engine | 243 | diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md index a8c82dff3ac..0f1f4bc146a 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md @@ -33,17 +33,17 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution. | Measure | Value | |---|---:| -| Write call sites | 275 | -| Object name statically decidable | 195 | +| Write call sites | 276 | +| Object name statically decidable | 196 | | Object name chosen at run time | 80 | -| Against a tenancy-enabled object | 189 | +| Against a tenancy-enabled object | 190 | | Against an object declaring tenancy off | 6 | -| Threading a tenant context | 208 | +| Threading a tenant context | 209 | | Provably carrying none | 10 | | …and decidably tenancy-enabled | 3 | | Options argument unreadable | 57 | | …and decidably tenancy-enabled | 30 | -| Threading a decidably elevated context | 152 | +| Threading a decidably elevated context | 153 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 113 | @@ -90,12 +90,12 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-08 at `fe3aea79c`. +Measured on 2026-11-08 at `da13e5987`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1063 | -| engine-shaped types recognised | 114 | +| tracked non-test sources scanned | 1068 | +| engine-shaped types recognised | 115 | | declared objects in the registry | 132 | | same-named calls subtracted as non-engine | 243 | @@ -158,6 +158,7 @@ Measured on 2026-11-08 at `fe3aea79c`. | `packages/plugins/plugin-auth/src/idp-group-mapping-admin.ts` | `delete` | `IDP_GROUP_MAPPING_OBJECT` | undecidable | PROVABLY NONE | 1 | | `packages/plugins/plugin-auth/src/idp-group-mapping-admin.ts` | `insert` | `IDP_GROUP_MAPPING_OBJECT` | undecidable | options unreadable | 1 | | `packages/plugins/plugin-auth/src/idp-group-mapping-admin.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 | +| `packages/plugins/plugin-auth/src/idp-group-mapping-admin.ts` | `delete` | `sys_user_permission_set` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/idp-locale-claim.ts` | `update` | `sys_user` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/mcp-client-last-use.ts` | `update` | `sys_oauth_consent` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/member-role-canonical.ts` | `update` | `MEMBER_OBJECT` | undecidable | elevated | 1 | diff --git a/packages/plugins/plugin-auth/src/idp-group-mapping-admin.ts b/packages/plugins/plugin-auth/src/idp-group-mapping-admin.ts index 18a164a70a2..6e63cb7c62c 100644 --- a/packages/plugins/plugin-auth/src/idp-group-mapping-admin.ts +++ b/packages/plugins/plugin-auth/src/idp-group-mapping-admin.ts @@ -289,7 +289,8 @@ async function revokeSsoProjectedGrants( const writer: IDataEngine = withSystemContext(engine); const users = new Set(); for (const grant of Array.isArray(grants) ? (grants as Record[]) : []) { - await writer.delete(GRANT_OBJECT, { where: { id: text(grant.id) } }); + // The grant's organization is the write's tenant, as on the sign-in's own writes. + await writer.delete(GRANT_OBJECT, { where: { id: text(grant.id) }, context: { isSystem: true, tenantId: organizationId } }); users.add(text(grant.user_id)); } return { reprojected: true, reconciledUsers: users.size };