Skip to content

Commit 9bb42bb

Browse files
committed
fix(plugin-auth): hold the environment-user outbox to the invitation rules
No invitation is sent to a deactivated person; a removal holds to pending people at the write; calls are recorded only on a cloud-managed kernel, where the worker drains them. Prose says which calls are recorded. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibx2sFAzcNAfxCPdUtF
1 parent 17f7933 commit 9bb42bb

11 files changed

Lines changed: 352 additions & 69 deletions

‎.changeset/33228-remove-pending-outbox.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
'@objectstack/cli': patch
66
---
77

8-
feat(auth): a cloud-managed environment can remove a pending person, cancelling their invitation, and every call to the environment-user host is retried from a durable outbox
8+
feat(auth): a cloud-managed environment can remove a pending person, cancelling their invitation, and every invitation call to the environment-user host is retried from a durable outbox
99

10-
Clause-②: yes (widening) — added: `POST /api/v1/auth/admin/remove-sso-user` (platform administrators, cloud-managed environments only) removes a person who is still pending (`sys_user.source = 'idp_pending'`) and cancels their invitation at the host; the environment-user host contract gains an optional `userRemoved` member and an optional `deliveryId` on every event; the add, import, ban and unban answers gain an optional `invitation: { id, status }`; a new read-only system object `sys_environment_user_outbox` records each call. Nothing that was accepted is refused, and no existing answer field changes.
10+
Clause-②: yes (widening) — added: `POST /api/v1/auth/admin/remove-sso-user` (platform administrators, cloud-managed environments only) removes a person who is still pending (`sys_user.source = 'idp_pending'`) and cancels their invitation at the host; the environment-user host contract gains an optional `userRemoved` member and an optional `deliveryId` on every event; the add, import, ban and unban answers gain an optional `invitation: { id, status }`; a new read-only system object `sys_environment_user_outbox` records each invitation call on a cloud-managed environment. Nothing that was accepted is refused, and no existing answer field changes.
1111
Metadata-protocol: none
1212

1313
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, and a host call that failed (a network error, a host outage) was logged and lost.
@@ -18,9 +18,9 @@ On a cloud-managed environment, a person added to sign in through the hosting or
1818
- A host refusal (403/409) answers with the host's sentence, and no one is removed.
1919
- A host that cannot be reached does not block the removal. The cancellation is queued and retried.
2020
- With no host wired, the person is removed and the answer says `host: { notified: false, reason: 'no_host' }`.
21-
- A person who is not pending answers `409`: deactivate them instead. 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, a re-send is queued so they stay pending as before.
21+
- A person who is not pending answers `409`: deactivate them instead. This holds at the removal itself, so a person who signs in while the host is asked is not removed. A person that other records still point at (`deleteBehavior: 'restrict'`) answers the engine's refusal, and nothing is removed. The answer says what the host was told. If the host had already taken the cancellation, a re-send is queued for a person who is still pending and not deactivated. A deactivated person is never sent an invitation.
2222
- On an environment that is not cloud-managed the door answers `409` and removes no one.
2323

24-
**Outbox.** Every call to the host about a person (invited, deactivated while pending, re-sent on reactivation, removed) writes a row to `sys_environment_user_outbox`. The door that acts still makes the first call itself, outside any database transaction, so a typed refusal (such as the developer member cap) still reaches the administrator on that request. A call the host did not take stays `pending` and a worker retries it, backing off from one minute to twelve hours, until the host takes it or twelve attempts fail (`failed`, logged as an error). A typed refusal on a retry ends the row as `failed` with the host's code and sentence, and the person stays pending. The worker starts only on a cloud-managed environment with a host wired. Each call carries the row id as `deliveryId`, so a host can drop a repeat. The newest row of a person is their invitation status, which Setup → Users reads through the data API (`get` / `list`, platform administrators only). An `added` row becomes `accepted` when the person first signs in.
24+
**Outbox.** On a cloud-managed environment, every invitation call to the host about a person (invited, deactivated while pending, re-sent on reactivation, removed) writes a row to `sys_environment_user_outbox`; the deactivation of a person who has signed in is asked of the host but not recorded, and off a cloud-managed environment nothing is recorded. The door that acts still makes the first call itself, outside any database transaction, so a typed refusal (such as the developer member cap) still reaches the administrator on that request. A call the host did not take stays `pending` and a worker retries it, backing off from one minute to twelve hours, until the host takes it or twelve attempts fail (`failed`, logged as an error). A typed refusal on a retry ends the row as `failed` with the host's code and sentence, and the person stays pending. The worker starts only on a cloud-managed environment with a host wired. Each call carries the row id as `deliveryId`, so a host can drop a repeat; a host cancels by `userId` or `deliveryId`, never by email address. The newest row of a person is their invitation status, which Setup → Users reads through the data API (`get` / `list`, platform administrators only). An `added` row becomes `accepted` when the person first signs in.
2525

