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
15 changes: 15 additions & 0 deletions .changeset/33759-ban-unban-without-admin-plugin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@objectstack/platform-objects': patch
'@objectstack/spec': patch
---

fix(platform-objects): Setup → Users offers Ban User and Unban User on environments without the better-auth admin plugin

Clause-②: no — offering an existing action in more kernels widens no accepted input set or public export; the dev measures the gaining kernels and the seat amends if the diff reads otherwise
Metadata-protocol: none

`sys_user.ban_user` and `sys_user.unban_user` no longer carry `requiresFeature: 'admin'`. Their doors, `POST /api/v1/auth/admin/ban-user` and `POST /api/v1/auth/admin/unban-user`, already work without the better-auth admin plugin: the ban is written through the data engine and the banned person's next session is refused with `403 BANNED_USER`. The two actions were still hidden wherever `features.admin` is off, so a platform administrator could not deactivate or reactivate a person from the console there.

They are now offered on every environment that runs without the admin plugin, self-hosted and cloud-managed alike, to a platform administrator only, and still one at a time by the row's `banned` state. Nothing else changes: `requiredPermissions` and the predicates stay as they were, environments with the admin plugin (or SCIM, which turns it on) see no difference, and `unlock_user`, `create_user`, `set_user_password` and `impersonate_user` keep their admin-plugin gate.

`PUBLIC_AUTH_FEATURES.admin.gatedInputs` in `@objectstack/spec/kernel` no longer lists `sys_user.actions.ban_user` and `sys_user.actions.unban_user`, since neither is gated on that flag any more.
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,15 @@ function visibleOf(def: { actions?: unknown }, name: string): string {
}

/** The verdict, or the fault spelled out so a faulting predicate fails loudly. */
function offered(source: string, record: Record<string, unknown>, user: Principal = ADMIN): boolean | string {
function offered(
source: string,
record: Record<string, unknown>,
user: Principal = ADMIN,
features: Record<string, unknown> = FEATURES,
): boolean | string {
const r = celEngine.evaluate(
{ dialect: 'cel', source },
{ record, extra: { current_user: user, user, ctx: { user }, features: FEATURES } },
{ record, extra: { current_user: user, user, ctx: { user }, features } },
);
if (!r.ok) return `FAULT ${r.error.message.split('\n')[0].trim()}`;
return typeof r.value === 'boolean' ? r.value : `NON-BOOLEAN ${JSON.stringify(r.value)}`;
Expand Down Expand Up @@ -78,6 +83,68 @@ describe('sys_user Ban / Unban switch with `banned`', () => {
});
});

/**
* Ban / Unban are offered on a kernel WITHOUT the better-auth admin plugin:
* their doors (plugin-auth `admin/ban-user` / `admin/unban-user`) are mounted
* and enforce the ban there too, so `features.admin` off, the flag every such
* kernel serves, managed or not, hides neither. The actions whose doors still
* need the plugin keep their `requiresFeature: 'admin'` gate.
*/
describe('sys_user Ban / Unban are offered without the admin plugin', () => {
const ban = visibleOf(SysUser, 'ban_user');
const unban = visibleOf(SysUser, 'unban_user');
/** What a kernel without the plugin serves: unmanaged (self-hosted) and managed (a Free or Team environment). */
const WITHOUT_PLUGIN = [
{ admin: false, apiKey: true, cloudManaged: false },
{ admin: false, apiKey: true, cloudManaged: true },
];

it('a user who is not banned is offered Ban and a banned one Unban, managed or not', () => {
for (const features of WITHOUT_PLUGIN) {
const where = JSON.stringify(features);
expect(offered(ban, { banned: false }, ADMIN, features), where).toBe(true);
expect(offered(unban, { banned: false }, ADMIN, features), where).toBe(false);
expect(offered(unban, { banned: true }, ADMIN, features), where).toBe(true);
expect(offered(ban, { banned: true }, ADMIN, features), where).toBe(false);
}
});

it('the standing leg stays: a caller without it is offered neither with the plugin off', () => {
for (const features of WITHOUT_PLUGIN) {
for (const banned of [true, false]) {
expect(offered(ban, { banned }, MEMBER, features)).toBe(false);
expect(offered(unban, { banned }, MEMBER, features)).toBe(false);
}
}
});

// CONTROL: the admin-plugin-only actions. Each row is one its predicate
// otherwise offers, so the flag alone decides.
const PLUGIN_ONLY: ReadonlyArray<[string, Record<string, unknown>]> = [
['unlock_user', { locked_until: '2999-01-01T00:00:00.000Z', two_factor_enabled: true }],
['create_user', {}],
['set_user_password', { source: 'env_native' }],
['impersonate_user', {}],
];

it('CONTROL: exactly the admin-plugin-only actions still read `features.admin`', () => {
const gated = ((SysUser.actions ?? []) as Array<Record<string, unknown>>)
.filter((a) => {
const raw = a.visible;
const source = typeof raw === 'string' ? raw : (raw as { source?: unknown } | undefined)?.source;
return typeof source === 'string' && /\bfeatures\.admin\b/.test(source);
})
.map((a) => a.name);
expect(gated).toEqual(PLUGIN_ONLY.map(([name]) => name));
});

it.each(PLUGIN_ONLY)('CONTROL: %s stays hidden without the plugin and is offered with it', (name, row) => {
const source = visibleOf(SysUser, name);
expect(offered(source, row, ADMIN, { admin: false, apiKey: true, cloudManaged: false })).toBe(false);
expect(offered(source, row, ADMIN, { admin: true, apiKey: true, cloudManaged: false })).toBe(true);
});
});

