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
8 changes: 8 additions & 0 deletions .changeset/35440-ban-unban-admin-audit-row.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@objectstack/plugin-auth': patch
---

Clause-②: no
Metadata-protocol: none

`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, the ban columns' write now carries the administrator's attribution too, so plugin-audit's own row for that change names the administrator instead of the system, as it already did with the admin plugin; the written fields are unchanged. 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.
12 changes: 9 additions & 3 deletions content/docs/permissions/authentication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1462,8 +1462,11 @@ 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.
and the answer says whether that worked. A removal that committed writes one
`sys_audit_log` row naming the administrator (`action: 'delete'`, `metadata`
`{ event: 'user.admin_removed_pending', hostNotified }`); a refused one writes
none. 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:
Expand All @@ -1480,7 +1483,10 @@ 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
gives.
gives. A ban or an unban that committed writes one `sys_audit_log` row naming
the administrator (`action: 'update'`, `metadata` `{ event, hostNotified }`, the
event `user.admin_banned` or `user.admin_unbanned`); a refused one writes none.
The reason and expiry are on the row plugin-audit records for the user's change.

#### SCIM Connection Credentials

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ a row or a number here — fix the code, or the census, and regenerate.
| …and decidably tenancy-enabled | 3 |
| Options argument unreadable | 28 |
| …and decidably tenancy-enabled | 16 |
| Threading a decidably elevated (`isSystem`) context | 42 |
| Threading a decidably elevated (`isSystem`) context | 41 |
| Threading a decidably non-elevated context | 0 |
| Threading a context of undecidable elevation | 45 |
| Threading a context of undecidable elevation | 46 |
| Receiver carried a readable engine type | 76 |
| Receiver erased, placed by the object NAME | 24 |
| Receiver erased, placed by an `object: string` PARAMETER | 1 |
Expand Down Expand Up @@ -123,5 +123,5 @@ a row or a number here — fix the code, or the census, and regenerate.
| `packages/plugins/plugin-auth/src/sso-provider-lifecycle.ts` | `delete` | `IDP_GROUP_MAPPING_OBJECT` | undecidable | PROVABLY NONE | 1 |
| `packages/plugins/plugin-auth/src/sso-provider-lifecycle.ts` | `delete` | `sys_user_permission_set` | enabled | elevated | 1 |
| `packages/plugins/plugin-auth/src/sys-session-revoke.ts` | `update` | `SystemObjectName.SESSION` | undecidable | elevated | 1 |
| `packages/plugins/plugin-auth/src/user-ban-write.ts` | `update` | `sys_user` | enabled | elevated | 1 |
| `packages/plugins/plugin-auth/src/user-ban-write.ts` | `update` | `sys_user` | enabled | context, elevation undecidable | 1 |
| `packages/plugins/plugin-auth/src/user-session-admission.ts` | `update` | `sys_user` | enabled | elevated | 2 |
26 changes: 25 additions & 1 deletion packages/plugins/plugin-auth/src/admin-ban-endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,15 @@
* false, … }` on the answer. The event names the administrator, the one at
* the keyboard on an impersonation session, and their cloud user id read
* from their linked `objectstack-cloud` account, never from the request.
*
* ── The admin audit row ─────────────────────────────────────────────────────
*
* A ban or an unban that committed writes the sibling doors' admin audit row
* (`writeAdminAudit`, action `update`, event `user.admin_banned` /
* `user.admin_unbanned`); a refused one writes none. plugin-audit's mirror row
* for the column write names the administrator on both writers (the engine
* one through `authSystemWriteContext`), but carries neither the event nor
* `hostNotified`, so it does not stand in for this row.
*/

import {
Expand All @@ -98,7 +107,7 @@ import {
LAST_LOCAL_CREDENTIAL_MESSAGE,
type CredentialAccountAdapter,
} from './last-local-credential.js';
import type { AdminActor, EndpointResult } from './admin-user-endpoints.js';
import { writeAdminAudit, type AdminActor, type EndpointResult } from './admin-user-endpoints.js';
import { applyUserBan, applyUserUnban, type UserBanWriter } from './user-ban-write.js';
import { readJsonRequestBody } from './request-json-body.js';
import { readUserSource } from './sso-only-local-password.js';
Expand Down Expand Up @@ -195,6 +204,19 @@ const HOST_UNANSWERED_DEACTIVATION: EndpointResult = {
},
};

/** The admin audit row for a ban or an unban that committed; never fails the answer. */
const auditBan = (
deps: AdminBanEndpointDeps,
actor: AdminActor,
userId: string,
event: 'user.admin_banned' | 'user.admin_unbanned',
host: EnvironmentUserHostOutcome | undefined,
): Promise<void> =>
writeAdminAudit(
{ getDataEngine: () => deps.getDataEngine?.(), logger: deps.logger },
{ action: 'update', actor, recordId: userId, metadata: { event, hostNotified: host?.notified === true } },
);

const isRefused = (outcome: unknown): outcome is EnvironmentUserHostRefused =>
!!outcome && typeof outcome === 'object' && 'refused' in outcome;

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