2626
Nothing to migrate. A host that ignores `deliveryId` keeps working: repeats of the same call already happen today when a person is re-added.

‎content/docs/permissions/authentication.mdx‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1338,15 +1338,20 @@ first, through its `userRemoved` member; a host without that member is asked
13381338
through `userDeactivated` for the pending person instead, which means the same
13391339
thing, but a host should implement `userRemoved`. A host's refusal leaves the
13401340
person as they are. A person who is not pending (they have signed in, or were
1341-
not added this way) is refused with `409`: deactivate them instead. A record
1341+
not added this way) is refused with `409`: deactivate them instead. That holds
1342+
at the removal itself, so a person who signs in while the host is asked is not
1343+
removed either, and the answer says the host was already told. A record
13421344
that still points at the person through a lookup that restricts deletes
13431345
refuses the removal with that lookup's own answer, and nothing is removed.
13441346
Like the add doors, it is platform-admin gated and answers `409` off a managed
13451347
environment.
13461348

1347-
Every call to the host about a person is recorded in
1349+
On a cloud-managed environment these calls are recorded in
13481350
`sys_environment_user_outbox`, one row per call, readable by platform
1349-
administrators. The door still makes the first call itself, so a refusal
1351+
administrators: every invitation sent (an add or re-add), every re-send (a
1352+
reactivation), and every cancellation (a removal, or the deactivation of a
1353+
person still pending). The deactivation of a person who has signed in is asked
1354+
of the host but not recorded. The door still makes the first call itself, so a refusal
13501355
reaches the administrator on that request, row by row. A call the host did not
13511356
take stays `pending` and is retried in the background with a growing wait (one
13521357
minute at first, up to twelve hours), and after twelve attempts it is
@@ -1358,8 +1363,10 @@ newest row of a person is their invitation status: `sent`, `accepted` once
13581363
their first sign-in clears the pending state, `failed`, or, for a deactivation
13591364
or removal, the cancelled invitation. A call can reach the host more than
13601365
once, so each carries the row's id as `deliveryId` for the host to drop a
1361-
repeat. The add, deactivate, reactivate and remove answers name the row as
1362-
`invitation: { id, status }`.
1366+
repeat. A host cancels an invitation by the event's `userId` or `deliveryId`, never by
1367+
its email address, which an administrator may have typed wrong and may type
1368+
again for someone else. The add, deactivate, reactivate and remove answers
1369+
name the row as `invitation: { id, status }`.
13631370

13641371
`admin/ban-user` and `admin/unban-user` work without the admin plugin: on a
13651372
deployment without it the ban is written by the platform, and a banned user is

‎packages/platform-objects/src/identity/sys-environment-user-outbox.object.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33
import { ObjectSchema, Field } from '@objectstack/spec/data';
44

55
/**
6-
* sys_environment_user_outbox — the durable record of every call the
7-
* environment makes to its environment-user host (the cloud, on a hosted
8-
* environment) about one person: an invitation sent when a pending person is
9-
* added or re-added, cancelled when one is deactivated or removed, and
10-
* re-sent when a person is reactivated.
6+
* sys_environment_user_outbox — on a cloud-managed environment, the durable
7+
* record of the calls the environment makes to its environment-user host (the
8+
* cloud) about one person's invitation: sent when a pending person is added or
9+
* re-added, cancelled when a pending person is deactivated or removed, and
10+
* re-sent when a person is reactivated. The deactivation of a person who has
11+
* signed in is asked of the host but not recorded here.
1112
*
1213
* Why it exists: the execution terms of the hosting rulings (relayed on the
1314
* pending-people card) ask for "a durable outbox with retry … with per-row

‎packages/plugins/plugin-auth/src/admin-ban-endpoints.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ import {
117117
newOutboxId,
118118
outboxDoc,
119119
outboxNextAttemptAt,
120+
OUTBOX_UNSENT_STATUSES,
120121
supersedeOpenOutboxRows,
121122
type OutboxBirth,
122123
} from './environment-user-outbox.js';
@@ -149,6 +150,11 @@ export interface AdminBanEndpointDeps {
149150
getDataEngine?(): any;
150151
/** Wakes the outbox worker for a reactivation queued for retry (`environment-user-outbox.ts`). */
151152
wakeOutbox?(atMs: number): void;
153+
/**
154+
* Whether the kernel is cloud-managed. Only there does the outbox worker
155+
* run, so only there is a call recorded; absent reads as not managed.
156+
*/
157+
isCloudManaged?(): boolean;
152158
logger?: { warn(msg: string): void; error?(msg: string, err?: Error): void };
153159
}
154160

