diff --git a/.changeset/33228-remove-pending-sso-user.md b/.changeset/33228-remove-pending-sso-user.md new file mode 100644 index 00000000000..d8a83ae3daa --- /dev/null +++ b/.changeset/33228-remove-pending-sso-user.md @@ -0,0 +1,24 @@ +--- +'@objectstack/plugin-auth': patch +--- + +feat(auth): a cloud-managed environment can remove a pending person, cancelling their invitation at the host + +Clause-②: yes (widening) — added: `POST /api/v1/auth/admin/remove-sso-user` (platform administrators, cloud-managed environments only); an optional `userRemoved` member on the environment-user host contract and the `'removed'` event kind; the `'deactivated'` value of the host outcome's `reason`. Nothing that was accepted is refused. +Metadata-protocol: none + +On a cloud-managed environment, a person added to sign in through the hosting organisation's identity provider stays pending until their first sign-in. Before this change a pending person with a typo in their email could only be deactivated. + +**Removing a pending person.** `POST /api/v1/auth/admin/remove-sso-user` with `{ "userId": "…" }` asks the host first, outside any transaction, then removes the person with their positions, permission sets and membership in one unit of work: + +- The host is told through `userRemoved`. A host without it is told through `userDeactivated` with `source: 'idp_pending'`, which already means "cancel the invitation". A host should implement `userRemoved`. +- A host refusal (403/409) answers with the host's sentence, and no one is removed. +- A host that cannot be reached refuses the removal with `503 SERVICE_UNAVAILABLE`, and no one is removed: the door calls the host once and keeps no record to ask again from, so try again. Durable retry is the host's job. +- With no host wired, the person is removed and the answer says `host: { notified: false, reason: 'no_host' }`. +- A person who is not pending answers `409`: deactivate them instead. This holds at the removal itself: the person is re-checked inside the unit of work and the delete carries `source: 'idp_pending'`, so a person whose first sign-in lands while the host is asked is not removed. On an object with cascading lookups (such as `sys_user`) the engine re-deletes by id after the cascade, so a first sign-in committing in that narrow window is not yet refused. +- A person that other records still point at (`deleteBehavior: 'restrict'`) answers the engine's refusal, and nothing is removed. If the host had already cancelled the invitation of a person who is still pending and not deactivated, the door sends it again through `userAdded`, once, and the answer says whether that worked. +- An unknown id answers `404`; a body with any key but `userId` answers `400`. Off a cloud-managed environment the door answers `409` and removes no one. + +**A deactivated person is never sent an invitation.** Adding a deactivated pending person again no longer calls `userAdded`; the answer says `host: { notified: false, reason: 'deactivated' }`. Reactivating them (`admin/unban-user`) is what tells the host again. + +Nothing to migrate. diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index d84e11237f9..4dec7b45a89 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -1316,7 +1316,8 @@ in the directory. A host can be told about people as they come and go: the `environmentUserHost` option of the auth plugin is called after a person is added, and before a -person is deactivated (`admin/ban-user`) or reactivated (`admin/unban-user`). +person is deactivated (`admin/ban-user`), reactivated (`admin/unban-user`) or, +while still pending, removed (`admin/remove-sso-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 @@ -1336,6 +1337,43 @@ 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. +A pending person who never signs in, for example one added with a mistyped +address, can be removed: `POST /api/v1/auth/admin/remove-sso-user` takes +`{ userId }`, removes the person with their positions, permission sets and +membership, and cancels their invitation at the host. The host is asked +first, through its `userRemoved` member; a host without that member is asked +through `userDeactivated` for the pending person instead, which means the same +thing, but a host should implement `userRemoved`. A host's refusal leaves the +person as they are. A host that cannot be reached refuses the removal too, +with `503` and nothing removed, as it refuses a deactivation: the door calls +the host once and keeps no record to ask again from, so try again once the +host is back. A person who is not pending (they have signed in, or were not +added this way) is refused with `409`: deactivate them instead. That holds at +the removal itself: the person is checked again inside the removal's unit of +work and the delete carries `source: 'idp_pending'`, so a person whose first +sign-in lands while the host is asked is not removed either, and the answer +says the host was already told. Because `sys_user` has cascading lookups, the +engine deletes the row by id after walking them, so a first sign-in that +commits in that narrow window is not yet refused. A record that +still points at the person through a lookup that restricts deletes refuses the +removal with that lookup's own answer, and nothing is removed; when the host +had already cancelled the invitation of a person who is still pending and not +deactivated, the door sends the invitation again through `userAdded`, once, +and the answer says whether that worked. Like the add doors, it is +platform-admin gated and answers `409` off a managed environment. + +A deactivated person is never sent an invitation: adding a deactivated pending +person again calls no host and answers `host: { notified: false, reason: +'deactivated' }`; reactivating them is what tells the host again. + +Each door calls the host once and keeps no record of the call. Delivering it +durably, and keeping each person's invitation status, is the host's job: a +host may queue and retry a call it could not complete. A call can reach a host +more than once (adding a person who is still pending again tells the host +again), so a host should treat a repeat as harmless, and should cancel an +invitation by the event's `userId`, never by its email address, which an +administrator may have typed wrong and may type again for someone else. + `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 diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index ea11e122e3d..c4b287f7ef1 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -389,12 +389,13 @@ export interface AuthPluginOptions extends Partial { * [#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. + * through `admin/ban-user`, reactivated through `admin/unban-user`, or a + * pending person is removed through `admin/remove-sso-user` (`userRemoved`, + * else `userDeactivated`). 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, a reactivation or a + * removal as `host: { notified: false, reason }`, which it never undoes. */ environmentUserHost?: EnvironmentUserHostAccessor; @@ -5243,6 +5244,25 @@ export class AuthPlugin implements Plugin { return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: INTERNAL_ERROR_MESSAGE } }, 500); } }); + + // Remove a person who is still pending (the email-typo case) and cancel + // their invitation at the host. Same gate and attribution as the two + // doors above; logic in `pending-sso-users.ts` (`runRemoveSsoUser`). + rawApp.post(`${basePath}/admin/remove-sso-user`, async (c: any) => { + try { + const actor = await gateAdmin(c); + if (actor instanceof Response) return actor; + const { runRemoveSsoUser } = await import('./pending-sso-users.js'); + const { status, body } = await runAttributedToUser(actor, () => + runRemoveSsoUser(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/remove-sso-user 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 6278391c6d9..9bf3e7c9190 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 @@ -288,6 +288,10 @@ describe('auth route ledger hygiene', () => { // below holds it to the same proof — better-auth serves no roster. 'POST /api/v1/auth/admin/list-platform-admins', 'POST /api/v1/auth/admin/oauth2/toggle-disabled', + // The pending-person remove door, on the same terms as the two above: + // `auth-plugin.ts` mounts it itself (a `rawApp.post` on the + // `${basePath}/admin/remove-sso-user` template); better-auth serves none. + 'POST /api/v1/auth/admin/remove-sso-user', // [#30958] On this pin's own terms: `auth-plugin.ts` mounts both itself // (`rawApp.post` on the `${basePath}/admin/scim/mint-credential` and // `${basePath}/admin/scim/revoke-credential` templates, ahead of the diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.ts index 3e1d13fe2b4..0e62e1afc54 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.ts @@ -258,8 +258,9 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [ { 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/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, unless the person is deactivated: then host reads deactivated and nothing is sent); 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/remove-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; removes a person who is still pending (sys_user.source idp_pending: the email-typo case) with their positions, permission sets and membership, and cancels their invitation at the environment-user host (userRemoved, else userDeactivated), which is asked first so its typed refusal leaves the person as they are; a host that cannot be reached refuses it with 503 SERVICE_UNAVAILABLE and nothing is removed (the door calls the host once and keeps no record to retry from); the person is re-checked inside the unit of work and the row delete carries source idp_pending, so a person who signs in while the host is asked is kept with 409 (on an object with cascading lookups the engine re-deletes by id, so a first sign-in committing in that narrow window is not yet refused); a removal that fails after the host took the cancellation sends the invitation again once through userAdded and says so; body { userId }; 404 RESOURCE_NOT_FOUND for an unknown id; 409 RESOURCE_CONFLICT off a managed environment or for a person who is not pending; a lookup that restricts the delete refuses it with the engine answer; 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/environment-user-host.ts b/packages/plugins/plugin-auth/src/environment-user-host.ts index f65f38f2b6f..076335cfbc6 100644 --- a/packages/plugins/plugin-auth/src/environment-user-host.ts +++ b/packages/plugins/plugin-auth/src/environment-user-host.ts @@ -2,10 +2,12 @@ /** * 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. + * environment) is told when a person is added, deactivated, reactivated or, + * while still pending, removed, so it can forward an invitation or cancel + * one. See `pending-sso-users.ts` for the add and remove halves and + * `admin-ban-endpoints.ts` for the deactivate / reactivate half. Each door + * calls the host once: a host that must not lose a call (an unreachable + * mail relay, an outage of its own) queues and retries it on its side. * * Two kinds of host failure are told apart: * @@ -65,11 +67,11 @@ export interface EnvironmentUserEvent { /** * 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. + * written; `userDeactivated`, `userReactivated` and `userRemoved` before the + * ban, unban or removal 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, a + * reactivation or a removal, which it never undoes or blocks. */ export interface EnvironmentUserHost { /** A person was added (or re-added while still pending) to this environment. */ @@ -78,6 +80,14 @@ export interface EnvironmentUserHost { userDeactivated(event: EnvironmentUserEvent): void | Promise; /** A person was reactivated (`admin/unban-user`). */ userReactivated(event: EnvironmentUserEvent): void | Promise; + /** + * A pending person was removed (`admin/remove-sso-user`): cancel their + * invitation. Optional: a host without it is called on `userDeactivated` + * for the pending person instead, which the hosting rulings make the same + * thing ("deleting or deactivating a pending row cancels its cloud + * invitation"). A host should implement it. + */ + userRemoved?(event: EnvironmentUserEvent): void | Promise; } /** @@ -122,24 +132,45 @@ export function isEnvironmentUserHostRefusal(error: unknown): error is Environme 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. */ +/** + * What a door answers about the host call, on the row it concerns. + * `deactivated`: the person is deactivated, so the host was not asked to + * invite them (a re-add of a deactivated pending person); reactivating them + * is what sends the invitation again. + */ export type EnvironmentUserHostOutcome = | { notified: true } - | { notified: false; reason: 'no_host' | 'host_failed' }; + | { notified: false; reason: 'no_host' | 'host_failed' | 'deactivated' }; /** 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'; +export type EnvironmentUserEventKind = 'added' | 'deactivated' | 'reactivated' | 'removed'; const HOST_MEMBER: Record = { added: 'userAdded', deactivated: 'userDeactivated', reactivated: 'userReactivated', + removed: 'userRemoved', }; +/** + * The member `kind` calls on `host`: its own, or for a removal on a host + * without `userRemoved`, `userDeactivated` (a pending person's deactivation + * cancels the invitation by ruling, which is what a removal asks). + */ +function hostMember( + host: EnvironmentUserHost | undefined, + kind: EnvironmentUserEventKind, +): ((event: EnvironmentUserEvent) => void | Promise) | undefined { + const own = host?.[HOST_MEMBER[kind]]; + if (typeof own === 'function') return own; + if (kind === 'removed' && typeof host?.userDeactivated === 'function') return host.userDeactivated; + return undefined; +} + /** The engine slice the actor's cloud id is read through. */ export interface ActorCloudIdReader { find(objectName: string, query?: unknown): Promise; @@ -219,8 +250,8 @@ export async function notifyEnvironmentUserHost( ); return { notified: false, reason: 'host_failed' }; } - const member = host?.[HOST_MEMBER[kind]]; - if (typeof member !== 'function') return { notified: false, reason: 'no_host' }; + const member = hostMember(host, kind); + if (!member) return { notified: false, reason: 'no_host' }; try { await member.call(host, event); return { notified: true }; @@ -243,6 +274,8 @@ const goesAhead = (kind: EnvironmentUserEventKind): string => ? '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.'; + : kind === 'removed' + ? 'The removal goes ahead.' + : 'The change goes ahead.'; const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error)); diff --git a/packages/plugins/plugin-auth/src/pending-sso-marker.ts b/packages/plugins/plugin-auth/src/pending-sso-marker.ts index 3f4595b7286..350faf1d549 100644 --- a/packages/plugins/plugin-auth/src/pending-sso-marker.ts +++ b/packages/plugins/plugin-auth/src/pending-sso-marker.ts @@ -35,6 +35,24 @@ export const PENDING_SSO_MESSAGES = { "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.', + notManagedRemove: + 'This environment is not cloud-managed, so it holds no pending people whose invitation could be cancelled. ' + + 'Deactivate the user instead (admin/ban-user). No one was removed.', + removeNotPending: + 'This person is not pending: they have signed in, or were not added to sign in through the hosting ' + + "organisation's identity provider, so they cannot be removed here. Deactivate them instead. No one was removed.", + removeRefused: 'This person could not be removed, and no one was removed.', + removeRefusedReinvited: + 'Their invitation had already been cancelled at the hosting organisation, so it was sent again and they stay ' + + 'pending as before.', + removeRefusedNotReinvited: + 'Their invitation had already been cancelled at the hosting organisation, and sending it again did not ' + + 'succeed, so they stay pending with no invitation: add them again to send one.', + removeHostCancelled: + 'The hosting organisation had already been told to cancel their invitation, and it is not sent again.', + removeHostUnreachable: + "The hosting organisation could not be reached to cancel this person's invitation, so they were not removed. " + + 'Nothing was changed; try again.', 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.", diff --git a/packages/plugins/plugin-auth/src/pending-sso-users.test.ts b/packages/plugins/plugin-auth/src/pending-sso-users.test.ts index 161b7f6e667..d85a0161601 100644 --- a/packages/plugins/plugin-auth/src/pending-sso-users.test.ts +++ b/packages/plugins/plugin-auth/src/pending-sso-users.test.ts @@ -1173,6 +1173,317 @@ describe('[#33759] Ban / Unban are offered and work without the admin plugin', ( }); }); +// ───────────────────────────────────────────────────────────────────────────── +// Removing a pending person, which cancels their invitation at the host +// ───────────────────────────────────────────────────────────────────────────── + +/** A recording host with a `userRemoved` member, unless `withRemoved` is false. */ +function removingHost(opts: { withRemoved?: boolean; removed?: () => void; added?: () => void } = {}) { + const told: Array<{ kind: string; event: EnvironmentUserEvent }> = []; + const host: EnvironmentUserHost = { + userAdded: (event) => { + told.push({ kind: 'added', event }); + opts.added?.(); + }, + userDeactivated: (event) => void told.push({ kind: 'deactivated', event }), + userReactivated: (event) => void told.push({ kind: 'reactivated', event }), + ...(opts.withRemoved === false + ? {} + : { + userRemoved: (event: EnvironmentUserEvent) => { + told.push({ kind: 'removed', event }); + opts.removed?.(); + }, + }), + }; + return { host, told }; +} + +/** Add one pending person with a position, a permission set and a membership; answers their id. */ +async function addPending(s: Awaited>, email: string): Promise { + const res = await s.fire( + '/admin/add-sso-user', + { email, name: 'Typo', positions: ['sales_rep'], permissionSets: ['crm_user'] }, + s.bearers.admin, + ); + expect(res.status, await res.clone().text()).toBe(201); + return String(s.row(email)!.id); +} + +/** Make the delete of `sys_user` answer a `restrict` refusal, as the engine's delete walk does (`DELETE_RESTRICTED`, 409). */ +const RESTRICTED = 'This User cannot be deleted because an Approval Rule still refers to it.'; +function restrictDelete(s: Awaited>): void { + const realDelete = s.engine.delete.bind(s.engine); + s.engine.delete = async (name: string, q: any = {}) => { + if (name === 'sys_user') throw Object.assign(new Error(RESTRICTED), { code: 'DELETE_RESTRICTED', status: 409 }); + return realDelete(name, q); + }; +} + +describe('[#33228] admin/remove-sso-user removes a pending person and cancels their invitation', () => { + it('removes the row, its grants and membership, and tells the host userRemoved first', async () => { + const { host, told } = removingHost(); + const s = await managedStage({ host }); + const id = await addPending(s, 'typo@exmaple.com'); + + const res = await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.admin); + const body: any = await res.json(); + + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data).toEqual({ userId: id, email: 'typo@exmaple.com', removed: true, host: { notified: true } }); + expect(s.row('typo@exmaple.com')).toBeUndefined(); + for (const table of ['sys_user_position', 'sys_user_permission_set', 'sys_member']) { + expect(s.rowsOf(table, id), table).toHaveLength(0); + } + expect(told.map((t) => t.kind)).toEqual(['added', 'removed']); + expect(told[1]!.event).toMatchObject({ userId: id, email: 'typo@exmaple.com', source: PENDING_SSO_SOURCE, actorId: s.ids.admin }); + }); + + it('a host without userRemoved is told userDeactivated for the pending person instead', async () => { + const { host, told } = removingHost({ withRemoved: false }); + const s = await managedStage({ host }); + const id = await addPending(s, 'fallback@example.com'); + + expect((await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.admin)).status).toBe(200); + + expect(told.map((t) => t.kind)).toEqual(['added', 'deactivated']); + expect(told[1]!.event).toMatchObject({ userId: id, source: PENDING_SSO_SOURCE }); + expect(s.row('fallback@example.com')).toBeUndefined(); + }); + + it('refuses a person who is not pending with 409, calls no host and removes no one', async () => { + const { host, told } = removingHost(); + const s = await managedStage({ host }); + for (const userId of [s.ids.member, s.ids.idp]) { + const v = await verdict(await s.fire('/admin/remove-sso-user', { userId }, s.bearers.admin)); + expect(v.status, v.text).toBe(409); + expect(v.code).toBe('RESOURCE_CONFLICT'); + expect(v.message?.split('. ')[0]).toBe(PENDING_SSO_MESSAGES.removeNotPending.split('. ')[0]); + } + expect(s.row(EMAILS.member)).toBeDefined(); + expect(s.row(EMAILS.idp)).toBeDefined(); + expect(told).toEqual([]); + }); + + it('a host\'s typed refusal leaves the person as they are: nothing removed', async () => { + const { host } = removingHost({ + removed: () => { + throw new EnvironmentUserHostRefusal(409, OWNER_CONFLICT.code, OWNER_CONFLICT.message); + }, + }); + const s = await managedStage({ host }); + const id = await addPending(s, 'refused.remove@example.com'); + + const v = await verdict(await s.fire('/admin/remove-sso-user', { userId: id }, 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(s.row('refused.remove@example.com')).toMatchObject({ source: PENDING_SSO_SOURCE }); + expect(s.rowsOf('sys_member', id).length).toBeGreaterThan(0); + }); + + it('a host that cannot be reached refuses the removal: 503, the person is kept and nothing is re-sent', async () => { + const { host, told } = removingHost({ + removed: () => { + throw new Error('host down'); + }, + }); + const s = await managedStage({ host }); + const id = await addPending(s, 'unreached.remove@example.com'); + + const v = await verdict(await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.admin)); + + expect([v.status, v.code, v.message]).toEqual([503, 'SERVICE_UNAVAILABLE', PENDING_SSO_MESSAGES.removeHostUnreachable]); + expect(s.row('unreached.remove@example.com')).toMatchObject({ id, source: PENDING_SSO_SOURCE }); + expect(s.rowsOf('sys_member', id).length).toBeGreaterThan(0); + // Asked once, and no invitation is sent again. + expect(told.map((t) => t.kind)).toEqual(['added', 'removed']); + }); + + it('with no host wired the person is removed and the answer says no_host', async () => { + const s = await managedStage({ host: 'none' }); + const id = await addPending(s, 'nohost.remove@example.com'); + const body: any = await (await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.admin)).json(); + expect(body.data).toEqual({ userId: id, email: 'nohost.remove@example.com', removed: true, host: { notified: false, reason: 'no_host' } }); + expect(s.row('nohost.remove@example.com')).toBeUndefined(); + }); + + it('a record that restricts the delete refuses it with the engine\'s answer; the person stays and is re-invited inline', async () => { + const { host, told } = removingHost(); + const s = await managedStage({ host }); + const id = await addPending(s, 'held@example.com'); + restrictDelete(s); + + const v = await verdict(await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.admin)); + + expect(v.status, v.text).toBe(409); + expect(v.code).toBe('DELETE_RESTRICTED'); + expect(v.message).toBe(`${PENDING_SSO_MESSAGES.removeRefused} ${RESTRICTED} ${PENDING_SSO_MESSAGES.removeRefusedReinvited}`); + expect(s.row('held@example.com')).toMatchObject({ source: PENDING_SSO_SOURCE }); + expect(told.map((t) => t.kind)).toEqual(['added', 'removed', 'added']); + expect(told[2]!.event).toMatchObject({ userId: id, email: 'held@example.com', source: PENDING_SSO_SOURCE }); + }); + + it('a re-invite the host does not take is said truthfully: the person stays pending with no invitation', async () => { + let calls = 0; + const { host } = removingHost({ + added: () => { + calls += 1; + if (calls > 1) throw new Error('host down'); + }, + }); + const s = await managedStage({ host }); + const id = await addPending(s, 'held.unsent@example.com'); + restrictDelete(s); + + const v = await verdict(await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.admin)); + + expect(v.status, v.text).toBe(409); + expect(v.message).toBe(`${PENDING_SSO_MESSAGES.removeRefused} ${RESTRICTED} ${PENDING_SSO_MESSAGES.removeRefusedNotReinvited}`); + expect(s.row('held.unsent@example.com')).toMatchObject({ source: PENDING_SSO_SOURCE }); + expect(calls).toBe(2); + }); + + it('refuses an unknown id 404, a missing id or an unknown key 400, and a non-admin 403', async () => { + const s = await managedStage(); + const unknown = await verdict(await s.fire('/admin/remove-sso-user', { userId: 'usr_nobody' }, s.bearers.admin)); + expect([unknown.status, unknown.code]).toEqual([404, 'RESOURCE_NOT_FOUND']); + const missing = await verdict(await s.fire('/admin/remove-sso-user', {}, s.bearers.admin)); + expect([missing.status, missing.code]).toEqual([400, 'INVALID_REQUEST']); + const extra = await verdict(await s.fire('/admin/remove-sso-user', { userId: s.ids.member, email: 'x@example.com' }, s.bearers.admin)); + expect([extra.status, extra.code]).toEqual([400, 'INVALID_REQUEST']); + const id = await addPending(s, 'guarded@example.com'); + const member = await verdict(await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.member)); + expect([member.status, member.code]).toEqual([403, 'PERMISSION_DENIED']); + expect(s.row('guarded@example.com')).toBeDefined(); + }); + + it('CONTROL: off a managed environment it answers 409 and removes no one', async () => { + const s = await stage(); + const v = await verdict(await s.fire('/admin/remove-sso-user', { userId: s.ids.member }, s.bearers.admin)); + expect([v.status, v.code, v.message]).toEqual([409, 'RESOURCE_CONFLICT', PENDING_SSO_MESSAGES.notManagedRemove]); + expect(s.row(EMAILS.member)).toBeDefined(); + }); +}); + +describe('[#33228] a deactivated person is never sent an invitation, and a removal is held to pending people', () => { + it('re-adding a deactivated pending person does not invite them: host reads deactivated', async () => { + const { host, told } = removingHost(); + const s = await managedStage({ host }); + const email = 'readd.banned@example.com'; + const id = await addPending(s, email); + expect((await s.fire('/admin/ban-user', { userId: id }, s.bearers.admin)).status).toBe(200); + + const res = await s.fire('/admin/add-sso-user', { email, name: 'Typo' }, s.bearers.admin); + const body: any = await res.json(); + + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data).toMatchObject({ userId: id, alreadyPending: true, host: { notified: false, reason: 'deactivated' } }); + expect(told.map((t) => t.kind)).toEqual(['added', 'deactivated']); + }); + + it('CONTROL: re-adding a pending person who is not deactivated invites them again', async () => { + const { host, told } = removingHost(); + const s = await managedStage({ host }); + const email = 'readd.active@example.com'; + const id = await addPending(s, email); + + const body: any = await (await s.fire('/admin/add-sso-user', { email, name: 'Typo' }, s.bearers.admin)).json(); + + expect(body.data).toMatchObject({ userId: id, alreadyPending: true, host: { notified: true } }); + expect(told.map((t) => t.kind)).toEqual(['added', 'added']); + }); + + it('a refused removal of a deactivated pending person sends no new invitation, and says the old one is cancelled', async () => { + const { host, told } = removingHost(); + const s = await managedStage({ host }); + const id = await addPending(s, 'held.banned@example.com'); + expect((await s.fire('/admin/ban-user', { userId: id }, s.bearers.admin)).status).toBe(200); + restrictDelete(s); + + const v = await verdict(await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.admin)); + + expect(v.status, v.text).toBe(409); + expect(v.message).toBe(`${PENDING_SSO_MESSAGES.removeRefused} ${RESTRICTED} ${PENDING_SSO_MESSAGES.removeHostCancelled}`); + expect(told.map((t) => t.kind)).toEqual(['added', 'deactivated', 'removed']); + }); + + it('a deactivated pending person whose banned column reads back as a string is not invited on a re-add', async () => { + const { host, told } = removingHost(); + const s = await managedStage({ host }); + const email = 'readd.banned.string@example.com'; + const id = await addPending(s, email); + for (const stored of ['1', 'true']) { + s.row(email)!.banned = stored; + const body: any = await (await s.fire('/admin/add-sso-user', { email, name: 'Typo' }, s.bearers.admin)).json(); + expect(body.data, stored).toMatchObject({ userId: id, alreadyPending: true, host: { notified: false, reason: 'deactivated' } }); + } + expect(told.map((t) => t.kind)).toEqual(['added']); + }); + + it('a person who signs in while the host is asked is not removed: 409, and the answer says the host was told', async () => { + const email = 'signs.in@example.com'; + let s!: Awaited>; + const { host } = removingHost({ + removed: () => { + s.row(email)!.source = 'idp_provisioned'; + }, + }); + s = await managedStage({ host }); + const id = await addPending(s, email); + + const v = await verdict(await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.admin)); + + expect(v.status, v.text).toBe(409); + expect(v.code).toBe('RESOURCE_CONFLICT'); + expect(v.message).toBe(`${PENDING_SSO_MESSAGES.removeNotPending} ${PENDING_SSO_MESSAGES.removeHostCancelled}`); + expect(s.row(email)).toMatchObject({ id, source: 'idp_provisioned' }); + expect(s.rowsOf('sys_member', id).length).toBeGreaterThan(0); + }); + + it('a person whose first sign-in commits inside the unit of work, after the pending read, is not removed: 409, and the child deletes roll back', async () => { + const email = 'signs.in.late@example.com'; + const { host } = removingHost(); + const s = await managedStage({ host }); + const id = await addPending(s, email); + const CHILDREN = ['sys_user_position', 'sys_user_permission_set', 'sys_member'] as const; + for (const table of CHILDREN) expect(s.rowsOf(table, id).length, table).toBeGreaterThan(0); + // The memory engine has no transaction, so the plugin's `runAtomically` + // would run the removal unatomically. Give it one: the seam calls + // `engine.transaction`, and a throw out of it restores every table this + // unit of work wrote. `sys_user` is left as it is, because its change is + // the concurrent sign-in's commit, not this unit of work's write. + let units = 0; + (s.engine as any).transaction = async (work: (trx: unknown, info: unknown) => Promise) => { + units += 1; + const before = new Map([...s.engine.tables].filter(([name]) => name !== 'sys_user').map(([name, rows]) => [name, structuredClone(rows)])); + try { + return await work({}, {}); + } catch (error) { + for (const [name, rows] of before) s.engine.tables.set(name, rows); + throw error; + } + }; + // The first sign-in lands between the in-unit pending read and the row's + // delete: the first child delete is the moment after that read. + const realDelete = s.engine.delete.bind(s.engine); + s.engine.delete = async (name: string, q: any = {}) => { + if (name === 'sys_user_position') s.row(email)!.source = 'idp_provisioned'; + return realDelete(name, q); + }; + + const v = await verdict(await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.admin)); + + expect(v.status, v.text).toBe(409); + expect(v.code).toBe('RESOURCE_CONFLICT'); + expect(v.message).toBe(`${PENDING_SSO_MESSAGES.removeNotPending} ${PENDING_SSO_MESSAGES.removeHostCancelled}`); + expect(s.row(email)).toMatchObject({ id, source: 'idp_provisioned' }); + expect(units, 'the removal ran inside the transactional seam').toBe(1); + for (const table of CHILDREN) expect(s.rowsOf(table, id).length, `${table} rolled back`).toBeGreaterThan(0); + }); +}); + // ───────────────────────────────────────────────────────────────────────────── // Setup → Users: Unlock is offered and works without the admin plugin // ───────────────────────────────────────────────────────────────────────────── diff --git a/packages/plugins/plugin-auth/src/pending-sso-users.ts b/packages/plugins/plugin-auth/src/pending-sso-users.ts index 55081adb195..d2608bc280f 100644 --- a/packages/plugins/plugin-auth/src/pending-sso-users.ts +++ b/packages/plugins/plugin-auth/src/pending-sso-users.ts @@ -227,19 +227,33 @@ function readPerson( async function findUserByEmail( engine: PendingSsoUserEngine, email: string, -): Promise<{ id: string; name?: string; source?: string | null } | undefined> { +): Promise<{ id: string; name?: string; source?: string | null; deactivated: boolean } | undefined> { const rows = await engine.find('sys_user', { where: { email }, - fields: ['id', 'name', 'source'], + fields: ['id', 'name', 'source', 'banned'], limit: 1, context: SYSTEM_CTX, }); - const row = Array.isArray(rows) ? (rows[0] as { id?: unknown; name?: unknown; source?: unknown } | undefined) : undefined; + const row = Array.isArray(rows) + ? (rows[0] as { id?: unknown; name?: unknown; source?: unknown; banned?: 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 } + ? { + id: row.id, + name: typeof row.name === 'string' ? row.name : undefined, + source: typeof row.source === 'string' ? row.source : null, + deactivated: isDeactivated(row), + } : undefined; } +/** + * Whether a `sys_user` row is deactivated. A boolean column reads back as + * `true`, `1`, or a string form (`'1'`, `'true'`) depending on the driver. + */ +const isDeactivated = (user: { banned?: unknown }): boolean => + user.banned === true || user.banned === 1 || user.banned === '1' || user.banned === 'true'; + /** 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); @@ -339,6 +353,11 @@ async function addOnePendingPerson( if (!isPendingSsoSource(existing.source)) { return { ok: false, result: fail(PENDING_SSO_REFUSAL_STATUS, PENDING_SSO_REFUSAL_CODE, PENDING_SSO_MESSAGES.alreadyExists) }; } + // A deactivated person is never sent an invitation: reactivating them + // (`admin/unban-user`) is what sends it again. + if (existing.deactivated) { + return { ok: true, userId: existing.id, alreadyPending: true, host: { notified: false, reason: 'deactivated' } }; + } const host = await notifyEnvironmentUserHost( deps.host, 'added', @@ -457,28 +476,45 @@ const hostRefusal = ({ refused }: EnvironmentUserHostRefused): EndpointResult => 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. + * Take a pending person back out: their grants, their membership and their + * row, as the system, in one unit of work, through the engine's delete, so a + * record that points at the person follows its lookup's `deleteBehavior`. + * Two callers: an add the host refused (the person was just written and + * never told anything), and `admin/remove-sso-user`, which passes + * `pendingOnly`. Then the person is re-checked inside the unit of work + * before anything is deleted, and the row's delete carries + * `source: 'idp_pending'` in its `where`: when it removes no row, + * {@link NoLongerPending} is thrown and the unit of work rolls the child + * deletes back. One window stays open: `sys_user` has cascading lookups, so + * the engine reads the matching ids, walks the cascade and then deletes by + * id alone, with no row lock, and a first sign-in committing between that + * read and that delete is not yet refused (#34373, an engine defect). A + * failure here is thrown: the caller must hear it rather than a clean + * answer. */ async function takeBackPerson( deps: PendingSsoUserDeps, engine: PendingSsoUserEngine, userId: string, settlement: RequestSettlement, + opts: { pendingOnly?: boolean } = {}, ): Promise { if (typeof engine.delete !== 'function') { - throw new Error(`The host refused user ${userId}, and this data engine cannot take the row back out`); + throw new Error(`This data engine cannot delete, so user ${userId} could not be taken back out`); } const remove = engine.delete.bind(engine); const work = async (): Promise => { + if (opts.pendingOnly) await assertStillPending(engine, userId); 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 }); + if (!opts.pendingOnly) { + await remove('sys_user', { where: { id: userId }, context }); + return; + } + const removed = await remove('sys_user', { where: { id: userId, source: PENDING_SSO_SOURCE }, multi: true, context }); + if (removed === 0 || removed === false || removed == null) throw new NoLongerPending(); }; const unit = settlement.grant?.seam ?? deps.createGrant; await (unit ? unit.runAtomically(work) : work()); @@ -684,3 +720,202 @@ export async function runImportSsoUsers( }, }; } + +const REMOVE_KEYS = new Set(['userId']); + +/** + * `POST /api/v1/auth/admin/remove-sso-user` — `{ userId }`. Removes a person + * who is still pending (the email-typo case) and cancels their invitation: + * the hosting rulings' "a pending row that never accepts … can be deleted, + * which cancels the invitation". The caller already passed the platform-admin + * gate. + * + * Refused for any row that is not pending (`409`): a person who has signed in + * is deactivated instead. The host is asked first, outside any transaction + * (`userRemoved`, or `userDeactivated` on a host without it), so its typed + * refusal leaves the person where they are. Then the person's positions, + * permission sets, membership and row are removed as the system, in one unit + * of work, through the engine's delete, so a record that points at the person + * follows its lookup's `deleteBehavior`: a `restrict` refuses the removal with + * the engine's own answer and nothing is removed. "Pending only" is held at + * the removal too: the person is re-checked inside the unit of work and the + * row's delete carries `source: 'idp_pending'`, so a person who signs in + * while the host is asked is answered `409` and kept (the narrow window the + * engine's delete leaves is in {@link takeBackPerson}). A host that could not be reached refuses the + * removal (`503`, nothing removed), as it refuses a deactivation: the door + * calls the host once and keeps no record to ask again from, so removing the + * person would leave an invitation nothing can cancel. With no host wired + * nothing is called. + */ +export async function runRemoveSsoUser( + deps: PendingSsoUserDeps, + actor: AdminActor & EnvironmentUserActor, + request: Request, +): Promise { + if (!deps.isCloudManaged()) { + return fail(PENDING_SSO_REFUSAL_STATUS, PENDING_SSO_REFUSAL_CODE, PENDING_SSO_MESSAGES.notManagedRemove); + } + 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) => !REMOVE_KEYS.has(key)); + if (unknownKeys.length > 0) return badRequest(`Unknown field(s): ${unknownKeys.join(', ')}. This door takes userId.`); + const userId = typeof body.userId === 'string' ? body.userId.trim() : ''; + if (!userId) return badRequest('userId is required'); + + const engine = deps.getDataEngine(); + if (!engine) return fail(503, 'SERVICE_UNAVAILABLE', 'Data engine unavailable, so no one was removed.'); + const rows = await engine.find('sys_user', { + where: { id: userId }, + fields: ['id', 'email', 'name', 'source'], + limit: 1, + context: SYSTEM_CTX, + }); + const target = (Array.isArray(rows) ? rows[0] : undefined) as + | { id?: unknown; email?: unknown; name?: unknown; source?: unknown } + | undefined; + if (!target) return fail(404, 'RESOURCE_NOT_FOUND', 'User not found'); + if (!isPendingSsoSource(target.source)) { + return fail(PENDING_SSO_REFUSAL_STATUS, PENDING_SSO_REFUSAL_CODE, PENDING_SSO_MESSAGES.removeNotPending); + } + const email = typeof target.email === 'string' ? target.email : ''; + const name = typeof target.name === 'string' ? target.name : ''; + + // The host first, outside any transaction: a refusal leaves the person as they are. + let host: EnvironmentUserHostOutcome; + let event: EnvironmentUserEvent | undefined; + if (deps.host) { + event = { + userId, + email, + name, + source: PENDING_SSO_SOURCE, + ...(await environmentUserAttribution(engine, actor, deps.logger)), + occurredAt: new Date().toISOString(), + }; + const answer = await notifyEnvironmentUserHost(deps.host, 'removed', event, deps.logger); + if ('refused' in answer) return hostRefusal(answer); + if (!answer.notified && answer.reason === 'host_failed') { + return fail(503, 'SERVICE_UNAVAILABLE', PENDING_SSO_MESSAGES.removeHostUnreachable); + } + host = answer; + } else { + host = { notified: false, reason: 'no_host' }; + } + + // Pending only, held at the write: the person may have signed in while the + // host was asked, and then they are not removed. + try { + await takeBackPerson(deps, engine, userId, {}, { pendingOnly: true }); + } catch (error) { + return removalNotDone(deps, engine, error, { userId, host, event }); + } + + return { status: 200, body: { success: true, data: { userId, email, removed: true, host } } }; +} + +/** Throws {@link NoLongerPending} unless the person is still pending, read now. */ +async function assertStillPending(engine: PendingSsoUserEngine, userId: string): Promise { + const now = await engine.find('sys_user', { where: { id: userId }, fields: ['id', 'source'], limit: 1, context: SYSTEM_CTX }); + const row = (Array.isArray(now) ? now[0] : undefined) as { source?: unknown } | undefined; + if (!row || !isPendingSsoSource(row.source)) throw new NoLongerPending(); +} + +/** Thrown inside the removal's unit of work when the person is no longer pending there. */ +class NoLongerPending extends Error { + constructor() { + super('The person is no longer pending'); + } +} + +/** + * The answer when the removal's unit of work did not commit: no one was + * removed. What the host was told is said as it happened. When the host had + * taken the cancellation and the person is still pending and not + * deactivated, their invitation is sent again here, once, through + * `userAdded`, and the answer says whether that worked; nothing is retried + * later. + */ +async function removalNotDone( + deps: PendingSsoUserDeps, + engine: PendingSsoUserEngine, + error: unknown, + call: { userId: string; host: EnvironmentUserHostOutcome; event: EnvironmentUserEvent | undefined }, +): Promise { + const { userId, host, event } = call; + // A host that could not be reached refused the removal before this, so the + // host was either told (and took the cancellation) or not called at all. + const told = event !== undefined && host.notified; + const hostSentence = told ? PENDING_SSO_MESSAGES.removeHostCancelled : ''; + + if (error instanceof NoLongerPending) { + return fail( + PENDING_SSO_REFUSAL_STATUS, + PENDING_SSO_REFUSAL_CODE, + [PENDING_SSO_MESSAGES.removeNotPending, hostSentence].filter(Boolean).join(' '), + ); + } + + const thrown = resolveThrownHttpError(error, 500); + const cause = thrown.status >= 500 ? INTERNAL_ERROR_MESSAGE : thrown.message; + if (thrown.status >= 500) { + const line = `[AuthPlugin] removing pending user ${userId} failed, so no one was removed`; + if (deps.logger?.error) deps.logger.error(line, error instanceof Error ? error : undefined); + else deps.logger?.warn(`${line}. Cause: ${error instanceof Error ? error.message : String(error)}`); + } + let after = hostSentence; + if (told) { + const person = await readPersonState(engine, userId); + if (person.pending && !person.deactivated) { + after = (await reinvite(deps, event!)) + ? PENDING_SSO_MESSAGES.removeRefusedReinvited + : PENDING_SSO_MESSAGES.removeRefusedNotReinvited; + } + } + return fail(thrown.status, thrown.code, [PENDING_SSO_MESSAGES.removeRefused, cause, after].filter(Boolean).join(' ')); +} + +/** Whether the person is pending and whether they are deactivated, read now; unreadable reads as neither safe. */ +async function readPersonState( + engine: PendingSsoUserEngine, + userId: string, +): Promise<{ pending: boolean; deactivated: boolean }> { + try { + const rows = await engine.find('sys_user', { + where: { id: userId }, + fields: ['id', 'source', 'banned'], + limit: 1, + context: SYSTEM_CTX, + }); + const row = (Array.isArray(rows) ? rows[0] : undefined) as { source?: unknown; banned?: unknown } | undefined; + if (!row) return { pending: false, deactivated: false }; + return { pending: isPendingSsoSource(row.source), deactivated: isDeactivated(row) }; + } catch { + return { pending: false, deactivated: true }; + } +} + +/** + * Send the invitation again, once, to a pending person whose removal failed + * after the host took the cancellation of theirs (`userAdded`). Answers + * whether the host took it; a refusal or failure is logged at `error`: the + * person stays pending with no invitation until they are added again. + */ +async function reinvite(deps: PendingSsoUserDeps, event: EnvironmentUserEvent): Promise { + const answer = await notifyEnvironmentUserHost( + deps.host, + 'added', + { ...event, occurredAt: new Date().toISOString() }, + deps.logger, + ); + if (!('refused' in answer) && answer.notified) return true; + const cause = 'refused' in answer ? `${answer.refused.code}: ${answer.refused.message}` : answer.reason; + const message = + `[AuthPlugin] removing pending user ${event.userId} failed after the hosting organisation was told to cancel ` + + 'their invitation, and sending it again did not succeed, so they stay pending with no invitation. ' + + `Add them again to send one. Cause: ${cause}`; + const logger = deps.logger as { warn(msg: string): void; error?(msg: string): void } | undefined; + if (logger?.error) logger.error(message); + else logger?.warn(message); + return false; +} 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 f8a0e33d20b..fe7099979b2 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 @@ -263,6 +263,10 @@ const ADMITTED = [ // `pending-sso-users.test.ts`. 'POST /api/v1/auth/admin/add-sso-user', 'POST /api/v1/auth/admin/import-sso-users', + // Remove a pending person (cancels their invitation): the same gate first, + // and off a managed environment the same `409 RESOURCE_CONFLICT`; its effect + // is pinned in plugin-auth's `pending-sso-users.test.ts`. + 'POST /api/v1/auth/admin/remove-sso-user', 'POST /api/v1/auth/admin/oauth2/toggle-disabled', 'POST /api/v1/auth/admin/impersonate-user', 'POST /api/v1/auth/admin/sso/register', @@ -760,6 +764,9 @@ describe('#9482: what an ObjectStack platform admin gets from every /admin/ rout 'POST /api/v1/auth/admin/import-sso-users': { body: { rows: [{ email: 'standing.sweep.pending.import@example.com', name: 'Sweep Pending Import' }] }, }, + // A valid remove body naming a person who is not pending, so even a + // managed boot would refuse it 409 and remove no one. + 'POST /api/v1/auth/admin/remove-sso-user': { body: { userId: targetUserId } }, // #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 e1bdf3b750e..7a533ec8db2 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 @@ -287,6 +287,14 @@ function expectationsFor(targetUserId: string): Record 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', }, + // The pending-person remove door: the same gate first, the same 409 off a + // managed environment. The probe names a person who is not pending, so a + // managed boot would refuse it 409 too and remove no one. + 'POST /api/v1/auth/admin/remove-sso-user': { + bucket: 'objectstack-gate', + body: { userId: targetUserId }, + note: 'the gate runs first; off a managed environment the admin gets 409 RESOURCE_CONFLICT and no one is removed', + }, // ── ADR-0095 D3 — the platform-admin roster (a read; no body is read) ─── 'POST /api/v1/auth/admin/list-platform-admins': { bucket: 'objectstack-gate',