Skip to content

Commit 64d7c50

Browse files
committed
fix(plugin-auth): ban and unban write the admin audit row; name the remove-sso-user row in the ledger note and docs
A ban or an unban that committed now writes the sibling doors' admin audit row (writeAdminAudit, action update, event user.admin_banned / user.admin_unbanned, hostNotified). A refused one writes none. Measured: without the admin plugin the engine ban writer carries no attributed user, so plugin-audit's mirror row names no administrator. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibyy9KSA69EGZtjDj9c
1 parent 598a34d commit 64d7c50

6 files changed

Lines changed: 95 additions & 5 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
Clause-②: no
6+
Metadata-protocol: none
7+
8+
`POST /api/v1/auth/admin/ban-user` and `POST /api/v1/auth/admin/unban-user` now write one `sys_audit_log` row for a change that committed, through the same writer the other admin user doors use: `action: 'update'` on the target `sys_user`, naming the administrator, with `metadata` `{ event: 'user.admin_banned' | 'user.admin_unbanned', hostNotified }`. A refused ban or unban writes no row. Without the admin plugin, plugin-audit's own row for the ban columns names no administrator, so this row is the record of who banned. The ban reason and expiry stay on plugin-audit's row for the user's change, not in `metadata`. The route ledger note for `admin/remove-sso-user` and the authentication docs now name that door's `user.admin_removed_pending` row.

‎content/docs/permissions/authentication.mdx‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1462,8 +1462,11 @@ still points at the person through a lookup that restricts deletes refuses the
14621462
removal with that lookup's own answer, and nothing is removed; when the host
14631463
had already cancelled the invitation of a person who is still pending and not
14641464
deactivated, the door sends the invitation again through `userAdded`, once,
1465-
and the answer says whether that worked. Like the add doors, it is
1466-
platform-admin gated and answers `409` off a managed environment.
1465+
and the answer says whether that worked. A removal that committed writes one
1466+
`sys_audit_log` row naming the administrator (`action: 'delete'`, `metadata`
1467+
`{ event: 'user.admin_removed_pending', hostNotified }`); a refused one writes
1468+
none. Like the add doors, it is platform-admin gated and answers `409` off a
1469+
managed environment.
14671470

14681471
A deactivated person is never sent an invitation: adding a deactivated pending
14691472
person again calls no host and answers `host: { notified: false, reason:
@@ -1480,7 +1483,10 @@ administrator may have typed wrong and may type again for someone else.
14801483
`admin/ban-user` and `admin/unban-user` work without the admin plugin: on a
14811484
deployment without it the ban is written by the platform, and a banned user is
14821485
refused a session with the same `403 BANNED_USER` answer the admin plugin
1483-
gives.
1486+
gives. A ban or an unban that committed writes one `sys_audit_log` row naming
1487+
the administrator (`action: 'update'`, `metadata` `{ event, hostNotified }`, the
1488+
event `user.admin_banned` or `user.admin_unbanned`); a refused one writes none.
1489+
The reason and expiry are on the row plugin-audit records for the user's change.
14841490

14851491
#### SCIM Connection Credentials
14861492

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

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,15 @@
9090
* false, … }` on the answer. The event names the administrator, the one at
9191
* the keyboard on an impersonation session, and their cloud user id read
9292
* from their linked `objectstack-cloud` account, never from the request.
93+
*
94+
* ── The admin audit row ─────────────────────────────────────────────────────
95+
*
96+
* A ban or an unban that committed writes the sibling doors' admin audit row
97+
* (`writeAdminAudit`, action `update`, event `user.admin_banned` /
98+
* `user.admin_unbanned`); a refused one writes none. plugin-audit's mirror row
99+
* for the column write does not stand in for it: without the admin plugin the
100+
* engine writer carries no attributed user, so that row names no
101+
* administrator, and on neither path does it carry the event or `hostNotified`.
93102
*/
94103

95104
import {
@@ -98,7 +107,7 @@ import {
98107
LAST_LOCAL_CREDENTIAL_MESSAGE,
99108
type CredentialAccountAdapter,
100109
} from './last-local-credential.js';
101-
import type { AdminActor, EndpointResult } from './admin-user-endpoints.js';
110+
import { writeAdminAudit, type AdminActor, type EndpointResult } from './admin-user-endpoints.js';
102111
import { applyUserBan, applyUserUnban, type UserBanWriter } from './user-ban-write.js';
103112
import { readJsonRequestBody } from './request-json-body.js';
104113
import { readUserSource } from './sso-only-local-password.js';
@@ -195,6 +204,19 @@ const HOST_UNANSWERED_DEACTIVATION: EndpointResult = {
195204
},
196205
};
197206

