diff --git a/.changeset/30959-scim-group-permission-set-mapping.md b/.changeset/30959-scim-group-permission-set-mapping.md new file mode 100644 index 00000000000..c8926790b09 --- /dev/null +++ b/.changeset/30959-scim-group-permission-set-mapping.md @@ -0,0 +1,22 @@ +--- +'@objectstack/plugin-auth': patch +'@objectstack/plugin-security': patch +'@objectstack/platform-objects': patch +'@objectstack/spec': patch +'@objectstack/cli': patch +--- + +feat(plugin-auth): a SCIM group push grants the ordinary permission set its group mapping names + +Clause-②: yes (widening) +Metadata-protocol: none + +An identity provider that pushes a group over SCIM now changes what its members may do. A platform administrator saves a mapping from one SCIM connection's group to one permission set with `POST /api/v1/auth/admin/scim/set-group-mapping` (`connectionId`, `groupExternalId` or `groupDisplayName`, `permissionSet`), and deletes one with `POST /api/v1/auth/admin/scim/delete-group-mapping` (`mappingId`). Both run the platform-admin gate the SCIM credential door runs. A connection whose credential names no organization, or whose credentials name two, is refused `400 VALIDATION_FAILED` on `connectionId`, so every mapping, and every grant it makes, belongs to exactly one organization. Only live credentials (active and unexpired, as the bearer verifier reads them) decide that organization: a credential revoked in one organization does not block a mapping once a new one is minted in another. Saving the same group and set again is idempotent; if that mapping was saved while another organization owned the connection, the save is refused `409 RESOURCE_CONFLICT` naming the old mapping, which must be deleted first. The rows live in the new platform object `sys_idp_group_mapping`, which the data API only lists. + +When a group's membership changes, `@better-auth/scim`'s projection grants each member the mapped set in the organization that owns the connection, inside the SCIM transaction, written by the connection (`svc:scim:CONNECTION_ID` in the audit trail). Removing a member removes that grant. A group nobody mapped grants nothing. The projection asks the boundary again before every grant it writes, so a set that becomes an administrator set after its mapping was saved grants nothing. A grant the projection did not make, such as one an administrator made by hand, is never removed. Saving or deleting a mapping applies it to the group's current members at once. + +A mapping can never make anyone an administrator. The save refuses, with `400 VALIDATION_FAILED` on `permissionSet`, every set outside the organization boundary: `admin_full_access`, the organization-administrator sets, the agent ceiling sets, a set with a superuser wildcard or an `adminScope`, and a set with a capability not scoped to the organization. The judgement is plugin-security's own delegated-administration predicate, now served as the optional `ISecurityService.organizationBoundaryFailure(setName)` member. Without a security service the save is refused `503` and nothing is granted. + +The break-glass guard's refusal no longer tells operators that "the SCIM group mapping is too broad": a group mapping never moves administrator standing, so the sentence now says to grant another account standing first. + +The v18 organization-ownership ceremony (`os migrate organization-ownership`) inventories `sys_idp_group_mapping` with the attribution fate, like the other organization-owned rows written with their organization: a database that holds the new table plans and applies as before. diff --git a/content/docs/permissions/tenant-audit-census.mdx b/content/docs/permissions/tenant-audit-census.mdx index e20438a456d..5e5303df990 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 **56 of the 270 sites are spelled that way**. A +forwarding shim cannot, and **57 of the 275 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. @@ -160,8 +160,8 @@ now **0**: nothing on this surface threads a context that provably lacks the fla **"No tenant context" counted sites it had not read.** An options argument the walker could not parse was folded into the same bucket as one it had read and -found empty. That published **64 sites "carrying no tenant context at all"** -when 8 said so and 56 were simply unread — an over-claim in the *alarming* +found empty. That published **67 sites "carrying no tenant context at all"** +when 10 said so and 57 were simply unread — an over-claim in the *alarming* direction, on the very figure this page tells other cards to cite. `carries` is now three-valued, and an unreadable argument can never contribute to the provable count. @@ -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 | **270** | -| 24 carrying no tenant context | quoted in the merged changeset | **2** 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 | **192 of 270** decidable, **78** undecidable | -| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 150 decidably elevated, 0 decidably not, 112 undecidable | +| 175 write call sites | quoted in the merged changeset | **275** | +| 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 | | 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 69 that name their object through a +through an erased (`any`) receiver, and the 71 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 -150 of 270 (56%) as decidably elevated, with 112 more whose elevation is a +152 of 275 (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 `2 / 270`, and say what it is**: the sites whose options argument was +⇒ **Cite `3 / 275`, 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,31 +233,31 @@ cannot read, and they are neither in nor out. | what | count | | :--- | ---: | -| write call sites on the application surface | **270** | -| …whose object name is statically decidable | 192 | -| …whose object name is chosen at run time | 78 | -| …against an object with tenancy ENABLED | 186 | +| write call sites on the application surface | **275** | +| …whose object name is statically decidable | 195 | +| …whose object name is chosen at run time | 80 | +| …against an object with tenancy ENABLED | 189 | | …against an object that declares tenancy off | 6 | -| threading a tenant context | 206 | -| PROVABLY carrying none (options read, no context key) | **8** | -| …of those, against a decidably tenancy-enabled object | **2** | -| options argument UNREADABLE — may or may not carry one | 56 | +| threading a tenant context | 208 | +| 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 | 150 | +| threading a decidably ELEVATED (`isSystem`) context | 152 | | threading a context that is decidably NOT elevated | 0 | -| threading a context whose elevation is a run-time fact | 112 | +| threading a context whose elevation is a run-time fact | 113 | | how the instrument reached the site | count | | :--- | ---: | -| receiver carried a readable engine type | 208 | +| receiver carried a readable engine type | 213 | | 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 | 123 | -| object name spelled through a `const` | 69 | +| object name spelled inline | 124 | +| object name spelled through a `const` | 71 | | object name is an `object: string` parameter | 7 | -| object name is some other run-time expression | 71 | +| object name is some other run-time expression | 73 | ### Subtractions the census could NOT defend — enforced @@ -307,13 +307,13 @@ 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 `759f4daa0`. +Measured on 2026-11-08 at `fe3aea79c`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1060 | +| tracked non-test sources scanned | 1063 | | engine-shaped types recognised | 114 | -| declared objects in the registry | 131 | +| declared objects in the registry | 132 | | same-named calls subtracted as non-engine | 243 | {/* END GENERATED: tenant-audit-census */} 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 20d3e496c1c..a8c82dff3ac 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,19 +33,19 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution. | Measure | Value | |---|---:| -| Write call sites | 270 | -| Object name statically decidable | 192 | -| Object name chosen at run time | 78 | -| Against a tenancy-enabled object | 186 | +| Write call sites | 275 | +| Object name statically decidable | 195 | +| Object name chosen at run time | 80 | +| Against a tenancy-enabled object | 189 | | Against an object declaring tenancy off | 6 | -| Threading a tenant context | 206 | -| Provably carrying none | 8 | -| …and decidably tenancy-enabled | 2 | -| Options argument unreadable | 56 | +| Threading a tenant context | 208 | +| Provably carrying none | 10 | +| …and decidably tenancy-enabled | 3 | +| Options argument unreadable | 57 | | …and decidably tenancy-enabled | 30 | -| Threading a decidably elevated context | 150 | +| Threading a decidably elevated context | 152 | | Threading a decidably non-elevated context | 0 | -| Threading a context of undecidable elevation | 112 | +| Threading a context of undecidable elevation | 113 | ## Subtractions the census could NOT defend — enforced @@ -90,13 +90,13 @@ 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 `759f4daa0`. +Measured on 2026-11-08 at `fe3aea79c`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1060 | +| tracked non-test sources scanned | 1063 | | engine-shaped types recognised | 114 | -| declared objects in the registry | 131 | +| declared objects in the registry | 132 | | same-named calls subtracted as non-engine | 243 | ## Every site @@ -155,6 +155,9 @@ Measured on 2026-11-08 at `759f4daa0`. | `packages/plugins/plugin-auth/src/ensure-default-organization.ts` | `update` | `sys_member` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/forced-reset-revocation.ts` | `update` | `SystemObjectName.API_KEY` | undecidable | elevated | 1 | | `packages/plugins/plugin-auth/src/forced-reset-revocation.ts` | `update` | `SystemObjectName.SESSION` | undecidable | elevated | 1 | +| `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-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 | @@ -173,6 +176,8 @@ Measured on 2026-11-08 at `759f4daa0`. | `packages/plugins/plugin-auth/src/scim-connection-admin.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/scim-connection-service.ts` | `insert` | `sys_scim_connection_credential` | enabled | PROVABLY NONE | 1 | | `packages/plugins/plugin-auth/src/scim-connection-service.ts` | `update` | `sys_scim_connection_credential` | enabled | elevated | 1 | +| `packages/plugins/plugin-auth/src/scim-group-projection.ts` | `delete` | `sys_user_permission_set` | enabled | PROVABLY NONE | 1 | +| `packages/plugins/plugin-auth/src/scim-group-projection.ts` | `insert` | `sys_user_permission_set` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/session-tombstone.ts` | `update` | `objectName` | undecidable | options unreadable | 1 | | `packages/plugins/plugin-auth/src/sso-client-secret.ts` | `update` | `sys_sso_provider` | disabled | elevated | 1 | | `packages/plugins/plugin-auth/src/sys-session-revoke.ts` | `update` | `SystemObjectName.SESSION` | undecidable | elevated | 1 | diff --git a/packages/cli/src/utils/organization-ownership-inventory.ts b/packages/cli/src/utils/organization-ownership-inventory.ts index 7ee05667807..1aa131f1002 100644 --- a/packages/cli/src/utils/organization-ownership-inventory.ts +++ b/packages/cli/src/utils/organization-ownership-inventory.ts @@ -784,6 +784,18 @@ export const ORGANIZATION_OWNERSHIP_INVENTORY: readonly InventoryEntry[] = [ `${CENSUS_MAIN}: systemFields.tenant: false; ${D7}: a declarative connector's stored credential is environment-level, ` + 'read by the reference its instances name, never by organization', }, + // #30959 (ruling record 6718345088, fork 1 (a)) — an identity-provider group + // mapping is saved by the platform administrator for one SCIM connection and + // always carries the organization that owns the connection's credential (the + // save refuses a connection whose credential names none), so a NULL row has + // no producer. + { + object: 'sys_idp_group_mapping', + census: PMAIN, + fate: 'attribution', + citation: `${CENSUS_MAIN} (in reach, added since the first census; one row per SCIM connection, in the organization that owns it); ${D10_SINGLE}`, + anchors: [], + }, // ADR-0143 D3 — a connector connection is made by an organization's // administrator and dispatched with by that organization's runs (Q1 = A): // every row is written with the organization that connected it, so a NULL diff --git a/packages/platform-objects/scripts/i18n-extract.config.ts b/packages/platform-objects/scripts/i18n-extract.config.ts index 6aded3dee16..b653c72d0f1 100644 --- a/packages/platform-objects/scripts/i18n-extract.config.ts +++ b/packages/platform-objects/scripts/i18n-extract.config.ts @@ -145,6 +145,7 @@ import { SysScimProjectionGrant, SysScimSubject, SysScimUser, + SysIdpGroupMapping, } from '../src/identity/index.js'; // ── Security ────────────────────────────────────────────────────────────── @@ -319,6 +320,7 @@ const config: ObjectStackDefinition = defineStack({ SysScimProjectionGrant, SysScimSubject, SysScimUser, + SysIdpGroupMapping, // Security: RBAC moved to @objectstack/plugin-security, sharing to // @objectstack/plugin-sharing (ADR-0029 K2 / D8). 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 2986a6e498c..5fd88ba5227 100644 --- a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts @@ -2649,6 +2649,54 @@ export const arObjects: NonNullable = { } } }, + sys_idp_group_mapping: { + label: "ربط مجموعة IdP", + pluralLabel: "روابط مجموعات IdP", + description: "يربط مجموعة من مزوّد الهوية بمجموعة الأذونات الممنوحة لأعضائها", + fields: { + id: { + label: "ID" + }, + source_kind: { + label: "نوع المصدر", + help: "ما يرسل المجموعة: اتصال SCIM.", + options: { + scim: "اتصال SCIM" + } + }, + source_id: { + label: "معرّف المصدر", + help: "معرّف اتصال SCIM الذي تصل عبره المجموعة، مثل \"okta-prod\"." + }, + group_external_id: { + label: "المعرّف الخارجي للمجموعة", + help: "قيمة externalId للمجموعة كما يرسلها مزوّد الهوية. اضبط هذا الحقل أو اسم العرض، وليس كليهما." + }, + group_display_name: { + label: "اسم عرض المجموعة", + help: "قيمة displayName للمجموعة، بمطابقة تامة. يُستخدم عندما لا يحدد الربط معرّفًا خارجيًا." + }, + permission_set: { + label: "مجموعة الأذونات", + help: "مجموعة الأذونات الممنوحة لعضو المجموعة. تُرفض مجموعات المسؤول." + }, + organization_id: { + label: "المؤسسة", + help: "المؤسسة التي يتم المنح فيها: المؤسسة المالكة لاتصال SCIM." + }, + created_at: { + label: "تاريخ الإنشاء" + }, + updated_at: { + label: "تاريخ التحديث" + } + }, + _views: { + all: { + label: "الكل" + } + } + }, sys_notification: { label: "حدث الإشعار", pluralLabel: "أحداث الإشعارات", diff --git a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts index 3e3629b8d7e..005fe9ce54f 100644 --- a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts @@ -25,6 +25,7 @@ export const arGeneratedSourceHashes: Readonly> = { "metadataForms.permission.fields.tabPermissions.helpText": "8942e2aebe59897c", "metadataForms.position.fields.name.helpText": "3594bba7cc2a3c8a", "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", + "objects.sys_idp_group_mapping.fields.id.label": "00b0385c9c152888", "objects.sys_job.fields.schedule_type.options.cron": "fd48d0e2cd59cab2", "objects.sys_oauth_application.fields.jwks.label": "b2cf79f9d66c0dbc", "objects.sys_oauth_application.fields.jwks_uri.label": "2a4339df734ab269", diff --git a/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts b/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts index 352de7491a7..403ac967da0 100644 --- a/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts +++ b/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts @@ -31,6 +31,8 @@ const OWNED_OBJECTS = new Set([ 'sys_scim_connection_binding', 'sys_scim_connection_credential', 'sys_scim_group', 'sys_scim_group_member', 'sys_scim_identity_tombstone', 'sys_scim_projection_grant', 'sys_scim_subject', 'sys_scim_user', + // identity — IdP group → permission set mapping (#30959; SCIM now, SSO group claims later) + 'sys_idp_group_mapping', // audit / messaging-adjacent (still owned here) 'sys_notification', 'sys_attachment', 'sys_email', 'sys_email_template', // (sys_saved_report / sys_report_schedule retired with the saved-report stack, #20102) 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 a6d8b8a9692..034ba9390fc 100644 --- a/packages/platform-objects/src/apps/translations/de.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.objects.generated.ts @@ -2649,6 +2649,54 @@ export const deObjects: NonNullable = { } } }, + sys_idp_group_mapping: { + label: "IdP-Gruppenzuordnung", + pluralLabel: "IdP-Gruppenzuordnungen", + description: "Ordnet eine Gruppe des Identitätsanbieters dem Berechtigungssatz zu, den ihre Mitglieder erhalten", + fields: { + id: { + label: "ID" + }, + source_kind: { + label: "Quellart", + help: "Was die Gruppe überträgt: eine SCIM-Verbindung.", + options: { + scim: "SCIM-Verbindung" + } + }, + source_id: { + label: "Quell-ID", + help: "Die ID der SCIM-Verbindung, über die die Gruppe eintrifft, z. B. \"okta-prod\"." + }, + group_external_id: { + label: "Externe Gruppen-ID", + help: "Die externalId der Gruppe, wie der Identitätsanbieter sie sendet. Legen Sie diese oder den Anzeigenamen fest, nicht beides." + }, + group_display_name: { + label: "Gruppen-Anzeigename", + help: "Der displayName der Gruppe, exakt abgeglichen. Wird verwendet, wenn die Zuordnung keine externe ID nennt." + }, + permission_set: { + label: "Berechtigungssatz", + help: "Der Berechtigungssatz, den ein Mitglied der Gruppe erhält. Administratorsätze werden abgelehnt." + }, + organization_id: { + label: "Organisation", + help: "Die Organisation, in der die Berechtigung erteilt wird: die Organisation, der die SCIM-Verbindung gehört." + }, + created_at: { + label: "Erstellt am" + }, + updated_at: { + label: "Aktualisiert am" + } + }, + _views: { + all: { + label: "Alle" + } + } + }, sys_notification: { label: "Benachrichtigungsereignis", pluralLabel: "Benachrichtigungsereignisse", diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index 0dfe24fbf22..3cc2d3d3b16 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -91,6 +91,7 @@ export const deGeneratedSourceHashes: Readonly> = { "objects.sys_exchange_rate.fields.id.label": "00b0385c9c152888", "objects.sys_exchange_rate.fields.source.options.app": "0c4630a782d594ab", "objects.sys_exchange_rate.fields.source.options.import": "05c80d3a61ec3290", + "objects.sys_idp_group_mapping.fields.id.label": "00b0385c9c152888", "objects.sys_import_job.fields.status.label": "64a420165247654b", "objects.sys_invitation.fields.status.label": "64a420165247654b", "objects.sys_invitation.fields.team_id.label": "42b87165ac826b2b", 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 690e8e7c36f..38a9468edc9 100644 --- a/packages/platform-objects/src/apps/translations/en.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.objects.generated.ts @@ -2649,6 +2649,54 @@ export const enObjects: NonNullable = { } } }, + sys_idp_group_mapping: { + label: "IdP Group Mapping", + pluralLabel: "IdP Group Mappings", + description: "Maps an identity provider group to the permission set its members are granted", + fields: { + id: { + label: "ID" + }, + source_kind: { + label: "Source Kind", + help: "What pushes the group: a SCIM connection.", + options: { + scim: "SCIM Connection" + } + }, + source_id: { + label: "Source ID", + help: "The SCIM connection ID the group arrives through, e.g. \"okta-prod\"." + }, + group_external_id: { + label: "Group External ID", + help: "The group's externalId as the identity provider sends it. Set this or the display name, not both." + }, + group_display_name: { + label: "Group Display Name", + help: "The group's displayName, matched exactly. Used when the mapping names no external ID." + }, + permission_set: { + label: "Permission Set", + help: "The permission set a member of the group is granted. Administrator sets are refused." + }, + organization_id: { + label: "Organization", + help: "The organization the grant is made in: the organization that owns the SCIM connection." + }, + created_at: { + label: "Created At" + }, + updated_at: { + label: "Updated At" + } + }, + _views: { + all: { + label: "All" + } + } + }, sys_notification: { label: "Notification Event", pluralLabel: "Notification Events", 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 8386a616c27..8bcb22f987b 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 @@ -2649,6 +2649,54 @@ export const esESObjects: NonNullable = { } } }, + sys_idp_group_mapping: { + label: "Asignación de grupo de IdP", + pluralLabel: "Asignaciones de grupo de IdP", + description: "Asigna un grupo del proveedor de identidad al conjunto de permisos que se concede a sus miembros", + fields: { + id: { + label: "ID" + }, + source_kind: { + label: "Tipo de origen", + help: "Qué envía el grupo: una conexión SCIM.", + options: { + scim: "Conexión SCIM" + } + }, + source_id: { + label: "ID de origen", + help: "El ID de la conexión SCIM por la que llega el grupo, p. ej. \"okta-prod\"." + }, + group_external_id: { + label: "ID externo del grupo", + help: "El externalId del grupo tal como lo envía el proveedor de identidad. Indique este o el nombre visible, no ambos." + }, + group_display_name: { + label: "Nombre visible del grupo", + help: "El displayName del grupo, con coincidencia exacta. Se usa cuando la asignación no indica un ID externo." + }, + permission_set: { + label: "Conjunto de permisos", + help: "El conjunto de permisos que se concede a un miembro del grupo. Se rechazan los conjuntos de administrador." + }, + organization_id: { + label: "Organización", + help: "La organización en la que se concede: la organización propietaria de la conexión SCIM." + }, + created_at: { + label: "Creado el" + }, + updated_at: { + label: "Actualizado el" + } + }, + _views: { + all: { + label: "Todos" + } + } + }, sys_notification: { label: "Notificación", pluralLabel: "Notificaciones", diff --git a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts index f1d665a29ff..21795afd616 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts @@ -25,6 +25,7 @@ export const esESGeneratedSourceHashes: Readonly> = { "objects.sys_email_template.fields.variables_json.label": "c2cfff50e8151e3d", "objects.sys_exchange_rate.fields.id.label": "00b0385c9c152888", "objects.sys_exchange_rate.fields.source.options.manual": "c2e7a98c066bec4a", + "objects.sys_idp_group_mapping.fields.id.label": "00b0385c9c152888", "objects.sys_job_run.fields.error.label": "786fed84bd8d5a32", "objects.sys_metadata.fields.bundle_member.help": "6912852b7523f266", "objects.sys_metadata.fields.bundle_member.label": "49b49e6b77397e92", 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 09e0807f340..950cb454acc 100644 --- a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts @@ -2649,6 +2649,54 @@ export const frObjects: NonNullable = { } } }, + sys_idp_group_mapping: { + label: "Correspondance de groupe IdP", + pluralLabel: "Correspondances de groupe IdP", + description: "Associe un groupe du fournisseur d’identité à l’ensemble d’autorisations accordé à ses membres", + fields: { + id: { + label: "ID" + }, + source_kind: { + label: "Type de source", + help: "Ce qui envoie le groupe : une connexion SCIM.", + options: { + scim: "Connexion SCIM" + } + }, + source_id: { + label: "ID de source", + help: "L’ID de la connexion SCIM par laquelle le groupe arrive, p. ex. \"okta-prod\"." + }, + group_external_id: { + label: "ID externe du groupe", + help: "L’externalId du groupe tel que l’envoie le fournisseur d’identité. Renseignez-le ou le nom d’affichage, pas les deux." + }, + group_display_name: { + label: "Nom d’affichage du groupe", + help: "Le displayName du groupe, en correspondance exacte. Utilisé quand la correspondance ne nomme aucun ID externe." + }, + permission_set: { + label: "Ensemble d’autorisations", + help: "L’ensemble d’autorisations accordé à un membre du groupe. Les ensembles administrateur sont refusés." + }, + organization_id: { + label: "Organisation", + help: "L’organisation dans laquelle l’attribution est faite : celle qui possède la connexion SCIM." + }, + created_at: { + label: "Créé le" + }, + updated_at: { + label: "Mis à jour le" + } + }, + _views: { + all: { + label: "Tous" + } + } + }, sys_notification: { label: "Événement de notification", pluralLabel: "Événements de notification", diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index 91fa1adb515..8beac585358 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -129,6 +129,7 @@ export const frGeneratedSourceHashes: Readonly> = { "objects.sys_exchange_rate.fields.id.label": "00b0385c9c152888", "objects.sys_exchange_rate.fields.source.label": "8fe786e8e29c8cec", "objects.sys_exchange_rate.fields.source.options.import": "05c80d3a61ec3290", + "objects.sys_idp_group_mapping.fields.id.label": "00b0385c9c152888", "objects.sys_invitation.label": "9bbd01ba5ed1a107", "objects.sys_invitation.pluralLabel": "4ebb9fd13de7a546", "objects.sys_job.fields.active.label": "eee107cf4e466779", 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 a218593358a..1077e497e8b 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 @@ -2649,6 +2649,54 @@ export const jaJPObjects: NonNullable = { } } }, + sys_idp_group_mapping: { + label: "IdP グループマッピング", + pluralLabel: "IdP グループマッピング", + description: "ID プロバイダーのグループを、そのメンバーに付与する権限セットに対応付けます", + fields: { + id: { + label: "ID" + }, + source_kind: { + label: "ソース種別", + help: "グループを送信するもの:SCIM 接続。", + options: { + scim: "SCIM 接続" + } + }, + source_id: { + label: "ソース ID", + help: "グループが届く SCIM 接続の ID(例:\"okta-prod\")。" + }, + group_external_id: { + label: "グループ外部 ID", + help: "ID プロバイダーが送信するグループの externalId。表示名とどちらか一方を設定し、両方は設定しません。" + }, + group_display_name: { + label: "グループ表示名", + help: "グループの displayName(完全一致)。マッピングに外部 ID がない場合に使用します。" + }, + permission_set: { + label: "権限セット", + help: "グループのメンバーに付与される権限セット。管理者セットは拒否されます。" + }, + organization_id: { + label: "組織", + help: "付与が行われる組織:SCIM 接続を所有する組織。" + }, + created_at: { + label: "作成日時" + }, + updated_at: { + label: "更新日時" + } + }, + _views: { + all: { + label: "すべて" + } + } + }, sys_notification: { label: "通知", pluralLabel: "通知", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts index 3e0dade624d..cf5b2ac4332 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts @@ -23,6 +23,7 @@ export const jaJPGeneratedSourceHashes: Readonly> = { "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", "objects.sys_email_template.fields.id.label": "00b0385c9c152888", "objects.sys_exchange_rate.fields.id.label": "00b0385c9c152888", + "objects.sys_idp_group_mapping.fields.id.label": "00b0385c9c152888", "objects.sys_metadata.fields.bundle_member.help": "6912852b7523f266", "objects.sys_metadata.fields.bundle_member.label": "49b49e6b77397e92", "objects.sys_metadata.fields.id.label": "00b0385c9c152888", 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 eb914e06211..ee2112422d2 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 @@ -2649,6 +2649,54 @@ export const ptBRObjects: NonNullable = { } } }, + sys_idp_group_mapping: { + label: "Mapeamento de grupo do IdP", + pluralLabel: "Mapeamentos de grupo do IdP", + description: "Mapeia um grupo do provedor de identidade para o conjunto de permissões concedido aos seus membros", + fields: { + id: { + label: "ID" + }, + source_kind: { + label: "Tipo de origem", + help: "O que envia o grupo: uma conexão SCIM.", + options: { + scim: "Conexão SCIM" + } + }, + source_id: { + label: "ID de origem", + help: "O ID da conexão SCIM pela qual o grupo chega, por exemplo \"okta-prod\"." + }, + group_external_id: { + label: "ID externo do grupo", + help: "O externalId do grupo como o provedor de identidade o envia. Defina este ou o nome de exibição, não ambos." + }, + group_display_name: { + label: "Nome de exibição do grupo", + help: "O displayName do grupo, com correspondência exata. Usado quando o mapeamento não indica um ID externo." + }, + permission_set: { + label: "Conjunto de permissões", + help: "O conjunto de permissões concedido a um membro do grupo. Conjuntos de administrador são recusados." + }, + organization_id: { + label: "Organização", + help: "A organização em que a concessão é feita: a organização proprietária da conexão SCIM." + }, + created_at: { + label: "Criado em" + }, + updated_at: { + label: "Atualizado em" + } + }, + _views: { + all: { + label: "Todos" + } + } + }, sys_notification: { label: "Evento de notificação", pluralLabel: "Eventos de notificação", diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts index b712863a1c2..782aafc8e50 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts @@ -54,6 +54,7 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "objects.sys_exchange_rate.fields.id.label": "00b0385c9c152888", "objects.sys_exchange_rate.fields.source.options.app": "0c4630a782d594ab", "objects.sys_exchange_rate.fields.source.options.manual": "c2e7a98c066bec4a", + "objects.sys_idp_group_mapping.fields.id.label": "00b0385c9c152888", "objects.sys_import_job.fields.status.label": "64a420165247654b", "objects.sys_invitation.fields.status.label": "64a420165247654b", "objects.sys_job.fields.schedule_type.options.cron": "fd48d0e2cd59cab2", 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 aab28e88ccf..e47f5df005e 100644 --- a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts @@ -2649,6 +2649,54 @@ export const ruObjects: NonNullable = { } } }, + sys_idp_group_mapping: { + label: "Сопоставление группы IdP", + pluralLabel: "Сопоставления групп IdP", + description: "Сопоставляет группу поставщика удостоверений с набором разрешений, который получают её участники", + fields: { + id: { + label: "ID" + }, + source_kind: { + label: "Тип источника", + help: "Что передаёт группу: подключение SCIM.", + options: { + scim: "Подключение SCIM" + } + }, + source_id: { + label: "ID источника", + help: "ID подключения SCIM, через которое приходит группа, например \"okta-prod\"." + }, + group_external_id: { + label: "Внешний ID группы", + help: "externalId группы в том виде, в каком его передаёт поставщик удостоверений. Укажите его или отображаемое имя, но не оба." + }, + group_display_name: { + label: "Отображаемое имя группы", + help: "displayName группы, точное совпадение. Используется, когда в сопоставлении не указан внешний ID." + }, + permission_set: { + label: "Набор разрешений", + help: "Набор разрешений, который получает участник группы. Наборы администратора отклоняются." + }, + organization_id: { + label: "Организация", + help: "Организация, в которой выдаётся разрешение: организация, которой принадлежит подключение SCIM." + }, + created_at: { + label: "Создано" + }, + updated_at: { + label: "Обновлено" + } + }, + _views: { + all: { + label: "Все" + } + } + }, sys_notification: { label: "Событие уведомления", pluralLabel: "События уведомлений", diff --git a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts index 04cddb53aeb..5df87ae884c 100644 --- a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts @@ -27,6 +27,7 @@ export const ruGeneratedSourceHashes: Readonly> = { "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", "objects.sys_email_template.fields.id.label": "00b0385c9c152888", "objects.sys_exchange_rate.fields.id.label": "00b0385c9c152888", + "objects.sys_idp_group_mapping.fields.id.label": "00b0385c9c152888", "objects.sys_job.fields.schedule_type.options.cron": "fd48d0e2cd59cab2", "objects.sys_job_queue.fields.status.options.dlq": "4aedfea31f7ea528", "objects.sys_metadata.fields.id.label": "00b0385c9c152888", 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 b33cc9e903f..c273eda04c0 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 @@ -2649,6 +2649,54 @@ export const zhCNObjects: NonNullable = { } } }, + sys_idp_group_mapping: { + label: "IdP 组映射", + pluralLabel: "IdP 组映射", + description: "将身份提供商的组映射到其成员被授予的权限集", + fields: { + id: { + label: "ID" + }, + source_kind: { + label: "来源类型", + help: "推送该组的来源:SCIM 连接。", + options: { + scim: "SCIM 连接" + } + }, + source_id: { + label: "来源 ID", + help: "该组经由的 SCIM 连接 ID,例如 \"okta-prod\"。" + }, + group_external_id: { + label: "组外部 ID", + help: "身份提供商发送的组 externalId。与显示名称二选一,不可同时设置。" + }, + group_display_name: { + label: "组显示名称", + help: "组的 displayName,精确匹配。映射未指定外部 ID 时使用。" + }, + permission_set: { + label: "权限集", + help: "授予该组成员的权限集。管理员权限集会被拒绝。" + }, + organization_id: { + label: "组织", + help: "授权所在的组织:拥有该 SCIM 连接的组织。" + }, + created_at: { + label: "创建时间" + }, + updated_at: { + label: "更新时间" + } + }, + _views: { + all: { + label: "全部" + } + } + }, sys_notification: { label: "通知", pluralLabel: "通知", diff --git a/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts index 65033c3554a..344ed47bf3d 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts @@ -21,6 +21,7 @@ export const zhCNGeneratedSourceHashes: Readonly> = { "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", "objects.sys_email_template.fields.id.label": "00b0385c9c152888", "objects.sys_exchange_rate.fields.id.label": "00b0385c9c152888", + "objects.sys_idp_group_mapping.fields.id.label": "00b0385c9c152888", "objects.sys_metadata.fields.bundle_member.help": "6912852b7523f266", "objects.sys_metadata.fields.bundle_member.label": "49b49e6b77397e92", "objects.sys_metadata.fields.id.label": "00b0385c9c152888", 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 340764545a8..00dbcc055c6 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 @@ -2649,6 +2649,54 @@ export const zhHantObjects: NonNullable = { } } }, + sys_idp_group_mapping: { + label: "IdP 群組對應", + pluralLabel: "IdP 群組對應", + description: "將身分識別提供者的群組對應到其成員獲授予的權限集", + fields: { + id: { + label: "ID" + }, + source_kind: { + label: "來源類型", + help: "推送該群組的來源:SCIM 連線。", + options: { + scim: "SCIM 連線" + } + }, + source_id: { + label: "來源 ID", + help: "該群組經由的 SCIM 連線 ID,例如 \"okta-prod\"。" + }, + group_external_id: { + label: "群組外部 ID", + help: "身分識別提供者傳送的群組 externalId。與顯示名稱擇一設定,不可同時設定。" + }, + group_display_name: { + label: "群組顯示名稱", + help: "群組的 displayName,精確比對。對應未指定外部 ID 時使用。" + }, + permission_set: { + label: "權限集", + help: "授予該群組成員的權限集。管理員權限集會被拒絕。" + }, + organization_id: { + label: "組織", + help: "授權所在的組織:擁有該 SCIM 連線的組織。" + }, + created_at: { + label: "建立時間" + }, + updated_at: { + label: "更新時間" + } + }, + _views: { + all: { + label: "全部" + } + } + }, sys_notification: { label: "通知", pluralLabel: "通知", diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts index bb52532bed3..de1fe9e7969 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts @@ -21,6 +21,7 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", "objects.sys_email_template.fields.id.label": "00b0385c9c152888", "objects.sys_exchange_rate.fields.id.label": "00b0385c9c152888", + "objects.sys_idp_group_mapping.fields.id.label": "00b0385c9c152888", "objects.sys_metadata.fields.bundle_member.help": "6912852b7523f266", "objects.sys_metadata.fields.bundle_member.label": "49b49e6b77397e92", "objects.sys_metadata.fields.id.label": "00b0385c9c152888", diff --git a/packages/platform-objects/src/identity/index.ts b/packages/platform-objects/src/identity/index.ts index 11f8dfd26d4..872a519756d 100644 --- a/packages/platform-objects/src/identity/index.ts +++ b/packages/platform-objects/src/identity/index.ts @@ -55,3 +55,5 @@ export { SysScimIdentityTombstone } from './sys-scim-identity-tombstone.object.j export { SysScimProjectionGrant } from './sys-scim-projection-grant.object.js'; export { SysScimSubject } from './sys-scim-subject.object.js'; export { SysScimUser } from './sys-scim-user.object.js'; +// The identity-provider group → permission-set mapping the SCIM projection reads. +export { SysIdpGroupMapping } from './sys-idp-group-mapping.object.js'; 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 new file mode 100644 index 00000000000..68d5aa11f8f --- /dev/null +++ b/packages/platform-objects/src/identity/sys-idp-group-mapping.object.ts @@ -0,0 +1,133 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +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 + * (`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. + * + * Who writes it: the platform administrator, through plugin-auth's + * `/admin/scim/set-group-mapping` and `/admin/scim/delete-group-mapping` + * mounts — the same gate as the SCIM credential door (ADR-0068 D2). The data + * API is list-only (`apiMethods` below), so no other writer exists. The door + * refuses, at save, a permission set outside the organization boundary + * (plugin-security's `organizationBoundaryFailure`: the administrator sets, + * the agent ceilings, superuser wildcards, an `adminScope`, a capability not + * scoped to the organization): an identity provider's group never confers + * 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. + * + * @namespace sys + */ +export const SysIdpGroupMapping = ObjectSchema.create({ + name: 'sys_idp_group_mapping', + label: 'IdP Group Mapping', + pluralLabel: 'IdP Group Mappings', + icon: 'users', + isSystem: true, + // plugin-auth's admin door is the only writer; no user CRUD, no better-auth model. + managedBy: 'engine-owned', + // [ADR-0066 D3] Admin-only identity configuration, the same object-level + // capability gate as the SCIM credential store beside it. + requiredPermissions: ['manage_platform_settings'], + protection: { + lock: 'full', + reason: 'ObjectStack-owned identity-provider group mapping — written only through the platform-admin SCIM door.', + docsUrl: 'https://objectstack.ai/docs/references/shared/protection', + }, + description: 'Maps an identity provider group to the permission set its members are granted', + displayNameField: 'permission_set', + nameField: 'permission_set', // [ADR-0079] canonical primary-title pointer + highlightFields: ['source_id', 'group_external_id', 'group_display_name', 'permission_set'], + + listViews: { + all: { + type: 'grid', + name: 'all', + label: 'All', + data: { provider: 'object', object: 'sys_idp_group_mapping' }, + columns: ['source_kind', 'source_id', 'group_external_id', 'group_display_name', 'permission_set', 'organization_id'], + sort: [{ field: 'source_id', order: 'asc' }], + pagination: { pageSize: 50 }, + }, + }, + + fields: { + id: Field.text({ label: 'ID', required: true, readonly: true, group: 'System' }), + + source_kind: Field.select({ + label: 'Source Kind', + required: true, + defaultValue: 'scim', + description: 'What pushes the group: a SCIM connection.', + group: 'Source', + options: [{ value: 'scim', label: 'SCIM Connection' }], + }), + + source_id: Field.text({ + label: 'Source ID', + required: true, + maxLength: 255, + description: 'The SCIM connection ID the group arrives through, e.g. "okta-prod".', + group: 'Source', + }), + + group_external_id: Field.text({ + label: 'Group External ID', + required: false, + maxLength: 255, + description: 'The group\'s externalId as the identity provider sends it. Set this or the display name, not both.', + group: 'Group', + }), + + group_display_name: Field.text({ + label: 'Group Display Name', + required: false, + maxLength: 255, + description: 'The group\'s displayName, matched exactly. Used when the mapping names no external ID.', + group: 'Group', + }), + + permission_set: Field.text({ + label: 'Permission Set', + required: true, + maxLength: 100, + description: 'The permission set a member of the group is granted. Administrator sets are refused.', + group: 'Grant', + }), + + organization_id: Field.text({ + label: 'Organization', + required: false, + maxLength: 255, + description: 'The organization the grant is made in: the organization that owns the SCIM connection.', + group: 'Grant', + }), + + created_at: Field.datetime({ label: 'Created At', defaultValue: 'NOW()', readonly: true, group: 'System' }), + updated_at: Field.datetime({ label: 'Updated At', defaultValue: 'NOW()', readonly: true, group: 'System' }), + }, + + indexes: [ + { fields: ['source_kind', 'source_id'] }, + { fields: ['organization_id'] }, + ], + + enable: { + trackHistory: true, + searchable: false, + apiEnabled: true, + // Written only through plugin-auth's platform-admin door, which judges the + // permission set against the organization boundary before any row lands. + apiMethods: ['list'], + }, +}); 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 293207b7eb9..84421974707 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts @@ -806,6 +806,7 @@ export async function buildPluginList(this: PluginListHost): Promise { const { verifyScimBearerToken, recordScimRequestConnection } = await import( './scim-connection-service.js' ); + const { createScimGroupProjection } = await import('./scim-group-projection.js'); const secret = this.resolveAuthSecret(); return scim({ connections: [], @@ -844,6 +845,15 @@ export async function buildPluginList(this: PluginListHost): Promise { identity: { reconcileUser: (state, context) => this.reconcileScimUserLifecycle(state, context), }, + // [ADR-0134 D4, filled for permission sets] A pushed group grants the + // permission sets its `sys_idp_group_mapping` rows name, inside the + // SCIM transaction; an unmapped group grants nothing, and no mapping + // can name an administrator set. See `scim-group-projection.ts`. + projection: createScimGroupProjection({ + getEngine: () => this.getDataEngine(), + boundary: async () => (await this.config.organizationBoundary?.().catch(() => undefined)) ?? undefined, + warn: (message) => this.config.logger?.warn?.(message), + }), }); }); } diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index 4ab558725ab..001613dd8bd 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -263,6 +263,7 @@ import { buildPluginList, type PluginListHost } from './auth-manager-plugin-list import { resolveTurnstileKeys } from './turnstile-sign-up.js'; import { assertTrustedAppSchemes, registeredAppSchemesOf } from './one-time-token-handoff.js'; import type { MintScimConnectionCredentialInput, MintedScimConnectionCredential } from './scim-connection-service.js'; +import type { OrganizationBoundaryJudge } from './scim-group-projection.js'; /** * Detect WebContainer (StackBlitz) environment. @@ -793,6 +794,17 @@ export interface AuthManagerOptions extends Partial { */ invitationPlacement?: () => Promise; + /** + * [ADR-0090 D12] Lazy accessor for the `security` service's + * `organizationBoundaryFailure` member (plugin-security). Wired by + * `AuthPlugin`; lazy because plugin-security starts after plugin-auth. The + * identity-provider group mapping door judges a mapped set by it at save, and + * the SCIM group projection re-judges at grant time. Absent (an embedding + * without plugin-security) ⇒ no set can be shown inside the boundary: a + * mapping save is refused and nothing is granted. + */ + organizationBoundary?: () => Promise; + onInvitationAccepted?: (data: { invitationId?: string; organizationId?: string; @@ -6733,6 +6745,27 @@ export class AuthManager { return mintScimConnectionCredential(engine as never, this.resolveAuthSecret(), input); } + /** The `security` service's organization-boundary predicate ({@link AuthManagerOptions.organizationBoundary}), or `undefined`. */ + public async organizationBoundaryJudge(): Promise { + return (await this.config.organizationBoundary?.().catch(() => undefined)) ?? undefined; + } + + /** + * Re-run the SCIM group projection for every user of one provisioning + * domain (the vendor's server-only `reconcileSCIMProjection`), so a saved or + * deleted `sys_idp_group_mapping` row reaches the members a group already + * has. The only caller is the platform-admin group-mapping door + * (`idp-group-mapping-admin.ts`). + */ + public async reconcileScimProjectionDomain(provisioningDomainId: string): Promise<{ reconciledUsers: number }> { + const auth = await this.getOrCreateAuth(); + const reconcile = (auth as { api?: { reconcileSCIMProjection?: (input: unknown) => Promise } }).api + ?.reconcileSCIMProjection; + if (typeof reconcile !== 'function') throw new Error('[auth] SCIM projection reconcile is not mounted (SCIM is off)'); + const result = (await reconcile({ body: { provisioningDomainId } })) as { reconciledUsers?: unknown }; + return { reconciledUsers: Number(result?.reconciledUsers ?? 0) }; + } + /** * Returns the data engine wired into this auth manager. Used by route * handlers (e.g. bootstrap-status) that need to query identity tables diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index df8d2bb06e3..aa7db9afe22 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -822,6 +822,21 @@ export class AuthPlugin implements Plugin { } }; + // [ADR-0090 D12] Lazy handle to the `security` service's organization + // boundary predicate, for the identity-provider group mapping (its save + // door and the SCIM group projection). Feature-detected: a security + // service without the member, or none at all, answers `undefined`, and + // both callers then fail closed. + authConfig.organizationBoundary = async () => { + try { + const svc = ctx.getService<{ organizationBoundaryFailure?: (setName: string) => Promise }>('security'); + const judge = svc?.organizationBoundaryFailure; + return typeof judge === 'function' ? { organizationBoundaryFailure: (setName: string) => judge.call(svc, setName) } : undefined; + } catch { + return undefined; + } + }; + // [#25495] A new organization takes its creator's default currency // (`localization.currency`), derived from their stored language or the // creating request's `Accept-Language`; nothing derivable ⇒ nothing @@ -4201,6 +4216,39 @@ export class AuthPlugin implements Plugin { return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500); } }); + + // [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 + // 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(), + boundary: () => this.authManager!.organizationBoundaryJudge(), + reconcile: (domain) => this.authManager!.reconcileScimProjectionDomain(domain), + attributed: (fn) => runAttributedToUser(actor, fn), + logger: { warn: (m) => ctx.logger.warn(m), error: (m) => ctx.logger.error(m) }, + }); + const groupMappingHandler = ( + label: string, + runner: 'runSetIdpGroupMapping' | 'runDeleteIdpGroupMapping', + ) => async (c: any) => { + try { + const actor = await gateAdmin(c); + if (actor instanceof Response) return actor; + const door = await import('./idp-group-mapping-admin.js'); + const { status, body } = await door[runner](groupMappingDeps(actor), actor, c.req.raw); + return c.json(body, status as any); + } catch (error) { + const err = error instanceof Error ? error : new Error(String(error)); + ctx.logger.error(`[AuthPlugin] ${label} failed`, err); + return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500); + } + }; + rawApp.post(`${basePath}/admin/scim/set-group-mapping`, groupMappingHandler('admin/scim/set-group-mapping', 'runSetIdpGroupMapping')); + rawApp.post(`${basePath}/admin/scim/delete-group-mapping`, groupMappingHandler('admin/scim/delete-group-mapping', 'runDeleteIdpGroupMapping')); } // ──────────────────────────────────────────────────────────────────── diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts index 76f6a0ef59d..8410f7c05b4 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts @@ -274,8 +274,13 @@ describe('auth route ledger hygiene', () => { // `${basePath}/admin/scim/revoke-credential` templates, ahead of the // catch-all), and the `live.has(route)` loop below holds them to the // same proof — stable `@better-auth/scim` serves no credential endpoint. + // The identity-provider group mapping door (delete and set), on the + // same terms: two `rawApp.post` templates `auth-plugin.ts` mounts beside + // the credential door; the vendor serves no mapping endpoint. + 'POST /api/v1/auth/admin/scim/delete-group-mapping', 'POST /api/v1/auth/admin/scim/mint-credential', 'POST /api/v1/auth/admin/scim/revoke-credential', + 'POST /api/v1/auth/admin/scim/set-group-mapping', // [#16678] The thirteenth, added on this pin's own terms exactly as the // set-initial-password row below was: `auth-plugin.ts` mounts it itself // (a `rawApp.post` on the `${basePath}/admin/set-user-manager` diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.ts index 0e9559097be..beb48032ed3 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.ts @@ -254,6 +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/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 new file mode 100644 index 00000000000..db80bd9cd4f --- /dev/null +++ b/packages/plugins/plugin-auth/src/idp-group-mapping-admin.ts @@ -0,0 +1,345 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The platform-admin door that saves and deletes identity-provider group + * mappings: `POST /api/v1/auth/admin/scim/set-group-mapping` and + * `POST /api/v1/auth/admin/scim/delete-group-mapping` (ADR-0134 D4's group + * seam, filled for ordinary permission sets). + * + * ## Who may use it + * + * The platform administrator only, the same population that mints the SCIM + * connection's bearer: both mounts run the shared `judgePlatformAdmin` gate + * (ADR-0068 D2) in `auth-plugin.ts` before this module reads anything. The + * `sys_idp_group_mapping` data API is list-only, so this is the only writer. + * + * ## What a save refuses, and why at save + * + * Every SCIM write runs as the system, so the delegated-administration gate + * that bounds an organization administrator's assignments never runs on a + * projected grant. The boundary therefore moves HERE: a mapping whose + * permission set fails the organization boundary (plugin-security's + * `organizationBoundaryFailure`, read through the `security` service, never a + * copy of its list) is refused with `400 VALIDATION_FAILED` on + * `permissionSet`. That covers the administrator sets, the agent ceilings, a + * superuser wildcard, an `adminScope` and a capability not scoped to the + * organization: an identity provider's group never confers administrator + * standing. With no security service to ask, nothing can be shown inside the + * boundary, and the save is refused `503`. + * + * The grant's organization is the one that owns the connection (its credential + * 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. + * + * ## After a save or delete + * + * The connection's provisioning domains are re-projected at once (the vendor's + * `reconcileSCIMProjection`), so the group's CURRENT members gain or lose the + * 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. + */ + +import type { IDataEngine } from '@objectstack/spec/contracts'; +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 { + IDP_GROUP_MAPPING_OBJECT, + SCIM_MAPPING_SOURCE_KIND, + type OrganizationBoundaryJudge, +} from './scim-group-projection.js'; + +export const IDP_GROUP_MAPPING_SET_PATH = '/admin/scim/set-group-mapping'; +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']); + +interface FieldRefusal { + field: string; + code: 'required' | 'unknown_field' | 'invalid_type' | 'max_length' | 'reference_not_found' | 'rule_violation'; + message: string; +} + +export interface IdpGroupMappingAdminResult { + status: 200 | 400 | 404 | 409 | 503; + body: + | { success: true; data: Record } + | { success: false; error: { code: string; message: string; fields?: FieldRefusal[] } }; +} + +export interface IdpGroupMappingAdminDeps { + getDataEngine: () => IDataEngine | null | undefined; + isScimEnabled: () => boolean; + /** The `security` service's boundary predicate, resolved per call. */ + boundary: () => Promise; + /** Re-project one provisioning domain (`AuthManager.reconcileScimProjectionDomain`). */ + reconcile: (provisioningDomainId: string) => Promise<{ reconciledUsers: number }>; + /** Run the writes credited to the administrator (attribution only). */ + attributed: (fn: () => Promise) => Promise; + logger?: { warn: (message: string) => void; error: (message: string) => void }; +} + +function fail(status: IdpGroupMappingAdminResult['status'], code: string, message: string, fields?: FieldRefusal[]): IdpGroupMappingAdminResult { + return { status, body: { success: false, error: { code, message, ...(fields ? { fields } : {}) } } }; +} + +function refuseFields(fields: FieldRefusal[]): IdpGroupMappingAdminResult { + return fail(400, 'VALIDATION_FAILED', fields.map((f) => f.message).join(' '), fields); +} + +const text = (v: unknown): string => (typeof v === 'string' ? v : v == null ? '' : String(v)); + +function registered(engine: IDataEngine, object: string): boolean { + const getSchema = (engine as unknown as { getSchema?: (name: string) => unknown }).getSchema; + return typeof getSchema !== 'function' || Boolean(getSchema.call(engine, object)); +} + +async function readObjectBody(request: Request): Promise<{ ok: true; body: Record } | { ok: false; result: IdpGroupMappingAdminResult }> { + const reading = await readJsonRequestBody(request); + if (!reading.ok) return { ok: false, result: fail(400, 'INVALID_REQUEST', reading.message) }; + const body = reading.body; + if (body === null || typeof body !== 'object' || Array.isArray(body)) { + return { ok: false, result: fail(400, 'INVALID_REQUEST', 'The request body must be a JSON object') }; + } + return { ok: true, body: body as Record }; +} + +/** An optional text member, trimmed: absent/blank → undefined. */ +function readText(body: Record, key: string, max: number, refusals: FieldRefusal[]): string | undefined { + const value = body[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== 'string') { + refusals.push({ field: key, code: 'invalid_type', message: `${key} must be a string.` }); + return undefined; + } + const trimmed = value.trim(); + if (trimmed.length > max) refusals.push({ field: key, code: 'max_length', message: `${key} is longer than ${max} characters.` }); + return trimmed === '' ? undefined : trimmed; +} + +/** + * The connection's credential rows: its owning organization, read from its LIVE + * credentials only (what the bearer verifier accepts: `scimCredentialIsLive`), + * and its provisioning domains, read from every row. A revoked credential stays + * stored (revoke switches `active` off), so counting it would let a credential + * revoked in one organization make the connection ambiguous forever once a new + * one is minted in another; the domains still include it, so a delete re-projects + * every domain the connection ever provisioned. + */ +async function readConnection( + engine: IDataEngine, + connectionId: string, +): Promise<{ found: false } | { found: true; organizations: string[]; domains: string[] }> { + const rows = await engine.find( + SCIM_CREDENTIAL_OBJECT, + { where: { connection_id: connectionId }, fields: ['organization_id', 'provisioning_domain_id', 'active', 'expires_at'] }, + { context: SYSTEM_CTX } as never, + ); + const list = Array.isArray(rows) ? (rows as Record[]) : []; + if (list.length === 0) return { found: false }; + return { + found: true, + organizations: [...new Set(list.filter((r) => scimCredentialIsLive(r)).map((r) => text(r.organization_id)))], + domains: [...new Set(list.map((r) => text(r.provisioning_domain_id) || connectionId))], + }; +} + +async function writeMappingAudit( + deps: IdpGroupMappingAdminDeps, + engine: IDataEngine, + entry: { action: 'create' | 'delete'; actor: PlatformAdminActor; mappingId: string; event: string; connectionId: string; permissionSet: string }, +): Promise { + if (!registered(engine, 'sys_audit_log')) return; // plugin-audit uninstalled: a declared skip + try { + await engine.insert( + 'sys_audit_log', + { + action: entry.action, + user_id: entry.actor.id, + actor: entry.actor.id, + object_name: IDP_GROUP_MAPPING_OBJECT, + record_id: entry.mappingId, + metadata: JSON.stringify({ + event: entry.event, + connectionId: entry.connectionId, + permissionSet: entry.permissionSet, + ...(entry.actor.impersonatedBy ? { impersonated_by: entry.actor.impersonatedBy } : {}), + }), + }, + { context: SYSTEM_CTX }, + ); + } 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. ` + + 'Remedy: restore write access to sys_audit_log, then treat this line as the audit record. ' + + `Cause: ${(error as Error)?.message ?? String(error)}`, + ); + } +} + +/** Re-project each domain; a failure is reported, never thrown (the row change stands). */ +async function reproject(deps: IdpGroupMappingAdminDeps, connectionId: string, domains: string[]): Promise> { + let reconciledUsers = 0; + try { + for (const domain of domains) reconciledUsers += (await deps.reconcile(domain)).reconciledUsers; + return { reprojected: true, reconciledUsers }; + } catch (error) { + deps.logger?.error( + `[AuthPlugin] IdP group mapping change for SCIM connection '${connectionId}' was SAVED, but applying it to the ` + + 'group\'s current members FAILED, so their grants still reflect the old mapping until each member\'s next SCIM ' + + `change. Remedy: save the mapping again once the cause is fixed. Cause: ${(error as Error)?.message ?? String(error)}`, + ); + return { reprojected: false, reconciledUsers }; + } +} + +/** `POST /admin/scim/set-group-mapping` — save one group → permission-set mapping for a SCIM connection. */ +export async function runSetIdpGroupMapping( + deps: IdpGroupMappingAdminDeps, + actor: PlatformAdminActor, + request: Request, +): Promise { + const reading = await readObjectBody(request); + if (!reading.ok) return reading.result; + const body = reading.body; + + 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).` }); + } + } + const connectionId = readText(body, 'connectionId', 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 (!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 (!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.'); + } + 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.` }]); + } + const organizationId = connection.organizations[0]; + + const judge = await deps.boundary(); + if (!judge) { + return fail(503, 'SERVICE_UNAVAILABLE', 'The security service is not available, so no permission set can be shown to be inside the organization boundary; nothing was saved.'); + } + const failure = await judge.organizationBoundaryFailure(permissionSet); + if (failure !== null) { + return refuseFields([{ + field: 'permissionSet', + code: 'rule_violation', + message: `An identity provider group grants only ordinary permission sets inside the organization boundary, never administrator standing; refused: ${failure}.`, + }]); + } + + const row = { + source_kind: SCIM_MAPPING_SOURCE_KIND, + source_id: connectionId, + ...(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 } }, + { 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 + // 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) { + 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.`, + ); + } + const existing = sameKey.find((r) => text(r.organization_id) === organizationId); + let mappingId: string; + if (existing) { + mappingId = text(existing.id); + } else { + 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 }); + } + const applied = await deps.attributed(() => reproject(deps, connectionId, connection.domains)); + return { + status: 200, + body: { + success: true, + data: { mappingId, created: !existing, connectionId, permissionSet, organizationId: organizationId || null, ...applied }, + }, + }; +} + +/** `POST /admin/scim/delete-group-mapping` — delete one mapping; the grants it projected go with it. */ +export async function runDeleteIdpGroupMapping( + deps: IdpGroupMappingAdminDeps, + actor: PlatformAdminActor, + request: Request, +): Promise { + const reading = await readObjectBody(request); + if (!reading.ok) return reading.result; + const mappingId = reading.body.mappingId; + if (typeof mappingId !== 'string' || mappingId.trim() === '') { + return refuseFields([{ field: 'mappingId', code: 'required', message: 'mappingId is required: the id the save answered.' }]); + } + 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 row = (await engine.findOne( + IDP_GROUP_MAPPING_OBJECT, + { where: { id: mappingId } }, + { 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 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 } } }; +} diff --git a/packages/plugins/plugin-auth/src/last-admin-guard.test.ts b/packages/plugins/plugin-auth/src/last-admin-guard.test.ts index b4ba3920fb1..8097d0f2d88 100644 --- a/packages/plugins/plugin-auth/src/last-admin-guard.test.ts +++ b/packages/plugins/plugin-auth/src/last-admin-guard.test.ts @@ -1161,8 +1161,11 @@ describe('[#5978] path 1 — downgrading the last administrator\'s sys_member ro await expect(setRole('mem_usr_owner', 'member')).rejects.toThrow(/sys_member/); await expect(setRole('mem_usr_owner', 'member')).rejects.toThrow(/ADR-0135 D5\.2/); await expect(setRole('mem_usr_owner', 'member')).rejects.toThrow(new RegExp(ADMIN_FULL_ACCESS)); - // An IdP drove most of these, so the message points at the group mapping. - await expect(setRole('mem_usr_owner', 'member')).rejects.toThrow(/SCIM group mapping/); + // The closing advice names the writers that move standing, and says an + // identity provider group mapping is not one of them (it grants ordinary + // permission sets only). + await expect(setRole('mem_usr_owner', 'member')).rejects.toThrow(/grant another account administrator standing first/); + await expect(setRole('mem_usr_owner', 'member')).rejects.toThrow(/never moves administrator standing/); }); it('a downgrade to ANOTHER administrative grade is allowed — the grade is not lost', async () => { @@ -1819,7 +1822,7 @@ describe('[#6084, ADR-0131 D3] path 4 — switching admin_full_access off in the // …and the closing advice names the doors that actually write this table, // NOT the SCIM sentence: nothing in an IdP writes the ledger. expect(message).toMatch(/disable action/); - expect(message).not.toMatch(/SCIM group mapping/); + expect(message).not.toMatch(/identity provider group mapping/); }); it('the payload is simulated, not pattern-matched: switching the row ON proceeds, OFF is refused', async () => { diff --git a/packages/plugins/plugin-auth/src/last-admin-guard.ts b/packages/plugins/plugin-auth/src/last-admin-guard.ts index 381ccd4110a..d81a913366d 100644 --- a/packages/plugins/plugin-auth/src/last-admin-guard.ts +++ b/packages/plugins/plugin-auth/src/last-admin-guard.ts @@ -32,8 +32,8 @@ * administrator" is not a fact stored on `sys_user` at all. It lives in the * two tables `resolveAdminUserIds` enumerates, so it is taken away by * writing THEM: downgrading (or deleting) the `sys_member` row that carries - * the `owner`/`admin` grade — better-auth's `updateMemberRole`, a SCIM - * group-mapping change — or deleting the `admin_full_access` + * the `owner`/`admin` grade — better-auth's `updateMemberRole`, an + * import, a script — or deleting the `admin_full_access` * `sys_user_permission_set` grant, or editing it until it no longer counts * (re-pointed at another set, scoped to an organization, moved outside its * ADR-0091 validity window). The end state is identical to (2): everyone is @@ -118,7 +118,8 @@ * * The standing halves judge EVERY membership downgrade, not only a caller * downgrading themselves. Narrowing to self-downgrade would miss the case that - * actually happens: an IdP group mapping that rewrites other people's roles. + * actually happens: an administrator, an import or a script rewriting other + * people's roles. * * ## What counts as an administrator * @@ -557,11 +558,13 @@ const OP_WORDS: Record = { * shape actually comes from, so the operator goes and fixes the source instead * of this guard. * - * The two identity tables are written by IdP integrations, so their refusals - * point at the SCIM group mapping. The activation ledger is not — nothing in - * SCIM or better-auth writes it; a disable action, an upgrade step or a script - * does. Sending THAT operator to look at an IdP group would send them into a - * system they may not even run. + * The two identity tables are written by administrators, better-auth's own + * membership doors, imports and scripts — never by an identity provider's group + * mapping, which grants only ordinary permission sets inside the organization + * boundary (`sys_idp_group_mapping`, refused at save otherwise), so it can + * neither confer nor take away administrator standing. Their refusals send the + * operator to grant standing elsewhere first. The activation ledger is written + * by a disable action, an upgrade step or a script, and says so. */ function standingOrigin(table: string, noun: string, op?: GuardedOp): string { if (op === 'organization-insert') { @@ -597,8 +600,9 @@ function standingOrigin(table: string, noun: string, op?: GuardedOp): string { ); } return ( - `If the ${noun} came from an identity provider, the SCIM group mapping is too broad — fix ` + - 'the IdP group, not this guard.' + `If the ${noun} came from an import, a script or an administrator, grant another account ` + + 'administrator standing first, then make the change. An identity provider group mapping never ' + + 'moves administrator standing: it grants ordinary permission sets only.' ); } @@ -1943,9 +1947,9 @@ export function registerLastAdminGuard( if (ctx.object !== SystemObjectName.MEMBER) return; const data = (ctx.input?.data ?? {}) as Record; // The whole downgrade family lands here: better-auth's `updateMemberRole`, - // a SCIM group-mapping change, an import, a script. It is NOT narrowed to - // "the caller downgrading themselves" — an IdP writes these on everyone's - // behalf, which is exactly the case ADR-0135 D5.2 exists for. + // an import, a script. It is NOT narrowed to "the caller downgrading + // themselves" — those write on everyone's behalf, which is exactly the + // case ADR-0135 D5.2 exists for. // // A payload touching neither `role` nor `user_id` provably cannot move the // enumeration (see MEMBER_STANDING_KEYS), so it costs no reads at all. diff --git a/packages/plugins/plugin-auth/src/manifest.ts b/packages/plugins/plugin-auth/src/manifest.ts index 726ef63a724..2f907775e53 100644 --- a/packages/plugins/plugin-auth/src/manifest.ts +++ b/packages/plugins/plugin-auth/src/manifest.ts @@ -12,6 +12,7 @@ import { SysAccount, SysApiKey, SysDeviceCode, + SysIdpGroupMapping, SysInvitation, SysMember, SysJwks, @@ -89,6 +90,9 @@ export const authIdentityObjects: any[] = [ SysScimProjectionGrant, SysScimSubject, SysScimUser, + // The group → permission-set mapping the SCIM projection reads + // (`scim-group-projection.ts`); written only by the platform-admin door. + SysIdpGroupMapping, ]; /** diff --git a/packages/plugins/plugin-auth/src/scim-connection-service.test.ts b/packages/plugins/plugin-auth/src/scim-connection-service.test.ts new file mode 100644 index 00000000000..9ce8062695c --- /dev/null +++ b/packages/plugins/plugin-auth/src/scim-connection-service.test.ts @@ -0,0 +1,27 @@ +// Unit cases for the SCIM credential liveness check that both the bearer +// verifier and the group-mapping door read (#30959 review nit N3): no stored +// row reaches an expired or falsy-active credential through the suites today. +import { describe, it, expect } from 'vitest'; +import { scimCredentialIsLive } from './scim-connection-service.js'; + +const NOW = Date.parse('2026-11-08T12:00:00.000Z'); + +describe('scimCredentialIsLive', () => { + it.each([false, 0, null, undefined])('refuses a credential whose active is %s', (active) => { + expect(scimCredentialIsLive({ active, expires_at: null }, NOW)).toBe(false); + }); + it('accepts an active credential with no expiry', () => { + expect(scimCredentialIsLive({ active: true, expires_at: null }, NOW)).toBe(true); + expect(scimCredentialIsLive({ active: 1 }, NOW)).toBe(true); + }); + it('refuses a credential that expired in the past', () => { + expect(scimCredentialIsLive({ active: true, expires_at: '2026-11-08T11:59:59.999Z' }, NOW)).toBe(false); + }); + it('refuses a credential that expires exactly now', () => { + expect(scimCredentialIsLive({ active: true, expires_at: new Date(NOW).toISOString() }, NOW)).toBe(false); + }); + it('accepts a credential that expires in the future, and refuses an unreadable expiry', () => { + expect(scimCredentialIsLive({ active: true, expires_at: '2026-11-08T12:00:00.001Z' }, NOW)).toBe(true); + expect(scimCredentialIsLive({ active: true, expires_at: 'not a date' }, NOW)).toBe(false); + }); +}); diff --git a/packages/plugins/plugin-auth/src/scim-connection-service.ts b/packages/plugins/plugin-auth/src/scim-connection-service.ts index 9557afe171b..0ab61434900 100644 --- a/packages/plugins/plugin-auth/src/scim-connection-service.ts +++ b/packages/plugins/plugin-auth/src/scim-connection-service.ts @@ -273,6 +273,24 @@ export interface ScimBearerVerification { expiresAt?: Date; } +/** + * Is credential `row` live — affirmatively `active` and not expired? The one + * reading of a credential row's liveness: the bearer verifier below refuses a + * row this answers `false` for, and the IdP group mapping door reads a + * connection's owning organization from live rows only, so a revoked credential + * never decides anything. + */ +export function scimCredentialIsLive(row: Record, now: number = Date.now()): boolean { + // sqlite hands booleans back as 0/1 — refuse anything not affirmatively active. + const active = row.active; + if (active === false || active === 0 || active == null) return false; + const rawExpiry = row.expires_at; + if (rawExpiry == null) return true; + const parsed = new Date(rawExpiry as string); + if (Number.isNaN(parsed.getTime())) return false; // unreadable expiry fails closed + return parsed.getTime() > now; +} + /** * Application-owned bearer verification for the stable scim plugin: digest the * presented token, probe the credential store by digest (unique index), refuse @@ -295,18 +313,9 @@ export async function verifyScimBearerToken( // A storage fault reads as "cannot verify", never as "verified". return null; } - if (!row) return null; - // sqlite hands booleans back as 0/1 — refuse anything not affirmatively active. - const active = (row as { active?: unknown }).active; - if (active === false || active === 0 || active == null) return null; + if (!row || !scimCredentialIsLive(row)) return null; const rawExpiry = (row as { expires_at?: unknown }).expires_at; - let expiresAt: Date | undefined; - if (rawExpiry != null) { - const parsed = new Date(rawExpiry as string); - if (Number.isNaN(parsed.getTime())) return null; // unreadable expiry fails closed - if (parsed.getTime() <= Date.now()) return null; - expiresAt = parsed; - } + const expiresAt = rawExpiry != null ? new Date(rawExpiry as string) : undefined; const connectionId = String((row as { connection_id?: unknown }).connection_id ?? ''); if (!connectionId) return null; const domain = (row as { provisioning_domain_id?: unknown }).provisioning_domain_id; diff --git a/packages/plugins/plugin-auth/src/scim-group-projection.test.ts b/packages/plugins/plugin-auth/src/scim-group-projection.test.ts new file mode 100644 index 00000000000..2a9608054c8 --- /dev/null +++ b/packages/plugins/plugin-auth/src/scim-group-projection.test.ts @@ -0,0 +1,486 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * An identity provider's group push grants the permission set its + * `sys_idp_group_mapping` row names, and only an ordinary one (ADR-0134 D4's + * group seam, filled for permission sets). + * + * Every case drives the real producer: `AuthManager.handleRequest()` with a + * real SCIM bearer over `@better-auth/scim`, whose `projection` is wired by + * `buildPluginList` (nothing here names it), on a real ObjectQL engine over + * better-sqlite3. The mapping is saved through the platform-admin door's own + * function (`runSetIdpGroupMapping`), judged by the REAL `security` service of + * `@objectstack/plugin-security` — its `organizationBoundaryFailure` member, + * the delegated-administration gate's own predicate — over a test catalog. + * + * Faces: (1) a mapped group push grants the set, written by the SCIM + * connection's actor; (2) removing the member revokes it; (3) a mapping naming + * an administrator set and (4) one naming a set outside the organization + * boundary are refused at save, code + status, and store nothing; (5) user + * provisioning with no mapping still works. Controls: an unmapped group grants + * nothing; a grant made by hand is never touched by reconcile. + */ + +import { describe, it, expect, afterEach, afterAll, vi } from 'vitest'; +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 { AuthManager } from './auth-manager.js'; +import { authIdentityObjects } from './manifest.js'; +import { createTenancyService } from './tenancy-service.js'; +import { mintScimConnectionCredential, revokeScimConnectionCredential } from './scim-connection-service.js'; +import { runDeleteIdpGroupMapping, runSetIdpGroupMapping, type IdpGroupMappingAdminDeps } from './idp-group-mapping-admin.js'; +import { createScimGroupProjection, scimGroupProjectionReason, 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 'better-auth'; +import 'better-auth/api'; +import 'better-auth/plugins'; +import 'better-auth/plugins/admin'; +import 'better-auth/plugins/organization'; +import '@better-auth/scim'; + +const BASE = 'http://localhost:3000'; +const AUTH = `${BASE}/api/v1/auth`; +const SECRET = 'test-secret-at-least-32-chars-long-30959'; +const CONNECTION = 'okta-30959'; +const ORG = 'org_scim_30959'; +const SCIM_ACTOR = `svc:scim:${CONNECTION}`; +const USER_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:User'; +const GROUP_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:Group'; +const PATCH_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:PatchOp'; +const SYSTEM = { context: { isSystem: true } } as const; + +/** An ordinary set, inside the organization boundary. */ +const SALES = 'sales_reader'; +/** Outside the boundary by condition (c): a capability no catalog entry declares `scope: 'org'`. */ +const PLATFORM_OPS = 'platform_ops'; + +/** The grant table, down to the columns the projection reads and writes. */ +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 }, + }, +}; + +const enginePool = sqliteEnginePool(bootEngine, { keepBootOrganizations: true }); +afterEach(enginePool.release); +afterEach(() => vi.restoreAllMocks()); +afterAll(enginePool.destroy); + +async function bootEngine(): Promise { + const engine = new ObjectQL(); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + engine.registerDriver(driver, true); + await engine.init(); + for (const object of [...authIdentityObjects, sysUserPermissionSet]) { + engine.registry.registerObject(object as never, '@objectstack/plugin-auth'); + } + await engine.syncSchemas(); + return { engine, driver }; +} + +/** The catalog the security service reads, rebuilt per boot; a case may redefine a set in place after its mapping is saved. */ +let catalogPermissions: Array> = []; + +/** The `security` service plugin-security registers, over a catalog bound to a stub engine (no middleware on the real one). */ +async function securityService(): Promise { + catalogPermissions = [{ name: SALES }, { name: ADMIN_FULL_ACCESS }, { name: PLATFORM_OPS, systemPermissions: ['manage_platform_settings'] }]; + const ql = bindTestSecurityCatalog( + { registerMiddleware: vi.fn(), getSchema: () => undefined }, + () => ({ permissions: catalogPermissions }), + ); + 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 Harness { + engine: ObjectQL; + manager: AuthManager; + token: string; + door: IdpGroupMappingAdminDeps; + send: (method: string, path: string, body?: unknown) => Promise; + judge: OrganizationBoundaryJudge; + credentialId: string; +} + +async function boot(): Promise { + const engine = await enginePool.take(); + const judge = await securityService(); + const manager = new AuthManager({ + secret: SECRET, + baseUrl: BASE, + dataEngine: engine as never, + getTenancy: () => createTenancyService({ requested: 'isolated', probeIsolation: () => true }), + plugins: { scim: true, organization: true }, + organizationBoundary: async () => judge, + } as never); + const { token, credentialId } = await mintScimConnectionCredential(engine as never, SECRET, { connectionId: CONNECTION, organizationId: ORG }); + const door: IdpGroupMappingAdminDeps = { + getDataEngine: () => manager.getDataEngine() as never, + isScimEnabled: () => manager.isScimWired(), + boundary: () => manager.organizationBoundaryJudge(), + reconcile: (domain) => manager.reconcileScimProjectionDomain(domain), + attributed: (fn) => fn(), + }; + const send = (method: string, path: string, body?: unknown) => + manager.handleRequest( + new Request(`${AUTH}/scim/v2${path}`, { + method, + headers: { + origin: BASE, + authorization: `Bearer ${token}`, + ...(body !== undefined ? { 'content-type': 'application/scim+json' } : {}), + }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }), + ); + return { engine, manager, token, credentialId, door, send, judge }; +} + +const ADMIN = { id: 'usr_platform_admin' }; + +function saveMapping(h: Harness, body: Record) { + return runSetIdpGroupMapping( + h.door, + ADMIN, + new Request(`${AUTH}/admin/scim/set-group-mapping`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }), + ); +} + +async function provision(h: Harness, localPart: string): Promise<{ scimId: string; userId: string }> { + const email = `${localPart}@example.com`; + const res = await h.send('POST', '/Users', { + schemas: [USER_SCHEMA], + userName: email, + name: { givenName: localPart, familyName: 'Example' }, + emails: [{ value: email, primary: true, type: 'work' }], + active: true, + }); + expect(res.status, `SCIM POST /Users failed: ${await res.clone().text()}`).toBe(201); + const scimId = ((await res.json()) as { id: string }).id; + const row = (await h.engine.findOne('sys_user', { where: { email }, fields: ['id'] }, SYSTEM)) as { id: string } | null; + expect(row, 'the SCIM create must have landed a sys_user row').toBeTruthy(); + return { scimId, userId: String(row!.id) }; +} + +async function pushGroup(h: Harness, group: { displayName: string; externalId?: string }, memberScimIds: string[]): Promise { + const res = await h.send('POST', '/Groups', { + schemas: [GROUP_SCHEMA], + displayName: group.displayName, + ...(group.externalId ? { externalId: group.externalId } : {}), + members: memberScimIds.map((value) => ({ value })), + }); + expect(res.status, `SCIM POST /Groups failed: ${await res.clone().text()}`).toBe(201); + return ((await res.json()) as { id: string }).id; +} + +async function removeMember(h: Harness, groupId: string, scimId: string): Promise { + const res = await h.send('PATCH', `/Groups/${groupId}`, { + schemas: [PATCH_SCHEMA], + Operations: [{ op: 'remove', path: `members[value eq "${scimId}"]` }], + }); + expect(res.status, `SCIM PATCH /Groups remove failed: ${await res.clone().text()}`).toBeLessThan(300); +} + +async function grantsOf(h: Harness, userId: string): Promise> { + const rows = await h.engine.find('sys_user_permission_set', { where: { user_id: userId } }, SYSTEM); + return (rows as Array>) + .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, with the actor its context carried (what the audit mirror records as `sys_audit_log.actor`). */ +function observeGrantWrites(h: Harness): Array<{ op: string; actor: unknown }> { + const writes: Array<{ op: string; actor: unknown }> = []; + const engine = h.engine as unknown as Record unknown>; + for (const op of ['insert', 'delete'] as const) { + const original = engine[op].bind(h.engine); + vi.spyOn(engine, op).mockImplementation(async (object: unknown, ...rest: unknown[]) => { + if (object === 'sys_user_permission_set') { + const options = (op === 'delete' ? rest[0] : rest[1]) as { context?: { actor?: unknown } } | undefined; + writes.push({ op, actor: options?.context?.actor }); + } + return original(object, ...rest); + }); + } + return writes; +} + +/** The id a successful save answered (the case fails here if the save was refused). */ +function mappingIdOf(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); +} + +/** The state the vendor hands `reconcileUser` for one user whose one group maps to `mappingId`. */ +function projectedState(userId: string, mappingId: string) { + return { + provisioningDomainId: CONNECTION, + userId, + active: true, + sources: [], + grants: [{ source: { type: 'group' as const, id: 'grp', externalId: 'okta-grp-sales', displayName: 'Sales' }, role: mappingId }], + } as never; +} + +/** `engine`, except that every row of `object` it reads back carries no `organization_id`. */ +function withoutOrganization(engine: ObjectQL, object: string): never { + const strip = (row: unknown) => (row && typeof row === 'object' ? { ...(row as Record), organization_id: null } : row); + return new Proxy(engine, { + get(target, prop, receiver) { + const value = Reflect.get(target, prop, receiver); + if (prop === 'find' || prop === 'findOne') { + return async (name: string, ...rest: unknown[]) => { + const result = await (value as (...a: unknown[]) => Promise).call(target, name, ...rest); + if (name !== object) return result; + return Array.isArray(result) ? result.map(strip) : strip(result); + }; + } + return typeof value === 'function' ? value.bind(target) : value; + }, + }) as never; +} + +const projected = (set: string) => ({ permission_set: set, organization_id: ORG, reason: scimGroupProjectionReason(CONNECTION) }); + +describe('SCIM group push → mapped permission set', () => { + it('(1) a mapped group push grants the set in the connection\'s organization, written by the SCIM connection', async () => { + const h = await boot(); + const saved = await saveMapping(h, { connectionId: CONNECTION, groupExternalId: 'okta-grp-sales', permissionSet: SALES }); + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + const alice = await provision(h, 'alice'); + const writes = observeGrantWrites(h); + + await pushGroup(h, { displayName: 'Sales', externalId: 'okta-grp-sales' }, [alice.scimId]); + + expect(await grantsOf(h, alice.userId)).toEqual([projected(SALES)]); + expect(writes).toEqual([{ op: 'insert', actor: SCIM_ACTOR }]); + }); + + it('(2) removing the member from the group revokes the projected grant', async () => { + const h = await boot(); + await saveMapping(h, { connectionId: CONNECTION, groupDisplayName: 'Sales', permissionSet: SALES }); + const alice = await provision(h, 'alice'); + const groupId = await pushGroup(h, { displayName: 'Sales' }, [alice.scimId]); + expect(await grantsOf(h, alice.userId)).toEqual([projected(SALES)]); + const writes = observeGrantWrites(h); + + await removeMember(h, groupId, alice.scimId); + + expect(await grantsOf(h, alice.userId)).toEqual([]); + expect(writes).toEqual([{ op: 'delete', actor: SCIM_ACTOR }]); + }); + + it('(3) a mapping naming an administrator set is refused at save and stores nothing', async () => { + const h = await boot(); + const refused = await saveMapping(h, { connectionId: CONNECTION, groupExternalId: 'okta-grp-admins', permissionSet: ADMIN_FULL_ACCESS }); + expect(refused.status).toBe(400); + const error = (refused.body as { error: { code: string; fields: Array<{ field: string; code: string }> } }).error; + expect(error.code).toBe('VALIDATION_FAILED'); + expect(error.fields.map((f) => [f.field, f.code])).toEqual([['permissionSet', 'rule_violation']]); + expect(await h.engine.find('sys_idp_group_mapping', {}, SYSTEM)).toEqual([]); + }); + + it('(4) a mapping naming a set outside the organization boundary is refused at save and stores nothing', async () => { + const h = await boot(); + const refused = await saveMapping(h, { connectionId: CONNECTION, groupExternalId: 'okta-grp-ops', permissionSet: PLATFORM_OPS }); + expect(refused.status).toBe(400); + const error = (refused.body as { error: { code: string; fields: Array<{ field: string; code: string }> } }).error; + expect(error.code).toBe('VALIDATION_FAILED'); + expect(error.fields.map((f) => [f.field, f.code])).toEqual([['permissionSet', 'rule_violation']]); + expect(await h.engine.find('sys_idp_group_mapping', {}, SYSTEM)).toEqual([]); + }); + + it('(5) with no mapping, provisioning and updating a user still work and grant nothing', async () => { + const h = await boot(); + const bob = await provision(h, 'bob'); + const res = await h.send('PATCH', `/Users/${bob.scimId}`, { + schemas: [PATCH_SCHEMA], + Operations: [{ op: 'replace', path: 'displayName', value: 'Bob Renamed' }], + }); + expect(res.status, await res.clone().text()).toBe(200); + expect(await grantsOf(h, bob.userId)).toEqual([]); + }); + + it('CONTROL: an unmapped group push grants nothing', async () => { + const h = await boot(); + await saveMapping(h, { connectionId: CONNECTION, groupExternalId: 'okta-grp-sales', permissionSet: SALES }); + const carol = await provision(h, 'carol'); + await pushGroup(h, { displayName: 'Sales', externalId: 'okta-grp-engineering' }, [carol.scimId]); + expect(await grantsOf(h, carol.userId)).toEqual([]); + }); + + it('CONTROL: grants made by hand are never touched by reconcile, the same set included', async () => { + const h = await boot(); + await saveMapping(h, { connectionId: CONNECTION, groupExternalId: 'okta-grp-sales', permissionSet: SALES }); + const dave = await provision(h, 'dave'); + await h.engine.insert('sys_user_permission_set', { user_id: dave.userId, permission_set: ADMIN_FULL_ACCESS, organization_id: ORG }, SYSTEM); + await h.engine.insert('sys_user_permission_set', { user_id: dave.userId, permission_set: SALES, organization_id: ORG }, SYSTEM); + const handMade = await grantsOf(h, dave.userId); + + const groupId = await pushGroup(h, { displayName: 'Sales', externalId: 'okta-grp-sales' }, [dave.scimId]); + expect(await grantsOf(h, dave.userId), 'the set is already held: nothing is written beside it').toEqual(handMade); + await removeMember(h, groupId, dave.scimId); + + expect(await grantsOf(h, dave.userId)).toEqual(handMade); + }); + + it('saving and deleting a mapping applies to the group\'s current members at once', async () => { + const h = await boot(); + const erin = await provision(h, 'erin'); + await pushGroup(h, { displayName: 'Support', externalId: 'okta-grp-support' }, [erin.scimId]); + expect(await grantsOf(h, erin.userId)).toEqual([]); + + const saved = await saveMapping(h, { connectionId: CONNECTION, groupExternalId: 'okta-grp-support', permissionSet: SALES }); + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + expect(await grantsOf(h, erin.userId)).toEqual([projected(SALES)]); + + const mappingId = mappingIdOf(saved); + const deleted = await runDeleteIdpGroupMapping( + h.door, + ADMIN, + new Request(`${AUTH}/admin/scim/delete-group-mapping`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ mappingId }) }), + ); + expect(deleted.status, JSON.stringify(deleted.body)).toBe(200); + expect(await grantsOf(h, erin.userId)).toEqual([]); + }); + it('(S1) a connection whose credentials carry no organization is refused at save, like one owned by two', async () => { + const h = await boot(); + // This engine refuses an organization-less credential row outright, so the case is staged at the door's read: + // a composition with no organization machinery (no sys_organization) stores the credential with none. + const door: IdpGroupMappingAdminDeps = { ...h.door, getDataEngine: () => withoutOrganization(h.engine, 'sys_scim_connection_credential') }; + const refused = await runSetIdpGroupMapping( + door, + ADMIN, + new Request(`${AUTH}/admin/scim/set-group-mapping`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ connectionId: CONNECTION, groupExternalId: 'okta-grp-sales', permissionSet: SALES }), + }), + ); + expect(refused.status).toBe(400); + const error = (refused.body as { error: { code: string; fields: Array<{ field: string; code: string }> } }).error; + expect(error.code).toBe('VALIDATION_FAILED'); + expect(error.fields.map((f) => [f.field, f.code])).toEqual([['connectionId', 'rule_violation']]); + expect(await h.engine.find('sys_idp_group_mapping', {}, SYSTEM)).toEqual([]); + }); + + it('(S1) the projection never writes a grant without an organization, whatever a mapping row holds', async () => { + const h = await boot(); + const saved = await saveMapping(h, { connectionId: CONNECTION, groupExternalId: 'okta-grp-sales', permissionSet: SALES }); + const mappingId = mappingIdOf(saved); + const frank = await provision(h, 'frank'); + const warn = vi.fn(); + const projection = createScimGroupProjection({ + getEngine: () => withoutOrganization(h.engine, 'sys_idp_group_mapping') as never, + boundary: async () => h.judge, + warn, + }); + + await projection.reconcileUser(projectedState(frank.userId, mappingId), {} as never); + + expect(await grantsOf(h, frank.userId)).toEqual([]); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0][0])).toMatch(/no organization/); + }); + + it('(S2) reconcile judges the boundary itself: a set redefined as administrator after the save is not granted', async () => { + const h = await boot(); + const saved = await saveMapping(h, { connectionId: CONNECTION, groupExternalId: 'okta-grp-sales', permissionSet: SALES }); + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + const mappingId = mappingIdOf(saved); + const gina = await provision(h, 'gina'); + catalogPermissions = catalogPermissions.map((p) => (p.name === SALES ? { ...p, adminScope: { businessUnits: ['*'] } } : p)); + expect(await h.judge.organizationBoundaryFailure(SALES), 'the redefined set is outside the boundary').not.toBeNull(); + const warn = vi.fn(); + + // reconcileUser alone, as a vendor path that does not consult roles.exists first would call it. + const projection = createScimGroupProjection({ getEngine: () => h.engine as never, boundary: async () => h.judge, warn }); + await projection.reconcileUser(projectedState(gina.userId, mappingId), {} as never); + + expect(await grantsOf(h, gina.userId)).toEqual([]); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0][0])).toMatch(/grants nothing/); + + // Through the vendor as well: the push lands, and grants nothing. + await pushGroup(h, { displayName: 'Sales', externalId: 'okta-grp-sales' }, [gina.scimId]); + expect(await grantsOf(h, gina.userId)).toEqual([]); + }); + it('(S4) a revoked credential does not count: revoke in one organization, mint in another, and the save lands in the new one', async () => { + const h = await boot(); + const ORG_B = 'org_scim_30959_b'; + expect((await revokeScimConnectionCredential(h.engine as never, h.credentialId)).outcome).toBe('revoked'); + await mintScimConnectionCredential(h.engine as never, SECRET, { connectionId: CONNECTION, organizationId: ORG_B }); + + const saved = await saveMapping(h, { connectionId: CONNECTION, groupExternalId: 'okta-grp-sales', permissionSet: SALES }); + + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + expect((saved.body as unknown as { data: { organizationId: string } }).data.organizationId).toBe(ORG_B); + const rows = (await h.engine.find('sys_idp_group_mapping', {}, SYSTEM)) as Array>; + expect(rows.map((r) => r.organization_id)).toEqual([ORG_B]); + }); + + it('(S5) a re-save after the connection moved organization is refused, never answered with an organization the row does not carry', async () => { + const h = await boot(); + const first = await saveMapping(h, { connectionId: CONNECTION, groupExternalId: 'okta-grp-sales', permissionSet: SALES }); + expect(first.status, JSON.stringify(first.body)).toBe(200); + const mappingId = mappingIdOf(first); + + // CONTROL: a re-save in the same organization is idempotent. + const again = await saveMapping(h, { connectionId: CONNECTION, groupExternalId: 'okta-grp-sales', permissionSet: SALES }); + expect(again.status).toBe(200); + expect((again.body as unknown as { data: { mappingId: string; created: boolean; organizationId: string } }).data) + .toMatchObject({ mappingId, created: false, organizationId: ORG }); + + const ORG_B = 'org_scim_30959_b'; + await revokeScimConnectionCredential(h.engine as never, h.credentialId); + await mintScimConnectionCredential(h.engine as never, SECRET, { connectionId: CONNECTION, organizationId: ORG_B }); + + const refused = await saveMapping(h, { connectionId: CONNECTION, groupExternalId: 'okta-grp-sales', permissionSet: SALES }); + expect(refused.status, JSON.stringify(refused.body)).toBe(409); + const error = (refused.body as { error: { code: string; message: string } }).error; + expect(error.code).toBe('RESOURCE_CONFLICT'); + expect(error.message).toContain(mappingId); + expect(error.message).toContain(ORG); + const rows = (await h.engine.find('sys_idp_group_mapping', {}, SYSTEM)) as Array>; + expect(rows.map((r) => [r.id, r.organization_id])).toEqual([[mappingId, ORG]]); + }); + + it('(S4) a connection whose every credential is revoked is refused at save', async () => { + const h = await boot(); + await revokeScimConnectionCredential(h.engine as never, h.credentialId); + const refused = await saveMapping(h, { connectionId: CONNECTION, groupExternalId: 'okta-grp-sales', permissionSet: SALES }); + expect(refused.status).toBe(400); + const error = (refused.body as { error: { code: string; fields: Array<{ field: string; code: string }> } }).error; + expect(error.code).toBe('VALIDATION_FAILED'); + expect(error.fields.map((f) => [f.field, f.code])).toEqual([['connectionId', 'rule_violation']]); + expect(await h.engine.find('sys_idp_group_mapping', {}, SYSTEM)).toEqual([]); + }); +}); diff --git a/packages/plugins/plugin-auth/src/scim-group-projection.ts b/packages/plugins/plugin-auth/src/scim-group-projection.ts new file mode 100644 index 00000000000..b250fa574b5 --- /dev/null +++ b/packages/plugins/plugin-auth/src/scim-group-projection.ts @@ -0,0 +1,237 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The SCIM group → permission-set projection: what an identity provider's + * group membership grants on this deployment (ADR-0134 D4's group seam, + * filled for ordinary permission sets only). + * + * ## The vendor seam + * + * `@better-auth/scim` (1.7.12) calls `scim({ projection })` on every user + * mutation and every group membership change, inside the SCIM transaction: + * + * - `roles.map` turns one (connection, group) into opaque role slugs. Here a + * slug is the id of a `sys_idp_group_mapping` row whose source is that + * connection and whose group key matches the group: its `group_external_id` + * against the group's `externalId` when the row names one, else its + * `group_display_name` against the group's `displayName`. An unmapped group + * maps to nothing and grants nothing. + * - `roles.exists` confirms a slug still names a mapping row of that + * connection that names an organization and whose set is still inside the + * organization boundary. A set whose definition grew an administrator bit + * after the mapping was saved is not granted (said once, at `warn`): an + * identity provider's group never confers administrator standing. + * - `reconcileUser` receives the user's COMPLETE desired grant set and makes + * `sys_user_permission_set` agree with it, idempotently. It asks the same + * question as `exists` again before every insert, so the boundary does not + * depend on the vendor having called `exists` on that path, and it never + * writes a grant without an organization. + * + * ## Which grants are the projection's + * + * A grant the projection writes carries `reason` = {@link scimGroupProjectionReason} + * for its provisioning domain, the same way the organization-admin reconcile + * marks its own (`auto-org-admin-grant.ts`). Reconcile removes only rows that + * carry that exact marker, so a grant an administrator made by hand is never + * touched, even when it names the same set. A desired set the user already + * holds in that organization through any other row is not written again (the + * grant table is unique on user, set and organization). + * + * ## Why the engine and not `context.database` + * + * The vendor's transaction adapter cannot address `sys_user_permission_set` + * (BetterAuthError "Model not found in schema", which turned every SCIM write + * into a 500 when tried). The ObjectQL engine can, and its writes join the SCIM + * request's engine transaction (`objectql-adapter.ts`, `scimRequestScope`), so + * a refused grant rolls the whole SCIM mutation back. Writes run as the system + * with the SCIM connection as actor (`authSystemWriteContext()`, so the audit + * row says `svc:scim:CONNECTION_ID`), and an engine refusal is rethrown as the + * 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. + */ + +import type { IDataEngine } from '@objectstack/core'; +import type { SCIMProjection, SCIMProjectedUserState } from '@better-auth/scim'; +import { withSystemContext, withValidationErrorMapping } from './objectql-adapter.js'; + +/** The mapping object the projection reads (platform-objects/identity). */ +export const IDP_GROUP_MAPPING_OBJECT = 'sys_idp_group_mapping'; + +/** The grant table the projection writes (plugin-security). */ +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 machine prefix of every grant the projection writes. */ +export const SCIM_GROUP_PROJECTION_REASON_PREFIX = 'scim-group-projection'; + +/** The `reason` a projected grant carries: the marker plus the provisioning domain it was projected for. */ +export function scimGroupProjectionReason(provisioningDomainId: string): string { + return `${SCIM_GROUP_PROJECTION_REASON_PREFIX}: provisioning domain '${provisioningDomainId}'`; +} + +/** The security service member that judges a set against the organization boundary. */ +export interface OrganizationBoundaryJudge { + organizationBoundaryFailure(setName: string): Promise; +} + +export interface ScimGroupProjectionDeps { + getEngine: () => IDataEngine | null | undefined; + /** Resolved per call: the security plugin starts after this one. */ + boundary: () => Promise; + warn: (message: string) => void; +} + +export interface MappingRow { + id?: unknown; + source_id?: unknown; + group_external_id?: unknown; + group_display_name?: unknown; + permission_set?: unknown; + organization_id?: unknown; +} + +const text = (v: unknown): string => (typeof v === 'string' ? v : v == null ? '' : String(v)); + +function registered(engine: IDataEngine, object: string): boolean { + const getSchema = (engine as unknown as { getSchema?: (name: string) => unknown }).getSchema; + return typeof getSchema !== 'function' || Boolean(getSchema.call(engine, object)); +} + +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 { + 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 }, + }), + ); +} + +/** 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); + if (externalId) return externalId === (group.externalId ?? ''); + const displayName = text(row.group_display_name); + 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; + }; + + /** + * 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 => { + 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'; + } else { + const judge = await deps.boundary(); + const failure = judge + ? await judge.organizationBoundaryFailure(text(row.permission_set)) + : 'the security service is not composed, so no set can be shown to be inside the organization boundary'; + refusal = failure === null + ? null + : `${failure}. An identity provider group never grants administrator standing. Delete the mapping, or map an ordinary permission set`; + } + 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}.`); + } + return false; + }; + + return { + roles: { + async map(input) { + const rows = await connectionMappings(engineOrThrow(), input.connectionId); + return rows.filter((row) => mappingMatchesGroup(row, input.source)).map((row) => text(row.id)); + }, + async exists(input) { + const rows = await connectionMappings(engineOrThrow(), input.connectionId); + const row = rows.find((r) => text(r.id) === input.role); + return row ? admits(row) : false; + }, + }, + reconcileUser: (state) => reconcileProjectedGrants(engineOrThrow(), state, admits), + }; +} + +/** + * 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. + */ +export async function reconcileProjectedGrants( + engine: IDataEngine, + state: SCIMProjectedUserState, + admits: (row: MappingRow) => Promise, +): Promise { + const reason = scimGroupProjectionReason(state.provisioningDomainId); + const mappingIds = [...new Set(state.grants.map((grant) => grant.role))]; + 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`); + } + const reader = withSystemContext(engine); + const writer = withValidationErrorMapping(withSystemContext(engine) as unknown as Record) as unknown as IDataEngine; + + const key = (set: string, org: string) => `${set}\u0000${org}`; + const desired = new Map(); + if (mappingIds.length > 0) { + const mappings = rowsOf(await reader.find(IDP_GROUP_MAPPING_OBJECT, { where: { id: { $in: mappingIds } } })); + for (const row of mappings as MappingRow[]) { + const set = text(row.permission_set); + const org = text(row.organization_id); + if (!set || !(await admits(row))) continue; + desired.set(key(set, org), { set, org }); + } + } + + const held = rowsOf( + await reader.find(GRANT_OBJECT, { + where: { user_id: state.userId }, + fields: ['id', 'permission_set', 'organization_id', 'reason'], + }), + ); + const heldKeys = new Set(held.map((row) => key(text(row.permission_set), text(row.organization_id)))); + + for (const [k, { set, org }] of desired) { + if (heldKeys.has(k)) continue; + // The grant's organization rides on the row AND as the write's tenant, so the + // engine owns it in that organization exactly as a session write would. + await writer.insert( + GRANT_OBJECT, + { user_id: state.userId, permission_set: set, organization_id: org, reason }, + { context: { isSystem: true, tenantId: org } }, + ); + } + for (const row of held) { + if (text(row.reason) !== reason) continue; + if (desired.has(key(text(row.permission_set), text(row.organization_id)))) continue; + await writer.delete(GRANT_OBJECT, { where: { id: text(row.id) } }); + } +} diff --git a/packages/plugins/plugin-security/src/delegated-admin-gate.ts b/packages/plugins/plugin-security/src/delegated-admin-gate.ts index 9e9aea0388c..5bcca0d19fb 100644 --- a/packages/plugins/plugin-security/src/delegated-admin-gate.ts +++ b/packages/plugins/plugin-security/src/delegated-admin-gate.ts @@ -628,6 +628,55 @@ function judgesTargetUserThroughCallerRead(ql: any): boolean { && Boolean(ql.getSchema(TARGET_USER_OBJECT)); } +/** + * [ADR-0090 D12, amended 2026-10-17] Is permission set `setName` inside the + * organization boundary? `null` when it is; otherwise the reason, naming the + * set and the condition it fails: + * + * - by name — {@link ORGANIZATION_BOUNDARY_DENYLIST}; + * - (a) its `objects['*']` entry carries `viewAllRecords` or `modifyAllRecords`; + * - (b) it carries an `adminScope`; + * - (c) a name in its `systemPermissions` is not a capability declared + * `scope: 'org'` in the security catalog (a name no declaration carries is + * not an organization capability). + * + * A set the catalog does not hold cannot be shown inside, and is not. + * + * Exported so a second save door that distributes permission sets judges them by + * THIS predicate and never by a copy of its list: plugin-auth's identity-provider + * group mapping refuses, at save, any set this answers a reason for. + */ +export async function organizationBoundaryFailure( + catalog: SecurityCatalogReader | undefined, + setName: string, +): Promise { + if (ORGANIZATION_BOUNDARY_DENYLIST.has(setName)) { + return `permission set '${setName}', which is outside the organization boundary by name (platform and organization administration and the agent ceilings are never assigned by an organization administrator)`; + } + const entry = catalog ? await catalog.resolve('permission', setName) : undefined; + if (!catalog || !entry) { + return `permission set '${setName}', which is not in the security catalog, so it cannot be shown to be inside the organization boundary`; + } + const definition: any = entry.definition; + const wildcard = (parseMaybeJson(definition.objects) ?? {})?.['*']; + for (const bit of ['viewAllRecords', 'modifyAllRecords'] as const) { + if (wildcard?.[bit] === true) { + return `permission set '${setName}', which fails condition (a) of the organization boundary: its objects['*'] entry carries the superuser bit '${bit}'`; + } + } + if (parseMaybeJson(definition.adminScope ?? definition.admin_scope)) { + return `permission set '${setName}', which fails condition (b) of the organization boundary: it carries an adminScope`; + } + const capabilities = parseMaybeJson(definition.systemPermissions); + for (const capability of Array.isArray(capabilities) ? capabilities : []) { + const declared = await catalog.resolve('capability', String(capability)); + if (declared?.definition.scope !== 'org') { + return `permission set '${setName}', which fails condition (c) of the organization boundary: its capability '${String(capability)}' is ${declared ? "not declared scope 'org'" : "declared nowhere, so it is not an organization capability"}`; + } + } + return null; +} + export class DelegatedAdminGate { constructor(private readonly deps: DelegatedAdminGateDeps) {} @@ -1280,47 +1329,9 @@ export class DelegatedAdminGate { return [...new Set(listed)]; } - /** - * [ADR-0090 D12, amended 2026-10-17] Is permission set `setName` inside the - * organization boundary? `null` when it is; otherwise the reason, naming the - * set and the condition it fails: - * - * - by name — {@link ORGANIZATION_BOUNDARY_DENYLIST}; - * - (a) its `objects['*']` entry carries `viewAllRecords` or `modifyAllRecords`; - * - (b) it carries an `adminScope`; - * - (c) a name in its `systemPermissions` is not a capability declared - * `scope: 'org'` in the security catalog (a name no declaration carries is - * not an organization capability). - * - * A set the catalog does not hold cannot be shown inside, and is not. - */ - private async organizationBoundaryFailure(setName: string): Promise { - if (ORGANIZATION_BOUNDARY_DENYLIST.has(setName)) { - return `permission set '${setName}', which is outside the organization boundary by name (platform and organization administration and the agent ceilings are never assigned by an organization administrator)`; - } - const catalog = this.catalog(); - const entry = catalog ? await catalog.resolve('permission', setName) : undefined; - if (!catalog || !entry) { - return `permission set '${setName}', which is not in the security catalog, so it cannot be shown to be inside the organization boundary`; - } - const definition: any = entry.definition; - const wildcard = (parseMaybeJson(definition.objects) ?? {})?.['*']; - for (const bit of ['viewAllRecords', 'modifyAllRecords'] as const) { - if (wildcard?.[bit] === true) { - return `permission set '${setName}', which fails condition (a) of the organization boundary: its objects['*'] entry carries the superuser bit '${bit}'`; - } - } - if (parseMaybeJson(definition.adminScope ?? definition.admin_scope)) { - return `permission set '${setName}', which fails condition (b) of the organization boundary: it carries an adminScope`; - } - const capabilities = parseMaybeJson(definition.systemPermissions); - for (const capability of Array.isArray(capabilities) ? capabilities : []) { - const declared = await catalog.resolve('capability', String(capability)); - if (declared?.definition.scope !== 'org') { - return `permission set '${setName}', which fails condition (c) of the organization boundary: its capability '${String(capability)}' is ${declared ? "not declared scope 'org'" : "declared nowhere, so it is not an organization capability"}`; - } - } - return null; + /** [ADR-0090 D12] {@link organizationBoundaryFailure}, against this gate's catalog. */ + private organizationBoundaryFailure(setName: string): Promise { + return organizationBoundaryFailure(this.catalog(), setName); } /** Is business unit `id` a unit of `organizationId`? Fail-closed on an unreadable unit. */ diff --git a/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts b/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts index b9e11e77fae..83475e9c6cb 100644 --- a/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts +++ b/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts @@ -82,6 +82,7 @@ const DECLARED_MEMBERS = { dismissAudienceBindingSuggestion: 'required', reopenAudienceBindingSuggestion: 'optional', contributeOwnershipFloorAlternates: 'optional', + organizationBoundaryFailure: 'optional', } as const satisfies DeclaredOptionality; /** diff --git a/packages/plugins/plugin-security/src/security-plugin-security-service.ts b/packages/plugins/plugin-security/src/security-plugin-security-service.ts index 5df59505110..02ddca6bd43 100644 --- a/packages/plugins/plugin-security/src/security-plugin-security-service.ts +++ b/packages/plugins/plugin-security/src/security-plugin-security-service.ts @@ -55,7 +55,7 @@ * * Nothing re-exports this module, so the published surface does not move. */ -import type { PluginContext } from '@objectstack/core'; +import { securityCatalogReaderOf, type PluginContext } from '@objectstack/core'; import type { AuthoredRowWriteOperation, DelegationNarrowing, @@ -71,6 +71,7 @@ import { intersectDelegatedScope, d10NarrowingStatement, } from './explain-engine.js'; +import { organizationBoundaryFailure } from './delegated-admin-gate.js'; import type { OwnershipFloorAlternate } from './platform-ownership-policies.js'; import { listAudienceBindingSuggestions, @@ -418,6 +419,13 @@ export function registerSecurityService( : alternates.map((a) => `${a.object}.${a.operation} (${a.name})`).join(', ')), ); }, + // [ADR-0090 D12] The organization boundary, judged by the gate's own + // predicate against this engine's security catalog: `null` when the set + // is inside, else the reason. plugin-auth's identity-provider group + // mapping door calls it at save, so an IdP group never grants a set an + // organization administrator could not assign. + organizationBoundaryFailure: (setName: string): Promise => + organizationBoundaryFailure(securityCatalogReaderOf(ql), setName), }); ctx.registerService('security', registeredSecurityService); // The member list is READ OFF the registered object, never typed by hand: diff --git a/packages/qa/dogfood/test/admin-platform-admin-standing.dogfood.test.ts b/packages/qa/dogfood/test/admin-platform-admin-standing.dogfood.test.ts index 8e2cdcb5645..169fb905d51 100644 --- a/packages/qa/dogfood/test/admin-platform-admin-standing.dogfood.test.ts +++ b/packages/qa/dogfood/test/admin-platform-admin-standing.dogfood.test.ts @@ -269,6 +269,13 @@ const ADMITTED = [ // and is audited) are pinned in `admin-identity-audit-trail.dogfood.test.ts`. 'POST /api/v1/auth/admin/scim/mint-credential', 'POST /api/v1/auth/admin/scim/revoke-credential', + // The identity-provider group mapping door, beside it: ObjectStack raw + // mounts whose FIRST statement is the ADR-0068 gate. The save names a + // connection with no credential, so the admin reaches the handler and gets + // 400 VALIDATION_FAILED on connectionId; the delete names a mapping that does + // not exist and gets 404. Nothing moves. + 'POST /api/v1/auth/admin/scim/set-group-mapping', + 'POST /api/v1/auth/admin/scim/delete-group-mapping', ] as const; /** @@ -762,6 +769,10 @@ describe('#9482: what an ObjectStack platform admin gets from every /admin/ rout // credential id that does not exist, so it moves nothing. 'POST /api/v1/auth/admin/scim/mint-credential': { body: { connectionId: 'standing-probe-scim' } }, 'POST /api/v1/auth/admin/scim/revoke-credential': { body: { credentialId: 'standing-probe-credential' } }, + 'POST /api/v1/auth/admin/scim/set-group-mapping': { + body: { connectionId: 'standing-probe-unminted', groupExternalId: 'standing-probe-group', permissionSet: 'standing_probe_set' }, + }, + 'POST /api/v1/auth/admin/scim/delete-group-mapping': { body: { mappingId: 'standing-probe-mapping' } }, 'POST /api/v1/auth/admin/ban-user': { body: { userId: targetUserId, banReason: 'sweep' } }, 'POST /api/v1/auth/admin/unban-user': { body: { userId: targetUserId } }, 'POST /api/v1/auth/admin/impersonate-user': { body: { userId: targetUserId } }, diff --git a/packages/qa/dogfood/test/admin-route-nonadmin-refusal.dogfood.test.ts b/packages/qa/dogfood/test/admin-route-nonadmin-refusal.dogfood.test.ts index 9ebfeb49456..92fe36ed6ca 100644 --- a/packages/qa/dogfood/test/admin-route-nonadmin-refusal.dogfood.test.ts +++ b/packages/qa/dogfood/test/admin-route-nonadmin-refusal.dogfood.test.ts @@ -313,6 +313,19 @@ function expectationsFor(targetUserId: string): Record body: { credentialId: 'refusal-probe-credential' }, note: 'the gate runs ahead of any body read; the admin passes it and lands on 404 RESOURCE_NOT_FOUND for the unknown credential', }, + // The identity-provider group mapping door beside it: the same gate first. + // The save names a connection with no credential and the delete a mapping + // that does not exist, so nothing moves for the admin either. + 'POST /api/v1/auth/admin/scim/set-group-mapping': { + bucket: 'objectstack-gate', + body: { connectionId: 'refusal-probe-unminted', groupExternalId: 'refusal-probe-group', permissionSet: 'refusal_probe_set' }, + note: 'the gate runs ahead of any body read; the admin passes it and lands on 400 VALIDATION_FAILED on connectionId, since the probe connection has no credential', + }, + 'POST /api/v1/auth/admin/scim/delete-group-mapping': { + bucket: 'objectstack-gate', + body: { mappingId: 'refusal-probe-mapping' }, + note: 'the gate runs ahead of any body read; the admin passes it and lands on 404 RESOURCE_NOT_FOUND for the unknown mapping', + }, // ── #9653: the /admin/sso/* bridges, gated ahead of their delegation ──── // // The ADR-0068 gate runs BEFORE the bridge re-dispatches into better-auth, diff --git a/packages/spec/src/contracts/security-service.ts b/packages/spec/src/contracts/security-service.ts index 0d59f3acf22..976ef40f654 100644 --- a/packages/spec/src/contracts/security-service.ts +++ b/packages/spec/src/contracts/security-service.ts @@ -1399,4 +1399,22 @@ export interface ISecurityService { plugin: string, alternates: readonly OwnershipFloorAlternate[], ): void; + /** + * [ADR-0090 D12] Is permission set `setName` inside the organization + * boundary? Resolves `null` when it is, otherwise the reason, naming the set + * and the condition it fails: outside by name (platform administration, the + * organization-administrator sets, the agent ceilings), a superuser bit on its + * `objects['*']` entry, an `adminScope`, or a capability not declared + * `scope: 'org'`. A set the security catalog does not hold cannot be shown + * inside, and is not. It is the same predicate the delegated-administration + * gate judges an organization administrator's assignment by, served so a + * second door that distributes permission sets (the identity-provider group + * mapping) judges them by it and never by a copy of its list. + * + * **OPTIONAL, and absence is a defined state, not a bug.** Callers + * feature-detect (`typeof svc.organizationBoundaryFailure === 'function'`) + * and fail CLOSED when it is absent: no set is shown to be inside, so nothing + * that depends on the answer is saved or granted. + */ + organizationBoundaryFailure?(setName: string): Promise; } diff --git a/packages/spec/src/system/constants/platform-object-names.ts b/packages/spec/src/system/constants/platform-object-names.ts index 4981e0557ba..59035ceb0c6 100644 --- a/packages/spec/src/system/constants/platform-object-names.ts +++ b/packages/spec/src/system/constants/platform-object-names.ts @@ -54,6 +54,7 @@ export const PLATFORM_OBJECTS_BY_PACKAGE: Readonly