return {
status: 200,
Expand Down Expand Up @@ -327,6 +350,7 @@ export async function runAdminUnbanUser(
if (isRefused(host)) return hostRefusal(host);

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

return { status: 200, body: { success: true, data: { userId, banned: false, ...(host ? { host } : {}) } } };
}
9 changes: 9 additions & 0 deletions packages/plugins/plugin-auth/src/admin-user-endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,15 @@ export type AdminAuditDecisions =
event: 'user.admin_removed_pending';
hostNotified: boolean;
}
| {
/**
* A ban or its lifting committed (`admin-ban-endpoints.ts`). `hostNotified`:
* the environment-user host took the deactivation or reactivation. The
* reason and expiry are fields of the user, so they ride the mirror row only.
*/
event: 'user.admin_banned' | 'user.admin_unbanned';
hostNotified: boolean;
}
| {
event: 'user.admin_password_set';
passwordGenerated: boolean;
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/plugin-auth/src/auth-route-ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [
// #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, 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)' },
{ 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)' },
{ 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)' },
{ 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)' },
{ 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
Expand Down
63 changes: 63 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 @@ -1573,6 +1573,69 @@ describe('[#34404] admin/remove-sso-user writes an admin audit row for a removal
// password refused while the lock holds, then judges and drives the DECLARED
// action against the door and signs in again.

/** The admin audit rows a ban or an unban writes (`writeAdminAudit`, action `update`). */
const banAuditRows = (s: Awaited<ReturnType<typeof stage>>): any[] =>
((s.engine.tables.get('sys_audit_log') ?? []) as any[]).filter((r) => r.action === 'update');

describe('[#35440] admin/ban-user and admin/unban-user write an admin audit row for a change that committed', () => {
for (const adminPlugin of [false, true]) {
it(`a ban and its lifting each write one update row naming the admin and the event (admin plugin ${adminPlugin ? 'on' : 'off'})`, async () => {
const s = await stage({ adminPlugin });

expect((await s.fire('/admin/ban-user', { userId: s.ids.member, banReason: 'left' }, s.bearers.admin)).status).toBe(200);
expect((await s.fire('/admin/unban-user', { userId: s.ids.member }, s.bearers.admin)).status).toBe(200);

const rows = banAuditRows(s);
expect(rows).toHaveLength(2);
for (const row of rows) {
expect(row).toMatchObject({ user_id: s.ids.admin, actor: s.ids.admin, object_name: 'sys_user', record_id: s.ids.member });
}
expect(rows.map((r) => JSON.parse(r.metadata))).toEqual([
{ event: 'user.admin_banned', hostNotified: true },
{ event: 'user.admin_unbanned', hostNotified: true },
]);
});
}

it('the ban columns\' write itself names the admin for plugin-audit\'s mirror row, with the admin plugin off as on', async () => {
for (const adminPlugin of [false, true]) {
const s = await stage({ adminPlugin });
const contexts: any[] = [];
const update = s.engine.update.bind(s.engine);
s.engine.update = (async (name: string, data: any, options?: any) => {
if (name === 'sys_user' && 'banned' in data) contexts.push(options?.context);
return update(name, data, options);
}) as typeof s.engine.update;

expect((await s.fire('/admin/ban-user', { userId: s.ids.member }, s.bearers.admin)).status).toBe(200);
expect((await s.fire('/admin/unban-user', { userId: s.ids.member }, s.bearers.admin)).status).toBe(200);

expect(contexts, `admin plugin ${adminPlugin ? 'on' : 'off'}`).toEqual([
expect.objectContaining({ isSystem: true, attributedUserId: s.ids.admin }),
expect.objectContaining({ isSystem: true, attributedUserId: s.ids.admin }),
]);
}
});

it('with no host wired the rows carry hostNotified false', async () => {
const s = await stage({ host: 'none' });
expect((await s.fire('/admin/ban-user', { userId: s.ids.member }, s.bearers.admin)).status).toBe(200);
expect(banAuditRows(s).map((r) => JSON.parse(r.metadata))).toEqual([{ event: 'user.admin_banned', hostNotified: false }]);
});

it('CONTROL: a refused ban and a refused unban write no row', async () => {
const banRefused = await stage({ host: refusingHost(OWNER_CONFLICT, { deactivated: true }).host });
expect((await banRefused.fire('/admin/ban-user', { userId: banRefused.ids.member }, banRefused.bearers.admin)).status).toBe(409);
expect((await banRefused.fire('/admin/ban-user', { userId: banRefused.ids.admin }, banRefused.bearers.admin)).status).toBe(400);
expect(banRefused.engine.tables.get('sys_audit_log') ?? []).toEqual([]);

const unbanRefused = await stage({ host: refusingHost(MEMBER_CAP, { reactivated: true }).host });
expect((await unbanRefused.fire('/admin/ban-user', { userId: unbanRefused.ids.member }, unbanRefused.bearers.admin)).status).toBe(200);
expect((await unbanRefused.fire('/admin/unban-user', { userId: unbanRefused.ids.member }, unbanRefused.bearers.admin)).status).toBe(403);
expect(banAuditRows(unbanRefused).map((r) => JSON.parse(r.metadata).event)).toEqual(['user.admin_banned']);
});
});

describe('[#34010] Unlock is offered and works without the admin plugin', () => {
const LOCKOUT = { lockoutThreshold: 3, lockoutDurationMinutes: 15 };
const WRONG_PASSWORD = 'Wr0ng!Guess-34010';
Expand Down
Loading
Loading