207+
/** The admin audit row for a ban or an unban that committed; never fails the answer. */
208+
const auditBan = (
209+
deps: AdminBanEndpointDeps,
210+
actor: AdminActor,
211+
userId: string,
212+
event: 'user.admin_banned' | 'user.admin_unbanned',
213+
host: EnvironmentUserHostOutcome | undefined,
214+
): Promise<void> =>
215+
writeAdminAudit(
216+
{ getDataEngine: () => deps.getDataEngine?.(), logger: deps.logger },
217+
{ action: 'update', actor, recordId: userId, metadata: { event, hostNotified: host?.notified === true } },
218+
);
219+
198220
const isRefused = (outcome: unknown): outcome is EnvironmentUserHostRefused =>
199221
!!outcome && typeof outcome === 'object' && 'refused' in outcome;
200222

@@ -291,6 +313,7 @@ export async function runAdminBanUser(
291313
});
292314
// Sign the banned user out everywhere, exactly as the vendor handler does.
293315
await ctx.internalAdapter.deleteUserSessions(userId);
316+
await auditBan(deps, actor, userId, 'user.admin_banned', host);
294317

295318
return {
296319
status: 200,
@@ -327,6 +350,7 @@ export async function runAdminUnbanUser(
327350
if (isRefused(host)) return hostRefusal(host);
328351

329352
await applyUserUnban(await banWriterFor(deps, ctx), userId);
353+
await auditBan(deps, actor, userId, 'user.admin_unbanned', host);
330354

331355
return { status: 200, body: { success: true, data: { userId, banned: false, ...(host ? { host } : {}) } } };
332356
}

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,6 +556,15 @@ export type AdminAuditDecisions =
556556
event: 'user.admin_removed_pending';
557557
hostNotified: boolean;
558558
}
559+
| {
560+
/**
561+
* A ban or its lifting committed (`admin-ban-endpoints.ts`). `hostNotified`:
562+
* the environment-user host took the deactivation or reactivation. The
563+
* reason and expiry are fields of the user, so they ride the mirror row only.
564+
*/
565+
event: 'user.admin_banned' | 'user.admin_unbanned';
566+
hostNotified: boolean;
567+
}
559568
| {
560569
event: 'user.admin_password_set';
561570
passwordGenerated: boolean;

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [
262262
// #16678 note below.
263263
{ 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 (email, name, positions, permissionSets, manager) plus an optional organizationId, admitted only when it equals the caller session active organization: a different organization is 400 INVALID_REQUEST naming both organizations, a non-string or empty value is 400 INVALID_REQUEST (a non-string value is checked before the session), a string organization with no session organization is 400 NO_ACTIVE_ORGANIZATION, and every refusal writes nothing and tells no host; it never widens scope (the joined organization is the session one); the environment-user host is told after the write commits, and its answer rides host; platform-admin gated (ADR-0068)' },
264264
{ 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; body { csv } or { rows } plus the same optional organizationId as admin/add-sso-user, admitted only when it equals the caller session active organization: a different organization is 400 INVALID_REQUEST naming both organizations, a non-string or empty value is 400 INVALID_REQUEST (a non-string value is checked before the session), a string organization with no session organization is 400 NO_ACTIVE_ORGANIZATION, and every refusal writes nothing and tells no host; it never widens scope; 409 RESOURCE_CONFLICT off a managed environment; platform-admin gated (ADR-0068)' },
265-
{ 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 } plus the same optional organizationId as admin/add-sso-user, admitted only when it equals the caller session active organization: a different organization is 400 INVALID_REQUEST naming both organizations, a non-string or empty value is 400 INVALID_REQUEST (a non-string value is checked before the session), a string organization with no session organization is 400 NO_ACTIVE_ORGANIZATION, and every refusal writes nothing and tells no host; it never widens scope; 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)' },
265+
{ 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 } plus the same optional organizationId as admin/add-sso-user, admitted only when it equals the caller session active organization: a different organization is 400 INVALID_REQUEST naming both organizations, a non-string or empty value is 400 INVALID_REQUEST (a non-string value is checked before the session), a string organization with no session organization is 400 NO_ACTIVE_ORGANIZATION, and every refusal writes nothing and tells no host; it never widens scope; 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; a removal that committed writes one admin audit row (sys_audit_log action delete, metadata event user.admin_removed_pending with hostNotified), a refused one none; platform-admin gated (ADR-0068)' },
266266
{ 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' },
267267
{ 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)' },
268268
// #30958 — the tracker id stays HERE and never in the `note` string, per the

‎packages/plugins/plugin-auth/src/pending-sso-users.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1573,6 +1573,49 @@ describe('[#34404] admin/remove-sso-user writes an admin audit row for a removal
15731573
// password refused while the lock holds, then judges and drives the DECLARED
15741574
// action against the door and signs in again.
15751575

1576+
/** The admin audit rows a ban or an unban writes (`writeAdminAudit`, action `update`). */
1577+
const banAuditRows = (s: Awaited<ReturnType<typeof stage>>): any[] =>
1578+
((s.engine.tables.get('sys_audit_log') ?? []) as any[]).filter((r) => r.action === 'update');
1579+
1580+
describe('[#35440] admin/ban-user and admin/unban-user write an admin audit row for a change that committed', () => {
1581+
for (const adminPlugin of [false, true]) {
1582+
it(`a ban and its lifting each write one update row naming the admin and the event (admin plugin ${adminPlugin ? 'on' : 'off'})`, async () => {
1583+
const s = await stage({ adminPlugin });
1584+
1585+
expect((await s.fire('/admin/ban-user', { userId: s.ids.member, banReason: 'left' }, s.bearers.admin)).status).toBe(200);
1586+
expect((await s.fire('/admin/unban-user', { userId: s.ids.member }, s.bearers.admin)).status).toBe(200);
1587+
1588+
const rows = banAuditRows(s);
1589+
expect(rows).toHaveLength(2);
1590+
for (const row of rows) {
1591+
expect(row).toMatchObject({ user_id: s.ids.admin, actor: s.ids.admin, object_name: 'sys_user', record_id: s.ids.member });
1592+
}
1593+
expect(rows.map((r) => JSON.parse(r.metadata))).toEqual([
1594+
{ event: 'user.admin_banned', hostNotified: true },
1595+
{ event: 'user.admin_unbanned', hostNotified: true },
1596+
]);
1597+
});
1598+
}
1599+
1600+
it('with no host wired the rows carry hostNotified false', async () => {
1601+
const s = await stage({ host: 'none' });
1602+
expect((await s.fire('/admin/ban-user', { userId: s.ids.member }, s.bearers.admin)).status).toBe(200);
1603+
expect(banAuditRows(s).map((r) => JSON.parse(r.metadata))).toEqual([{ event: 'user.admin_banned', hostNotified: false }]);
1604+
});
1605+
1606+
it('CONTROL: a refused ban and a refused unban write no row', async () => {
1607+
const banRefused = await stage({ host: refusingHost(OWNER_CONFLICT, { deactivated: true }).host });
1608+
expect((await banRefused.fire('/admin/ban-user', { userId: banRefused.ids.member }, banRefused.bearers.admin)).status).toBe(409);
1609+
expect((await banRefused.fire('/admin/ban-user', { userId: banRefused.ids.admin }, banRefused.bearers.admin)).status).toBe(400);
1610+
expect(banRefused.engine.tables.get('sys_audit_log') ?? []).toEqual([]);
1611+
1612+
const unbanRefused = await stage({ host: refusingHost(MEMBER_CAP, { reactivated: true }).host });
1613+
expect((await unbanRefused.fire('/admin/ban-user', { userId: unbanRefused.ids.member }, unbanRefused.bearers.admin)).status).toBe(200);
1614+
expect((await unbanRefused.fire('/admin/unban-user', { userId: unbanRefused.ids.member }, unbanRefused.bearers.admin)).status).toBe(403);
1615+
expect(banAuditRows(unbanRefused).map((r) => JSON.parse(r.metadata).event)).toEqual(['user.admin_banned']);
1616+
});
1617+
});
1618+
15761619
describe('[#34010] Unlock is offered and works without the admin plugin', () => {
15771620
const LOCKOUT = { lockoutThreshold: 3, lockoutDurationMinutes: 15 };
15781621
const WRONG_PASSWORD = 'Wr0ng!Guess-34010';

0 commit comments

Comments
 (0)