describe('sys_user Unlock is offered on an account that can hold a lock', () => {
const unlock = visibleOf(SysUser, 'unlock_user');

Expand Down
28 changes: 19 additions & 9 deletions packages/platform-objects/src/identity/sys-user.object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,14 +174,26 @@ export const SysUser = ObjectSchema.create({
},
},

// ── Platform admin operations (require better-auth `admin` plugin) ─
// ── Platform admin operations ───────────────────────────────────────
//
// These actions hit /api/v1/auth/admin/* endpoints that are only
// wired when `auth.plugins.admin` is enabled, so each one is gated on
// `requiresFeature: 'admin'` (#2874) — when the plugin is off the UI
// hides them instead of rendering buttons that 404. SCIM deployments
// keep them: SCIM forces the admin plugin (and `features.admin`) on
// (ADR-0134). UI surfaces them under the row menu AND the
// `unlock_user`, `create_user` and the actions further down that carry
// `requiresFeature: 'admin'` (#2874) are gated on the better-auth `admin`
// plugin: when `features.admin` is off the UI hides them instead of
// rendering buttons that 404. SCIM deployments keep them: SCIM forces the
// admin plugin (and `features.admin`) on (ADR-0134).
//
// Ban / Unban carry NO `requiresFeature: 'admin'`, deliberately. Their
// doors, plugin-auth's `admin/ban-user` / `admin/unban-user`, are
// ObjectStack mounts registered whether or not the vendor plugin is on
// (`admin-ban-endpoints.ts`): without it the ban is written through the
// data engine and the session refusal answers `403 BANNED_USER`
// (`user-session-admission.ts`). So `features.admin == true` would hide a
// working Deactivate / Reactivate on every kernel that runs without the
// plugin, managed environments included. Pinned in
// `action-state-visibility.test.ts` (the offer) and plugin-auth's
// `pending-sso-users.test.ts` (the declared targets, driven live).
//
// UI surfaces them under the row menu AND the
// record-detail header (`record_header`, overflowing into the ⋯
// "More" menu) so platform admins can manage an account from either
// the Users list or an open user record — without dropping to SQL or
Expand Down Expand Up @@ -222,7 +234,6 @@ export const SysUser = ObjectSchema.create({
// Platform-admin standing (ADR-0068 D4), then a user not banned yet —
// see the block header above. A null `banned` reads as not banned.
visible: 'current_user.isPlatformAdmin == true && has(record.banned) && record.banned != true',
requiresFeature: 'admin',
recordIdParam: 'userId',
successMessage: 'User banned',
refreshAfter: true,
Expand Down Expand Up @@ -261,7 +272,6 @@ export const SysUser = ObjectSchema.create({
// Platform-admin standing (ADR-0068 D4), then a banned user — see the
// block header above.
visible: 'current_user.isPlatformAdmin == true && has(record.banned) && record.banned == true',
requiresFeature: 'admin',
recordIdParam: 'userId',
successMessage: 'User unbanned',
refreshAfter: true,
Expand Down
6 changes: 4 additions & 2 deletions packages/platform-objects/src/platform-objects.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -798,8 +798,10 @@ describe('feature-gate lowering matrix (#2874)', () => {
// Their doors are platform-admin gated, so the standing leads.
// The three also read the row's state after the standing (the
// evaluated truth tables are `identity/action-state-visibility.test.ts`).
['SysUser', SysUser, 'ban_user', `(${STANDING} && has(record.banned) && record.banned != true) && features.admin == true`],
['SysUser', SysUser, 'unban_user', `(${STANDING} && has(record.banned) && record.banned == true) && features.admin == true`],
// Ban / Unban carry no `admin` gate: their doors work without the plugin,
// so nothing is lowered onto the hand-written predicate.
['SysUser', SysUser, 'ban_user', `${STANDING} && has(record.banned) && record.banned != true`],
['SysUser', SysUser, 'unban_user', `${STANDING} && has(record.banned) && record.banned == true`],
['SysUser', SysUser, 'unlock_user', `(${STANDING} && ((has(record.locked_until) && record.locked_until != null) || (has(record.two_factor_enabled) && record.two_factor_enabled == true))) && features.admin == true`],
['SysUser', SysUser, 'set_user_password', `(${STANDING} && ${MANAGED}) && features.admin == true`],
['SysUser', SysUser, 'impersonate_user', `(${STANDING}) && features.admin == true`],
Expand Down
83 changes: 83 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 @@ -34,6 +34,7 @@ import { INTERNAL_ERROR_MESSAGE } from '@objectstack/types';
import { createMemoryEngine } from './impersonation-bearer-rotation.test';
import { inviteForAudienceGate } from './audience-gate-test-support';
import { SysUser } from '@objectstack/platform-objects/identity';
import { celEngine } from '@objectstack/formula';

const SECRET = 'test-secret-at-least-32-chars-long!!';
const PASSWORD = 'S3cure!Passw0rd-33181';
Expand Down Expand Up @@ -1077,3 +1078,85 @@ describe('[#33186] the Setup → Users add actions reach the pending-person door
expect(s.row(ADD_DIALOG.email)).toBeUndefined();
});
});

// ─────────────────────────────────────────────────────────────────────────────
// Setup → Users: Deactivate / Reactivate are offered without the admin plugin
// ─────────────────────────────────────────────────────────────────────────────
//
// `sys_user.ban_user` / `unban_user` are the deactivate / reactivate doors'
// first-party callers. On a kernel without the better-auth admin plugin the
// doors work (above), so the console must offer them there too. Each case
// judges the DECLARED action's `visible` against the features THIS kernel
// serves (`getPublicConfig().features`, what `/auth/config` hands the console)
// through the engine the console delegates to, then posts what the action
// submits — its `recordIdParam` naming the row, its params collected — to its
// `target`. CONTROL: an action whose door needs the plugin stays hidden there.

describe('[#33759] Ban / Unban are offered and work without the admin plugin', () => {
/** The session payload's principal for the staged admin: the platform-admin rung the doors' gate judges. */
const ADMIN_PRINCIPAL = { id: 'staged-admin', email: EMAILS.admin, positions: [] as string[], isPlatformAdmin: true };

function declaredAction(name: string) {
const action = (SysUser.actions ?? []).find((a) => a.name === name);
if (!action) throw new Error(`sys_user declares no action named "${name}"`);
return action;
}

/** The console's verdict on the declared action for this row, under the features this kernel serves. */
function offeredOn(s: Awaited<ReturnType<typeof stage>>, name: string, row: Record<string, unknown>): boolean | string {
const raw = declaredAction(name).visible as unknown;
const source = typeof raw === 'string' ? raw : (raw as { source?: unknown } | undefined)?.source;
if (typeof source !== 'string') return `NO CEL SOURCE on ${name}`;
const features = (s.manager.getPublicConfig() as any).features;
const user = { ...ADMIN_PRINCIPAL, id: s.ids.admin };
const r = celEngine.evaluate({ dialect: 'cel', source }, { record: row, extra: { current_user: user, user, ctx: { user }, features } });
if (!r.ok) return `FAULT ${r.error.message.split('\n')[0]!.trim()}`;
return typeof r.value === 'boolean' ? r.value : `NON-BOOLEAN ${JSON.stringify(r.value)}`;
}

/** What the action posts for this row: the record id under `recordIdParam`, then the collected params. */
function actionCall(name: string, userId: string, collected: Record<string, unknown> = {}) {
const action = declaredAction(name);
const target = String(action.target);
expect(target.startsWith(BASE), `${name} targets the auth mount`).toBe(true);
const declaredNames = (action.params ?? []).map((p) => p.name ?? p.field);
for (const key of Object.keys(collected)) expect(declaredNames, `${name} declares the ${key} param`).toContain(key);
return { path: target.slice(BASE.length), body: { [String(action.recordIdParam)]: userId, ...collected } };
}

it.each([
['unmanaged', false],
['managed', true],
] as const)('%s kernel: Ban is offered and refuses the next session, then Unban is offered and restores it', async (_kind, managed) => {
const s = managed ? await managedStage() : await stage();
expect((s.manager.getPublicConfig() as any).features.admin, 'this kernel serves features.admin off').toBe(false);

expect(offeredOn(s, 'ban_user', s.row(EMAILS.member)!)).toBe(true);
expect(offeredOn(s, 'unban_user', s.row(EMAILS.member)!)).toBe(false);
const ban = actionCall('ban_user', s.ids.member, { banReason: 'left the company' });
const banned = await s.fire(ban.path, ban.body, s.bearers.admin);
expect(banned.status, await banned.clone().text()).toBe(200);
expect(s.row(EMAILS.member)!.banned).toBe(true);

const refused = await verdict(await s.signIn(EMAILS.member));
expect(refused.status, refused.text).toBe(403);
expect(refused.code).toBe(BANNED_USER_SESSION_REFUSAL.code);
expect(s.rowsOf('sys_session', s.ids.member)).toHaveLength(0);

expect(offeredOn(s, 'unban_user', s.row(EMAILS.member)!)).toBe(true);
expect(offeredOn(s, 'ban_user', s.row(EMAILS.member)!)).toBe(false);
const unban = actionCall('unban_user', s.ids.member);
const unbanned = await s.fire(unban.path, unban.body, s.bearers.admin);
expect(unbanned.status, await unbanned.clone().text()).toBe(200);
expect(s.row(EMAILS.member)!.banned).toBe(false);
expect((await s.signIn(EMAILS.member)).status).toBe(200);
});

it('CONTROL: an admin-plugin-only action stays hidden on that kernel and is offered once the plugin is on', async () => {
const off = await stage();
expect(offeredOn(off, 'impersonate_user', off.row(EMAILS.member)!)).toBe(false);
const on = await stage({ adminPlugin: true });
expect((on.manager.getPublicConfig() as any).features.admin).toBe(true);
expect(offeredOn(on, 'impersonate_user', on.row(EMAILS.member)!)).toBe(true);
});
});
5 changes: 3 additions & 2 deletions packages/spec/src/kernel/public-auth-features.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,8 +257,9 @@ export const PUBLIC_AUTH_FEATURES = {
semantics: 'opt-in',
gatedInputs: [
'sys_user.actions.create_user',
'sys_user.actions.ban_user',
'sys_user.actions.unban_user',
// `ban_user` / `unban_user` are not booked: their doors are ObjectStack
// mounts that work without the admin plugin, so neither is gated on this
// flag (see the admin block header in sys-user.object.ts).
'sys_user.actions.unlock_user',
'sys_user.actions.set_user_password',
// 'sys_user.actions.set_user_role' retired (#9968) — see the removal
Expand Down
Loading