Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/34404-remove-sso-user-audit-row.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/plugin-auth': patch
---

fix(plugin-auth): removing a pending person writes an admin audit row, and the host-failure texts say the removal is refused

Clause-②: no
Metadata-protocol: none

`POST /api/v1/auth/admin/remove-sso-user` now writes one `sys_audit_log` row for a removal that committed, through the same writer the add doors use: `action: 'delete'` on the removed `sys_user`, naming the administrator, with `metadata` `{ event: 'user.admin_removed_pending', hostNotified }` (`hostNotified` is whether the environment-user host took the cancellation of the invitation; `false` with no host wired). A refused removal (a host that cannot be reached, a host's refusal, a person who is not pending, a failed delete) writes no row. With plugin-audit uninstalled no row is written, as for the other admin user doors.

The removal door already refused with `503 SERVICE_UNAVAILABLE` when the environment-user host could not be reached, but the `warn` line logged in that case still said "The removal goes ahead.", and the `EnvironmentUserHost` and `environmentUserHost` option docs said a host failure is only reported on a removal. All three now say the removal is refused. Behaviour of the door is unchanged.
11 changes: 10 additions & 1 deletion packages/plugins/plugin-auth/src/admin-user-endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,15 @@ export type AdminAuditDecisions =
membershipCreated: boolean;
organizationId?: string;
}
| {
/**
* A pending person was removed (`pending-sso-users.ts`, `admin/remove-sso-user`).
* `hostNotified`: the environment-user host took the cancellation of their
* invitation (false when no host is wired; a host that failed refused the removal).
*/
event: 'user.admin_removed_pending';
hostNotified: boolean;
}
| {
event: 'user.admin_password_set';
passwordGenerated: boolean;
Expand Down Expand Up @@ -618,7 +627,7 @@ export type AdminAuditDecisions =
export async function writeAdminAudit(
deps: Pick<AdminUserEndpointDeps, 'getDataEngine' | 'logger'>,
entry: {
action: 'create' | 'update';
action: 'create' | 'update' | 'delete';
actor: AdminActor;
recordId: string;
metadata: AdminAuditDecisions;
Expand Down
4 changes: 2 additions & 2 deletions packages/plugins/plugin-auth/src/auth-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -395,8 +395,8 @@ export interface AuthPluginOptions extends Partial<AuthConfig> {
* 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.
* deactivation or a removal (`503`) and is reported on an add or a
* reactivation as `host: { notified: false, reason }`, which it never undoes.
*/
environmentUserHost?: EnvironmentUserHostAccessor;

Expand Down
13 changes: 7 additions & 6 deletions packages/plugins/plugin-auth/src/environment-user-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@
* `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' }`.
* side. On a removal it refuses the removal (`503`, nothing removed): the
* door calls the host once and keeps no record to ask again from. 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.
Expand Down Expand Up @@ -70,8 +71,8 @@ export interface EnvironmentUserEvent {
* 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.
* refuses a deactivation or a removal (`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. */
Expand Down Expand Up @@ -275,7 +276,7 @@ const goesAhead = (kind: EnvironmentUserEventKind): string =>
: kind === 'deactivated'
? 'The deactivation is refused: only the host can say whether this person may be removed.'
: kind === 'removed'
? 'The removal goes ahead.'
? 'The removal is refused: the door keeps no record to ask the host again from.'
: 'The change goes ahead.';

const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));
76 changes: 76 additions & 0 deletions packages/plugins/plugin-auth/src/pending-sso-users.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1484,6 +1484,82 @@ describe('[#33228] a deactivated person is never sent an invitation, and a remov
});
});

/** The admin audit rows a removal writes (`writeAdminAudit`, action `delete`); an add's row is `create`. */
const removalAuditRows = (s: Awaited<ReturnType<typeof stage>>): any[] =>
((s.engine.tables.get('sys_audit_log') ?? []) as any[]).filter((r) => r.action === 'delete');

describe('[#34404] admin/remove-sso-user writes an admin audit row for a removal that committed', () => {
it('a removal the host took writes one delete row naming the admin, the person and the decision', async () => {
const { host } = removingHost();
const s = await managedStage({ host });
const id = await addPending(s, 'audit.typo@exmaple.com');

const res = await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.admin);

expect(res.status, await res.clone().text()).toBe(200);
expect(s.row('audit.typo@exmaple.com')).toBeUndefined();
const rows = removalAuditRows(s);
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({
action: 'delete',
user_id: s.ids.admin,
actor: s.ids.admin,
object_name: 'sys_user',
record_id: id,
});
expect(JSON.parse(rows[0].metadata)).toEqual({ event: 'user.admin_removed_pending', hostNotified: true });
});

it('a removal with no host wired writes the row with hostNotified false', async () => {
const s = await managedStage({ host: 'none' });
const id = await addPending(s, 'audit.nohost@example.com');

expect((await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.admin)).status).toBe(200);

const rows = removalAuditRows(s);
expect(rows).toHaveLength(1);
expect(JSON.parse(rows[0].metadata)).toEqual({ event: 'user.admin_removed_pending', hostNotified: false });
});

it('CONTROL: a host that cannot be reached refuses the removal with 503 and no row is written', async () => {
const { host } = removingHost({
removed: () => {
throw new Error('connect ECONNREFUSED');
},
});
const s = await managedStage({ host });
const id = await addPending(s, 'audit.unreachable@example.com');

const v = await verdict(await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.admin));

expect(v.status, v.text).toBe(503);
expect(v.code).toBe('SERVICE_UNAVAILABLE');
expect(s.row('audit.unreachable@example.com')).toBeDefined();
expect(removalAuditRows(s)).toHaveLength(0);
});

it('CONTROL: a host refusal and a person who is not pending write no row', async () => {
const { host } = removingHost({
removed: () => {
throw new EnvironmentUserHostRefusal(409, 'RESOURCE_CONFLICT', 'An organization owner cannot be removed here.');
},
});
const s = await managedStage({ host });
const id = await addPending(s, 'audit.refused@example.com');

const refused = await verdict(await s.fire('/admin/remove-sso-user', { userId: id }, s.bearers.admin));
expect(refused.status, refused.text).toBe(409);
expect(refused.code).toBe('RESOURCE_CONFLICT');
expect(s.row('audit.refused@example.com')).toBeDefined();

const notPending = await verdict(await s.fire('/admin/remove-sso-user', { userId: s.ids.member }, s.bearers.admin));
expect(notPending.status, notPending.text).toBe(409);
expect(notPending.code).toBe('RESOURCE_CONFLICT');

expect(removalAuditRows(s)).toHaveLength(0);
});
});

// ─────────────────────────────────────────────────────────────────────────────
// Setup → Users: Unlock is offered and works without the admin plugin
// ─────────────────────────────────────────────────────────────────────────────
Expand Down
11 changes: 10 additions & 1 deletion packages/plugins/plugin-auth/src/pending-sso-users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -800,7 +800,8 @@ const REMOVE_KEYS = new Set(['userId']);
* 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.
* nothing is called. A removal that commits writes one admin audit row
* (`writeAdminAudit`, `user.admin_removed_pending`); a refused one writes none.
*/
export async function runRemoveSsoUser(
deps: PendingSsoUserDeps,
Expand Down Expand Up @@ -868,6 +869,14 @@ export async function runRemoveSsoUser(
return removalNotDone(deps, engine, error, { userId, host, event });
}

// The admin audit row the add doors write, for the removal that committed:
// never on a refusal (nothing was removed), never failing the answer.
await writeAdminAudit(deps, {
action: 'delete',
actor,
recordId: userId,
metadata: { event: 'user.admin_removed_pending', hostNotified: host.notified },
});
return { status: 200, body: { success: true, data: { userId, email, removed: true, host } } };
}

Expand Down
Loading