@@ -188,7 +194,9 @@ async function askHost(
188194
occurredAt: new Date().toISOString(),
189195
};
190196
const deliveryId = newOutboxId();
191-
const outcome = await notifyEnvironmentUserHost(deps.host, kind, { ...event, deliveryId }, deps.logger);
197+
const outcome = await notifyEnvironmentUserHost(deps.host, kind, { ...event, deliveryId }, deps.logger, {
198+
retried: deps.isCloudManaged?.() === true,
199+
});
192200
return { outcome, event, deliveryId };
193201
}
194202

@@ -205,13 +213,15 @@ async function recordAsk(
205213
kind: 'deactivated' | 'reactivated',
206214
ask: HostAsk,
207215
): Promise<{ id: string; status: 'sent' | 'pending' } | undefined> {
216+
// Off a cloud-managed kernel no worker drains the outbox, so nothing is recorded.
217+
if (deps.isCloudManaged?.() !== true) return undefined;
208218
const engine = deps.getDataEngine?.();
209219
if (!engine || 'refused' in ask.outcome) return undefined;
210220
const outcome = ask.outcome;
211221
if (!outcome.notified && outcome.reason === 'no_host') return undefined;
212222
try {
213223
if (kind === 'deactivated') {
214-
await supersedeOpenOutboxRows(engine, ask.event.userId, ['added', 'reactivated']);
224+
await supersedeOpenOutboxRows(engine, ask.event.userId, ['added', 'reactivated'], OUTBOX_UNSENT_STATUSES);
215225
if (!outcome.notified || !isPendingSsoSource(ask.event.source)) return undefined;
216226
} else {
217227
await supersedeOpenOutboxRows(engine, ask.event.userId, ['reactivated']);

‎packages/plugins/plugin-auth/src/auth-plugin.ts‎

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -394,12 +394,15 @@ export interface AuthPluginOptions extends Partial<AuthConfig> {
394394
* [#33181] The environment-user host (`environment-user-host.ts`): told
395395
* after a person is added through `admin/add-sso-user` or
396396
* `admin/import-sso-users`, and asked before a person is deactivated
397-
* through `admin/ban-user` or reactivated through `admin/unban-user`. Read
398-
* per call, so a host wired after boot is still found. A typed
399-
* `EnvironmentUserHostRefusal` refuses the operation (a refused add is
400-
* taken back out); any other failure refuses a deactivation (`503`) and is
401-
* reported on an add or a reactivation as `host: { notified: false,
402-
* reason }`, which it never undoes.
397+
* through `admin/ban-user`, reactivated through `admin/unban-user`, or a
398+
* pending person is removed through `admin/remove-sso-user` (`userRemoved`,
399+
* else `userDeactivated`). Read per call, so a host wired after boot is
400+
* still found. A typed `EnvironmentUserHostRefusal` refuses the operation
401+
* (a refused add is taken back out); any other failure refuses a
402+
* deactivation (`503`) and is reported on an add, a reactivation or a
403+
* removal as `host: { notified: false, reason }`, which it never undoes.
404+
* On a cloud-managed kernel those calls are recorded in the
405+
* environment-user outbox and retried (`environment-user-outbox.ts`).
403406
*/
404407
environmentUserHost?: EnvironmentUserHostAccessor;
405408

@@ -2294,14 +2297,24 @@ export class AuthPlugin implements Plugin {
22942297
// The environment-user outbox (`environment-user-outbox.ts`): on a
22952298
// cloud-managed kernel with a host wired, a pending person's
22962299
// invitation reads `accepted` once they sign in, and the worker
2297-
// retries every call the host did not take. Elsewhere no outbox row
2298-
// is ever written, so neither runs.
2300+
// retries every recorded call the host did not take. The doors
2301+
// record only on a cloud-managed kernel, so elsewhere neither runs.
2302+
// A boot that fails is logged here, never left to the catch below:
2303+
// the rows it would drain wait for the next boot.
22992304
if (!this.environmentUserOutbox) {
2300-
this.environmentUserOutbox = bootEnvironmentUserOutbox(engine as unknown as OutboxHookEngine, {
2301-
host: this.options.environmentUserHost,
2302-
isCloudManaged,
2303-
logger: ctx.logger,
2304-
}) ?? null;
2305+
try {
2306+
this.environmentUserOutbox = bootEnvironmentUserOutbox(engine as unknown as OutboxHookEngine, {
2307+
host: this.options.environmentUserHost,
2308+
isCloudManaged,
2309+
logger: ctx.logger,
2310+
}) ?? null;
2311+
} catch (e) {
2312+
ctx.logger.error(
2313+
'[AuthPlugin] the environment-user outbox worker did not start, so invitations and cancellations '
2314+
+ 'the hosting organisation did not take are not retried until the next boot. Cause: '
2315+
+ `${e instanceof Error ? e.message : String(e)}`,
2316+
);
2317+
}
23052318
}
23062319
try {
23072320
await refreshAllMappingMatches(engine);
@@ -4951,6 +4964,7 @@ export class AuthPlugin implements Plugin {
49514964
...(this.options.environmentUserHost ? { host: this.options.environmentUserHost } : {}),
49524965
getDataEngine: () => this.authManager!.getDataEngine(),
49534966
wakeOutbox: this.wakeEnvironmentUserOutbox,
4967+
isCloudManaged: () => isCloudManaged(),
49544968
logger: ctx.logger,
49554969
});
49564970

‎packages/plugins/plugin-auth/src/environment-user-host.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,13 +236,16 @@ export async function environmentUserAttribution(
236236
/**
237237
* Tell the host, once. Never throws. A typed refusal is answered as
238238
* `{ refused }` for the door to return; any other failure as `host_failed`
239-
* on the caller's row, logged at `warn` with its message.
239+
* on the caller's row, logged at `warn` with its message. `opts.retried`
240+
* says the caller records the call in the outbox, so the log may say it is
241+
* retried; a caller that records nothing leaves it unset.
240242
*/
241243
export async function notifyEnvironmentUserHost(
242244
accessor: EnvironmentUserHostAccessor | undefined,
243245
kind: EnvironmentUserEventKind,
244246
event: EnvironmentUserEvent,
245247
logger?: { warn(msg: string): void },
248+
opts: { retried?: boolean } = {},
246249
): Promise<EnvironmentUserHostOutcome | EnvironmentUserHostRefused> {
247250
let host: EnvironmentUserHost | undefined;
248251
try {
@@ -266,7 +269,7 @@ export async function notifyEnvironmentUserHost(
266269
logger?.warn(
267270
`[AuthPlugin] the environment-user host refused or failed to take the news that user ${event.userId} was `
268271
+ `${kind}. ${goesAhead(kind)} The answer says so. `
269-
+ (kind === 'deactivated' ? '' : 'The call is retried. ')
272+
+ (opts.retried && kind !== 'deactivated' ? 'The call is retried. ' : '')
270273
+ `Cause: ${describe(error)}`,
271274
);
272275
return { notified: false, reason: 'host_failed' };

‎packages/plugins/plugin-auth/src/environment-user-outbox.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,28 @@ describe('the worker\'s pass', () => {
211211
expect(active.calls.map((c) => c.member)).toEqual(['userReactivated']);
212212
});
213213

214+
it('an invitation for a pending person who was deactivated is superseded, waiting or stranded in flight; the host is not called', async () => {
215+
const h = harness({ user: { banned: 1 } });
216+
h.seed(h.pendingRow());
217+
h.seed(h.pendingRow({ id: 'row_2', status: 'in_flight', claim_token: 'dead', claimed_until: NOW - 1 }));
218+
await runEnvironmentUserOutboxTick(h.deps);
219+
expect(h.calls).toHaveLength(0);
220+
expect(h.rows().map((r) => r.status)).toEqual(['superseded', 'superseded']);
221+
});
222+
223+
it('a cancellation for a person who signed in meanwhile is superseded; CONTROL: one for a person still pending is sent', async () => {
224+
const signedIn = harness({ user: { source: 'idp_provisioned' } });
225+
signedIn.seed(signedIn.pendingRow({ kind: 'removed' }));
226+
await runEnvironmentUserOutboxTick(signedIn.deps);
227+
expect(signedIn.calls).toHaveLength(0);
228+
expect(signedIn.rows()[0]).toMatchObject({ status: 'superseded' });
229+
230+
const pending = harness();
231+
pending.seed(pending.pendingRow({ kind: 'removed' }));
232+
await runEnvironmentUserOutboxTick(pending.deps);
233+
expect(pending.calls.map((c) => c.member)).toEqual(['userDeactivated']);
234+
});
235+
214236
it('a removal is sent on userRemoved, or on userDeactivated by a host without it', async () => {
215237
const removed = vi.fn();
216238
const own = harness({ user: null, host: { userRemoved: removed } });

0 commit comments

Comments
 (0)