diff --git a/.changeset/33181-pending-sso-users.md b/.changeset/33181-pending-sso-users.md new file mode 100644 index 00000000000..99bc7d10512 --- /dev/null +++ b/.changeset/33181-pending-sso-users.md @@ -0,0 +1,22 @@ +--- +'@objectstack/plugin-auth': patch +'@objectstack/platform-objects': patch +--- + +feat(auth)!: a managed environment adds pending, SSO-only people with their positions, permission sets and manager, and ban works without the admin plugin + +Clause-②: yes (narrowing) — narrowed: ban works without the admin plugin — `admin/ban-user` now works without the admin plugin, and a banned row is refused a session, with the admin plugin's own `403 BANNED_USER` answer; both ban doors answered `501 NOT_IMPLEMENTED` there. Widened: two doors, `POST /admin/add-sso-user` and `POST /admin/import-sso-users` (cloud-managed environments only; `409 RESOURCE_CONFLICT` elsewhere); the `idp_pending` value of `sys_user.source`, which every password door and every session refuses; the auth plugin's optional `environmentUserHost` option; `AuthManager#isAdminPluginMounted()`; the exports of `pending-sso-marker`, `environment-user-host` and `pending-sso-users`; and, re-exported from the package root, the helpers `bindUserToSoleOrganization`, `writeAdminAudit`, `joinCurrentOrganization` and `multiOrgCreationJoinsCurrentOrganization`, the class `CreationRefused`, the type `AdminAuditDecisions` (with its `user.admin_added_pending` event), `SetInitialPasswordOptions` (the optional third argument of `runSetInitialPassword`) and the optional `getBanWriter`, `host`, `getDataEngine` and `logger` members of `AdminBanEndpointDeps`. The cloud-managed refusals of `create-user`, `import-users` and the invitation doors point to Setup → Users. +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches the admin user doors, the ban doors or the cloud-managed refusals; `content/docs/permissions/authentication.mdx` gains the two doors, the pending state, the host option and the ban change in this change. + + + +**BREAKING** for a deployment that runs without the better-auth admin plugin (`auth.plugins.admin` off, and SCIM off): `admin/ban-user` now works without the admin plugin, and a banned row is refused a session, with the admin plugin's own `403 BANNED_USER` code and sentence. `admin/unban-user` lifts the ban there too. A ban with an expiry that has passed is lifted at the next sign-in, as the admin plugin does. A deployment with the admin plugin on answers exactly as before: the plugin still decides. + +Unchanged: the admin plugin's own ban enforcement where it is mounted; `create-user` and `import-users` off a managed environment; every row whose `source` is `env_native` or `idp_provisioned`. + +What to do: before upgrading a deployment that runs without the admin plugin, list the users whose `sys_user.banned` is true, platform administrators first, and unban every one who should keep signing in: turn the admin plugin on (`auth.plugins.admin`), call `POST /admin/unban-user` for each, then turn it off again. A banned sole platform administrator cannot reach `admin/unban-user` after the upgrade. After it, a user who should not be banned is unbanned with `POST /admin/unban-user`. + +New on a cloud-managed environment (`OS_CLOUD_MANAGED=1`): a platform administrator adds a person ahead of their first sign-in with `POST /admin/add-sso-user` (email, name, and optionally positions, permission sets and the manager's email address), or many with `POST /admin/import-sso-users` (CSV or rows, at most 500, a result per row, a bad row failing alone). The person is stored with `sys_user.source` = `idp_pending`: no password, refused by `set-user-password`, `set-initial-password`, `reset-password` and `phone-number/reset-password`, and refused a session on every channel, until their first sign-in through the platform identity provider attaches to the row and moves it to `idp_provisioned`. Positions, permission sets and the manager apply from the moment the person is added. Adding a person who is still pending again re-tells the host and changes nothing else; positions, permission sets or a manager sent with it are named on the answer as `notApplied`. A host passed as `environmentUserHost` is told after a person is added, and asked before a person is deactivated (`ban-user`) or reactivated (`unban-user`), never inside a transaction; the event names the administrator, the administrator at the keyboard on an impersonation session (`impersonatedBy`), and the administrator's cloud user id from their linked `objectstack-cloud` account. A host may refuse with `EnvironmentUserHostRefusal` (`409` or `403`, such as `DEVELOPER_ORGANIZATION_MEMBER_LIMIT_REACHED`): the door answers with it, a refused deactivation or reactivation writes nothing, and a refused add takes that person back out (one import row fails alone). Any other host failure refuses a deactivation (`503`, nothing written), and never undoes an add or a reactivation, whose answer says so on the row. + +`@objectstack/platform-objects`: `sys_user.source` gains the option `idp_pending` ("Pending SSO Sign-In"). diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index b52c6bab4ba..a69b9f59819 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -1260,6 +1260,63 @@ rows that resolve to a temporary password (all of them under `temporary`, only the unreachable ones under `auto`) — reveals the generated passwords once with a download, splitting files above 500 rows into batches automatically. +#### Adding people on a cloud-managed environment + +On a cloud-managed environment (`OS_CLOUD_MANAGED=1`) people sign in through +the identity provider of the organisation that hosts the environment, so +`create-user` and `import-users` answer `409 RESOURCE_CONFLICT` there. Two +doors add a person ahead of their first sign-in instead. Neither needs the +admin plugin, and both are platform-admin gated: + +- `POST /api/v1/auth/admin/add-sso-user` takes `email`, `name`, and optionally + `positions`, `permissionSets` (lists of machine names) and `manager` (the + manager's email address). It answers `201`, or `200` with `alreadyPending` + when the person was already added and has not signed in yet. +- `POST /api/v1/auth/admin/import-sso-users` takes `csv` (columns `email`, + `name`, `positions`, `permission_sets`, `manager_id`; lists separated by + `;`, `manager_id` holding the manager's email address) or `rows`, at most + 500 rows. Each row is judged and written on its own, so a bad row fails + with its own message and the good rows land. The answer carries a + `summary` and one result per row. + +The person is stored **pending** (`sys_user.source` reads `idp_pending`): no +password, and no session until they sign in through the hosting +organisation's identity provider. Every password door refuses a pending +person (`set-user-password`, `set-initial-password`, the email and phone +reset), and so does every other way to open a session. Their first sign-in +through the platform identity provider attaches to the row and the source +becomes `idp_provisioned`; only that provider clears the pending state, and a +sign-in through any other one leaves the person pending. Their positions, permission sets and manager apply +from the moment they are added, so seed data and approval flows can name them +before they sign in. Off a managed environment both doors answer `409`. + +A host can be told about people as they come and go: the `environmentUserHost` +option of the auth plugin is called after a person is added, and before a +person is deactivated (`admin/ban-user`) or reactivated (`admin/unban-user`). +It is never called inside a database transaction. Each event names the +administrator who acted, the administrator at the keyboard when the session +is an impersonation (`impersonatedBy`), and, when the acting administrator +holds a linked `objectstack-cloud` account, their cloud user id from that +account. None of these is read from the request. + +A host can refuse by throwing `EnvironmentUserHostRefusal` with a `409` (for +example, an organization owner or admin, who is removed in the console) or a +`403` (for example, `DEVELOPER_ORGANIZATION_MEMBER_LIMIT_REACHED`). The door +answers with that status, code and sentence: a refused deactivation or +reactivation writes nothing, and a refused add takes that person back out +(on an import, that row alone fails). Any other host failure refuses a +deactivation with `503` and writes nothing, since only the host can say +whether the person is an organization owner or admin. It never undoes or +blocks an add or a reactivation: the answer carries `host: { notified: false, +reason }`. Adding a person who is still pending again tells the host again +and changes nothing else: positions, permission sets or a manager sent with +it are listed on the answer as `notApplied`; set them on the person's record. + +`admin/ban-user` and `admin/unban-user` work without the admin plugin: on a +deployment without it the ban is written by the platform, and a banned user is +refused a session with the same `403 BANNED_USER` answer the admin plugin +gives. + #### SCIM Connection Credentials With SCIM enabled (`OS_SCIM_ENABLED=true`, or `plugins.scim`), an identity @@ -1480,6 +1537,10 @@ All endpoints are available under `/api/v1/auth/*`: - `POST /api/v1/auth/admin/unlock-user` - Clear a brute-force lockout early - `POST /api/v1/auth/admin/ban-user` - Ban a user (blocks sign-in and revokes live sessions; the user's API keys are refused at every door while the ban holds; their OAuth access tokens are refused at the MCP endpoint and read as not valid at `/oauth2/userinfo` and `/oauth2/introspect`, and the token endpoint issues them no new token; a ban with an expiry stops binding once it expires. Neither the keys nor the OAuth tokens are revoked) - `POST /api/v1/auth/admin/unban-user` - Lift a ban, restoring the account's ability to sign in and its API keys (each key is still judged by its own lifecycle: a key left unused past the inactivity window during the ban answers as inactive, and needs replacing) +- `POST /api/v1/auth/admin/add-sso-user` - Add one pending person who signs in only through the hosting organisation's identity provider (cloud-managed environments only) +- `POST /api/v1/auth/admin/import-sso-users` - Add pending people from a CSV or JSON rows (cloud-managed environments only; ≤500 rows, per-row results) + +`ban-user`, `unban-user`, `add-sso-user` and `import-sso-users` answer without `plugins.admin` too. #### Organization Membership (requires `plugins.organization`; platform-admin gated) diff --git a/content/docs/permissions/tenant-audit-census.mdx b/content/docs/permissions/tenant-audit-census.mdx index 3bbcac10fcd..793cd0dfda7 100644 --- a/content/docs/permissions/tenant-audit-census.mdx +++ b/content/docs/permissions/tenant-audit-census.mdx @@ -93,7 +93,7 @@ what moved this page's population from 225 to 227; nothing about the two sites changed, only whether this instrument could see them. **The expensive failure direction is a keyword.** Sites whose receiver the author -typed `any` have no type to read, and there are 62 of them — just over a fifth +typed `any` have no type to read, and there are 66 of them — just over a fifth of the population, concentrated in exactly the seed and bootstrap paths this control exists for. Scoring an unreadable receiver as "not an engine" would have dropped every one of them silently, with a clean exit and a smaller number that @@ -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 **59 of the 315 sites are spelled that way**. A +forwarding shim cannot, and **59 of the 321 sites are spelled that way**. A context resolved from an inline literal or a local `const` can be tested for `isSystem`; one arriving from a helper call cannot. @@ -197,10 +197,10 @@ reproduce them. Where it disagrees, it disagrees on the page: | carried figure | where it survives | this census | | :--- | :--- | ---: | -| 175 write call sites | quoted in the merged changeset | **315** | +| 175 write call sites | quoted in the merged changeset | **321** | | 24 carrying no tenant context | quoted in the merged changeset | **3** provable and tenancy-enabled; **32** more whose options argument is unreadable | -| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **220 of 315** decidable, **95** undecidable | -| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 178 decidably elevated, 0 decidably not, 125 undecidable | +| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **226 of 321** decidable, **95** undecidable | +| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 181 decidably elevated, 0 decidably not, 128 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 @@ -210,18 +210,18 @@ be stated is what this instrument counts, which is written above and re-runnable 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 +one, and both are counted in the generated tables below: the 66 sites reached through an erased (`any`) receiver, and the 86 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 -178 of 315 (57%) as decidably elevated, with 125 more whose elevation is a +181 of 321 (56%) as decidably elevated, with 128 more whose elevation is a run-time fact — so the claim is neither confirmed nor refuted, and the honest answer is that a static reading cannot settle it. -⇒ **Cite `3 / 315`, and say what it is**: the sites whose options argument was +⇒ **Cite `3 / 321`, 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" — **32 further sites** have an options argument this @@ -233,28 +233,28 @@ cannot read, and they are neither in nor out. | what | count | | :--- | ---: | -| write call sites on the application surface | **315** | -| …whose object name is statically decidable | 220 | +| write call sites on the application surface | **321** | +| …whose object name is statically decidable | 226 | | …whose object name is chosen at run time | 95 | -| …against an object with tenancy ENABLED | 213 | +| …against an object with tenancy ENABLED | 219 | | …against an object that declares tenancy off | 7 | -| threading a tenant context | 244 | +| threading a tenant context | 250 | | PROVABLY carrying none (options read, no context key) | **12** | | …of those, against a decidably tenancy-enabled object | **3** | | options argument UNREADABLE — may or may not carry one | 59 | | …of those, against a decidably tenancy-enabled object | 32 | -| threading a decidably ELEVATED (`isSystem`) context | 178 | +| threading a decidably ELEVATED (`isSystem`) context | 181 | | threading a context that is decidably NOT elevated | 0 | -| threading a context whose elevation is a run-time fact | 125 | +| threading a context whose elevation is a run-time fact | 128 | | how the instrument reached the site | count | | :--- | ---: | -| receiver carried a readable engine type | 253 | -| receiver erased, placed by the object NAME | 52 | +| receiver carried a readable engine type | 255 | +| receiver erased, placed by the object NAME | 56 | | receiver erased, placed by an `object: string` PARAMETER | 5 | | receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 | -| object name spelled inline | 134 | +| object name spelled inline | 140 | | object name spelled through a `const` | 86 | | object name is an `object: string` parameter | 10 | | object name is some other run-time expression | 85 | @@ -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-15 at `c1014aa8e`. +Measured on 2026-11-15 at `2ab05f460`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1170 | -| engine-shaped types recognised | 139 | +| tracked non-test sources scanned | 1176 | +| engine-shaped types recognised | 141 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 309 | +| same-named calls subtracted as non-engine | 311 | {/* 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 98a68b76d73..d9225ca889b 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 | 315 | -| Object name statically decidable | 220 | +| Write call sites | 321 | +| Object name statically decidable | 226 | | Object name chosen at run time | 95 | -| Against a tenancy-enabled object | 213 | +| Against a tenancy-enabled object | 219 | | Against an object declaring tenancy off | 7 | -| Threading a tenant context | 244 | +| Threading a tenant context | 250 | | Provably carrying none | 12 | | …and decidably tenancy-enabled | 3 | | Options argument unreadable | 59 | | …and decidably tenancy-enabled | 32 | -| Threading a decidably elevated context | 178 | +| Threading a decidably elevated context | 181 | | Threading a decidably non-elevated context | 0 | -| Threading a context of undecidable elevation | 125 | +| Threading a context of undecidable elevation | 128 | ## Subtractions the census could NOT defend — enforced @@ -90,14 +90,14 @@ 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-15 at `c1014aa8e`. +Measured on 2026-11-15 at `2ab05f460`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1170 | -| engine-shaped types recognised | 139 | +| tracked non-test sources scanned | 1176 | +| engine-shaped types recognised | 141 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 309 | +| same-named calls subtracted as non-engine | 311 | ## Every site @@ -184,6 +184,9 @@ Measured on 2026-11-15 at `c1014aa8e`. | `packages/plugins/plugin-auth/src/organization-delete.ts` | `delete` | `sys_team` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/organization-delete.ts` | `delete` | `sys_team_member` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/organization-delete.ts` | `delete` | `sys_user_permission_set` | enabled | elevated | 1 | +| `packages/plugins/plugin-auth/src/pending-sso-users.ts` | `insert` | `sys_user` | enabled | context, elevation undecidable | 1 | +| `packages/plugins/plugin-auth/src/pending-sso-users.ts` | `insert` | `sys_user_permission_set` | enabled | context, elevation undecidable | 1 | +| `packages/plugins/plugin-auth/src/pending-sso-users.ts` | `insert` | `sys_user_position` | enabled | context, elevation undecidable | 1 | | `packages/plugins/plugin-auth/src/reconcile-membership.ts` | `insert` | `sys_member` | enabled | context, elevation undecidable | 1 | | `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 | @@ -203,6 +206,8 @@ Measured on 2026-11-15 at `c1014aa8e`. | `packages/plugins/plugin-auth/src/sso-provider-lifecycle.ts` | `delete` | `IDP_GROUP_MAPPING_OBJECT` | undecidable | PROVABLY NONE | 1 | | `packages/plugins/plugin-auth/src/sso-provider-lifecycle.ts` | `delete` | `sys_user_permission_set` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/sys-session-revoke.ts` | `update` | `SystemObjectName.SESSION` | undecidable | elevated | 1 | +| `packages/plugins/plugin-auth/src/user-ban-write.ts` | `update` | `sys_user` | enabled | elevated | 1 | +| `packages/plugins/plugin-auth/src/user-session-admission.ts` | `update` | `sys_user` | enabled | elevated | 2 | | `packages/plugins/plugin-email/src/attachment-reclaim.ts` | `update` | `object` | undecidable | elevated | 1 | | `packages/plugins/plugin-email/src/email-plugin.ts` | `insert` | `object` | undecidable | elevated | 1 | | `packages/plugins/plugin-email/src/email-plugin.ts` | `update` | `object` | undecidable | elevated | 1 | 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 aab38171a1b..620764577f4 100644 --- a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts @@ -120,7 +120,8 @@ export const arObjects: NonNullable = { help: "طريقة إنشاء هذه الهوية — idp_provisioned (توفير فوري عبر SSO الموحَّد) أو env_native (تسجيل محلي / مستخدم نهائي للتطبيق). يديره النظام؛ لا تعدّله.", options: { idp_provisioned: "مُوفَّر من مزوّد الهوية", - env_native: "حساب محلي" + env_native: "حساب محلي", + idp_pending: "Pending SSO Sign-In" } }, id: { 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 7ad0364ff44..65d6ae14250 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 @@ -84,4 +84,5 @@ export const arGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider._actions.register_sso_provider.params.tokenEndpoint.label": "7cba958c95cef146", "objects.sys_sso_provider.fields.sign_out_of_idp.help": "ab8ff5fce3001c81", "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", + "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", }; 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 c07e3acc604..216a9c0cd31 100644 --- a/packages/platform-objects/src/apps/translations/de.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.objects.generated.ts @@ -120,7 +120,8 @@ export const deObjects: NonNullable = { help: "Wie diese Identität angelegt wurde – idp_provisioned (föderiertes SSO, Just-in-Time) oder env_native (lokale Registrierung / Endbenutzer der App). Vom System verwaltet; nicht bearbeiten.", options: { idp_provisioned: "Vom IdP bereitgestellt", - env_native: "Lokales Konto" + env_native: "Lokales Konto", + idp_pending: "Pending SSO Sign-In" } }, id: { 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 4994ede3579..6fc5da51ab8 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 @@ -226,4 +226,5 @@ export const deGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.register_service_account.params.name.label": "5274417ff1ccaf01", "objects.sys_user.fields.name.label": "5274417ff1ccaf01", "objects.sys_user.fields.principal_kind.options.human": "ed18d3469e10aef2", + "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", }; 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 336da2fbb1e..2f3f2642695 100644 --- a/packages/platform-objects/src/apps/translations/en.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.objects.generated.ts @@ -117,10 +117,11 @@ export const enObjects: NonNullable = { }, source: { label: "Identity Source", - help: "How this identity was created — idp_provisioned (federated SSO JIT or SCIM directory provisioning) or env_native (local signup, a local password, or an app end-user). System-managed; do not edit.", + help: "How this identity was created — idp_provisioned (federated SSO JIT or SCIM directory provisioning), env_native (local signup, a local password, or an app end-user), or idp_pending (added on a managed environment and waiting for the first sign-in through the hosting organisation identity provider). System-managed; do not edit.", options: { idp_provisioned: "IdP-Provisioned", - env_native: "Local Account" + env_native: "Local Account", + idp_pending: "Pending SSO Sign-In" } }, id: { 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 dcd60a3efe0..74bb59fdff1 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 @@ -120,7 +120,8 @@ export const esESObjects: NonNullable = { help: "Cómo se creó esta identidad: idp_provisioned (JIT de SSO federado) o env_native (registro local / usuario final de la aplicación). Gestionado por el sistema; no editar.", options: { idp_provisioned: "Aprovisionada por IdP", - env_native: "Cuenta local" + env_native: "Cuenta local", + idp_pending: "Pending SSO Sign-In" } }, id: { 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 9801c5bc69b..0c7bf26abf7 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 @@ -159,4 +159,5 @@ export const esESGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.id.label": "00b0385c9c152888", "objects.sys_sso_provider.fields.sign_out_of_idp.help": "ab8ff5fce3001c81", "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", + "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", }; 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 8d68842d351..675285a95c9 100644 --- a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts @@ -120,7 +120,8 @@ export const frObjects: NonNullable = { help: "Comment cette identité a été créée — idp_provisioned (JIT par SSO fédéré) ou env_native (inscription locale / utilisateur final de l’application). Géré par le système ; ne pas modifier.", options: { idp_provisioned: "Provisionné par l’IdP", - env_native: "Compte local" + env_native: "Compte local", + idp_pending: "Pending SSO Sign-In" } }, id: { 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 2aab1557ba3..ad1a675472e 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 @@ -251,4 +251,5 @@ export const frGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.sign_out_of_idp.help": "ab8ff5fce3001c81", "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", "objects.sys_two_factor.fields.secret.label": "03cb32e33fa5cc45", + "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", }; 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 639ba70e049..74714ddecb0 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 @@ -120,7 +120,8 @@ export const jaJPObjects: NonNullable = { help: "この ID の作成方法 — idp_provisioned(フェデレーション SSO の JIT)または env_native(ローカルサインアップ/アプリのエンドユーザー)。システム管理のため編集しないでください。", options: { idp_provisioned: "IdP プロビジョニング", - env_native: "ローカルアカウント" + env_native: "ローカルアカウント", + idp_pending: "Pending SSO Sign-In" } }, id: { 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 1aaf304b3f5..5517b0af108 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 @@ -149,4 +149,5 @@ export const jaJPGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.id.label": "00b0385c9c152888", "objects.sys_sso_provider.fields.sign_out_of_idp.help": "ab8ff5fce3001c81", "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", + "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", }; diff --git a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts index c5284992a68..97f2dac4eca 100644 --- a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts @@ -120,7 +120,8 @@ export const koObjects: NonNullable = { help: "이 ID가 만들어진 방식입니다. idp_provisioned(페더레이션 SSO JIT) 또는 env_native(로컬 가입 / 앱 최종 사용자)입니다. 시스템이 관리하므로 편집하지 마세요.", options: { idp_provisioned: "IdP에서 프로비저닝됨", - env_native: "로컬 계정" + env_native: "로컬 계정", + idp_pending: "Pending SSO Sign-In" } }, id: { diff --git a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts index 11bbccdce1c..b2254c8965f 100644 --- a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts @@ -114,4 +114,5 @@ export const koGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.id.label": "00b0385c9c152888", "objects.sys_sso_provider.fields.sign_out_of_idp.help": "ab8ff5fce3001c81", "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", + "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", }; 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 8dfdfcc5b03..3bc6b629511 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 @@ -120,7 +120,8 @@ export const ptBRObjects: NonNullable = { help: "Como esta identidade foi criada — idp_provisioned (SSO federado JIT) ou env_native (cadastro local / usuário final do app). Gerenciado pelo sistema; não edite.", options: { idp_provisioned: "Provisionado pelo IdP", - env_native: "Conta local" + env_native: "Conta local", + idp_pending: "Pending SSO Sign-In" } }, id: { 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 287b52b7a78..f421b878d77 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 @@ -157,4 +157,5 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.id.label": "00b0385c9c152888", "objects.sys_sso_provider.fields.sign_out_of_idp.help": "ab8ff5fce3001c81", "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", + "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", }; 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 b7af55924dc..eff9c03a096 100644 --- a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts @@ -120,7 +120,8 @@ export const ruObjects: NonNullable = { help: "Как была создана эта учётная запись — idp_provisioned (JIT через федеративный SSO) или env_native (локальная регистрация / конечный пользователь приложения). Управляется системой; не редактируйте.", options: { idp_provisioned: "Создан IdP", - env_native: "Локальная учётная запись" + env_native: "Локальная учётная запись", + idp_pending: "Pending SSO Sign-In" } }, id: { 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 affaccdc25a..01fb03eae43 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 @@ -113,4 +113,5 @@ export const ruGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.id.label": "00b0385c9c152888", "objects.sys_sso_provider.fields.sign_out_of_idp.help": "ab8ff5fce3001c81", "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", + "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", }; 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 85e34ae1f94..808fc51e05e 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 @@ -120,7 +120,8 @@ export const zhCNObjects: NonNullable = { help: "该身份的创建方式——idp_provisioned(联合 SSO 即时开通)或 env_native(本地注册 / 应用最终用户)。系统维护,请勿编辑。", options: { idp_provisioned: "IdP 开通", - env_native: "本地账号" + env_native: "本地账号", + idp_pending: "Pending SSO Sign-In" } }, id: { 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 ad9357bd076..912ad71f677 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 @@ -89,4 +89,5 @@ export const zhCNGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.id.label": "00b0385c9c152888", "objects.sys_sso_provider.fields.sign_out_of_idp.help": "ab8ff5fce3001c81", "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", + "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", }; 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 3a81ecc6ed2..0d1b30185d5 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 @@ -120,7 +120,8 @@ export const zhHantObjects: NonNullable = { help: "該身分的建立方式——idp_provisioned(聯合 SSO 即時開通)或 env_native(本地註冊 / 應用程式終端使用者)。系統維護,請勿編輯。", options: { idp_provisioned: "IdP 開通", - env_native: "本地帳號" + env_native: "本地帳號", + idp_pending: "Pending SSO Sign-In" } }, id: { 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 b86e96943b8..b7e4d2e51f3 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 @@ -107,4 +107,5 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.id.label": "00b0385c9c152888", "objects.sys_sso_provider.fields.sign_out_of_idp.help": "ab8ff5fce3001c81", "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", + "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", }; diff --git a/packages/platform-objects/src/identity/sys-user-identity-source-label.test.ts b/packages/platform-objects/src/identity/sys-user-identity-source-label.test.ts index ce196b3bb2f..8b5f714d23e 100644 --- a/packages/platform-objects/src/identity/sys-user-identity-source-label.test.ts +++ b/packages/platform-objects/src/identity/sys-user-identity-source-label.test.ts @@ -33,10 +33,16 @@ function bundleOptionLabel(bundle: Record, value: string): unkn describe('sys_user.source identity-source labels', () => { it('keeps the field a select over the same stored values and default', () => { expect(sourceField.type).toBe('select'); - expect(sourceField.options.map((o) => o.value)).toEqual(['idp_provisioned', 'env_native']); + // [#33181] `idp_pending`: a person added on a managed environment who has + // not signed in through the hosting organisation's identity provider yet. + expect(sourceField.options.map((o) => o.value)).toEqual(['idp_provisioned', 'env_native', 'idp_pending']); expect(sourceField.defaultValue).toBe('env_native'); }); + it('labels idp_pending "Pending SSO Sign-In"', () => { + expect(sourceField.options.find((o) => o.value === 'idp_pending')?.label).toBe('Pending SSO Sign-In'); + }); + it('labels env_native "Local Account"', () => { expect(sourceField.options.find((o) => o.value === 'env_native')?.label).toBe('Local Account'); }); diff --git a/packages/platform-objects/src/identity/sys-user.object.ts b/packages/platform-objects/src/identity/sys-user.object.ts index 050ffa6430b..91eae23cc09 100644 --- a/packages/platform-objects/src/identity/sys-user.object.ts +++ b/packages/platform-objects/src/identity/sys-user.object.ts @@ -1397,8 +1397,13 @@ export const SysUser = ObjectSchema.create({ options: [ { label: 'IdP-Provisioned', value: 'idp_provisioned' }, { label: 'Local Account', value: 'env_native' }, + // [#33181] A person added on a managed environment who has not signed + // in yet: no password, no session, until their first sign-in through + // the hosting organisation's identity provider moves the row to + // `idp_provisioned` (`plugin-auth` `pending-sso-marker.ts`). + { label: 'Pending SSO Sign-In', value: 'idp_pending' }, ], - description: 'How this identity was created — idp_provisioned (federated SSO JIT or SCIM directory provisioning) or env_native (local signup, a local password, or an app end-user). System-managed; do not edit.', + description: 'How this identity was created — idp_provisioned (federated SSO JIT or SCIM directory provisioning), env_native (local signup, a local password, or an app end-user), or idp_pending (added on a managed environment and waiting for the first sign-in through the hosting organisation identity provider). System-managed; do not edit.', }), id: Field.text({ diff --git a/packages/plugins/plugin-auth/src/admin-ban-endpoints.ts b/packages/plugins/plugin-auth/src/admin-ban-endpoints.ts index 7121911dad1..6cd92af3e3d 100644 --- a/packages/plugins/plugin-auth/src/admin-ban-endpoints.ts +++ b/packages/plugins/plugin-auth/src/admin-ban-endpoints.ts @@ -65,6 +65,31 @@ * The refusal envelope is ObjectStack's (ADR-0112 `{success,error:{code}}`), * NOT better-auth's flat `{message,code}`: these routes are ObjectStack's, and * the dogfood sweep distinguishes the two envelopes on purpose. + * + * ── Without the admin plugin ──────────────────────────────────────────────── + * + * A kernel without the vendor admin plugin (a Free or Team hosted + * environment, where it mounts only with SCIM) has no `banReason` / + * `banExpires` fields on better-auth's user model, so `internalAdapter` + * cannot land the write, and no vendor session hook reads `banned`. There the + * mount passes `getBanWriter`, which writes the same three columns through + * the data engine (`engineUserBanWriter`), and the session refusal in + * `user-session-admission.ts` enforces the ban with the vendor's own answer. + * + * ── The host seam ─────────────────────────────────────────────────────────── + * + * With an environment-user host wired (`environment-user-host.ts`), a ban + * asks it to deactivate the person and an unban to reactivate them, BEFORE + * the write and outside any transaction. A typed host refusal (an + * organization owner or admin, `409`; the developer member cap, `403`) + * refuses the whole operation with the host's answer and nothing is written. + * Any other host failure refuses a deactivation (`503`, nothing written): + * only the host can say whether the person is an organization owner or + * admin, whom ruling 5 keeps out of reach from the environment side. It + * never blocks a reactivation, which goes ahead with `host: { notified: + * false, … }` on the answer. The event names the administrator, the one at + * the keyboard on an impersonation session, and their cloud user id read + * from their linked `objectstack-cloud` account, never from the request. */ import { @@ -74,8 +99,18 @@ import { type CredentialAccountAdapter, } from './last-local-credential.js'; import type { AdminActor, EndpointResult } from './admin-user-endpoints.js'; -import { applyUserBan, applyUserUnban } from './user-ban-write.js'; +import { applyUserBan, applyUserUnban, type UserBanWriter } from './user-ban-write.js'; import { readJsonRequestBody } from './request-json-body.js'; +import { readUserSource } from './sso-only-local-password.js'; +import { + environmentUserAttribution, + notifyEnvironmentUserHost, + type EnvironmentUserActor, + type EnvironmentUserEventKind, + type EnvironmentUserHostAccessor, + type EnvironmentUserHostOutcome, + type EnvironmentUserHostRefused, +} from './environment-user-host.js'; /** * Minimal better-auth `$context` surface these two routes touch. Mirrors what @@ -92,8 +127,77 @@ export interface AuthBanContextLike { export interface AdminBanEndpointDeps { getAuthContext(): Promise; + /** + * The writer the ban columns land through, when it is not better-auth's + * `internalAdapter`: the engine-backed one on a kernel without the admin + * plugin. Absent, or answering `undefined`, means the `internalAdapter`. + */ + getBanWriter?(): Promise; + /** The environment-user host, asked before a ban (deactivated) or an unban (reactivated). */ + host?: EnvironmentUserHostAccessor; + /** Reads the row's `source` and the administrator's linked cloud account for the host event. */ + getDataEngine?(): any; + logger?: { warn(msg: string): void }; } +async function banWriterFor(deps: AdminBanEndpointDeps, ctx: AuthBanContextLike): Promise { + return (await deps.getBanWriter?.()) ?? ctx.internalAdapter; +} + +/** + * Ask the host, when one is wired; `undefined` leaves the answer as it was. + * A typed refusal comes back as `{ refused }` for the door to answer. + */ +async function askHost( + deps: AdminBanEndpointDeps, + kind: EnvironmentUserEventKind, + user: unknown, + userId: string, + actor: AdminActor & EnvironmentUserActor, +): Promise { + if (!deps.host) return undefined; + const row = (user && typeof user === 'object' ? user : {}) as { email?: unknown; name?: unknown }; + const engine = deps.getDataEngine?.(); + const source = engine ? await readUserSource(engine, userId) : undefined; + const attribution = await environmentUserAttribution(engine, actor, deps.logger); + return notifyEnvironmentUserHost( + deps.host, + kind, + { + userId, + email: typeof row.email === 'string' ? row.email : '', + name: typeof row.name === 'string' ? row.name : '', + source: source?.ok && typeof source.value === 'string' ? source.value : null, + ...attribution, + occurredAt: new Date().toISOString(), + }, + deps.logger, + ); +} + +/** The door's answer for a host's typed refusal: its status, code and sentence; nothing was written. */ +const hostRefusal = ({ refused }: EnvironmentUserHostRefused): EndpointResult => ({ + status: refused.status, + body: { success: false, error: { code: refused.code, message: refused.message } }, +}); + +/** The answer when a wired host could not be asked whether the person may be deactivated. */ +const HOST_UNANSWERED_DEACTIVATION: EndpointResult = { + status: 503, + body: { + success: false, + error: { + code: 'SERVICE_UNAVAILABLE', + message: + 'The hosting organisation could not be asked whether this person may be deactivated, so they were not. ' + + 'Nothing was changed; try again.', + }, + }, +}; + +const isRefused = (outcome: unknown): outcome is EnvironmentUserHostRefused => + !!outcome && typeof outcome === 'object' && 'refused' in outcome; + const invalid = (message: string): EndpointResult => ({ status: 400, body: { success: false, error: { code: 'INVALID_REQUEST', message } }, @@ -159,7 +263,8 @@ export async function runAdminBanUser( } const ctx = await deps.getAuthContext(); - if (!(await ctx.internalAdapter.findUserById(userId))) return notFound(); + const target = await ctx.internalAdapter.findUserById(userId); + if (!target) return notFound(); // Break-glass — the guard the shadowed vendor route used to inherit from // `auth-manager.ts`'s before-hook, which a raw mount no longer reaches. @@ -173,7 +278,14 @@ export async function runAdminBanUser( }; } - await applyUserBan(ctx.internalAdapter, userId, { + // The host first: an organization owner or admin it refuses is not deactivated at all. + const host = await askHost(deps, 'deactivated', target, userId, actor); + if (isRefused(host)) return hostRefusal(host); + // A wired host that did not answer: the owner / admin question is open, so + // the deactivation does not happen (ruling 5). + if (host && !host.notified && host.reason === 'host_failed') return HOST_UNANSWERED_DEACTIVATION; + + await applyUserBan(await banWriterFor(deps, ctx), userId, { banReason, ...(banExpires ? { banExpires } : {}), }); @@ -189,6 +301,7 @@ export async function runAdminBanUser( banned: true, banReason, ...(banExpires ? { banExpires: banExpires.toISOString() } : {}), + ...(host ? { host } : {}), }, }, }; @@ -197,7 +310,7 @@ export async function runAdminBanUser( /** `POST /api/v1/auth/admin/unban-user` — the caller is already gated. */ export async function runAdminUnbanUser( deps: AdminBanEndpointDeps, - _actor: AdminActor, + actor: AdminActor, request: Request, ): Promise { const read = await parseJson(request); @@ -206,9 +319,14 @@ export async function runAdminUnbanUser( if (!userId) return invalid('userId is required'); const ctx = await deps.getAuthContext(); - if (!(await ctx.internalAdapter.findUserById(userId))) return notFound(); + const target = await ctx.internalAdapter.findUserById(userId); + if (!target) return notFound(); + + // The host first: a reactivation it refuses (the member cap) leaves the person deactivated. + const host = await askHost(deps, 'reactivated', target, userId, actor); + if (isRefused(host)) return hostRefusal(host); - await applyUserUnban(ctx.internalAdapter, userId); + await applyUserUnban(await banWriterFor(deps, ctx), userId); - return { status: 200, body: { success: true, data: { userId, banned: false } } }; + return { status: 200, body: { success: true, data: { userId, banned: false, ...(host ? { host } : {}) } } }; } diff --git a/packages/plugins/plugin-auth/src/admin-user-endpoints.ts b/packages/plugins/plugin-auth/src/admin-user-endpoints.ts index ee8f0ff9d8c..d3ff3d56f6d 100644 --- a/packages/plugins/plugin-auth/src/admin-user-endpoints.ts +++ b/packages/plugins/plugin-auth/src/admin-user-endpoints.ts @@ -240,6 +240,7 @@ import { readJsonRequestBody } from './request-json-body.js'; import { cloudManagedRefusal } from './cloud-managed.js'; import { identitySourceUnreadable, judgeSsoOnlyLocalPassword, readUserSource, ssoOnlyPasswordRefusal } from './sso-only-local-password.js'; import { temporaryPasswordLength } from './temporary-password-length.js'; +import { isPendingSsoSource, pendingSsoPasswordRefusal } from './pending-sso-marker.js'; import { isCloudManaged } from '@objectstack/core'; import { resolveThrownHttpError, validationFailureDetails } from '@objectstack/types'; import type { FieldErrorCode } from '@objectstack/spec/api'; @@ -479,8 +480,8 @@ async function stampMustChangePassword( * `membershipCreated: false` — the account is created, the membership is not. * A `failed` / `no-target-org` / `agent-account` outcome reports `false`. */ -async function bindUserToSoleOrganization( - deps: AdminUserEndpointDeps, +export async function bindUserToSoleOrganization( + deps: Pick, userId: string, ): Promise<{ organizationId: string | null; membershipCreated: boolean }> { const engine = deps.getDataEngine(); @@ -527,7 +528,7 @@ async function bindUserToSoleOrganization( * mirror row for the same write, in the snapshot column the ledger's read * side narrows. */ -type AdminAuditDecisions = +export type AdminAuditDecisions = | { event: 'user.admin_created'; placeholderEmail: boolean; @@ -535,6 +536,12 @@ type AdminAuditDecisions = membershipCreated: boolean; organizationId?: string; } + | { + /** A pending, SSO-only person was added (`pending-sso-users.ts`); no password exists. */ + event: 'user.admin_added_pending'; + membershipCreated: boolean; + organizationId?: string; + } | { event: 'user.admin_password_set'; passwordGenerated: boolean; @@ -603,8 +610,8 @@ type AdminAuditDecisions = * the pins in `admin-user-endpoints.test.ts` fail on any key outside the * decision set and on any value this call wrote into the user. */ -async function writeAdminAudit( - deps: AdminUserEndpointDeps, +export async function writeAdminAudit( + deps: Pick, entry: { action: 'create' | 'update'; actor: AdminActor; @@ -949,7 +956,7 @@ interface CreatedAccount { } /** [#25338] Thrown out of the unit of work so it rolls back; carries the refusal the caller answers. */ -class CreationRefused extends Error { +export class CreationRefused extends Error { constructor(readonly result: EndpointResult) { super(result.body.error?.message ?? 'user creation refused'); this.name = 'CreationRefused'; @@ -979,8 +986,8 @@ class CreationRefused extends Error { * host's `user.create.after` hook, say) — the same rule the single-org bind * answers by. */ -async function joinCurrentOrganization( - deps: AdminUserEndpointDeps, +export async function joinCurrentOrganization( + deps: Pick, addMember: AddMemberCapableApi['addMember'], userId: string, organizationId: string, @@ -1022,7 +1029,9 @@ async function joinCurrentOrganization( * default-organization bind, unchanged. A host that wires no way to read the * caller's current organization does not join either. */ -function multiOrgCreationJoinsCurrentOrganization(deps: AdminUserEndpointDeps): boolean { +export function multiOrgCreationJoinsCurrentOrganization( + deps: Pick, +): boolean { return deps.getTenancy?.()?.isolationActive === true && typeof deps.getCallerActiveOrganizationId === 'function'; } @@ -1102,6 +1111,17 @@ export async function runAdminSetUserPassword( return { status: 404, body: { success: false, error: { code: 'RESOURCE_NOT_FOUND', message: 'User not found' } } }; } + // A pending person (`sys_user.source = 'idp_pending'`, added through + // `admin/add-sso-user`) signs in only through the hosting organisation's + // identity provider and holds no local password until then, in every mode + // and for every caller (`pending-sso-users.ts`). A source that cannot be + // read is judged by the arms below exactly as before: none of them existed + // for a pending row, and no row carried the marker before it did. + const pendingSource = await readUserSource(deps.getDataEngine(), userId); + if (pendingSource.ok && isPendingSsoSource(pendingSource.value)) { + return pendingSsoPasswordRefusal('setUserPassword'); + } + // [#25083] On a cloud-managed environment a password is set here only on // a local account. An `idp_provisioned` user signs in through the hosting // organisation's identity provider, which owns their password; an diff --git a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts index b7ae3b8df27..dd2be3f9aad 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts @@ -79,7 +79,9 @@ import { resolveResetDoorUserId, SSO_ONLY_REFUSAL_CODE, SSO_ONLY_REFUSAL_MESSAGES, + readUserSource, } from './sso-only-local-password.js'; +import { isPendingSsoSource, PENDING_SSO_MESSAGES } from './pending-sso-marker.js'; import { ORGANIZATION_DELETE_PATH } from './organization-delete.js'; import { carriesPrincipalSession } from './principal-session-mint.js'; import { SSO_PROVIDER_DELETE_PATH } from './sign-in-method-floor.js'; @@ -206,11 +208,30 @@ export async function globalBeforeHook( // request is answered exactly as before; a reset record that cannot be // read fails closed (503). Ahead of the complexity check, // so the refusal names the real reason. - if ( - (ctx?.path === RESET_PASSWORD_PATH || ctx?.path === PHONE_RESET_PASSWORD_PATH) && - this.isSsoOnlyMode() - ) { - const subject = await resolveResetDoorUserId(ctx, this.config.phoneOtp?.allowedAttempts ?? 3); + // + // ── A pending person gets no local password either ── + // A row still reading `idp_pending` (added through `admin/add-sso-user`, + // `pending-sso-marker.ts`) signs in only through the hosting organisation's + // identity provider: both reset doors refuse it in EVERY mode, with no + // exception, judged by the same non-spending read of the presented token or + // code. A record or source that cannot be read leaves the request to the + // arm below exactly as before, since no row carried the marker before it. + const resetDoor = ctx?.path === RESET_PASSWORD_PATH || ctx?.path === PHONE_RESET_PASSWORD_PATH; + const resetSubject = resetDoor + ? await resolveResetDoorUserId(ctx, this.config.phoneOtp?.allowedAttempts ?? 3) + : undefined; + if (resetSubject?.ok && resetSubject.userId) { + const source = await readUserSource(this.getDataEngine(), resetSubject.userId); + if (source.ok && isPendingSsoSource(source.value)) { + const { APIError } = await import('better-auth/api'); + throw new APIError('CONFLICT', { + message: PENDING_SSO_MESSAGES.resetPassword, + code: 'RESOURCE_CONFLICT', + }); + } + } + if (resetDoor && resetSubject && this.isSsoOnlyMode()) { + const subject = resetSubject; // A reset record that cannot be read fails closed, as a source that // cannot be read does. let verdict: 'allow' | 'refuse' | 'unreadable' = subject.ok ? 'allow' : 'unreadable'; diff --git a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts index cbe9d3d54df..d1a4ae5b605 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts @@ -62,7 +62,10 @@ import { holdPrincipalSessionExpiry } from './principal-session-mint.js'; import { canonicalClientAddress } from './client-address-canonical.js'; import { readRequestClientAddress } from './request-client-address.js'; import { SESSION_SCOPING_REFUSAL } from './organization-access-policy.js'; -import { refuseAgentAccountCredential, refuseAgentAccountSession } from './service-account-identity.js'; +import { readSessionUserRow, refuseAgentAccountCredential } from './service-account-identity.js'; +import { refuseInactiveUserSession, SESSION_ADMISSION_ROW_FIELDS } from './user-session-admission.js'; +import { PLATFORM_IDP_PROVIDER_ID } from './implicit-account-linking.js'; +import { PENDING_SSO_SOURCE } from './pending-sso-marker.js'; /** * The `AuthManager` members the functions below read — every one of them, and @@ -77,6 +80,7 @@ export interface DatabaseHooksHost { readonly idpLocale: AuthManager['idpLocale']; audienceLogError: AuthManager['audienceLogError']; getDataEngine: AuthManager['getDataEngine']; + isAdminPluginMounted: AuthManager['isAdminPluginMounted']; isCreatedInThisRequest: AuthManager['isCreatedInThisRequest']; enforceConcurrentCap: AuthManager['enforceConcurrentCap']; judgeSessionScoping: AuthManager['judgeSessionScoping']; @@ -92,7 +96,7 @@ export interface DatabaseHooksHost { /** The body of `AuthManager#composeDatabaseHooks`; the method's docblock there is its contract. */ export function composeDatabaseHooks( - this: Pick, + this: Pick, host?: BetterAuthOptions['databaseHooks'], ): BetterAuthOptions['databaseHooks'] { // A landed link ends a standing unlink record (implicit-account-linking.ts, @@ -359,7 +363,16 @@ export function composeDatabaseHooks( // impersonation or minted session gets a session for one, whatever runs // after it. See service-account-identity.ts. const sessionBefore = async (session: any, ctx: any) => { - await refuseAgentAccountSession(this.config.dataEngine, session); + // [#33181] The same one read of the row carries the columns the next + // refusal judges: a pending person holds no session but the platform + // sign-in's, and a ban holds on a kernel without the vendor admin plugin + // (whose own hook enforces it where it is mounted). See + // user-session-admission.ts. + const userRow = await readSessionUserRow(this.config.dataEngine, session, SESSION_ADMISSION_ROW_FIELDS); + await refuseInactiveUserSession(this.config.dataEngine, session, { + row: userRow, + enforceBan: async () => !(await this.isAdminPluginMounted()), + }); const captured = await captureSessionAddress(session); const result = sessionActiveOrgBefore ? await sessionActiveOrgBefore(captured, ctx) : undefined; if (result === false) return false; @@ -591,6 +604,16 @@ export async function stampIdentitySource(this: Pick this.config; const readIdpLocale = () => this.idpLocale; - const hookHost: Pick = { + const hookHost: Pick = { audienceLogError: (...a) => this.audienceLogError(...a), get config() { return readConfig(); }, get idpLocale() { return readIdpLocale(); }, isCreatedInThisRequest: (...a) => this.isCreatedInThisRequest(...a), + isAdminPluginMounted: () => this.isAdminPluginMounted(), enforceConcurrentCap: (...a) => this.enforceConcurrentCap(...a), judgeSessionScoping: (...a) => this.judgeSessionScoping(...a), judgeSessionSwitch: (...a) => this.judgeSessionSwitch(...a), @@ -7728,6 +7729,19 @@ export class AuthManager { return resolveScimEnabled(this.config.plugins); } + /** + * Is better-auth's admin plugin mounted on the built instance? Asked of the + * instance itself (its `banUser` endpoint, the seam `admin/create-user` and + * `admin/ban-user` have always tested), never of the configuration, so a + * plugin that failed to mount reads as absent. Where it is absent the + * platform enforces a ban itself (`user-session-admission.ts`) and writes + * one through the data engine (`user-ban-write.ts`). + */ + public async isAdminPluginMounted(): Promise { + const api = (await this.getApi()) as { banUser?: unknown } | undefined; + return typeof api?.banUser === 'function'; + } + /** * [#30958] Mint a SCIM connection bearer with this deployment's auth secret, * the key the mounted SCIM plugin's verifier digests with diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 131c0b801ab..9658e0c011d 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -162,7 +162,8 @@ import { type DemoStaffRefusal, } from './demo-staff.js'; import { cloudManagedRefusal } from './cloud-managed.js'; -import { identitySourceUnreadable, judgeSsoOnlyLocalPassword, ssoOnlyPasswordRefusal } from './sso-only-local-password.js'; +import { identitySourceUnreadable, judgeSsoOnlyLocalPassword, readUserSource, ssoOnlyPasswordRefusal } from './sso-only-local-password.js'; +import { isPendingSsoSource, pendingSsoPasswordRefusal } from './pending-sso-marker.js'; import { registerCopyInvitationLinkAction } from './invitation-link-action.js'; import { ALLOWED_IP_RANGES_ENV, @@ -184,6 +185,8 @@ import { runAdminUnbanUser, type AdminBanEndpointDeps, } from './admin-ban-endpoints.js'; +import { engineUserBanWriter, type UserBanEngine } from './user-ban-write.js'; +import type { EnvironmentUserHostAccessor } from './environment-user-host.js'; /** @@ -378,6 +381,19 @@ export interface AuthPluginOptions extends Partial { */ hostSignInHandoff?: boolean; + /** + * [#33181] The environment-user host (`environment-user-host.ts`): told + * after a person is added through `admin/add-sso-user` or + * `admin/import-sso-users`, and asked before a person is deactivated + * through `admin/ban-user` or reactivated through `admin/unban-user`. Read + * per call, so a host wired after boot is still found. A typed + * `EnvironmentUserHostRefusal` refuses the operation (a refused add is + * taken back out); any other failure refuses a deactivation (`503`) and is + * reported on an add or a reactivation as `host: { notified: false, + * reason }`, which it never undoes. + */ + environmentUserHost?: EnvironmentUserHostAccessor; + /** * Direct sign-in (`direct-sign-in.ts`): a person who opens the deployment * signed out goes straight to the identity provider and returns to the page @@ -4097,7 +4113,23 @@ export class AuthPlugin implements Plugin { } } } - const { status, body } = await runSetInitialPassword(authApi as any, c.req.raw); + // A pending person (`idp_pending`, `pending-sso-marker.ts`) signs in + // only through the hosting organisation's identity provider and is + // given no local password, in every mode and with no exception — a + // platform administrator's standing included. Such a row is refused a + // session too (`user-session-admission.ts`); this arm holds the door on + // its own, whatever session reaches it. Judged once the body holds a password and + // before anything is written; a source that cannot be read is judged + // by the arms above as before. + const { status, body } = await runSetInitialPassword(authApi as any, c.req.raw, { + beforeWrite: async () => { + const session: SessionRead | null = await authApi.getSession(inProcessSessionReadInput(c.req.raw.headers)); + const callerId = session?.user?.id; + if (!callerId) return undefined; + const source = await readUserSource(this.authManager!.getDataEngine(), String(callerId)); + return source.ok && isPendingSsoSource(source.value) ? pendingSsoPasswordRefusal('setInitialPassword') : undefined; + }, + }); return c.json(body, status); } catch (error) { const err = error instanceof Error ? error : new Error(String(error)); @@ -4857,35 +4889,32 @@ export class AuthPlugin implements Plugin { // break-glass last-local-credential guard used to fire on // `/admin/ban-user` from `auth-manager.ts`. `runAdminBanUser` re-runs it // from the shared module. + // [#33181] Without the vendor admin plugin (a Free or Team hosted + // environment, where it mounts only with SCIM) the ban columns are not + // fields of better-auth's user model, so the write goes through the data + // engine, and the session refusal in `user-session-admission.ts` + // enforces the ban with the vendor's own answer. With the plugin + // mounted, nothing changes: the `internalAdapter` writes and the + // vendor's hook enforces. const adminBanDeps = (): AdminBanEndpointDeps => ({ getAuthContext: () => this.authManager!.getAuthContext(), + getBanWriter: async () => { + if (await this.authManager!.isAdminPluginMounted()) return undefined; + const engine = this.authManager!.getDataEngine() as UserBanEngine | undefined; + if (!engine || typeof engine.update !== 'function') { + throw new Error('The data engine is not available, so the ban could not be written'); + } + return engineUserBanWriter(engine); + }, + ...(this.options.environmentUserHost ? { host: this.options.environmentUserHost } : {}), + getDataEngine: () => this.authManager!.getDataEngine(), + logger: ctx.logger, }); - /** - * Refuse when the admin plugin is off, exactly as create-user does. - * - * Without this the shadowing mounts would answer 200 on a deployment - * that has no admin plugin — writing `banned: true` while the vendor's - * session hook that ENFORCES a ban is not loaded. That is a - * declared-but-not-enforced ban: the console reports success and the - * banned user signs straight back in. `banUser` on the api surface is - * the same seam create-user tests for. - */ - const adminPluginMissing = async (c: any): Promise => { - const authApi: any = await this.authManager!.getApi(); - if (typeof authApi.banUser === 'function') return undefined; - return c.json( - { success: false, error: { code: 'NOT_IMPLEMENTED', message: 'The better-auth admin plugin is not enabled (auth.plugins.admin)' } }, - 501, - ); - }; - rawApp.post(`${basePath}/admin/ban-user`, async (c: any) => { try { const actor = await gateAdmin(c); if (actor instanceof Response) return actor; - const unavailable = await adminPluginMissing(c); - if (unavailable) return unavailable; // Attributed to the admin for the same reason create-user is: the // write is driven server-side and never passes through // `AuthManager.handleRequest`, so the request-scoped actor seam is @@ -4905,8 +4934,6 @@ export class AuthPlugin implements Plugin { try { const actor = await gateAdmin(c); if (actor instanceof Response) return actor; - const unavailable = await adminPluginMissing(c); - if (unavailable) return unavailable; const { status, body } = await runAttributedToUser(actor, () => runAdminUnbanUser(adminBanDeps(), actor, c.req.raw), ); @@ -5136,6 +5163,69 @@ export class AuthPlugin implements Plugin { return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: INTERNAL_ERROR_MESSAGE } }, 500); } }); + + // ── [#33181] Add / import a pending, SSO-only person (managed only) ── + // + // On a cloud-managed environment the people who sign in come through + // the hosting organisation's identity provider, so `create-user` / + // `import-users` answer 409 there. These two doors are the managed + // way to add someone: the row reads `idp_pending` (no password, no + // session) until the person's first platform sign-in binds to it. + // Off managed they answer 409, the mirror image. Logic, the marker + // and the host seam: `pending-sso-users.ts`. Gate and attribution are + // create-user's. + const pendingSsoUserDeps = (c: any): import('./pending-sso-users.js').PendingSsoUserDeps => ({ + isCloudManaged: () => isCloudManaged(), + getDataEngine: () => this.authManager!.getDataEngine() as any, + createGrant: createGrantFor(c), + getAddMember: async () => { + const authApi: any = await this.authManager!.getApi(); + return typeof authApi.addMember === 'function' ? authApi.addMember.bind(authApi) : undefined; + }, + getTenancy: () => this.tenancy ?? undefined, + getMembershipPolicy: () => this.authManager!.getMembershipPolicy(), + getCallerActiveOrganizationId: async () => { + const authApi: any = await this.authManager!.getApi(); + const session = (await authApi.getSession(inProcessSessionReadInput(c.req.raw.headers))) as + | { session?: { activeOrganizationId?: string | null } } + | null; + return session?.session?.activeOrganizationId ?? null; + }, + ...(this.options.environmentUserHost ? { host: this.options.environmentUserHost } : {}), + logger: ctx.logger, + }); + + rawApp.post(`${basePath}/admin/add-sso-user`, async (c: any) => { + try { + const actor = await gateAdmin(c); + if (actor instanceof Response) return actor; + const { runAddSsoUser } = await import('./pending-sso-users.js'); + const { status, body } = await runAttributedToUser(actor, () => + runAddSsoUser(pendingSsoUserDeps(c), 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] admin/add-sso-user failed', err); + return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: INTERNAL_ERROR_MESSAGE } }, 500); + } + }); + + rawApp.post(`${basePath}/admin/import-sso-users`, async (c: any) => { + try { + const actor = await gateAdmin(c); + if (actor instanceof Response) return actor; + const { runImportSsoUsers } = await import('./pending-sso-users.js'); + const { status, body } = await runAttributedToUser(actor, () => + runImportSsoUsers(pendingSsoUserDeps(c), 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] admin/import-sso-users failed', err); + return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: INTERNAL_ERROR_MESSAGE } }, 500); + } + }); } // ──────────────────────────────────────────────────────────────────── 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 e96617a3e78..6278391c6d9 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 @@ -273,7 +273,14 @@ describe('auth route ledger hygiene', () => { // catch-all), and the `live.has(route)` loop below holds them to the same // proof — better-auth's own withdraw is `/oauth2/delete-consent`, a // different path. + // [#33181] Both pending-person doors, on this pin's own terms: + // `auth-plugin.ts` mounts each itself (a `rawApp.post` on the + // `${basePath}/admin/add-sso-user` and `${basePath}/admin/import-sso-users` + // templates), and the `live.has(route)` loop below holds them to the same + // proof — better-auth serves neither. + 'POST /api/v1/auth/admin/add-sso-user', 'POST /api/v1/auth/admin/authorized-clients/withdraw', + 'POST /api/v1/auth/admin/import-sso-users', 'POST /api/v1/auth/admin/import-users', // On this pin's own terms: `auth-plugin.ts` mounts it itself (a // `rawApp.post` on the `${basePath}/admin/list-platform-admins` diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.ts index af9f964c075..47ee1c7e57e 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.ts @@ -256,6 +256,10 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [ // #16678 note below. { route: 'GET /api/v1/auth/admin/client-address', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the console\'s Authentication settings page reads it beside the Allowed IP ranges field. Answers { clientAddress, trustProxy }: the caller\'s address exactly as the allowed_ip_ranges save check and the sign-in gate judge it (the save check\'s own call to AuthManager.resolveClientAddress, server.trustProxy deciding whether forwarded headers count), null when the server cannot establish one; Cache-Control: no-store; closed, empty query set; platform-admin gated (ADR-0068), ADR-0069 D5' }, { route: 'POST /api/v1/auth/admin/import-users', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — objectui app-shell\'s identity-import wizard (views/identityImport.ts) posts it directly from the Users list; platform-admin gated (ADR-0068). A dedicated identity-import door rather than the generic sys_user import, because a direct ObjectQL write would bypass better-auth\'s password hashing and mint no sys_account credential' }, + // #33181 — the tracker id stays HERE and never in the `note` string, per the + // #16678 note below. + { route: 'POST /api/v1/auth/admin/add-sso-user', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — Setup → Users on a cloud-managed environment posts it; adds one person who signs in only through the hosting organisation identity provider: a sys_user row marked idp_pending (no password, refused a session) with optional positions, permission sets and manager, joined to the organization; 201, or 200 alreadyPending for a person already pending (the host is told again); 409 RESOURCE_CONFLICT off a managed environment or for an address already in use; closed body key set; the environment-user host is told after the write commits, and its answer rides host; platform-admin gated (ADR-0068)' }, + { route: 'POST /api/v1/auth/admin/import-sso-users', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — Setup → Users on a cloud-managed environment posts it; the CSV or JSON twin of admin/add-sso-user (columns email, name, positions, permission_sets, manager_id), at most 500 rows, each judged and written on its own so a bad row fails alone; answers a summary and one result per row; 409 RESOURCE_CONFLICT off a managed environment; platform-admin gated (ADR-0068)' }, { route: 'POST /api/v1/auth/admin/list-platform-admins', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_user list_platform_admins action posts it directly from the Users list; answers who holds platform-admin standing (the last-admin guard\'s enumerator, each id confirmed by hasPlatformAdminStanding), served only to a caller who holds that standing; reads no body. ADR-0095 D3' }, { route: 'POST /api/v1/auth/admin/oauth2/toggle-disabled', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_oauth_application disable/enable actions post it directly; ObjectStack mount closing a vendor gap (better-auth\'s /admin/oauth2/update-client strips `disabled` from its body schema), platform-admin gated (ADR-0068)' }, // #30958 — the tracker id stays HERE and never in the `note` string, per the diff --git a/packages/plugins/plugin-auth/src/cloud-managed.ts b/packages/plugins/plugin-auth/src/cloud-managed.ts index 12853f23794..749f8fc4dcc 100644 --- a/packages/plugins/plugin-auth/src/cloud-managed.ts +++ b/packages/plugins/plugin-auth/src/cloud-managed.ts @@ -6,8 +6,9 @@ * * A hosted environment is managed (the maintainer's ruling on * objectstack-ai/cloud#3132, cloud ADR-0024 D5.2, mirrored here as ADR-0135 - * D5.2): the organisation that hosts it invites its people in the cloud, their - * accounts arrive through the cloud's identity provider, and authorization — + * D5.2): its people sign in through the hosting organisation's identity + * provider — added ahead of their first sign-in in Setup → Users as pending + * people (#33181, `pending-sso-users.ts`), or arriving on it — and authorization — * positions, permission sets — stays in the environment. Whether this process * is one is `isCloudManaged()` from `@objectstack/core` (`OS_CLOUD_MANAGED=1` * on the cloud's containers); every door below asks it and nothing else. @@ -35,23 +36,29 @@ export const CLOUD_MANAGED_REFUSAL_STATUS = 409; /** One message per door, keyed by the door. */ export const CLOUD_MANAGED_REFUSAL_MESSAGES = { + // [#33181] The four sentences below point to Setup → Users, where a + // managed environment now adds a person (`admin/add-sso-user`, + // `admin/import-sso-users`): the person signs in through the hosting + // organisation's identity provider. Kept together so the wording can be + // swapped in one place. invitation: - 'This environment is cloud-managed: the people who use it are invited by the organisation that hosts it, in the cloud, ' - + 'so an invitation cannot be created here. Invite them from the organisation in the cloud console; their account ' - + 'arrives on their first sign-in. No invitation was created.', + 'This environment is cloud-managed: the people who use it sign in through the identity provider of the organisation ' + + 'that hosts it, so an invitation cannot be created here. Add them in Setup → Users instead; they sign in through ' + + 'that identity provider. No invitation was created.', // [#27843] `sys_invitation.copy_invitation_link`: the invitation's accept - // link, which the hosting organisation's cloud invitation replaces here. + // link, which adding the person in Setup → Users replaces here. invitationLink: - 'This environment is cloud-managed: the people who use it are invited by the organisation that hosts it, in the cloud, ' - + 'so an invitation link is not handed out here. Invite them from the organisation in the cloud console; their account ' - + 'arrives on their first sign-in. No link was returned.', + 'This environment is cloud-managed: the people who use it sign in through the identity provider of the organisation ' + + 'that hosts it, so an invitation link is not handed out here. Add them in Setup → Users instead; they sign in ' + + 'through that identity provider. No link was returned.', createUser: - 'This environment is cloud-managed: its users are invited by the organisation that hosts it, in the cloud, so a ' - + 'local user cannot be created here. Invite the person from the organisation in the cloud console; their account ' - + 'arrives on their first sign-in. No user was created.', + 'This environment is cloud-managed: its users sign in through the identity provider of the organisation that hosts ' + + 'it, so a user with a local password cannot be created here. Add the person in Setup → Users instead; they sign ' + + 'in through that identity provider. No user was created.', importUsers: - 'This environment is cloud-managed: its users are invited by the organisation that hosts it, in the cloud, so users ' - + 'cannot be imported here. Invite them from the organisation in the cloud console. No user was imported.', + 'This environment is cloud-managed: its users sign in through the identity provider of the organisation that hosts ' + + 'it, so users with local passwords cannot be imported here. Import them in Setup → Users instead; they sign in ' + + 'through that identity provider. No user was imported.', setUserPassword: "This environment is cloud-managed and this user signs in through the hosting organisation's identity provider, so " + 'their password is managed there. A password can be set here only on a local account (source env_native), such ' diff --git a/packages/plugins/plugin-auth/src/environment-user-host.ts b/packages/plugins/plugin-auth/src/environment-user-host.ts new file mode 100644 index 00000000000..f65f38f2b6f --- /dev/null +++ b/packages/plugins/plugin-auth/src/environment-user-host.ts @@ -0,0 +1,248 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The host seam for environment users: a host (the cloud, on a hosted + * environment) is told when a person is added, deactivated or reactivated, so + * it can forward an invitation or a removal. See `pending-sso-users.ts` for + * the add half and `admin-ban-endpoints.ts` for the deactivate / reactivate + * half. + * + * Two kinds of host failure are told apart: + * + * - a **typed refusal** ({@link EnvironmentUserHostRefusal}: an organization + * owner or admin who cannot be removed from the environment side (`409`), + * or the developer organization's member cap (`403` + * `DEVELOPER_ORGANIZATION_MEMBER_LIMIT_REACHED`)) is the host saying the + * operation must not happen. Deactivation and reactivation ask the host + * BEFORE their write, so a refusal leaves the row as it was; an add asks + * after its write and undoes that one person. The door answers with the + * host's own status, code and sentence. + * - any other throw (the host is unreachable, times out, fails) is logged at + * `warn`. On a deactivation it refuses the deactivation (`503`, nothing + * written): only the host can say whether the person is an organization + * owner or admin, whom ruling 5 keeps out of reach from the environment + * side. On an add or a reactivation it never undoes or blocks the + * operation: the answer carries `host: { notified: false, reason: + * 'host_failed' }`. + * + * The host is never called inside a database transaction: each door calls it + * outside its unit of work. + */ + +import { PLATFORM_IDP_PROVIDER_ID } from './implicit-account-linking.js'; + +/** What a host is told about one person. */ +export interface EnvironmentUserEvent { + userId: string; + email: string; + name: string; + /** The row's `sys_user.source` when the event fired (`idp_pending` for an added person). */ + source: string | null; + /** The administrator who acted: the session's user. */ + actorId: string; + /** + * The administrator at the keyboard when the session is an impersonation + * (`session.impersonatedBy`, read from the session, never the request); + * absent otherwise. The host attributes the operation to this person. + * A session minted by a host's own sign-in handoff carries no record of + * who entered through it: the host that minted it attributes those. + */ + impersonatedBy?: string; + /** + * The administrator's cloud user id: the `account_id` of their linked + * `objectstack-cloud` account, read from `sys_account` on every call and + * never from the request. Absent when they hold no such link (a + * self-hosted deployment, or a local administrator). + */ + actorCloudUserId?: string; + /** + * ISO-8601 time the host was called: after the person was written for an + * add, before the ban or unban is written for a deactivation or + * reactivation. + */ + occurredAt: string; +} + +/** + * The host's side of the seam. `userAdded` is called after the person is + * written; `userDeactivated` and `userReactivated` before the ban or unban is + * written. A member that throws {@link EnvironmentUserHostRefusal} refuses + * the operation. Any other throw refuses a deactivation (`503`) and is + * reported on the answer for an add or a reactivation, which it never undoes + * or blocks. + */ +export interface EnvironmentUserHost { + /** A person was added (or re-added while still pending) to this environment. */ + userAdded(event: EnvironmentUserEvent): void | Promise; + /** A person was deactivated (`admin/ban-user`). */ + userDeactivated(event: EnvironmentUserEvent): void | Promise; + /** A person was reactivated (`admin/unban-user`). */ + userReactivated(event: EnvironmentUserEvent): void | Promise; +} + +/** + * How the plugin reaches the host: read per call, so a host wired late is still + * found. An accessor that answers no host is treated as no host wired, and a + * deactivation then goes ahead. A managed host must therefore answer a host or + * throw; it must never answer `undefined` while it is still starting. + */ +export type EnvironmentUserHostAccessor = () => + | EnvironmentUserHost + | undefined + | Promise; + +/** The statuses a host may refuse with: an owner / admin conflict, or the member cap. */ +export type EnvironmentUserHostRefusalStatus = 403 | 409; + +const REFUSAL_BRAND = Symbol.for('objectstack.environmentUserHostRefusal'); + +/** + * Thrown by a host member to refuse the operation, with the answer the door + * gives: the status (`409` for an organization owner or admin, `403` for the + * member cap), the machine code and the sentence the administrator reads. + * Recognised by a registered symbol, so a host built against another copy of + * this package is still understood. + */ +export class EnvironmentUserHostRefusal extends Error { + readonly [REFUSAL_BRAND] = true; + constructor( + readonly status: EnvironmentUserHostRefusalStatus, + readonly code: string, + message: string, + ) { + super(message); + this.name = 'EnvironmentUserHostRefusal'; + } +} + +/** Whether `error` is a host's typed refusal with a status the seam honours. */ +export function isEnvironmentUserHostRefusal(error: unknown): error is EnvironmentUserHostRefusal { + if (!error || typeof error !== 'object' || (error as Record)[REFUSAL_BRAND] !== true) return false; + const { status, code, message } = error as { status?: unknown; code?: unknown; message?: unknown }; + return (status === 403 || status === 409) && typeof code === 'string' && code.length > 0 && typeof message === 'string'; +} + +/** What a door answers about the host call, on the row it concerns. */ +export type EnvironmentUserHostOutcome = + | { notified: true } + | { notified: false; reason: 'no_host' | 'host_failed' }; + +/** A host's typed refusal, as the door answers it. */ +export interface EnvironmentUserHostRefused { + refused: { status: EnvironmentUserHostRefusalStatus; code: string; message: string }; +} + +export type EnvironmentUserEventKind = 'added' | 'deactivated' | 'reactivated'; + +const HOST_MEMBER: Record = { + added: 'userAdded', + deactivated: 'userDeactivated', + reactivated: 'userReactivated', +}; + +/** The engine slice the actor's cloud id is read through. */ +export interface ActorCloudIdReader { + find(objectName: string, query?: unknown): Promise; +} + +/** + * The acting administrator's cloud user id: the `account_id` of their + * `sys_account` row for the platform identity provider. Never read from + * request input. `undefined` when there is no such link, and when the read + * fails (logged): the host then sees no cloud actor and decides itself. + */ +export async function readActorCloudUserId( + engine: ActorCloudIdReader | undefined | null, + actorId: string, + logger?: { warn(msg: string): void }, +): Promise { + if (!engine) return undefined; + try { + const rows = await engine.find('sys_account', { + where: { user_id: actorId, provider_id: PLATFORM_IDP_PROVIDER_ID }, + fields: ['account_id'], + limit: 1, + context: { isSystem: true, positions: [], permissions: [] }, + }); + const accountId = Array.isArray(rows) ? (rows[0] as { account_id?: unknown } | undefined)?.account_id : undefined; + return typeof accountId === 'string' && accountId.length > 0 ? accountId : undefined; + } catch (error) { + logger?.warn( + `[AuthPlugin] the linked cloud account of administrator ${actorId} could not be read, so the environment-user ` + + `host is told without their cloud id. Cause: ${describe(error)}`, + ); + return undefined; + } +} + +/** The acting administrator, as the platform-admin gate admits them. */ +export interface EnvironmentUserActor { + id: string; + /** Present on an impersonation session: the administrator at the keyboard. */ + impersonatedBy?: string; +} + +/** The event's attribution fields for `actor`: never read from the request. */ +export async function environmentUserAttribution( + engine: ActorCloudIdReader | undefined | null, + actor: EnvironmentUserActor, + logger?: { warn(msg: string): void }, +): Promise> { + const actorCloudUserId = await readActorCloudUserId(engine, actor.id, logger); + const impersonatedBy = + typeof actor.impersonatedBy === 'string' && actor.impersonatedBy.trim() !== '' ? actor.impersonatedBy.trim() : undefined; + return { + actorId: actor.id, + ...(actorCloudUserId ? { actorCloudUserId } : {}), + ...(impersonatedBy ? { impersonatedBy } : {}), + }; +} + +/** + * Tell the host, once. Never throws. A typed refusal is answered as + * `{ refused }` for the door to return; any other failure as `host_failed` + * on the caller's row, logged at `warn` with its message. + */ +export async function notifyEnvironmentUserHost( + accessor: EnvironmentUserHostAccessor | undefined, + kind: EnvironmentUserEventKind, + event: EnvironmentUserEvent, + logger?: { warn(msg: string): void }, +): Promise { + let host: EnvironmentUserHost | undefined; + try { + host = await accessor?.(); + } catch (error) { + logger?.warn( + `[AuthPlugin] the environment-user host could not be resolved, so it was not told that user ${event.userId} ` + + `was ${kind}. ${goesAhead(kind)} Cause: ${describe(error)}`, + ); + return { notified: false, reason: 'host_failed' }; + } + const member = host?.[HOST_MEMBER[kind]]; + if (typeof member !== 'function') return { notified: false, reason: 'no_host' }; + try { + await member.call(host, event); + return { notified: true }; + } catch (error) { + if (isEnvironmentUserHostRefusal(error)) { + return { refused: { status: error.status, code: error.code, message: error.message } }; + } + logger?.warn( + `[AuthPlugin] the environment-user host refused or failed to take the news that user ${event.userId} was ` + + `${kind}. ${goesAhead(kind)} The answer says so. ` + + (kind === 'added' ? 'Adding the person again while they are still pending tells the host again. ' : '') + + `Cause: ${describe(error)}`, + ); + return { notified: false, reason: 'host_failed' }; + } +} + +const goesAhead = (kind: EnvironmentUserEventKind): string => + kind === 'added' + ? 'The addition itself stands.' + : kind === 'deactivated' + ? 'The deactivation is refused: only the host can say whether this person may be removed.' + : 'The change goes ahead.'; + +const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error)); diff --git a/packages/plugins/plugin-auth/src/implicit-account-linking.test.ts b/packages/plugins/plugin-auth/src/implicit-account-linking.test.ts index 7309f7e2b41..fc22a6bdb0d 100644 --- a/packages/plugins/plugin-auth/src/implicit-account-linking.test.ts +++ b/packages/plugins/plugin-auth/src/implicit-account-linking.test.ts @@ -731,6 +731,145 @@ describe('implicit link on external sign-in, end to end', () => { }); }); +// ───────────────────────────────────────────────────────────────────────────── +// [#33181] A pending person's first platform sign-in +// ───────────────────────────────────────────────────────────────────────────── + +describe('a pending person signs in through the platform identity provider', () => { + /** A row as `admin/add-sso-user` leaves one: no credential, unverified, `idp_pending`. */ + const pendingRow = async (manager: AuthManager, engine: any, email: string) => { + await signUp(manager, email); + const user = userRow(engine, email); + engine.tables.set( + 'sys_account', + (engine.tables.get('sys_account') ?? []).filter((a: any) => !(a.user_id === user.id && a.provider_id === 'credential')), + ); + engine.tables.set('sys_session', (engine.tables.get('sys_session') ?? []).filter((s: any) => s.user_id !== user.id)); + user.source = 'idp_pending'; + user.email_verified = false; + return user; + }; + const sessionsOf = (engine: any, userId: string) => + (engine.tables.get('sys_session') ?? []).filter((s: any) => s.user_id === userId); + + it('binds to the pending row, clears the marker and opens the session', async () => { + const engine = createMemoryEngine(); + const manager = makeManager(engine); + const email = 'pending.bind@example.test'; + const user = await pendingRow(manager, engine, email); + idpProfile[PLATFORM_IDP_PROVIDER_ID] = { sub: 'cloud-pending-1', email, email_verified: true }; + + const target = await oauthRoundTrip(manager, PLATFORM_IDP_PROVIDER_ID, 'sign-in/social'); + + expect(target.searchParams.get('error')).toBeNull(); + expect(accountsOf(engine, user.id, PLATFORM_IDP_PROVIDER_ID)).toHaveLength(1); + expect((engine.tables.get('sys_user') ?? []).filter((u: any) => u.email === email)).toHaveLength(1); + expect(userRow(engine, email).source).toBe('idp_provisioned'); + expect(sessionsOf(engine, user.id)).toHaveLength(1); + }); + + it('an enterprise provider does not bind to the pending row, which stays pending with no session', async () => { + const engine = createMemoryEngine(); + const manager = makeManager(engine); + const email = 'pending.enterprise@example.test'; + const user = await pendingRow(manager, engine, email); + idpProfile[EXTERNAL] = { sub: 'ext-pending-1', email, email_verified: true }; + + const target = await oauthRoundTrip(manager, EXTERNAL, 'sign-in/social'); + + expect(target.searchParams.get('error')).toBe(IMPLICIT_LINK_REFUSED); + expect(accountsOf(engine, user.id, EXTERNAL)).toHaveLength(0); + expect(userRow(engine, email).source).toBe('idp_pending'); + expect(sessionsOf(engine, user.id)).toHaveLength(0); + }); + + it('a session minted for the pending row by any other channel is refused, and the row stays pending', async () => { + const engine = createMemoryEngine(); + const manager = makeManager(engine); + const email = 'pending.minted@example.test'; + const user = await pendingRow(manager, engine, email); + const ctx: any = await manager.getAuthContext(); + + await expect(ctx.internalAdapter.createSession(user.id)).rejects.toMatchObject({ + statusCode: 403, + body: expect.objectContaining({ code: 'PERMISSION_DENIED' }), + }); + expect(sessionsOf(engine, user.id)).toHaveLength(0); + expect(userRow(engine, email).source).toBe('idp_pending'); + }); + + it('a link from a provider other than the platform one leaves the marker, so no session opens', async () => { + const engine = createMemoryEngine(); + const manager = makeManager(engine); + const email = 'pending.verified@example.test'; + const user = await pendingRow(manager, engine, email); + setVerified(engine, email, true); + idpProfile[EXTERNAL] = { sub: 'ext-pending-verified', email, email_verified: true }; + + await oauthRoundTrip(manager, EXTERNAL, 'sign-in/social'); + + expect(userRow(engine, email).source).toBe('idp_pending'); + expect(sessionsOf(engine, user.id)).toHaveLength(0); + }); + + it('CONTROL: the platform link on the same verified pending row clears the marker and opens the session', async () => { + const engine = createMemoryEngine(); + const manager = makeManager(engine); + const email = 'pending.verified.platform@example.test'; + const user = await pendingRow(manager, engine, email); + setVerified(engine, email, true); + idpProfile[PLATFORM_IDP_PROVIDER_ID] = { sub: 'cloud-pending-verified', email, email_verified: true }; + + expect((await oauthRoundTrip(manager, PLATFORM_IDP_PROVIDER_ID, 'sign-in/social')).searchParams.get('error')).toBeNull(); + + expect(userRow(engine, email).source).toBe('idp_provisioned'); + expect(sessionsOf(engine, user.id)).toHaveLength(1); + }); + + it('a pending row that already holds its platform account (its stamp did not land) is stamped and admitted', async () => { + const engine = createMemoryEngine(); + const manager = makeManager(engine); + const email = 'pending.missed.stamp@example.test'; + const user = await pendingRow(manager, engine, email); + const accounts = engine.tables.get('sys_account') ?? []; + accounts.push({ id: 'acc-missed-stamp', user_id: user.id, provider_id: PLATFORM_IDP_PROVIDER_ID, account_id: 'cloud-missed-1' }); + engine.tables.set('sys_account', accounts); + const ctx: any = await manager.getAuthContext(); + + await ctx.internalAdapter.createSession(user.id); + + expect(sessionsOf(engine, user.id)).toHaveLength(1); + expect(userRow(engine, email).source).toBe('idp_provisioned'); + }); + + it('CONTROL: a pending row holding only another provider\'s account is still refused', async () => { + const engine = createMemoryEngine(); + const manager = makeManager(engine); + const email = 'pending.other.account@example.test'; + const user = await pendingRow(manager, engine, email); + const accounts = engine.tables.get('sys_account') ?? []; + accounts.push({ id: 'acc-other', user_id: user.id, provider_id: EXTERNAL, account_id: 'ext-other-1' }); + engine.tables.set('sys_account', accounts); + const ctx: any = await manager.getAuthContext(); + + await expect(ctx.internalAdapter.createSession(user.id)).rejects.toMatchObject({ statusCode: 403 }); + expect(userRow(engine, email).source).toBe('idp_pending'); + }); + + it('CONTROL: the same mint for an idp_provisioned row and an env_native row opens a session', async () => { + const engine = createMemoryEngine(); + const manager = makeManager(engine); + const ctx: any = await manager.getAuthContext(); + const user = await pendingRow(manager, engine, 'control.mint@example.test'); + for (const source of ['idp_provisioned', 'env_native']) { + user.source = source; + const before = sessionsOf(engine, user.id).length; + await ctx.internalAdapter.createSession(user.id); + expect(sessionsOf(engine, user.id), source).toHaveLength(before + 1); + } + }); +}); + describe('with SSO domain verification on, an SSO sign-in reaches an existing account only with an address at a domain the provider has proven', () => { const PROVIDER = 'acme-okta'; const provenRow = { provider_id: PROVIDER, domain: 'acme.com', domain_verified: 1 }; diff --git a/packages/plugins/plugin-auth/src/implicit-account-linking.ts b/packages/plugins/plugin-auth/src/implicit-account-linking.ts index 20d63354d89..4308c632841 100644 --- a/packages/plugins/plugin-auth/src/implicit-account-linking.ts +++ b/packages/plugins/plugin-auth/src/implicit-account-linking.ts @@ -59,6 +59,20 @@ * write decision that cannot be read is judged as a write. Verification * off, a non-SSO source and an explicit link are not judged. * + * ## A pending person's first sign-in (#33181) + * + * A person added on a managed environment (`pending-sso-users.ts`) is a row + * with `emailVerified: false` and `source: 'idp_pending'`, and no account. + * Their first sign-in through the platform identity provider is rule 2's + * exception: the link attaches to that row, and the identity-source stamp in + * `account.create.after` (`stampIdentitySource`) moves it to + * `idp_provisioned` before the session that sign-in creates, which is how the + * pending marker clears. An enterprise provider gets no such link (rule 1), + * so the pending row waits for the platform sign-in. Measured on the + * installed version: the link lands whatever `email_verified` the identity + * provider asserts, and the row's `emailVerified` then follows the identity + * provider's value. + * * ## Why the enforcement point is `user.validateUserInfo` * * Measured against better-auth `1.7.12` (re-measured 2026-10-21 for #25096) diff --git a/packages/plugins/plugin-auth/src/index.ts b/packages/plugins/plugin-auth/src/index.ts index b8cd618be9d..3e2688922d5 100644 --- a/packages/plugins/plugin-auth/src/index.ts +++ b/packages/plugins/plugin-auth/src/index.ts @@ -93,6 +93,14 @@ export * from './platform-admin-gate.js'; // twin of one of these doors (the cloud's per-environment `set-initial-password`, // objectstack-ai/cloud#3169) answers with the same status, code and message. export * from './cloud-managed.js'; +// [#33181] Pending, SSO-only people on a managed environment: the add and +// import doors, the `idp_pending` marker and its refusals, and the host seam a +// hosting layer implements to hear about added, deactivated and reactivated +// people. +export * from './pending-sso-marker.js'; +export * from './environment-user-host.js'; +export * from './pending-sso-users.js'; + // Direct sign-in: the `directSignIn` option's shape, for a host that sets it. export type { DirectSignInOptions, DirectSignInLocalPath } from './direct-sign-in.js'; export * from './last-local-credential.js'; diff --git a/packages/plugins/plugin-auth/src/password-reset-ends-sessions.test.ts b/packages/plugins/plugin-auth/src/password-reset-ends-sessions.test.ts index 815772b18fa..940b6e3150e 100644 --- a/packages/plugins/plugin-auth/src/password-reset-ends-sessions.test.ts +++ b/packages/plugins/plugin-auth/src/password-reset-ends-sessions.test.ts @@ -38,6 +38,7 @@ import { describe, it, expect, afterAll, afterEach, beforeEach, vi } from 'vitest'; import { ObjectQL } from '@objectstack/objectql'; +import { PENDING_SSO_MESSAGES, PENDING_SSO_SOURCE } from './pending-sso-marker'; import { SqlDriver } from '@objectstack/driver-sql'; import { AuthManager } from './auth-manager.js'; import { runAdminSetUserPassword, type AdminUserEndpointDeps } from './admin-user-endpoints.js'; @@ -967,3 +968,87 @@ describe('SSO-only mode keeps IdP-provisioned users off local passwords at the r }, 60_000); }); }); + +// ───────────────────────────────────────────────────────────────────────────── +// [#33181] A pending person gets no password at the reset doors +// ───────────────────────────────────────────────────────────────────────────── + +describe('a pending, SSO-only person is refused at the reset doors', () => { + const PHONE = '+15550181'; + + async function userIdOf(engine: ObjectQL): Promise { + const [user] = (await engine.find('sys_user', { where: { email: EMAIL }, limit: 1 }, SYS)) as Array<{ id: string }>; + return user.id; + } + + async function credentialOf(engine: ObjectQL): Promise<{ id: string } | undefined> { + const rows = (await engine.find( + 'sys_account', + { where: { user_id: await userIdOf(engine), provider_id: 'credential' } }, + SYS, + )) as Array<{ id: string }>; + return rows[0]; + } + + /** The staged account as `admin/add-sso-user` leaves one: `idp_pending`, no local credential. */ + async function markedPending(a: Account): Promise { + const id = await userIdOf(a.engine); + await a.engine.update('sys_user', { id, source: PENDING_SSO_SOURCE }, SYS); + const credential = await credentialOf(a.engine); + await a.engine.delete('sys_account', { where: { id: credential!.id }, context: { isSystem: true } } as never); + expect(await credentialOf(a.engine), 'fixture invariant: the pending person holds no credential').toBeUndefined(); + } + + async function expectPendingRefusal(res: Response): Promise { + const text = await res.clone().text(); + const body = JSON.parse(text) as { code?: unknown; message?: unknown }; + expect({ status: res.status, code: body.code, message: body.message }, text).toEqual({ + status: 409, + code: 'RESOURCE_CONFLICT', + message: PENDING_SSO_MESSAGES.resetPassword, + }); + } + + it('the emailed reset link refuses a pending person with 409 and writes no credential', async () => { + const a = await signedInAccount(); + const token = await requestResetToken(a); + await markedPending(a); + + await expectPendingRefusal(await post(a.manager, '/reset-password', { token, newPassword: SECOND })); + expect(await credentialOf(a.engine)).toBeUndefined(); + }, 60_000); + + it('the texted reset code refuses a pending person with 409 and writes no credential', async () => { + const a = await signedInAccount({ plugins: { phoneNumber: true } }); + const texts: Array<{ templateParams?: { code?: string } }> = []; + a.manager.setSmsService({ + async send(input: { templateParams?: { code?: string } }) { + texts.push(input); + return { id: `sms${texts.length}`, status: 'sent' }; + }, + isConfigured: () => true, + } as never); + await a.engine.update('sys_user', { id: await userIdOf(a.engine), phone_number: PHONE, phone_number_verified: true }, SYS); + const requested = await post(a.manager, '/phone-number/request-password-reset', { phoneNumber: PHONE }); + expect(requested.status, await requested.clone().text()).toBe(200); + await vi.waitFor(() => expect(texts.length).toBe(1)); + const otp = String(texts[0].templateParams?.code ?? ''); + await markedPending(a); + + await expectPendingRefusal( + await post(a.manager, '/phone-number/reset-password', { phoneNumber: PHONE, otp, newPassword: SECOND }), + ); + expect(await credentialOf(a.engine)).toBeUndefined(); + }, 60_000); + + it('CONTROL: the same reset for an env_native person who holds no password writes one, as before', async () => { + const a = await signedInAccount(); + const token = await requestResetToken(a); + const id = await userIdOf(a.engine); + await a.engine.update('sys_user', { id, source: 'env_native' }, SYS); + + const reset = await post(a.manager, '/reset-password', { token, newPassword: SECOND }); + expect(reset.status, await reset.clone().text()).toBe(200); + expect(await credentialOf(a.engine)).toBeDefined(); + }, 60_000); +}); diff --git a/packages/plugins/plugin-auth/src/pending-sso-marker.ts b/packages/plugins/plugin-auth/src/pending-sso-marker.ts new file mode 100644 index 00000000000..3f4595b7286 --- /dev/null +++ b/packages/plugins/plugin-auth/src/pending-sso-marker.ts @@ -0,0 +1,67 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The pending marker of a person added before their first sign-in on a + * cloud-managed environment, and the refusal every password door answers for + * it. The doors that add such a person, and why, are `pending-sso-users.ts`. + * A leaf module: the password doors import it without importing the doors. + * + * The sentences an administrator or a person reads are collected in + * {@link PENDING_SSO_MESSAGES} so the wording can move in one place. + */ + +import type { StandardErrorCode } from '@objectstack/spec/api'; + +/** The `sys_user.source` value of a person added here who has not signed in yet. */ +export const PENDING_SSO_SOURCE = 'idp_pending'; + +/** Is `source` the pending marker? */ +export function isPendingSsoSource(source: unknown): boolean { + return source === PENDING_SSO_SOURCE; +} + +/** The ADR-0112 code every pending refusal and conflict carries (registered; no code minted). */ +export const PENDING_SSO_REFUSAL_CODE: StandardErrorCode = 'RESOURCE_CONFLICT'; + +/** The status every pending refusal and conflict answers. */ +export const PENDING_SSO_REFUSAL_STATUS = 409; + +/** + * Every sentence this module's doors and refusals answer, in one place. + * Each says what was not done and what to do instead. + */ +export const PENDING_SSO_MESSAGES = { + notManaged: + "This environment is not cloud-managed, so there is no hosting organisation's sign-in for a pending person to " + + 'arrive through. Create the user with a password or an invitation instead (admin/create-user, ' + + 'admin/import-users). No user was added.', + alreadyExists: + 'A user with this email address already exists in this environment, so no one was added. Change the existing ' + + "user's positions, permission sets or manager on their record instead.", + setUserPassword: + "This person has not signed in yet: they were added to sign in through the hosting organisation's identity " + + 'provider, and a local password cannot be set for them. No password was changed.', + setInitialPassword: + "Your account was added to sign in through the hosting organisation's identity provider, so a local password " + + 'cannot be set for it. Sign in with single sign-on. No password was set.', + resetPassword: + "This account was added to sign in through the hosting organisation's identity provider, so it has no local " + + 'password to reset. Sign in with single sign-on. No password was set.', + session: + "This account was added to sign in through the hosting organisation's identity provider and has not done so " + + 'yet. Sign in with single sign-on first; until then no other sign-in method opens a session.', +} as const; + +/** The doors whose pending refusal is a `409` envelope. */ +export type PendingSsoPasswordDoor = 'setUserPassword' | 'setInitialPassword' | 'resetPassword'; + +/** The ADR-0112 envelope a raw route answers when `door` meets a pending row. */ +export function pendingSsoPasswordRefusal(door: PendingSsoPasswordDoor): { + status: typeof PENDING_SSO_REFUSAL_STATUS; + body: { success: false; error: { code: StandardErrorCode; message: string } }; +} { + return { + status: PENDING_SSO_REFUSAL_STATUS, + body: { success: false, error: { code: PENDING_SSO_REFUSAL_CODE, message: PENDING_SSO_MESSAGES[door] } }, + }; +} diff --git a/packages/plugins/plugin-auth/src/pending-sso-seams.test.ts b/packages/plugins/plugin-auth/src/pending-sso-seams.test.ts new file mode 100644 index 00000000000..e366593d6ba --- /dev/null +++ b/packages/plugins/plugin-auth/src/pending-sso-seams.test.ts @@ -0,0 +1,254 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#33181] The seams under the pending-person doors, one module at a time: +// the host notifier (fail-open, never throws), the session admission refusal +// (pending, banned without the admin plugin, a read that fails), the +// engine-backed ban writer, and the ban doors choosing their writer and +// telling the host. The doors end to end are pinned in +// `pending-sso-users.test.ts`. + +import { describe, it, expect, vi } from 'vitest'; +import { notifyEnvironmentUserHost, type EnvironmentUserEvent } from './environment-user-host'; +import { + BANNED_USER_SESSION_REFUSAL, + PENDING_SSO_SESSION_REFUSAL, + refuseInactiveUserSession, +} from './user-session-admission'; +import { USER_ROW_READ_FAULT_REFUSAL } from './service-account-identity'; +import { engineUserBanWriter } from './user-ban-write'; +import { runAdminBanUser, runAdminUnbanUser, type AuthBanContextLike } from './admin-ban-endpoints'; +import { isPendingSsoSource, pendingSsoPasswordRefusal, PENDING_SSO_MESSAGES, PENDING_SSO_SOURCE } from './pending-sso-marker'; + +const EVENT: EnvironmentUserEvent = { + userId: 'usr_1', + email: 'one@example.com', + name: 'One', + source: PENDING_SSO_SOURCE, + actorId: 'usr_admin', + occurredAt: '2026-11-14T00:00:00.000Z', +}; + +describe('[#33181] the environment-user host notifier', () => { + it('calls the member for the kind, once, and answers notified', async () => { + const host = { userAdded: vi.fn(), userDeactivated: vi.fn(), userReactivated: vi.fn() }; + expect(await notifyEnvironmentUserHost(() => host, 'deactivated', EVENT)).toEqual({ notified: true }); + expect(host.userDeactivated).toHaveBeenCalledExactlyOnceWith(EVENT); + expect(host.userAdded).not.toHaveBeenCalled(); + expect(host.userReactivated).not.toHaveBeenCalled(); + }); + + it('a host that throws is answered host_failed and logged, never rethrown', async () => { + const warn = vi.fn(); + const host = { userAdded: () => Promise.reject(new Error('cloud down')), userDeactivated: vi.fn(), userReactivated: vi.fn() }; + expect(await notifyEnvironmentUserHost(() => host, 'added', EVENT, { warn })).toEqual({ notified: false, reason: 'host_failed' }); + expect(warn).toHaveBeenCalledOnce(); + expect(String(warn.mock.calls[0]![0])).toContain('cloud down'); + }); + + it('an accessor that throws is answered host_failed too', async () => { + const outcome = await notifyEnvironmentUserHost(() => { + throw new Error('not wired yet'); + }, 'reactivated', EVENT); + expect(outcome).toEqual({ notified: false, reason: 'host_failed' }); + }); + + it('no accessor, or one that answers nothing, is answered no_host', async () => { + expect(await notifyEnvironmentUserHost(undefined, 'added', EVENT)).toEqual({ notified: false, reason: 'no_host' }); + expect(await notifyEnvironmentUserHost(() => undefined, 'added', EVENT)).toEqual({ notified: false, reason: 'no_host' }); + }); +}); + +/** An engine with one `sys_user` row; records updates. */ +function rowEngine( + row: Record | undefined, + opts: { readFails?: boolean; accounts?: Array> } = {}, +) { + const updates: Array> = []; + return { + updates, + find: vi.fn(async (object: string, query?: { where?: Record }) => { + if (opts.readFails) throw new Error('store down'); + if (object === 'sys_account') { + return (opts.accounts ?? []).filter((a) => + Object.entries(query?.where ?? {}).every(([k, v]) => { + // Scalar equality only: a combinator is refused, never read as a field name. + if (k.startsWith('$')) throw new Error(`rowEngine double: unsupported where operator ${k}`); + return a[k] === v; + }), + ); + } + return row ? [row] : []; + }), + update: vi.fn(async (_object: string, data: Record) => { + updates.push(data); + return data; + }), + }; +} + +describe('[#33181] the session admission refusal', () => { + const admitAll = { enforceBan: () => true }; + + it('refuses a pending row 403 PERMISSION_DENIED', async () => { + const engine = rowEngine({ id: 'u', source: PENDING_SSO_SOURCE }); + await expect(refuseInactiveUserSession(engine, { userId: 'u' }, admitAll)).rejects.toMatchObject({ + statusCode: 403, + body: expect.objectContaining({ code: 'PERMISSION_DENIED', message: PENDING_SSO_SESSION_REFUSAL.message }), + }); + }); + + it('refuses a banned row 403 BANNED_USER when it enforces bans, asking only for a banned row', async () => { + const enforceBan = vi.fn(() => true); + await expect( + refuseInactiveUserSession(rowEngine({ id: 'u', source: 'env_native', banned: true }), { userId: 'u' }, { enforceBan }), + ).rejects.toMatchObject({ + statusCode: 403, + body: expect.objectContaining({ code: 'BANNED_USER', message: BANNED_USER_SESSION_REFUSAL.message }), + }); + expect(enforceBan).toHaveBeenCalledOnce(); + + enforceBan.mockClear(); + await refuseInactiveUserSession(rowEngine({ id: 'u', source: 'env_native', banned: false }), { userId: 'u' }, { enforceBan }); + expect(enforceBan).not.toHaveBeenCalled(); + }); + + it('admits a banned row when the admin plugin decides instead', async () => { + const engine = rowEngine({ id: 'u', source: 'env_native', banned: true }); + await expect(refuseInactiveUserSession(engine, { userId: 'u' }, { enforceBan: () => false })).resolves.toBeUndefined(); + expect(engine.updates).toEqual([]); + }); + + it('lifts a ban whose expiry has passed and admits the session', async () => { + const engine = rowEngine({ id: 'u', banned: 1, ban_expires: new Date(Date.now() - 1000).toISOString() }); + await expect(refuseInactiveUserSession(engine, { userId: 'u' }, admitAll)).resolves.toBeUndefined(); + expect(engine.updates).toEqual([{ id: 'u', banned: false, ban_reason: null, ban_expires: null, updated_at: expect.any(Date) }]); + }); + + it('a ban whose expiry has not passed still refuses', async () => { + const engine = rowEngine({ id: 'u', banned: true, ban_expires: new Date(Date.now() + 60_000).toISOString() }); + await expect(refuseInactiveUserSession(engine, { userId: 'u' }, admitAll)).rejects.toMatchObject({ statusCode: 403 }); + expect(engine.updates).toEqual([]); + }); + + it('a read that fails refuses the session 503, never admits it', async () => { + await expect( + refuseInactiveUserSession(rowEngine(undefined, { readFails: true }), { userId: 'u' }, admitAll), + ).rejects.toMatchObject({ + statusCode: 503, + body: expect.objectContaining({ code: 'SERVICE_UNAVAILABLE', message: USER_ROW_READ_FAULT_REFUSAL.message }), + }); + }); + + it('CONTROL: env_native, idp_provisioned, a missing row and a missing engine are admitted', async () => { + for (const source of ['env_native', 'idp_provisioned', null]) { + await expect(refuseInactiveUserSession(rowEngine({ id: 'u', source }), { userId: 'u' }, admitAll)).resolves.toBeUndefined(); + } + await expect(refuseInactiveUserSession(rowEngine(undefined), { userId: 'u' }, admitAll)).resolves.toBeUndefined(); + await expect(refuseInactiveUserSession(undefined, { userId: 'u' }, admitAll)).resolves.toBeUndefined(); + }); +}); + +describe('[#33181] the engine-backed ban writer', () => { + it('lands the vendor-shaped ban write on the sys_user columns, as the system', async () => { + const engine = rowEngine(undefined); + const expires = new Date('2026-12-01T00:00:00.000Z'); + const updatedAt = new Date('2026-11-14T00:00:00.000Z'); + await engineUserBanWriter(engine).updateUser('u', { banned: true, banReason: 'r', banExpires: expires, updatedAt }); + expect(engine.update).toHaveBeenCalledWith( + 'sys_user', + { id: 'u', banned: true, ban_reason: 'r', ban_expires: expires, updated_at: updatedAt }, + { context: expect.objectContaining({ isSystem: true }) }, + ); + }); + + it('refuses a field that is not part of the ban write instead of guessing its column', async () => { + const engine = rowEngine(undefined); + await expect(engineUserBanWriter(engine).updateUser('u', { role: 'admin' })).rejects.toThrow(/not a ban field/); + expect(engine.update).not.toHaveBeenCalled(); + }); +}); + +describe('[#33181] the ban doors choose their writer and tell the host', () => { + const ADMIN = { id: 'usr_admin', email: 'admin@example.com' }; + const post = (body: unknown) => + new Request('http://local/api/v1/auth/admin/ban-user', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + const context = () => { + const vendorWrites: Array> = []; + const ctx: AuthBanContextLike = { + internalAdapter: { + findUserById: async (id) => ({ id, email: 'target@example.com', name: 'Target' }), + updateUser: async (_id, data) => void vendorWrites.push(data), + deleteUserSessions: async () => true, + }, + adapter: { findOne: async () => null, findMany: async () => [] }, + }; + return { ctx, vendorWrites }; + }; + + it('with a writer handed in, the ban and the unban land through it and not through the vendor adapter', async () => { + const { ctx, vendorWrites } = context(); + const writes: Array> = []; + const deps = { + getAuthContext: async () => ctx, + getBanWriter: async () => ({ updateUser: async (_id: string, data: Record) => void writes.push(data) }), + }; + expect((await runAdminBanUser(deps, ADMIN, post({ userId: 'usr_t' }))).status).toBe(200); + expect((await runAdminUnbanUser(deps, ADMIN, post({ userId: 'usr_t' }))).status).toBe(200); + expect(writes.map((w) => w.banned)).toEqual([true, false]); + expect(vendorWrites).toEqual([]); + }); + + it('CONTROL: a writer answering undefined (the admin plugin mounted) leaves the vendor adapter writing, and no host keeps the answer as it was', async () => { + const { ctx, vendorWrites } = context(); + const res = await runAdminBanUser({ getAuthContext: async () => ctx, getBanWriter: async () => undefined }, ADMIN, post({ userId: 'usr_t' })); + expect(res.status).toBe(200); + expect(vendorWrites.map((w) => w.banned)).toEqual([true]); + expect(res.body.data).not.toHaveProperty('host'); + }); + + it('with a host wired, a ban tells it deactivated and an unban reactivated, with the row\'s source', async () => { + const { ctx } = context(); + const host = { userAdded: vi.fn(), userDeactivated: vi.fn(), userReactivated: vi.fn() }; + const deps = { + getAuthContext: async () => ctx, + host: () => host, + getDataEngine: () => rowEngine({ id: 'usr_t', source: 'idp_provisioned' }), + }; + const banned = await runAdminBanUser(deps, ADMIN, post({ userId: 'usr_t' })); + const unbanned = await runAdminUnbanUser(deps, ADMIN, post({ userId: 'usr_t' })); + expect(banned.body.data).toMatchObject({ host: { notified: true } }); + expect(unbanned.body.data).toMatchObject({ host: { notified: true } }); + expect(host.userDeactivated).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'usr_t', email: 'target@example.com', source: 'idp_provisioned', actorId: ADMIN.id }), + ); + expect(host.userReactivated).toHaveBeenCalledOnce(); + }); +}); + +describe('[#33181] the pending marker', () => { + it('reads only its own value as pending', () => { + expect(isPendingSsoSource('idp_pending')).toBe(true); + for (const other of ['idp_provisioned', 'env_native', null, undefined, '']) expect(isPendingSsoSource(other)).toBe(false); + }); + + it('each password door answers 409 RESOURCE_CONFLICT with its own sentence', () => { + for (const door of ['setUserPassword', 'setInitialPassword', 'resetPassword'] as const) { + expect(pendingSsoPasswordRefusal(door)).toEqual({ + status: 409, + body: { success: false, error: { code: 'RESOURCE_CONFLICT', message: PENDING_SSO_MESSAGES[door] } }, + }); + } + }); + + it('the package entry exports the doors, the marker and the host seam', async () => { + const entry = await import('./index'); + expect(entry.PENDING_SSO_SOURCE).toBe('idp_pending'); + expect(typeof entry.runAddSsoUser).toBe('function'); + expect(typeof entry.runImportSsoUsers).toBe('function'); + expect(typeof entry.notifyEnvironmentUserHost).toBe('function'); + }); +}); diff --git a/packages/plugins/plugin-auth/src/pending-sso-users.test.ts b/packages/plugins/plugin-auth/src/pending-sso-users.test.ts new file mode 100644 index 00000000000..5b948143460 --- /dev/null +++ b/packages/plugins/plugin-auth/src/pending-sso-users.test.ts @@ -0,0 +1,985 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#33181] Pending, SSO-only people on a cloud-managed environment, on a +// kernel WITHOUT the better-auth admin plugin (a Free or Team hosted +// environment, where it mounts only with SCIM). +// +// `admin/add-sso-user` and `admin/import-sso-users` add a person ahead of +// their first sign-in: a `sys_user` row marked `idp_pending`, no password, +// with positions, permission sets and a manager. Every password door refuses +// that row, and so does session creation, until the first platform sign-in +// binds to it (pinned in `implicit-account-linking.test.ts`). `admin/ban-user` +// and `admin/unban-user` work without the admin plugin, and a banned row is +// refused a session. A host is told on add, deactivate and reactivate. +// +// Every door is driven through the REAL seam: a real `AuthManager` on the +// installed better-auth, behind `AuthPlugin.registerAuthRoutes` mounted on a +// real Hono app. Each refusal asserts the code AND the status, and that +// nothing was written; the CONTROL legs show `env_native` and +// `idp_provisioned` rows answered as before. + +import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; +import { Hono } from 'hono'; +import type { PluginContext } from '@objectstack/core'; +import { resetCloudManagedForTesting } from '@objectstack/core'; +import { AuthManager } from './auth-manager'; +import { AuthPlugin } from './auth-plugin'; +import { CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed'; +import { PENDING_SSO_MESSAGES, PENDING_SSO_SOURCE } from './pending-sso-marker'; +import { BANNED_USER_SESSION_REFUSAL, PENDING_SSO_SESSION_REFUSAL } from './user-session-admission'; +import { EnvironmentUserHostRefusal, type EnvironmentUserEvent, type EnvironmentUserHost } from './environment-user-host'; +import { runAdminUnbanUser } from './admin-ban-endpoints'; +import { runAddSsoUser } from './pending-sso-users'; +import { INTERNAL_ERROR_MESSAGE } from '@objectstack/types'; +import { createMemoryEngine } from './impersonation-bearer-rotation.test'; +import { inviteForAudienceGate } from './audience-gate-test-support'; + +const SECRET = 'test-secret-at-least-32-chars-long!!'; +const PASSWORD = 'S3cure!Passw0rd-33181'; +const NEW_PASSWORD = 'An0ther!Passw0rd-33181'; +const ORIGIN = 'http://localhost:3000'; +const BASE = '/api/v1/auth'; +const DEFAULT_ORG = 'org_default'; + +const MANAGED_ENV = 'OS_CLOUD_MANAGED'; +const SSO_ONLY_ENV = 'OS_AUTH_SSO_ONLY'; +const OWNER_ENV = 'OS_PLATFORM_OWNER_EMAIL'; +const savedEnv: Record = {}; + +const EMAILS = { + admin: 'admin.33181@example.com', + member: 'member.33181@example.com', + idp: 'idp.33181@example.com', +} as const; + +/** The managed switch, as the cloud's containers set it; off = unset, as on a self-hosted image. */ +function setManaged(on: boolean): void { + if (on) process.env[MANAGED_ENV] = '1'; + else delete process.env[MANAGED_ENV]; + // `isCloudManaged()` memoizes its first read (#25306), so every switch + // re-reads it; without this the first case's answer would stick. + resetCloudManagedForTesting(); +} + +beforeEach(() => { + for (const key of [MANAGED_ENV, SSO_ONLY_ENV, OWNER_ENV]) savedEnv[key] = process.env[key]; + setManaged(false); + delete process.env[SSO_ONLY_ENV]; + // The platform-admin standing the doors' gate judges, with the admin plugin + // off: the configured owner address on a verified row (ADR-0068). + process.env[OWNER_ENV] = EMAILS.admin; + vi.spyOn(console, 'info').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); +afterEach(() => { + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + resetCloudManagedForTesting(); + vi.restoreAllMocks(); +}); + +const mockCtx = (): PluginContext => + ({ + registerService: vi.fn(), + getService: vi.fn((name: string) => (name === 'manifest' ? { register: vi.fn() } : undefined)), + getServices: vi.fn(() => new Map()), + hook: vi.fn(), + trigger: vi.fn(), + logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }, + getKernel: vi.fn(), + }) as any; + +/** Status + the error code the body carries, in either envelope shape. */ +async function verdict(res: Response): Promise<{ status: number; code?: string; message?: string; text: string }> { + const text = await res.text(); + let code: string | undefined; + let message: string | undefined; + try { + const parsed = JSON.parse(text); + code = parsed?.error?.code ?? parsed?.code; + message = parsed?.error?.message ?? parsed?.message; + } catch { + /* non-JSON body → no code */ + } + return { status: res.status, code, message, text }; +} + +const singleOrgTenancy = () => + ({ + posture: 'single', + requestedPosture: 'single', + isolationActive: false, + requested: false, + degraded: false, + defaultOrgId: async () => DEFAULT_ORG, + }) as any; + +const makeManager = ( + engine: ReturnType, + adminPlugin: boolean, + extra: Record = {}, +) => + new AuthManager({ + secret: SECRET, + baseUrl: ORIGIN, + dataEngine: engine, + plugins: { admin: adminPlugin }, + membershipPolicy: 'auto', + getTenancy: () => singleOrgTenancy(), + ...extra, + } as any); + +/** + * The staged rows every door case starts from, produced ONCE for the file + * (#23181): staging signs three users up, and each sign-up is a fresh-salt + * production scrypt derivation, the cost that made fourteen identical + * stagings the bulk of this file's wall. Staged UNMANAGED (so the fixture + * users can sign up through the invitation lane), with SSO-only off. + * + * - `admin`: a platform admin (the legacy `role` scalar, which + * `isPlatformAdminUser` accepts) and the owner of the default organization, + * so it can reach invite-member, create-user, import-users and the + * password doors. + * - `member`: an ordinary `env_native` user holding a local password. + * - `idp`: an `idp_provisioned` user with no local credential, the + * population the cloud's identity provider owns. + * + * The bearers are the sessions better-auth minted at staging; they live as + * `sys_session` rows, so every copy of the tables carries them. + */ +async function produceStagedRows() { + const engine = createMemoryEngine(); + engine.tables.set('sys_organization', [{ id: DEFAULT_ORG, name: 'Default', slug: 'default' }]); + const manager = makeManager(engine, true); + + const direct = (path: string, body: unknown) => + manager.handleRequest( + new Request(`${ORIGIN}${BASE}${path}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }), + ); + + const emails = EMAILS; + for (const email of Object.values(emails)) { + const invitationId = await inviteForAudienceGate(manager, email); + const res = await direct('/sign-up/email', { email, password: PASSWORD, name: email, invitationId }); + expect(res.status, `sign-up ${email}: ${await res.clone().text()}`).toBe(200); + } + + const users = () => (engine.tables.get('sys_user') ?? []) as any[]; + const accounts = () => (engine.tables.get('sys_account') ?? []) as any[]; + const idFor = (email: string) => String(users().find((r) => r.email === email)!.id); + const ids = { admin: idFor(emails.admin), member: idFor(emails.member), idp: idFor(emails.idp) }; + + users().find((r) => String(r.id) === ids.admin)!.role = 'admin'; + const adminMembership = ((engine.tables.get('sys_member') ?? []) as any[]).find( + (m) => m.organization_id === DEFAULT_ORG && String(m.user_id) === ids.admin, + ); + expect(adminMembership, 'fixture invariant: the admin must hold a default-org membership').toBeDefined(); + adminMembership.role = 'owner'; + + const bearerFor = async (email: string) => { + const res = await direct('/sign-in/email', { email, password: PASSWORD }); + const token = res.headers.get('set-auth-token'); + expect(token, `sign-in ${email} must mint a bearer or the authenticated legs prove nothing`).toBeTruthy(); + return token!; + }; + const bearers = { + admin: await bearerFor(emails.admin), + member: await bearerFor(emails.member), + idp: await bearerFor(emails.idp), + }; + + // The idp user, as the cloud's identity provider leaves one: no local + // credential, `source` stamped `idp_provisioned`. + engine.tables.set( + 'sys_account', + accounts().filter((r) => !(r.provider_id === 'credential' && String(r.user_id) === ids.idp)), + ); + users().find((r) => String(r.id) === ids.idp)!.source = 'idp_provisioned'; + users().find((r) => String(r.id) === ids.member)!.source = 'env_native'; + users().find((r) => String(r.id) === ids.admin)!.email_verified = true; + users().find((r) => String(r.id) === ids.admin)!.source = 'env_native'; + + return { tables: structuredClone(new Map(engine.tables)), ids, bearers }; +} + +let staged: Awaited>; + +beforeAll(async () => { + const saved = { [MANAGED_ENV]: process.env[MANAGED_ENV], [SSO_ONLY_ENV]: process.env[SSO_ONLY_ENV] }; + setManaged(false); + delete process.env[SSO_ONLY_ENV]; + const quiet = (['info', 'warn', 'error'] as const).map((level) => + vi.spyOn(console, level).mockImplementation(() => {}), + ); + try { + staged = await produceStagedRows(); + } finally { + for (const spy of quiet) spy.mockRestore(); + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + resetCloudManagedForTesting(); + } +}, 120_000); + +/** + * One deployment over its OWN copy of the staged rows: a fresh engine, a fresh + * `AuthManager` and a fresh mount chain per case, exactly as a per-case + * staging gave, so no case sees another's writes. The tests switch the mode + * on afterwards: every door under test reads the accessor per request. + */ +async function stage(opts: { adminPlugin?: boolean; host?: EnvironmentUserHost | 'none'; tables?: Map } = {}) { + const engine = createMemoryEngine(); + for (const [name, rows] of structuredClone(opts.tables ?? staged.tables)) engine.tables.set(name, rows); + const manager = makeManager(engine, opts.adminPlugin ?? false); + const told: Array<{ kind: string; event: EnvironmentUserEvent }> = []; + const recordingHost: EnvironmentUserHost = { + userAdded: (event) => void told.push({ kind: 'added', event }), + userDeactivated: (event) => void told.push({ kind: 'deactivated', event }), + userReactivated: (event) => void told.push({ kind: 'reactivated', event }), + }; + const host = opts.host === 'none' ? undefined : (opts.host ?? recordingHost); + const { ids, bearers } = staged; + + const users = () => (engine.tables.get('sys_user') ?? []) as any[]; + const accounts = () => (engine.tables.get('sys_account') ?? []) as any[]; + + const app = new Hono(); + const ctx = mockCtx(); + const plugin = new AuthPlugin({ secret: SECRET, ...(host ? { environmentUserHost: () => host } : {}) }); + await plugin.init(ctx); + (plugin as any).authManager = manager; + // The tenancy service `init` builds reads the engine from the kernel, which + // this harness does not have; the same single-organization answer the + // manager is given stands in for it. + (plugin as any).tenancy = singleOrgTenancy(); + (plugin as any).registerAuthRoutes({ getRawApp: () => app, getPort: () => 0 }, ctx); + + const fire = (path: string, body: unknown, bearer?: string) => + app.request(`${ORIGIN}${BASE}${path}`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + origin: ORIGIN, + ...(bearer ? { authorization: `Bearer ${bearer}` } : {}), + }, + body: JSON.stringify(body), + }); + + const credentialOf = (userId: string) => + accounts().find((r) => r.provider_id === 'credential' && String(r.user_id) === userId); + const invitationsOf = (email: string) => + ((engine.tables.get('sys_invitation') ?? []) as any[]).filter( + (r) => r.email === email && r.organization_id === DEFAULT_ORG, + ); + + const signIn = (email: string, password = PASSWORD) => + manager.handleRequest( + new Request(`${ORIGIN}${BASE}/sign-in/email`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', origin: ORIGIN }, + body: JSON.stringify({ email, password }), + }), + ); + const row = (email: string) => users().find((r) => r.email === email); + const rowsOf = (table: string, userId: string) => + ((engine.tables.get(table) ?? []) as any[]).filter((r) => String(r.user_id) === userId); + + return { engine, manager, fire, ids, bearers, users, credentialOf, invitationsOf, told, signIn, row, rowsOf }; +} + + +const managedStage = async (opts: Parameters[0] = {}) => { + const s = await stage(opts); + setManaged(true); + return s; +}; + +// ───────────────────────────────────────────────────────────────────────────── +// Adding one person +// ───────────────────────────────────────────────────────────────────────────── + +describe('[#33181] admin/add-sso-user on a managed environment without the admin plugin', () => { + it('adds a pending person with positions, permission sets and a manager, and tells the host', async () => { + const s = await managedStage(); + const email = 'new.person@example.com'; + + const res = await s.fire( + '/admin/add-sso-user', + { email, name: 'New Person', positions: ['sales_rep'], permissionSets: ['crm_user', 'report_viewer'], manager: EMAILS.member }, + s.bearers.admin, + ); + const body: any = await res.json(); + + expect(res.status, JSON.stringify(body)).toBe(201); + const row = s.row(email)!; + expect(row.source).toBe(PENDING_SSO_SOURCE); + expect(row.email_verified).toBeFalsy(); + expect(String(row.manager_id)).toBe(s.ids.member); + expect(s.rowsOf('sys_account', String(row.id))).toHaveLength(0); + expect(s.rowsOf('sys_user_position', String(row.id)).map((r) => r.position)).toEqual(['sales_rep']); + expect(s.rowsOf('sys_user_permission_set', String(row.id)).map((r) => r.permission_set).sort()).toEqual(['crm_user', 'report_viewer']); + expect(s.rowsOf('sys_member', String(row.id)).map((m) => m.organization_id)).toEqual([DEFAULT_ORG]); + expect(body.data).toMatchObject({ userId: String(row.id), alreadyPending: false, manager: 'linked', host: { notified: true } }); + expect(s.told).toEqual([ + { + kind: 'added', + event: expect.objectContaining({ userId: String(row.id), email, name: 'New Person', source: PENDING_SSO_SOURCE, actorId: s.ids.admin }), + }, + ]); + }); + + it('adding a still-pending person again answers 200 alreadyPending, writes no second row, and tells the host again', async () => { + const s = await managedStage(); + const email = 'again.person@example.com'; + expect((await s.fire('/admin/add-sso-user', { email, name: 'Again' }, s.bearers.admin)).status).toBe(201); + + const res = await s.fire('/admin/add-sso-user', { email, name: 'Again' }, s.bearers.admin); + const body: any = await res.json(); + + expect(res.status).toBe(200); + expect(body.data.alreadyPending).toBe(true); + expect(s.users().filter((r) => r.email === email)).toHaveLength(1); + expect(s.told.map((t) => t.kind)).toEqual(['added', 'added']); + }); + + it('refuses an address already held by a person who is not pending, with 409, and tells no host', async () => { + const s = await managedStage(); + for (const email of [EMAILS.member, EMAILS.idp]) { + const v = await verdict(await s.fire('/admin/add-sso-user', { email, name: 'Taken' }, s.bearers.admin)); + expect(v.status, v.text).toBe(409); + expect(v.code).toBe('RESOURCE_CONFLICT'); + expect(v.message).toBe(PENDING_SSO_MESSAGES.alreadyExists); + } + expect(s.row(EMAILS.member)!.source).toBe('env_native'); + expect(s.row(EMAILS.idp)!.source).toBe('idp_provisioned'); + expect(s.told).toEqual([]); + }); + + it('refuses a body key it does not take, such as a password, with 400 and adds no one', async () => { + const s = await managedStage(); + const v = await verdict( + await s.fire('/admin/add-sso-user', { email: 'pw.person@example.com', name: 'Pw', password: NEW_PASSWORD }, s.bearers.admin), + ); + expect(v.status, v.text).toBe(400); + expect(s.row('pw.person@example.com')).toBeUndefined(); + }); + + it('a caller without platform-admin standing is refused 403 and no one is added', async () => { + const s = await managedStage(); + const v = await verdict(await s.fire('/admin/add-sso-user', { email: 'nope@example.com', name: 'Nope' }, s.bearers.member)); + expect(v.status, v.text).toBe(403); + expect(v.code).toBe('PERMISSION_DENIED'); + expect(s.row('nope@example.com')).toBeUndefined(); + }); + + it('CONTROL: off a managed environment both doors answer 409 and add no one', async () => { + const s = await stage(); + for (const [path, body] of [ + ['/admin/add-sso-user', { email: 'off.person@example.com', name: 'Off' }], + ['/admin/import-sso-users', { rows: [{ email: 'off.person@example.com', name: 'Off' }] }], + ] as const) { + const v = await verdict(await s.fire(path, body, s.bearers.admin)); + expect(v.status, v.text).toBe(409); + expect(v.code).toBe('RESOURCE_CONFLICT'); + expect(v.message).toBe(PENDING_SSO_MESSAGES.notManaged); + } + expect(s.row('off.person@example.com')).toBeUndefined(); + expect(s.told).toEqual([]); + }); + + it('a host that fails does not undo the add; the answer says host_failed', async () => { + const s = await managedStage({ + host: { + userAdded: () => { + throw new Error('host down'); + }, + userDeactivated: () => {}, + userReactivated: () => {}, + }, + }); + const res = await s.fire('/admin/add-sso-user', { email: 'hostfail@example.com', name: 'Host Fail' }, s.bearers.admin); + const body: any = await res.json(); + expect(res.status).toBe(201); + expect(body.data.host).toEqual({ notified: false, reason: 'host_failed' }); + expect(s.row('hostfail@example.com')!.source).toBe(PENDING_SSO_SOURCE); + }); + + it('with no host wired the add stands and the answer says no_host', async () => { + const s = await managedStage({ host: 'none' }); + const res = await s.fire('/admin/add-sso-user', { email: 'nohost@example.com', name: 'No Host' }, s.bearers.admin); + const body: any = await res.json(); + expect(res.status).toBe(201); + expect(body.data.host).toEqual({ notified: false, reason: 'no_host' }); + }); +}); + +// ───────────────────────────────────────────────────────────────────────────── +// Importing +// ───────────────────────────────────────────────────────────────────────────── + +describe('[#33181] admin/import-sso-users on a managed environment without the admin plugin', () => { + it('a bad row fails alone and the good rows land, managers resolved across the file', async () => { + const s = await managedStage(); + const csv = [ + 'email,name,positions,permission_sets,manager_id', + 'lead@example.com,Team Lead,sales_manager,crm_user,', + 'rep@example.com,Sales Rep,sales_rep,crm_user;report_viewer,lead@example.com', + 'not-an-email,Broken,,,', + 'rep@example.com,Duplicate,,,', + `${EMAILS.member},Taken,,,`, + ].join('\n'); + + const res = await s.fire('/admin/import-sso-users', { csv }, s.bearers.admin); + const body: any = await res.json(); + + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data.summary).toMatchObject({ total: 5, added: 2, failed: 3 }); + const byRow = Object.fromEntries(body.data.rows.map((r: any) => [r.row, r])); + expect(byRow[1].ok && byRow[2].ok).toBe(true); + expect([byRow[3].ok, byRow[4].ok, byRow[5].ok]).toEqual([false, false, false]); + expect(byRow[2].manager).toBe('linked'); + + const lead = s.row('lead@example.com')!; + const rep = s.row('rep@example.com')!; + expect([lead.source, rep.source]).toEqual([PENDING_SSO_SOURCE, PENDING_SSO_SOURCE]); + expect(rep.name).toBe('Sales Rep'); + expect(String(rep.manager_id)).toBe(String(lead.id)); + expect(s.rowsOf('sys_user_position', String(rep.id)).map((r) => r.position)).toEqual(['sales_rep']); + expect(s.rowsOf('sys_user_permission_set', String(rep.id)).map((r) => r.permission_set).sort()).toEqual(['crm_user', 'report_viewer']); + expect(s.row('not-an-email')).toBeUndefined(); + expect(s.row(EMAILS.member)!.source).toBe('env_native'); + expect(s.told.map((t) => t.event.email).sort()).toEqual(['lead@example.com', 'rep@example.com']); + }); + + it('refuses an unknown column, such as a password, with 400 and imports no one', async () => { + const s = await managedStage(); + const v = await verdict( + await s.fire('/admin/import-sso-users', { rows: [{ email: 'col@example.com', name: 'Col', password: NEW_PASSWORD }] }, s.bearers.admin), + ); + expect(v.status, v.text).toBe(400); + expect(s.row('col@example.com')).toBeUndefined(); + }); + + it('a caller without platform-admin standing is refused 403 and no one is imported', async () => { + const s = await managedStage(); + const v = await verdict(await s.fire('/admin/import-sso-users', { rows: [{ email: 'nope2@example.com', name: 'N' }] }, s.bearers.member)); + expect(v.status, v.text).toBe(403); + expect(s.row('nope2@example.com')).toBeUndefined(); + }); +}); + +// ───────────────────────────────────────────────────────────────────────────── +// The password doors and the session +// ───────────────────────────────────────────────────────────────────────────── + +describe('[#33181] a pending person gets no password and no session', () => { + const addPending = async (s: Awaited>, email: string) => { + const res = await s.fire('/admin/add-sso-user', { email, name: 'Pending' }, s.bearers.admin); + expect(res.status, await res.clone().text()).toBe(201); + return String(s.row(email)!.id); + }; + + it('admin set-user-password refuses a pending target with 409 and writes no credential', async () => { + const s = await managedStage(); + const id = await addPending(s, 'pw.pending@example.com'); + const v = await verdict(await s.fire('/admin/set-user-password', { userId: id, newPassword: NEW_PASSWORD }, s.bearers.admin)); + expect(v.status, v.text).toBe(409); + expect(v.code).toBe('RESOURCE_CONFLICT'); + expect(v.message).toBe(PENDING_SSO_MESSAGES.setUserPassword); + expect(s.credentialOf(id)).toBeUndefined(); + expect(s.row('pw.pending@example.com')!.source).toBe(PENDING_SSO_SOURCE); + }); + + it('admin set-user-password refuses a pending target off a managed environment too', async () => { + const s = await managedStage(); + const id = await addPending(s, 'pw.unmanaged@example.com'); + setManaged(false); + const v = await verdict(await s.fire('/admin/set-user-password', { userId: id, newPassword: NEW_PASSWORD }, s.bearers.admin)); + expect(v.status, v.text).toBe(409); + expect(v.message).toBe(PENDING_SSO_MESSAGES.setUserPassword); + expect(s.credentialOf(id)).toBeUndefined(); + }); + + it('set-initial-password refuses a pending caller with 409 and writes no credential, managed or not', async () => { + for (const managed of [true, false]) { + const s = await stage(); + setManaged(managed); + // A session held from before the row was marked pending (no new one can be opened for it). + s.users().find((r) => String(r.id) === s.ids.idp)!.source = PENDING_SSO_SOURCE; + const v = await verdict(await s.fire('/set-initial-password', { newPassword: NEW_PASSWORD }, s.bearers.idp)); + expect(v.status, `managed=${managed}: ${v.text}`).toBe(409); + expect(v.code).toBe('RESOURCE_CONFLICT'); + // Managed, the cloud-managed arm answers a caller without platform-admin standing first. + expect(v.message).toBe(managed ? CLOUD_MANAGED_REFUSAL_MESSAGES.setInitialPassword : PENDING_SSO_MESSAGES.setInitialPassword); + expect(s.credentialOf(s.ids.idp)).toBeUndefined(); + } + }); + + it('set-initial-password refuses a pending caller who holds platform-admin standing, whom the managed arm admits', async () => { + const s = await stage(); + setManaged(true); + process.env[OWNER_ENV] = EMAILS.idp; + s.users().find((r) => String(r.id) === s.ids.idp)!.email_verified = true; + s.users().find((r) => String(r.id) === s.ids.idp)!.source = PENDING_SSO_SOURCE; + const v = await verdict(await s.fire('/set-initial-password', { newPassword: NEW_PASSWORD }, s.bearers.idp)); + expect(v.status, v.text).toBe(409); + expect(v.message).toBe(PENDING_SSO_MESSAGES.setInitialPassword); + expect(s.credentialOf(s.ids.idp)).toBeUndefined(); + }); + + it('CONTROL: off a managed environment an idp_provisioned caller sets their initial password as before', async () => { + const s = await stage(); + const v = await verdict(await s.fire('/set-initial-password', { newPassword: NEW_PASSWORD }, s.bearers.idp)); + expect(v.status, v.text).toBe(200); + expect(s.credentialOf(s.ids.idp)).toBeDefined(); + }); + + it('CONTROL: set-user-password still answers 200 on an env_native target', async () => { + const s = await managedStage(); + const v = await verdict(await s.fire('/admin/set-user-password', { userId: s.ids.member, newPassword: NEW_PASSWORD }, s.bearers.admin)); + expect(v.status, v.text).toBe(200); + }); + + it('a session minted for a pending person is refused 403, on every channel that creates one', async () => { + const s = await managedStage(); + const id = await addPending(s, 'session.pending@example.com'); + const ctx: any = await s.manager.getAuthContext(); + await expect(ctx.internalAdapter.createSession(id)).rejects.toMatchObject({ + statusCode: 403, + body: expect.objectContaining({ code: 'PERMISSION_DENIED', message: PENDING_SSO_SESSION_REFUSAL.message }), + }); + expect(s.rowsOf('sys_session', id)).toHaveLength(0); + }); + + it('CONTROL: the same mint opens a session for an env_native and an idp_provisioned row', async () => { + const s = await managedStage(); + const ctx: any = await s.manager.getAuthContext(); + for (const id of [s.ids.member, s.ids.idp]) { + const before = s.rowsOf('sys_session', id).length; + await ctx.internalAdapter.createSession(id); + expect(s.rowsOf('sys_session', id)).toHaveLength(before + 1); + } + }); +}); + +// ───────────────────────────────────────────────────────────────────────────── +// Deactivate and reactivate without the admin plugin +// ───────────────────────────────────────────────────────────────────────────── + +describe('[#33181] ban works without the admin plugin', () => { + it('admin/ban-user bans, signs the user out, refuses their next sign-in, and tells the host', async () => { + const s = await managedStage(); + const res = await s.fire('/admin/ban-user', { userId: s.ids.member, banReason: 'left the company' }, s.bearers.admin); + const body: any = await res.json(); + + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data).toMatchObject({ userId: s.ids.member, banned: true, host: { notified: true } }); + const row = s.row(EMAILS.member)!; + expect(row.banned).toBe(true); + expect(row.ban_reason).toBe('left the company'); + expect(s.rowsOf('sys_session', s.ids.member)).toHaveLength(0); + + const signIn = await verdict(await s.signIn(EMAILS.member)); + expect(signIn.status, signIn.text).toBe(403); + expect(signIn.code).toBe(BANNED_USER_SESSION_REFUSAL.code); + expect(signIn.message).toBe(BANNED_USER_SESSION_REFUSAL.message); + expect(s.rowsOf('sys_session', s.ids.member)).toHaveLength(0); + expect(s.told).toEqual([ + { kind: 'deactivated', event: expect.objectContaining({ userId: s.ids.member, email: EMAILS.member, source: 'env_native', actorId: s.ids.admin }) }, + ]); + }); + + it('admin/unban-user restores sign-in and tells the host', async () => { + const s = await managedStage(); + expect((await s.fire('/admin/ban-user', { userId: s.ids.member }, s.bearers.admin)).status).toBe(200); + expect((await s.signIn(EMAILS.member)).status).toBe(403); + + const res = await s.fire('/admin/unban-user', { userId: s.ids.member }, s.bearers.admin); + const body: any = await res.json(); + + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data).toMatchObject({ banned: false, host: { notified: true } }); + const row = s.row(EMAILS.member)!; + expect(row.banned).toBe(false); + expect(row.ban_reason ?? null).toBeNull(); + expect((await s.signIn(EMAILS.member)).status).toBe(200); + expect(s.told.map((t) => t.kind)).toEqual(['deactivated', 'reactivated']); + }); + + it('a row banned while the admin plugin was on stays refused after the plugin is turned off', async () => { + const on = await stage({ adminPlugin: true }); + expect((await on.fire('/admin/ban-user', { userId: on.ids.member }, on.bearers.admin)).status).toBe(200); + expect((await on.signIn(EMAILS.member)).status).toBe(403); + + const off = await stage({ adminPlugin: false, tables: on.engine.tables }); + const v = await verdict(await off.signIn(EMAILS.member)); + expect(v.status, v.text).toBe(403); + expect(v.code).toBe(BANNED_USER_SESSION_REFUSAL.code); + expect(off.rowsOf('sys_session', off.ids.member)).toHaveLength(0); + }); + + it('a ban whose expiry has passed is lifted at the next sign-in, as the admin plugin does', async () => { + const s = await managedStage(); + const row = s.row(EMAILS.member)!; + Object.assign(row, { banned: true, ban_reason: 'cooling off', ban_expires: new Date(Date.now() - 60_000).toISOString() }); + + expect((await s.signIn(EMAILS.member)).status).toBe(200); + expect(s.row(EMAILS.member)!.banned).toBe(false); + }); + + it('CONTROL: with the admin plugin on, the ban is the vendor plugin\'s and its answer is unchanged', async () => { + const s = await managedStage({ adminPlugin: true }); + const res = await s.fire('/admin/ban-user', { userId: s.ids.member }, s.bearers.admin); + expect(res.status).toBe(200); + const v = await verdict(await s.signIn(EMAILS.member)); + expect(v.status, v.text).toBe(403); + expect(v.code).toBe('BANNED_USER'); + expect(v.message).toBe(BANNED_USER_SESSION_REFUSAL.message); + }); + + it('CONTROL: unbanned env_native rows sign in as before without the admin plugin', async () => { + const s = await managedStage(); + expect((await s.signIn(EMAILS.member)).status).toBe(200); + expect((await s.signIn(EMAILS.admin)).status).toBe(200); + }); +}); + +// ───────────────────────────────────────────────────────────────────────────── +// The host's typed refusals, and the administrator's cloud id +// ───────────────────────────────────────────────────────────────────────────── + +const OWNER_CONFLICT = { status: 409, code: 'ORGANIZATION_OWNER_OR_ADMIN', message: 'An organization owner or admin is removed in the console.' } as const; +const MEMBER_CAP = { status: 403, code: 'DEVELOPER_ORGANIZATION_MEMBER_LIMIT_REACHED', message: 'The organization has reached its member limit.' } as const; + +/** A host that refuses with `refusal` for the members named, and records every call. */ +function refusingHost( + refusal: { status: 403 | 409; code: string; message: string }, + refuse: { added?: (e: EnvironmentUserEvent) => boolean; deactivated?: boolean; reactivated?: boolean }, +) { + const told: Array<{ kind: string; event: EnvironmentUserEvent }> = []; + const answer = (kind: string, event: EnvironmentUserEvent, refused: boolean) => { + told.push({ kind, event }); + if (refused) throw new EnvironmentUserHostRefusal(refusal.status, refusal.code, refusal.message); + }; + const host: EnvironmentUserHost = { + userAdded: (e) => answer('added', e, refuse.added?.(e) ?? false), + userDeactivated: (e) => answer('deactivated', e, refuse.deactivated ?? false), + userReactivated: (e) => answer('reactivated', e, refuse.reactivated ?? false), + }; + return { host, told }; +} + +describe('[#33181] a host\'s typed refusal refuses the operation', () => { + it('an owner or admin 409 refuses the whole deactivation: nothing is written and the person stays signed in', async () => { + const { host, told } = refusingHost(OWNER_CONFLICT, { deactivated: true }); + const s = await managedStage({ host }); + expect((await s.signIn(EMAILS.member)).status).toBe(200); + const sessionsBefore = s.rowsOf('sys_session', s.ids.member).length; + + const v = await verdict(await s.fire('/admin/ban-user', { userId: s.ids.member }, s.bearers.admin)); + + expect(v.status, v.text).toBe(409); + expect(v.code).toBe(OWNER_CONFLICT.code); + expect(v.message).toBe(OWNER_CONFLICT.message); + expect(Boolean(s.row(EMAILS.member)!.banned)).toBe(false); + expect(s.rowsOf('sys_session', s.ids.member)).toHaveLength(sessionsBefore); + expect((await s.signIn(EMAILS.member)).status).toBe(200); + expect(told.map((t) => t.kind)).toEqual(['deactivated']); + }); + + it('a member-cap 403 refuses the reactivation: the person stays deactivated', async () => { + const { host } = refusingHost(MEMBER_CAP, { reactivated: true }); + const s = await managedStage({ host }); + expect((await s.fire('/admin/ban-user', { userId: s.ids.member }, s.bearers.admin)).status).toBe(200); + + const v = await verdict(await s.fire('/admin/unban-user', { userId: s.ids.member }, s.bearers.admin)); + + expect(v.status, v.text).toBe(403); + expect(v.code).toBe(MEMBER_CAP.code); + expect(v.message).toBe(MEMBER_CAP.message); + expect(s.row(EMAILS.member)!.banned).toBe(true); + expect((await s.signIn(EMAILS.member)).status).toBe(403); + }); + + it('a member-cap 403 on an add takes the person back out: no row, grants or membership remain', async () => { + const { host, told } = refusingHost(MEMBER_CAP, { added: () => true }); + const s = await managedStage({ host }); + const email = 'capped@example.com'; + + const v = await verdict( + await s.fire('/admin/add-sso-user', { email, name: 'Capped', positions: ['sales_rep'], permissionSets: ['crm_user'] }, s.bearers.admin), + ); + + expect(v.status, v.text).toBe(403); + expect(v.code).toBe(MEMBER_CAP.code); + expect(v.message).toBe(MEMBER_CAP.message); + const id = String(told[0]!.event.userId); + expect(s.row(email)).toBeUndefined(); + for (const table of ['sys_user_position', 'sys_user_permission_set', 'sys_member']) { + expect(s.rowsOf(table, id), table).toHaveLength(0); + } + }); + + it('a member-cap 403 on one import row fails that row alone; the others land', async () => { + const { host } = refusingHost(MEMBER_CAP, { added: (e) => e.email === 'over@example.com' }); + const s = await managedStage({ host }); + const csv = ['email,name,positions,permission_sets,manager_id', 'first@example.com,First,,crm_user,', 'over@example.com,Over,,crm_user,', 'third@example.com,Third,,,'].join('\n'); + + const res = await s.fire('/admin/import-sso-users', { csv }, s.bearers.admin); + const body: any = await res.json(); + + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data.summary).toMatchObject({ total: 3, added: 2, failed: 1 }); + expect(body.data.rows[1]).toMatchObject({ row: 2, ok: false, error: { code: MEMBER_CAP.code, message: MEMBER_CAP.message } }); + expect(s.row('over@example.com')).toBeUndefined(); + expect([s.row('first@example.com')?.source, s.row('third@example.com')?.source]).toEqual([PENDING_SSO_SOURCE, PENDING_SSO_SOURCE]); + }); + + it('a refused re-add of a still-pending person fails the request and leaves their row as it was', async () => { + let refuse = false; + const { host } = refusingHost(MEMBER_CAP, { added: () => refuse }); + const s = await managedStage({ host }); + expect((await s.fire('/admin/add-sso-user', { email: 'again@example.com', name: 'Again' }, s.bearers.admin)).status).toBe(201); + refuse = true; + + const v = await verdict(await s.fire('/admin/add-sso-user', { email: 'again@example.com', name: 'Again' }, s.bearers.admin)); + + expect(v.status, v.text).toBe(403); + expect(v.code).toBe(MEMBER_CAP.code); + expect(s.row('again@example.com')!.source).toBe(PENDING_SSO_SOURCE); + }); + + it('a wired host that does not answer refuses the deactivation with 503, and nothing is written', async () => { + const s = await managedStage({ + host: { + userAdded: () => {}, + userDeactivated: () => { + throw Object.assign(new Error('gateway timeout'), { status: 409, code: OWNER_CONFLICT.code }); + }, + userReactivated: () => {}, + }, + }); + expect((await s.signIn(EMAILS.member)).status).toBe(200); + const v = await verdict(await s.fire('/admin/ban-user', { userId: s.ids.member }, s.bearers.admin)); + expect(v.status, v.text).toBe(503); + expect(v.code).toBe('SERVICE_UNAVAILABLE'); + expect(Boolean(s.row(EMAILS.member)!.banned)).toBe(false); + expect((await s.signIn(EMAILS.member)).status).toBe(200); + }); + + it('CONTROL: a host that does not answer never blocks a reactivation; the answer says host_failed', async () => { + let failing = false; + const s = await managedStage({ + host: { + userAdded: () => {}, + userDeactivated: () => {}, + userReactivated: () => { + if (failing) throw new Error('gateway timeout'); + }, + }, + }); + expect((await s.fire('/admin/ban-user', { userId: s.ids.member }, s.bearers.admin)).status).toBe(200); + failing = true; + const res = await s.fire('/admin/unban-user', { userId: s.ids.member }, s.bearers.admin); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data.host).toEqual({ notified: false, reason: 'host_failed' }); + expect(s.row(EMAILS.member)!.banned).toBe(false); + }); + + it('CONTROL: a typed refusal with a status the seam does not honour is a host failure, not that status', async () => { + const s = await managedStage({ + host: { + userAdded: () => {}, + userDeactivated: () => { + throw new EnvironmentUserHostRefusal(500 as never, 'UPSTREAM', 'upstream failed'); + }, + userReactivated: () => {}, + }, + }); + const v = await verdict(await s.fire('/admin/ban-user', { userId: s.ids.member }, s.bearers.admin)); + expect(v.status, v.text).toBe(503); + expect(v.code).toBe('SERVICE_UNAVAILABLE'); + }); + + it('CONTROL: with no host wired the deactivation goes ahead', async () => { + const s = await managedStage({ host: 'none' }); + const res = await s.fire('/admin/ban-user', { userId: s.ids.member }, s.bearers.admin); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data).not.toHaveProperty('host'); + expect(s.row(EMAILS.member)!.banned).toBe(true); + }); +}); + +describe('[#33181] a re-add of a still-pending person names what it did not apply', () => { + it('add-sso-user answers notApplied for the positions, permission sets and manager it did not apply', async () => { + const s = await managedStage(); + const email = 'readd@example.com'; + expect((await s.fire('/admin/add-sso-user', { email, name: 'Re Add' }, s.bearers.admin)).status).toBe(201); + const id = String(s.row(email)!.id); + + const res = await s.fire( + '/admin/add-sso-user', + { email, name: 'Re Add', positions: ['sales_rep'], permissionSets: ['crm_user'], manager: EMAILS.member }, + s.bearers.admin, + ); + const body: any = await res.json(); + + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data).toMatchObject({ alreadyPending: true, notApplied: ['positions', 'permissionSets', 'manager'] }); + expect(s.rowsOf('sys_user_position', id)).toHaveLength(0); + expect(s.row(email)!.manager_id ?? null).toBeNull(); + }); + + it('import-sso-users names the columns a re-added row did not apply', async () => { + const s = await managedStage(); + expect((await s.fire('/admin/add-sso-user', { email: 'readd.csv@example.com', name: 'Re Add' }, s.bearers.admin)).status).toBe(201); + const csv = ['email,name,positions,permission_sets,manager_id', `readd.csv@example.com,Re Add,,crm_user,${EMAILS.member}`].join('\n'); + const body: any = await (await s.fire('/admin/import-sso-users', { csv }, s.bearers.admin)).json(); + expect(body.data.rows[0]).toMatchObject({ ok: true, alreadyPending: true, notApplied: ['permission_sets', 'manager_id'] }); + }); + + it('CONTROL: a re-add that sends no grants or manager carries no notApplied', async () => { + const s = await managedStage(); + expect((await s.fire('/admin/add-sso-user', { email: 'readd.plain@example.com', name: 'Plain' }, s.bearers.admin)).status).toBe(201); + const body: any = await (await s.fire('/admin/add-sso-user', { email: 'readd.plain@example.com', name: 'Plain' }, s.bearers.admin)).json(); + expect(body.data.alreadyPending).toBe(true); + expect(body.data).not.toHaveProperty('notApplied'); + }); +}); + +describe('[#33181] an import row that faults answers the generic sentence', () => { + it('a fault while writing one row answers INTERNAL_ERROR_MESSAGE on that row, never the fault\'s own text', async () => { + const s = await managedStage(); + const insert = (s.engine as any).insert.bind(s.engine) as (...args: unknown[]) => Promise; + (s.engine as any).insert = async (object: string, doc: any, ...rest: unknown[]) => { + if (object === 'sys_user' && doc?.email === 'faulty@example.com') throw new Error('driver detail: relation sys_user_7 is locked'); + return insert(object, doc, ...rest); + }; + const csv = ['email,name,positions,permission_sets,manager_id', 'faulty@example.com,Faulty,,,', 'fine@example.com,Fine,,,'].join('\n'); + const body: any = await (await s.fire('/admin/import-sso-users', { csv }, s.bearers.admin)).json(); + expect(body.data.rows[0].ok).toBe(false); + expect(body.data.rows[0].error.message).toContain(INTERNAL_ERROR_MESSAGE); + expect(body.data.rows[0].error.message).not.toContain('driver detail'); + expect(body.data.rows[1]).toMatchObject({ ok: true }); + }); + + it('CONTROL: a declared refusal on a row keeps its own sentence', async () => { + const s = await managedStage(); + const csv = ['email,name,positions,permission_sets,manager_id', `${EMAILS.member},Taken,,,`].join('\n'); + const body: any = await (await s.fire('/admin/import-sso-users', { csv }, s.bearers.admin)).json(); + expect(body.data.rows[0].error.message).toBe(PENDING_SSO_MESSAGES.alreadyExists); + }); +}); + +describe('[#33181] the host event names the administrator at the keyboard on an impersonation session', () => { + const recording = () => { + const told: EnvironmentUserEvent[] = []; + const host: EnvironmentUserHost = { + userAdded: (e) => void told.push(e), + userDeactivated: (e) => void told.push(e), + userReactivated: (e) => void told.push(e), + }; + return { told, host }; + }; + const unbanRequest = () => + new Request(`${ORIGIN}${BASE}/admin/unban-user`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ userId: 'target-1', impersonatedBy: 'forged' }), + }); + const banDeps = (host: EnvironmentUserHost) => ({ + getAuthContext: async () => ({ + internalAdapter: { + findUserById: async () => ({ id: 'target-1', email: 'target@example.com', name: 'Target' }), + updateUser: async () => ({}), + deleteUserSessions: async () => ({}), + }, + adapter: {} as any, + }), + host: () => host, + getDataEngine: () => ({ find: async () => [], findOne: async () => null }), + }); + + it('carries impersonatedBy from the session actor, never from the body', async () => { + const { told, host } = recording(); + const res = await runAdminUnbanUser(banDeps(host) as any, { id: 'admin-1', impersonatedBy: 'real-admin-9' } as any, unbanRequest()); + expect(res.status).toBe(200); + expect(told[0]).toMatchObject({ actorId: 'admin-1', impersonatedBy: 'real-admin-9' }); + }); + + it('CONTROL: an ordinary session carries no impersonatedBy, whatever the body says', async () => { + const { told, host } = recording(); + const res = await runAdminUnbanUser(banDeps(host) as any, { id: 'admin-1' }, unbanRequest()); + expect(res.status).toBe(200); + expect(told[0]).not.toHaveProperty('impersonatedBy'); + }); + + it('the add door carries it too', async () => { + const { told, host } = recording(); + const engine = createMemoryEngine(); + const res = await runAddSsoUser( + { isCloudManaged: () => true, getDataEngine: () => engine as any, host: () => host } as any, + { id: 'admin-1', impersonatedBy: 'real-admin-9' } as any, + new Request(`${ORIGIN}${BASE}/admin/add-sso-user`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ email: 'imp.added@example.com', name: 'Imp Added' }), + }), + ); + expect(res.status, JSON.stringify(res.body)).toBe(201); + expect(told[0]).toMatchObject({ actorId: 'admin-1', impersonatedBy: 'real-admin-9' }); + }); +}); + +describe('[#33181] the host event names the administrator\'s cloud id from their linked account', () => { + const linkAdminToCloud = (s: Awaited>, accountId: string) => { + const accounts = (s.engine.tables.get('sys_account') ?? []) as any[]; + accounts.push({ id: `acc_cloud_${accountId}`, user_id: s.ids.admin, provider_id: 'objectstack-cloud', account_id: accountId }); + s.engine.tables.set('sys_account', accounts); + }; + + it('add, ban and unban carry actorCloudUserId read from the linked objectstack-cloud account', async () => { + const s = await managedStage(); + linkAdminToCloud(s, 'cloud-user-7'); + + expect((await s.fire('/admin/add-sso-user', { email: 'attributed@example.com', name: 'Attributed' }, s.bearers.admin)).status).toBe(201); + expect((await s.fire('/admin/ban-user', { userId: s.ids.member }, s.bearers.admin)).status).toBe(200); + expect((await s.fire('/admin/unban-user', { userId: s.ids.member }, s.bearers.admin)).status).toBe(200); + + expect(s.told.map((t) => [t.kind, t.event.actorCloudUserId])).toEqual([ + ['added', 'cloud-user-7'], + ['deactivated', 'cloud-user-7'], + ['reactivated', 'cloud-user-7'], + ]); + }); + + it('a cloud id in the request body is ignored: the linked account wins, and with no link it is absent', async () => { + const s = await managedStage(); + expect((await s.fire('/admin/ban-user', { userId: s.ids.member, actorCloudUserId: 'forged' }, s.bearers.admin)).status).toBe(200); + linkAdminToCloud(s, 'cloud-user-7'); + expect((await s.fire('/admin/unban-user', { userId: s.ids.member, actorCloudUserId: 'forged' }, s.bearers.admin)).status).toBe(200); + + expect(s.told[0]!.event).not.toHaveProperty('actorCloudUserId'); + expect(s.told[1]!.event.actorCloudUserId).toBe('cloud-user-7'); + }); + + it('CONTROL: an account of another provider is not a cloud id', async () => { + const s = await managedStage(); + const accounts = (s.engine.tables.get('sys_account') ?? []) as any[]; + accounts.push({ id: 'acc_okta', user_id: s.ids.admin, provider_id: 'okta', account_id: 'okta-user-1' }); + s.engine.tables.set('sys_account', accounts); + expect((await s.fire('/admin/add-sso-user', { email: 'okta.actor@example.com', name: 'Okta Actor' }, s.bearers.admin)).status).toBe(201); + expect(s.told[0]!.event).not.toHaveProperty('actorCloudUserId'); + }); +}); diff --git a/packages/plugins/plugin-auth/src/pending-sso-users.ts b/packages/plugins/plugin-auth/src/pending-sso-users.ts new file mode 100644 index 00000000000..ac139776d3c --- /dev/null +++ b/packages/plugins/plugin-auth/src/pending-sso-users.ts @@ -0,0 +1,685 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Pending, SSO-only users on a cloud-managed environment — the add door, the + * CSV / JSON import door, the pending marker and the host seam. + * + * ## Why this door exists + * + * On a cloud-managed environment (`isCloudManaged()`, `cloud-managed.ts`) the + * people who use it sign in through the hosting organisation's identity + * provider, and the environment keeps its own authorization: positions, + * permission sets, the manager line. The password-capable doors + * (`admin/create-user`, `admin/import-users`) answer `409` there, and on a Free + * or Team kernel the better-auth admin plugin they build on is not even + * mounted. Until a person had signed in once there was no row to point a seed, + * an approval rule or a manager link at. + * + * This module adds a person BEFORE their first sign-in, as a **pending** row: + * + * - `sys_user.source = 'idp_pending'` ({@link PENDING_SSO_SOURCE}) — its own + * value, never `env_native`, so no rule that admits a local account admits + * it; no `sys_account` (no password, no link); `email_verified: false`; + * - the positions, permission sets and manager the administrator chose, + * written under the administrator's own execution context, so the security + * service judges each grant exactly as Setup's grant forms are judged; + * - the organization membership the create-user door gives (ADR-0093 D3). + * + * The door does not depend on the better-auth admin plugin: the row is written + * through the data engine, as the system, attributed to the administrator, + * the way the AI service-account door writes its rows. That makes the row + * born pending, in one insert: `source` is on the write that creates it, so + * no moment exists where the row reads `env_native` (which + * `set-user-password` admits). The engine's `sys_user` hooks judge the insert + * as they judge any user row. better-auth's `internalAdapter.createUser` + * would not do here: it needs the endpoint context a vendor route opens, and + * these routes are the platform's own mounts. + * + * ## How a pending row becomes a person + * + * The first sign-in through the platform identity provider binds to it. The + * bind needs no code here: `implicit-account-linking.ts` rule 2 lets the + * platform provider link to an unverified local row, and the federated branch + * of `stampIdentitySource` (`auth-manager-database-hooks.ts`) then stamps + * `idp_provisioned` on a row that holds no local password, which clears the + * marker in the same request, before the session is created. Only the + * platform provider's link clears the marker: the stamp leaves `idp_pending` + * on a link from any other provider, so such a row is still refused a + * session. A platform link whose stamp did not land is healed at the next + * session (`user-session-admission.ts`). + * + * Adding a person who is still pending again re-tells the host and changes + * nothing else: positions, permission sets or a manager sent with the re-add + * are named on the answer as `notApplied` (set them on the record instead). + * + * ## What a pending row is refused + * + * Every door that would give it a local password answers `409 + * RESOURCE_CONFLICT` ({@link pendingSsoPasswordRefusal}): `admin/set-user-password`, + * `set-initial-password`, `/reset-password` and `/phone-number/reset-password`. + * A session is refused to it on every path but the platform sign-in + * (`user-session-admission.ts`): until the bind it holds no sign-in of its own. + * + * ## The host seam + * + * A host (the cloud, on a hosted environment) is told when a person is added, + * deactivated and reactivated, so it can forward an invitation or a removal + * ({@link EnvironmentUserHost}). An add calls it after the person's unit of + * work has committed, never inside it. A host that fails does not undo the + * operation: the answer carries `host: { notified: false, reason: + * 'host_failed' }` and the plugin logs it once, so the caller is told (a + * failure handed to the caller, AGENTS.md degradation rule). A host's typed + * refusal (the developer member cap, `403 + * DEVELOPER_ORGANIZATION_MEMBER_LIMIT_REACHED`) is different: that person is + * taken back out (grants, membership, row) and their add fails with the + * host's answer, alone, on its own import row. Adding a person who is still + * pending again re-fires the seam, which is the retry; a refusal of a re-add + * fails that request and leaves the existing pending row as it was. The event + * carries the administrator's cloud user id from their linked + * `objectstack-cloud` account, never from the request. With no host wired + * nothing is called. + * + * The sentences an administrator reads are collected in + * {@link PENDING_SSO_MESSAGES} so the wording can move in one place. + */ + +import { parseCsvToRows } from '@objectstack/rest'; +import { INTERNAL_ERROR_MESSAGE, resolveThrownHttpError, validationFailureDetails } from '@objectstack/types'; +import { + bindUserToSoleOrganization, + CreationRefused, + isLikelyEmail, + joinCurrentOrganization, + multiOrgCreationJoinsCurrentOrganization, + writeAdminAudit, + type AdminActor, + type AdminCreateGrantSeam, + type AdminUserEndpointDeps, + type EndpointResult, +} from './admin-user-endpoints.js'; +import { applyUserManagerLink, type SetUserManagerEngine } from './admin-set-user-manager.js'; +import type { AddMemberCapableApi } from './organization-add-member.js'; +import { readJsonRequestBody } from './request-json-body.js'; +import { authSystemWriteContext } from './auth-actor-attribution.js'; +import { + isPendingSsoSource, + PENDING_SSO_MESSAGES, + PENDING_SSO_REFUSAL_CODE, + PENDING_SSO_REFUSAL_STATUS, + PENDING_SSO_SOURCE, +} from './pending-sso-marker.js'; +import { + notifyEnvironmentUserHost, + environmentUserAttribution, + type EnvironmentUserActor, + type EnvironmentUserEvent, + type EnvironmentUserHostAccessor, + type EnvironmentUserHostOutcome, + type EnvironmentUserHostRefused, +} from './environment-user-host.js'; + +/** The most rows one import request may carry, the identity import's own bound. */ +export const IMPORT_SSO_USERS_MAX_ROWS = 500; + +// ───────────────────────────────────────────────────────────────────────────── +// The doors +// ───────────────────────────────────────────────────────────────────────────── + +/** The data engine slice the doors use. */ +export interface PendingSsoUserEngine extends SetUserManagerEngine { + insert(object: string, doc: Record, opts?: unknown): Promise; + /** Takes a person back out when the host refuses them. */ + delete?(object: string, opts?: unknown): Promise; + getSchema?(objectName: string): unknown; +} + +/** What the doors need from the plugin. */ +export interface PendingSsoUserDeps + extends Pick { + /** Whether this process is a cloud-managed environment (`isCloudManaged()`), read per call. */ + isCloudManaged(): boolean; + getDataEngine(): PendingSsoUserEngine | undefined; + /** The caller's execution context and one engine transaction (create-user's seam). */ + createGrant?: AdminCreateGrantSeam; + /** better-auth's `addMember`, for the multi-organization join; absent when the organization plugin is off. */ + getAddMember?(): Promise; + host?: EnvironmentUserHostAccessor; + logger?: { warn(msg: string): void }; +} + +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] }; + +const fail = (status: number, code: string, message: string): EndpointResult => ({ + status, + body: { success: false, error: { code, message } }, +}); + +const badRequest = (message: string): EndpointResult => fail(400, 'INVALID_REQUEST', message); + +/** One person, as either door reads them. */ +interface PendingPersonInput { + email: string; + name: string; + positions: string[]; + permissionSets: string[]; + /** The manager's email address, or undefined for none. */ + manager?: string; +} + +/** The manager outcome a row reports: linked, not found, or the set-user-manager refusal reason. */ +type ManagerOutcome = 'linked' | 'unresolved' | string; + +/** One person's outcome. */ +type AddOutcome = + | { + ok: true; + userId: string; + alreadyPending: boolean; + organizationId?: string | null; + manager?: ManagerOutcome; + managerError?: string; + host: EnvironmentUserHostOutcome; + } + | { ok: false; result: EndpointResult }; + +const ADD_KEYS = new Set(['email', 'name', 'positions', 'permissionSets', 'manager']); +const ADD_FIELD_NAMES = { positions: 'positions', permissionSets: 'permissionSets', manager: 'manager' } as const; +const IMPORT_FIELD_NAMES = { positions: 'positions', permissionSets: 'permission_sets', manager: 'manager_id' } as const; + +/** A list cell: an array of names, or one `;`-separated string. Empty entries are dropped. */ +function readNameList(raw: unknown, label: string): string[] | string { + if (raw === undefined || raw === null || raw === '') return []; + const parts = typeof raw === 'string' ? raw.split(';') : Array.isArray(raw) ? raw : undefined; + if (!parts) return `${label} must be a list of machine names`; + const out: string[] = []; + for (const part of parts) { + if (typeof part !== 'string') return `${label} must be a list of machine names`; + const name = part.trim(); + if (name && !out.includes(name)) out.push(name); + } + return out; +} + +/** Read one person from the add body or an import row. A string answer is the refusal sentence. */ +function readPerson( + raw: Record, + keys: { positions: string; permissionSets: string; manager: string }, +): PendingPersonInput | string { + const email = typeof raw.email === 'string' ? raw.email.trim().toLowerCase() : ''; + if (!email || !isLikelyEmail(email)) return 'email must be an email address'; + const name = typeof raw.name === 'string' && raw.name.trim() ? raw.name.trim() : email.split('@')[0]!; + const positions = readNameList(raw[keys.positions], keys.positions); + if (typeof positions === 'string') return positions; + const permissionSets = readNameList(raw[keys.permissionSets], keys.permissionSets); + if (typeof permissionSets === 'string') return permissionSets; + const rawManager = raw[keys.manager]; + let manager: string | undefined; + if (rawManager !== undefined && rawManager !== null && rawManager !== '') { + if (typeof rawManager !== 'string' || !isLikelyEmail(rawManager.trim())) { + return `${keys.manager} must be the manager's email address`; + } + manager = rawManager.trim().toLowerCase(); + } + return { email, name, positions, permissionSets, ...(manager ? { manager } : {}) }; +} + +async function findUserByEmail( + engine: PendingSsoUserEngine, + email: string, +): Promise<{ id: string; name?: string; source?: string | null } | undefined> { + const rows = await engine.find('sys_user', { + where: { email }, + fields: ['id', 'name', 'source'], + limit: 1, + context: SYSTEM_CTX, + }); + const row = Array.isArray(rows) ? (rows[0] as { id?: unknown; name?: unknown; source?: unknown } | undefined) : undefined; + return row && typeof row.id === 'string' + ? { id: row.id, name: typeof row.name === 'string' ? row.name : undefined, source: typeof row.source === 'string' ? row.source : null } + : undefined; +} + +/** The answer for a grant the security service refused: its own status and code, and that no one was added. */ +function grantRefused(what: string, error: unknown): EndpointResult { + const thrown = resolveThrownHttpError(error, 500); + const validation = validationFailureDetails(error); + return { + status: thrown.status, + body: { + success: false, + error: { + code: thrown.code, + message: `The ${what} was not assigned, so no one was added. ${thrown.message}`, + ...(validation ? { fields: validation.fields } : {}), + }, + }, + }; +} + +/** + * What one request settles before any person is written: the caller's context + * for the grants, and the organization a multi-organization deployment joins. + */ +interface RequestSettlement { + /** The event's attribution (cloud id, impersonator), read once when a host is wired. */ + attribution?: Pick; + grant?: { seam: AdminCreateGrantSeam; engine: PendingSsoUserEngine; context: Record }; + join?: { addMember: AddMemberCapableApi['addMember']; organizationId: string }; +} + +async function settleRequest( + deps: PendingSsoUserDeps, + actor: AdminActor & EnvironmentUserActor, + needsGrant: boolean, +): Promise { + const settlement: RequestSettlement = {}; + if (deps.host) settlement.attribution = await environmentUserAttribution(deps.getDataEngine(), actor, deps.logger); + if (multiOrgCreationJoinsCurrentOrganization(deps)) { + const organizationId = await deps.getCallerActiveOrganizationId!(); + if (typeof organizationId !== 'string' || organizationId.length === 0) { + return fail( + 400, + 'NO_ACTIVE_ORGANIZATION', + 'You are not working in an organization, so no one was added. Switch to the organization the person ' + + 'belongs to, then add them there.', + ); + } + const addMember = await deps.getAddMember?.(); + if (!deps.createGrant || typeof addMember !== 'function') { + return fail( + 501, + 'NOT_IMPLEMENTED', + 'This server cannot add a person to your organization while adding them, so no one was added.', + ); + } + settlement.join = { addMember, organizationId }; + } + if (needsGrant) { + const seam = deps.createGrant; + const engine = deps.getDataEngine(); + if (!seam || !engine) { + return fail( + 501, + 'NOT_IMPLEMENTED', + 'This server cannot assign positions or permission sets while adding a person, so no one was added. ' + + 'Add the person without them, then grant them on their record.', + ); + } + const context = await seam.resolveActorContext(); + if (!context) { + return fail( + 403, + 'PERMISSION_DENIED', + 'Your own access could not be resolved, so the positions and permission sets could not be judged and no ' + + 'one was added.', + ); + } + settlement.grant = { seam, engine, context }; + } + return settlement; +} + +/** + * Add one person. Answers `alreadyPending` (and re-tells the host) for an + * address that is still pending, and a `409` for any other existing address. + * The account, its membership and its grants are one unit of work. + */ +async function addOnePendingPerson( + deps: PendingSsoUserDeps, + actor: AdminActor, + person: PendingPersonInput, + settlement: RequestSettlement, +): Promise { + const engine = deps.getDataEngine(); + if (!engine) return { ok: false, result: fail(503, 'SERVICE_UNAVAILABLE', 'Data engine unavailable, so no one was added.') }; + + const existing = await findUserByEmail(engine, person.email); + if (existing) { + if (!isPendingSsoSource(existing.source)) { + return { ok: false, result: fail(PENDING_SSO_REFUSAL_STATUS, PENDING_SSO_REFUSAL_CODE, PENDING_SSO_MESSAGES.alreadyExists) }; + } + const host = await notifyEnvironmentUserHost( + deps.host, + 'added', + eventFor(existing.id, person.email, existing.name ?? person.name, actor, settlement), + deps.logger, + ); + // A refused re-add leaves the existing pending row as it was: this request did not write it. + if ('refused' in host) return { ok: false, result: hostRefusal(host) }; + return { ok: true, userId: existing.id, alreadyPending: true, host }; + } + + const work = async (): Promise<{ userId: string; organizationId: string | null }> => { + const inserted: unknown = await engine.insert( + 'sys_user', + { email: person.email, name: person.name, email_verified: false, source: PENDING_SSO_SOURCE }, + { context: await authSystemWriteContext() }, + ); + const insertedRow = (Array.isArray(inserted) ? inserted[0] : inserted) as { id?: unknown } | undefined; + const userId = typeof insertedRow?.id === 'string' ? insertedRow.id : ''; + if (!userId) throw new CreationRefused(fail(500, 'INTERNAL_ERROR', 'The user row was written without an id, so no one was added.')); + + const membership = settlement.join + ? await joinCurrentOrganization(deps, settlement.join.addMember, userId, settlement.join.organizationId) + : await bindUserToSoleOrganization(deps, userId); + + if (settlement.grant) { + const { engine: grantEngine, context } = settlement.grant; + for (const position of person.positions) { + try { + await grantEngine.insert('sys_user_position', { user_id: userId, position }, { context }); + } catch (error) { + throw new CreationRefused(grantRefused(`position ${position}`, error)); + } + } + for (const permissionSet of person.permissionSets) { + try { + await grantEngine.insert('sys_user_permission_set', { user_id: userId, permission_set: permissionSet }, { context }); + } catch (error) { + throw new CreationRefused(grantRefused(`permission set ${permissionSet}`, error)); + } + } + } + return { userId, organizationId: membership.organizationId }; + }; + + let written: { userId: string; organizationId: string | null }; + try { + const unit = settlement.grant?.seam ?? (settlement.join ? deps.createGrant : undefined); + written = unit ? await unit.runAtomically(work) : await work(); + } catch (error) { + if (error instanceof CreationRefused) return { ok: false, result: error.result }; + throw error; + } + + // The host, outside the unit of work. A typed refusal takes this person back out. + const host = await notifyEnvironmentUserHost( + deps.host, + 'added', + eventFor(written.userId, person.email, person.name, actor, settlement), + deps.logger, + ); + if ('refused' in host) { + await takeBackPerson(deps, engine, written.userId, settlement); + return { ok: false, result: hostRefusal(host) }; + } + + await writeAdminAudit(deps, { + action: 'create', + actor, + recordId: written.userId, + metadata: { + event: 'user.admin_added_pending', + membershipCreated: written.organizationId !== null, + ...(written.organizationId ? { organizationId: written.organizationId } : {}), + }, + }); + return { ok: true, userId: written.userId, alreadyPending: false, organizationId: written.organizationId, host }; +} + +/** + * What a re-add of a still-pending person did not apply: the add never + * changes an existing person's grants or manager (set those on the record), + * so each one sent is named on the answer rather than silently dropped. + */ +function notAppliedOn(person: PendingPersonInput, names: { positions: string; permissionSets: string; manager: string }): string[] { + return [ + ...(person.positions.length > 0 ? [names.positions] : []), + ...(person.permissionSets.length > 0 ? [names.permissionSets] : []), + ...(person.manager ? [names.manager] : []), + ]; +} + +function eventFor( + userId: string, + email: string, + name: string, + actor: AdminActor, + settlement: RequestSettlement, +): EnvironmentUserEvent { + return { + userId, + email, + name, + source: PENDING_SSO_SOURCE, + actorId: actor.id, + ...settlement.attribution, + occurredAt: new Date().toISOString(), + }; +} + +/** The add's answer for a host's typed refusal: its status, code and sentence. */ +const hostRefusal = ({ refused }: EnvironmentUserHostRefused): EndpointResult => + fail(refused.status, refused.code, refused.message); + +/** The rows an add wrote for one person, children first, the person last. */ +const TAKE_BACK_OBJECTS = ['sys_user_position', 'sys_user_permission_set', 'sys_member'] as const; + +/** + * Take a person the host refused back out: their grants, their membership + * and their row, as the system, in one unit of work. The person was never + * told anything and never signed in, so nothing else points at them. A + * failure here is thrown: the person would stay without the host's consent, + * and the caller must hear that rather than a clean refusal. + */ +async function takeBackPerson( + deps: PendingSsoUserDeps, + engine: PendingSsoUserEngine, + userId: string, + settlement: RequestSettlement, +): Promise { + if (typeof engine.delete !== 'function') { + throw new Error(`The host refused user ${userId}, and this data engine cannot take the row back out`); + } + const remove = engine.delete.bind(engine); + const work = async (): Promise => { + const context = await authSystemWriteContext(); + for (const object of TAKE_BACK_OBJECTS) { + await remove(object, { where: { user_id: userId }, multi: true, context }); + } + await remove('sys_user', { where: { id: userId }, context }); + }; + const unit = settlement.grant?.seam ?? deps.createGrant; + await (unit ? unit.runAtomically(work) : work()); +} + +/** + * Link `userId` to the manager named by email, by the set-user-manager + * derivation (imported, never copied). Never undoes the person. + */ +async function linkManager( + deps: PendingSsoUserDeps, + userId: string, + managerEmail: string, +): Promise<{ manager: ManagerOutcome; managerError?: string }> { + const engine = deps.getDataEngine(); + const managerRow = engine ? await findUserByEmail(engine, managerEmail) : undefined; + if (!managerRow) { + return { + manager: 'unresolved', + managerError: 'No user in this environment has the manager email address, so no manager was set.', + }; + } + const refusal = await applyUserManagerLink({ getDataEngine: () => engine, logger: deps.logger as never }, userId, managerRow.id); + if (refusal) return { manager: refusal.reason, managerError: refusal.message }; + return { manager: 'linked' }; +} + +/** `POST /api/v1/auth/admin/add-sso-user` — the caller already passed the platform-admin gate. */ +export async function runAddSsoUser( + deps: PendingSsoUserDeps, + actor: AdminActor, + request: Request, +): Promise { + if (!deps.isCloudManaged()) return fail(PENDING_SSO_REFUSAL_STATUS, PENDING_SSO_REFUSAL_CODE, PENDING_SSO_MESSAGES.notManaged); + const reading = await readJsonRequestBody(request); + if (!reading.ok) return badRequest(reading.message); + const body = (reading.body && typeof reading.body === 'object' ? reading.body : {}) as Record; + const unknown = Object.keys(body).filter((key) => !ADD_KEYS.has(key)); + if (unknown.length > 0) { + return badRequest(`Unknown field(s): ${unknown.join(', ')}. This door takes email, name, positions, permissionSets and manager; it sets no password.`); + } + const person = readPerson(body, { positions: 'positions', permissionSets: 'permissionSets', manager: 'manager' }); + if (typeof person === 'string') return badRequest(person); + + const settlement = await settleRequest(deps, actor, person.positions.length + person.permissionSets.length > 0); + if ('status' in settlement) return settlement; + const outcome = await addOnePendingPerson(deps, actor, person, settlement); + if (!outcome.ok) return outcome.result; + const manager = person.manager && !outcome.alreadyPending ? await linkManager(deps, outcome.userId, person.manager) : undefined; + + return { + status: outcome.alreadyPending ? 200 : 201, + body: { + success: true, + data: { + userId: outcome.userId, + email: person.email, + source: PENDING_SSO_SOURCE, + alreadyPending: outcome.alreadyPending, + ...(outcome.alreadyPending ? {} : { positions: person.positions, permissionSets: person.permissionSets }), + ...(outcome.alreadyPending && notAppliedOn(person, ADD_FIELD_NAMES).length > 0 + ? { notApplied: notAppliedOn(person, ADD_FIELD_NAMES) } + : {}), + ...(outcome.organizationId ? { organizationId: outcome.organizationId } : {}), + ...(manager ? manager : {}), + host: outcome.host, + }, + }, + }; +} + +const IMPORT_BODY_KEYS = new Set(['csv', 'rows']); +const IMPORT_COLUMNS = new Set(['email', 'name', 'positions', 'permission_sets', 'manager_id']); + +/** One row's answer in the import report. */ +export interface ImportSsoUserRowResult { + /** 1-based data row number (the CSV header is row 0). */ + row: number; + email?: string; + ok: boolean; + userId?: string; + alreadyPending?: boolean; + /** On a re-add of a still-pending person: the columns sent that were not applied. */ + notApplied?: string[]; + error?: { code: string; message: string }; + manager?: ManagerOutcome; + managerError?: string; + host?: EnvironmentUserHostOutcome; +} + +/** + * `POST /api/v1/auth/admin/import-sso-users` — `{ csv }` (a header row, then + * one person per line) or `{ rows }` (JSON objects), columns `email`, `name`, + * `positions` and `permission_sets` (`;`-separated machine names) and + * `manager_id` (the manager's email address). Every row is judged and written + * on its own: a bad row fails alone with its sentence and the good rows land. + * Manager links run in a second pass, so a manager added later in the same + * file is found. + */ +export async function runImportSsoUsers( + deps: PendingSsoUserDeps, + actor: AdminActor, + request: Request, +): Promise { + if (!deps.isCloudManaged()) return fail(PENDING_SSO_REFUSAL_STATUS, PENDING_SSO_REFUSAL_CODE, PENDING_SSO_MESSAGES.notManaged); + const reading = await readJsonRequestBody(request); + if (!reading.ok) return badRequest(reading.message); + const body = (reading.body && typeof reading.body === 'object' ? reading.body : {}) as Record; + const unknownKeys = Object.keys(body).filter((key) => !IMPORT_BODY_KEYS.has(key)); + if (unknownKeys.length > 0) return badRequest(`Unknown field(s): ${unknownKeys.join(', ')}. Send { csv } or { rows }.`); + + let rows: Array>; + if (typeof body.csv === 'string' && body.rows === undefined) { + rows = parseCsvToRows(body.csv); + } else if (Array.isArray(body.rows) && body.csv === undefined) { + if (!body.rows.every((r) => r && typeof r === 'object' && !Array.isArray(r))) return badRequest('rows must be objects'); + rows = body.rows as Array>; + } else { + return badRequest('Send exactly one of csv (text with a header row) or rows (an array of objects).'); + } + if (rows.length === 0) return badRequest('The import holds no rows.'); + if (rows.length > IMPORT_SSO_USERS_MAX_ROWS) { + return badRequest(`The import holds ${rows.length} rows; split it into batches of at most ${IMPORT_SSO_USERS_MAX_ROWS}.`); + } + const unknownColumns = [...new Set(rows.flatMap((r) => Object.keys(r)))].filter((key) => !IMPORT_COLUMNS.has(key)); + if (unknownColumns.length > 0) { + return badRequest( + `Unknown column(s): ${unknownColumns.join(', ')}. The columns are email, name, positions, permission_sets and ` + + 'manager_id; this import sets no password.', + ); + } + + const people = rows.map((r) => readPerson(r, { positions: 'positions', permissionSets: 'permission_sets', manager: 'manager_id' })); + const needsGrant = people.some((p) => typeof p !== 'string' && p.positions.length + p.permissionSets.length > 0); + const settlement = await settleRequest(deps, actor, needsGrant); + if ('status' in settlement) return settlement; + + const results: ImportSsoUserRowResult[] = []; + const seen = new Set(); + for (let i = 0; i < people.length; i++) { + const person = people[i]!; + const row = i + 1; + if (typeof person === 'string') { + results.push({ row, ok: false, error: { code: 'INVALID_REQUEST', message: person } }); + continue; + } + if (seen.has(person.email)) { + results.push({ + row, + email: person.email, + ok: false, + error: { code: PENDING_SSO_REFUSAL_CODE, message: 'This email address appears on an earlier row of the same import; this row was not added.' }, + }); + continue; + } + seen.add(person.email); + let outcome: AddOutcome; + try { + outcome = await addOnePendingPerson(deps, actor, person, settlement); + } catch (error) { + const thrown = resolveThrownHttpError(error, 500); + // A declared refusal keeps its own sentence; any other fault answers the + // generic one, as the single-add door does, so no driver text leaks. + const message = thrown.status >= 500 ? INTERNAL_ERROR_MESSAGE : thrown.message; + results.push({ row, email: person.email, ok: false, error: { code: thrown.code, message: `This row was not added. ${message}` } }); + continue; + } + if (!outcome.ok) { + const err = outcome.result.body.error; + results.push({ row, email: person.email, ok: false, error: { code: err?.code ?? 'INTERNAL_ERROR', message: err?.message ?? 'not added' } }); + continue; + } + const notApplied = outcome.alreadyPending ? notAppliedOn(person, IMPORT_FIELD_NAMES) : []; + results.push({ + row, + email: person.email, + ok: true, + userId: outcome.userId, + alreadyPending: outcome.alreadyPending, + ...(notApplied.length > 0 ? { notApplied } : {}), + host: outcome.host, + }); + } + + // Second pass: the manager links, now that every row of the file exists. + for (let i = 0; i < people.length; i++) { + const person = people[i]!; + const result = results[i]!; + if (typeof person === 'string' || !result.ok || result.alreadyPending || !person.manager || !result.userId) continue; + Object.assign(result, await linkManager(deps, result.userId, person.manager)); + } + + const added = results.filter((r) => r.ok && !r.alreadyPending).length; + const alreadyPending = results.filter((r) => r.ok && r.alreadyPending).length; + return { + status: 200, + body: { + success: true, + data: { + summary: { total: results.length, added, alreadyPending, failed: results.filter((r) => !r.ok).length }, + rows: results as unknown as Record[], + } as Record, + }, + }; +} diff --git a/packages/plugins/plugin-auth/src/service-account-identity.ts b/packages/plugins/plugin-auth/src/service-account-identity.ts index 07a65c07338..9093ed3b7fc 100644 --- a/packages/plugins/plugin-auth/src/service-account-identity.ts +++ b/packages/plugins/plugin-auth/src/service-account-identity.ts @@ -133,10 +133,14 @@ const has = (data: Record, key: string): boolean => /** True when a written value leaves the column empty. */ const isEmpty = (v: unknown): boolean => v === undefined || v === null || v === ''; -async function readUserRow(engine: any, userId: string): Promise | undefined> { +async function readUserRow( + engine: any, + userId: string, + extraFields: readonly string[] = [], +): Promise | undefined> { let found: any = await engine.find(USER_OBJECT, { where: { id: userId }, - fields: [...SERVICE_ACCOUNT_ROW_FIELDS], + fields: [...SERVICE_ACCOUNT_ROW_FIELDS, ...extraFields], limit: 1, context: SYSTEM_CTX, }); @@ -188,14 +192,30 @@ async function readFault(door: 'session' | 'credential', cause: unknown): Promis * the row that fails refuses with {@link USER_ROW_READ_FAULT_REFUSAL}. */ export async function refuseAgentAccountSession(engine: any, session: unknown): Promise { - const userId = (session as { userId?: unknown } | null | undefined)?.userId; - let agent: boolean; + await readSessionUserRow(engine, session); +} + +/** + * [#33181] {@link refuseAgentAccountSession}, reading the row ONCE for every + * session refusal composed after it: `extraFields` join the read, and the row + * is handed on (`undefined` when there is no user id, no engine or no row). + * The refusals and the read fault are exactly the agent refusal's. + */ +export async function readSessionUserRow( + engine: any, + session: unknown, + extraFields: readonly string[] = [], +): Promise | undefined> { + const id = str((session as { userId?: unknown } | null | undefined)?.userId); + if (!id || !engine || typeof engine.find !== 'function') return undefined; + let row: Record | undefined; try { - agent = await isAgentAccountUser(engine, userId); + row = await readUserRow(engine, id, extraFields); } catch (cause) { return readFault('session', cause); } - if (agent) await forbidden(AGENT_ACCOUNT_SESSION_REFUSAL); + if (isAgentAccountRow(row)) await forbidden(AGENT_ACCOUNT_SESSION_REFUSAL); + return row; } /** diff --git a/packages/plugins/plugin-auth/src/set-initial-password.ts b/packages/plugins/plugin-auth/src/set-initial-password.ts index d6a2d2c4b50..976c17a304f 100644 --- a/packages/plugins/plugin-auth/src/set-initial-password.ts +++ b/packages/plugins/plugin-auth/src/set-initial-password.ts @@ -47,9 +47,20 @@ export interface SetInitialPasswordResult { * cookie that better-auth's session middleware reads, and its * body carries `{ newPassword }`. */ +export interface SetInitialPasswordOptions { + /** + * [#33181] Asked once the body has been read and holds a `newPassword`, and + * before anything is written: an answer refuses the request with it, + * `undefined` lets it through. A host twin that passes nothing is + * unchanged. + */ + beforeWrite?(): Promise; +} + export async function runSetInitialPassword( authApi: SetPasswordCapableApi, request: Request, + options: SetInitialPasswordOptions = {}, ): Promise { // [#24032] A declared-JSON body that does not parse is refused before // `setPassword` is reached: it was read as `{}`, which answered @@ -69,6 +80,9 @@ export async function runSetInitialPassword( }; } + const refused = await options.beforeWrite?.(); + if (refused) return refused; + try { // better-auth's session middleware reads the session from `headers`; // length checks + the "already set" guard happen inside setPassword. diff --git a/packages/plugins/plugin-auth/src/user-ban-write.ts b/packages/plugins/plugin-auth/src/user-ban-write.ts index 31b30eeca6e..8c0f462c04e 100644 --- a/packages/plugins/plugin-auth/src/user-ban-write.ts +++ b/packages/plugins/plugin-auth/src/user-ban-write.ts @@ -77,3 +77,39 @@ export async function applyUserUnban(writer: UserBanWriter, userId: string): Pro updatedAt: new Date(), }); } + +/** The engine surface `engineUserBanWriter` writes through. */ +export interface UserBanEngine { + update(object: string, data: Record, options?: unknown): Promise; +} + +/** The better-auth field names of the ban write, as `sys_user` columns. */ +const BAN_COLUMN: Record = { + banned: 'banned', + banReason: 'ban_reason', + banExpires: 'ban_expires', + updatedAt: 'updated_at', +}; + +/** + * [#33181] The ban write on a kernel WITHOUT the vendor admin plugin. There + * `banReason` / `banExpires` are not fields of better-auth's user model, so + * `internalAdapter.updateUser` would not land them; this writer lands the + * same columns through the data engine, as the system. The break-glass + * last-administrator guard judges engine writes in every context, `isSystem` + * included, so it holds here too. A field the ban write does not know is + * refused rather than written under a guessed column. + */ +export function engineUserBanWriter(engine: UserBanEngine): UserBanWriter { + return { + async updateUser(id, data) { + const patch: Record = { id }; + for (const [field, value] of Object.entries(data)) { + const column = BAN_COLUMN[field]; + if (!column) throw new Error(`engineUserBanWriter: "${field}" is not a ban field`); + patch[column] = value; + } + return engine.update('sys_user', patch, { context: { isSystem: true, positions: [], permissions: [] } }); + }, + }; +} diff --git a/packages/plugins/plugin-auth/src/user-session-admission.ts b/packages/plugins/plugin-auth/src/user-session-admission.ts new file mode 100644 index 00000000000..c5d60d36666 --- /dev/null +++ b/packages/plugins/plugin-auth/src/user-session-admission.ts @@ -0,0 +1,160 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Two refusals at `session.create.before`, read from one `sys_user` row: + * + * 1. **A pending person holds no session.** A row still reading + * `idp_pending` (`pending-sso-marker.ts`) was added to sign in through the + * hosting organisation's identity provider, and no other sign-in method — + * a magic link, an email or phone code, an impersonation, a minted session + * — opens one for it. The platform sign-in itself passes: its link lands in + * `account.create.after`, whose identity-source stamp + * (`stampIdentitySource`) moves the row to `idp_provisioned` before the + * session that sign-in creates. That stamp is fail-soft and runs once, at + * the link; a row that still reads `idp_pending` while it already holds a + * platform (`objectstack-cloud`) account is therefore stamped here and + * admitted, so a stamp that did not land never locks the person out. Only + * the platform account clears the marker: any other link leaves it. + * + * 2. **A ban holds without the better-auth admin plugin.** The vendor's admin + * plugin refuses a banned user's session from its own `session.create` + * hook. On a kernel without the plugin (a Free or Team hosted + * environment, where it mounts only with SCIM) this refusal enforces the + * ban instead. It is the vendor's, field for field — `403`, + * `BANNED_USER`, the vendor's default sentence; an expired ban is lifted + * and the session admitted — and it runs only when the plugin is NOT + * mounted, so a kernel with the plugin answers exactly as before (the + * vendor still decides there). `enforceBan` is asked lazily, only for a + * banned row. + * + * The row is read once per session: the AI-service-account refusal composed + * before this one (`readSessionUserRow`) reads these columns with its own and + * hands the row on. Called on its own, this refusal reads the row itself. A + * read that throws refuses the session (`503`), as the AI-service-account + * refusal does; a missing engine or row admits it. + */ + +import { isPendingSsoSource, PENDING_SSO_MESSAGES } from './pending-sso-marker.js'; +import { PLATFORM_IDP_PROVIDER_ID } from './implicit-account-linking.js'; +import { USER_ROW_READ_FAULT_REFUSAL } from './service-account-identity.js'; + +/** The refusal a pending person's session meets. */ +export const PENDING_SSO_SESSION_REFUSAL = Object.freeze({ + code: 'PERMISSION_DENIED', + message: PENDING_SSO_MESSAGES.session, +}); + +/** + * The vendor admin plugin's ban refusal: its code and its default sentence + * (`better-auth/plugins/admin`, `bannedUserMessage` unset in this plugin's + * configuration), so a client reads one answer whichever side enforces. + */ +export const BANNED_USER_SESSION_REFUSAL = Object.freeze({ + code: 'BANNED_USER', + message: 'You have been banned from this application. Please contact support if you believe this is an error.', +}); + +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] }; + +const isTrue = (value: unknown): boolean => value === true || value === 1; + +/** The `sys_user` columns this refusal reads. */ +export const SESSION_ADMISSION_ROW_FIELDS = ['source', 'banned', 'ban_expires'] as const; + +export interface SessionAdmissionOptions { + /** Whether this refusal enforces a ban: true only when the vendor admin plugin is not mounted. */ + enforceBan(): boolean | Promise; + /** + * The row, already read with {@link SESSION_ADMISSION_ROW_FIELDS} by the + * refusal composed before this one (`readSessionUserRow`), so a session + * costs one read of `sys_user`. Present (even `undefined`) means no read here. + */ + row?: Record | undefined; +} + +/** The `503` a session meets when a row this refusal must read or write cannot be. */ +async function serviceUnavailable(cause: unknown): Promise { + const { APIError } = await import('better-auth/api'); + const err = new APIError('SERVICE_UNAVAILABLE', { + code: 'SERVICE_UNAVAILABLE', + message: USER_ROW_READ_FAULT_REFUSAL.message, + }); + (err as { cause?: unknown }).cause = cause; + return err; +} + +/** + * Whether a pending row already holds its platform account, and so only + * missed its stamp; when it does, stamp it `idp_provisioned` now. A read or a + * write that throws refuses the session `503`. + */ +async function healPendingPlatformLink(engine: any, userId: string): Promise { + if (typeof engine.find !== 'function' || typeof engine.update !== 'function') return false; + try { + let found: any = await engine.find('sys_account', { + where: { user_id: userId, provider_id: PLATFORM_IDP_PROVIDER_ID }, + fields: ['id'], + limit: 1, + context: SYSTEM_CTX, + }); + if (found && found.value) found = found.value; + if (!Array.isArray(found) || found.length === 0) return false; + await engine.update('sys_user', { id: userId, source: 'idp_provisioned' }, { context: SYSTEM_CTX }); + return true; + } catch (cause) { + throw await serviceUnavailable(cause); + } +} + +/** Read the row this refusal judges; a read that throws refuses the session `503`. */ +async function readAdmissionRow(engine: any, userId: string): Promise | undefined> { + if (typeof engine.find !== 'function') return undefined; + try { + let found: any = await engine.find('sys_user', { + where: { id: userId }, + fields: ['id', ...SESSION_ADMISSION_ROW_FIELDS], + limit: 1, + context: SYSTEM_CTX, + }); + if (found && found.value) found = found.value; + return Array.isArray(found) && found[0] && typeof found[0] === 'object' ? found[0] : undefined; + } catch (cause) { + throw await serviceUnavailable(cause); + } +} + +/** Refuse a session for a pending person, or for a banned user on a kernel without the admin plugin. */ +export async function refuseInactiveUserSession( + engine: any, + session: unknown, + options: SessionAdmissionOptions, +): Promise { + const userId = (session as { userId?: unknown } | null | undefined)?.userId; + if (typeof userId !== 'string' || !userId || !engine) return; + const row = 'row' in options ? options.row : await readAdmissionRow(engine, userId); + if (!row) return; + + if (isPendingSsoSource(row.source) && !(await healPendingPlatformLink(engine, userId))) { + const { APIError } = await import('better-auth/api'); + throw new APIError('FORBIDDEN', { code: 'PERMISSION_DENIED', message: PENDING_SSO_SESSION_REFUSAL.message }); + } + + if (isTrue(row.banned) && (await options.enforceBan())) { + const expires = row.ban_expires ? new Date(row.ban_expires as string | number | Date) : undefined; + if (expires && !Number.isNaN(expires.getTime()) && expires.getTime() < Date.now()) { + // The vendor lifts an expired ban as it admits the session; so does this. + try { + await engine.update( + 'sys_user', + { id: userId, banned: false, ban_reason: null, ban_expires: null, updated_at: new Date() }, + { context: SYSTEM_CTX }, + ); + } catch (cause) { + throw await serviceUnavailable(cause); + } + return; + } + const { APIError } = await import('better-auth/api'); + throw new APIError('FORBIDDEN', { code: 'BANNED_USER', message: BANNED_USER_SESSION_REFUSAL.message }); + } +} 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 0ed5220fd2b..f8a0e33d20b 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 @@ -255,6 +255,14 @@ const ADMITTED = [ 'POST /api/v1/auth/admin/authorized-clients/withdraw', 'POST /api/v1/auth/admin/unlock-user', 'POST /api/v1/auth/admin/import-users', + // #33181 — add pending, SSO-only people: ObjectStack raw mounts whose FIRST + // statement is the ADR-0068 gate. This stack is not cloud-managed, so the + // admin passes the gate and lands on `409 RESOURCE_CONFLICT` (the doors + // answer only on a managed environment), like the SSO bridges' capability + // error above; the add's effect is pinned in plugin-auth's + // `pending-sso-users.test.ts`. + 'POST /api/v1/auth/admin/add-sso-user', + 'POST /api/v1/auth/admin/import-sso-users', 'POST /api/v1/auth/admin/oauth2/toggle-disabled', 'POST /api/v1/auth/admin/impersonate-user', 'POST /api/v1/auth/admin/sso/register', @@ -747,6 +755,11 @@ describe('#9482: what an ObjectStack platform admin gets from every /admin/ rout body: { format: 'json', rows: [{ email: 'standing.sweep.imported@example.com', name: 'Sweep Imported' }] }, }, 'POST /api/v1/auth/admin/unlock-user': { body: { userId: targetUserId } }, + // #33181. A valid add body, so a managed boot would reach the handler too. + 'POST /api/v1/auth/admin/add-sso-user': { body: { email: 'standing.sweep.pending@example.com', name: 'Sweep Pending' } }, + 'POST /api/v1/auth/admin/import-sso-users': { + body: { rows: [{ email: 'standing.sweep.pending.import@example.com', name: 'Sweep Pending Import' }] }, + }, // #16678. The CLEAR, not a set: it is idempotent, so the sweep leaves // `manager_id` as it found it, and it still reaches a 2xx rather than a // semantic error — measured 200 `{"success":true,...,"managerId":null}`. 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 4772970c5a6..e1bdf3b750e 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 @@ -272,6 +272,21 @@ function expectationsFor(targetUserId: string): Record body: { userId: targetUserId, managerId: null }, note: 'the gate runs ahead of any body read, so the member 403 holds even on an empty body; the admin gets 200 from the idempotent clear', }, + // ── #33181 — add pending, SSO-only people (cloud-managed environments) ── + // ObjectStack raw mounts whose FIRST statement is the ADR-0068 gate. This + // stack is not cloud-managed, so the admin passes the gate and lands on + // `409 RESOURCE_CONFLICT` (the doors answer only on a managed + // environment): a semantic answer, not a gate verdict. + 'POST /api/v1/auth/admin/add-sso-user': { + bucket: 'objectstack-gate', + body: { email: 'refusal.probe.pending@example.com', name: 'Pending Probe' }, + note: 'the gate runs first; off a managed environment the admin gets 409 RESOURCE_CONFLICT and no one is added', + }, + 'POST /api/v1/auth/admin/import-sso-users': { + bucket: 'objectstack-gate', + body: { rows: [{ email: 'refusal.probe.pending.import@example.com', name: 'Pending Import Probe' }] }, + note: 'the gate runs first; off a managed environment the admin gets 409 RESOURCE_CONFLICT and no one is imported', + }, // ── ADR-0095 D3 — the platform-admin roster (a read; no body is read) ─── 'POST /api/v1/auth/admin/list-platform-admins': { bucket: 'objectstack-gate',