diff --git a/.changeset/34010-unlock-without-admin-plugin.md b/.changeset/34010-unlock-without-admin-plugin.md new file mode 100644 index 00000000000..05583661ae4 --- /dev/null +++ b/.changeset/34010-unlock-without-admin-plugin.md @@ -0,0 +1,15 @@ +--- +'@objectstack/platform-objects': patch +'@objectstack/spec': patch +--- + +fix(platform-objects): Setup → Users offers Unlock Account on environments without the better-auth admin plugin + +Clause-②: no +Metadata-protocol: none + +`sys_user.unlock_user` no longer carries `requiresFeature: 'admin'`. Its door, `POST /api/v1/auth/admin/unlock-user`, already works without the better-auth admin plugin: the sign-in lockout is ObjectStack's own (`sys_user.locked_until` / `failed_login_count`), and the unlock clears it through the data engine. The action was still hidden wherever `features.admin` is off, so a platform administrator there could not release a locked-out person early and had to wait for the lock to expire. + +It is now offered on every environment that runs without the admin plugin, self-hosted and cloud-managed alike, to a platform administrator only, and only on an account that has a lock stamp or two-factor enabled. Nothing else changes: `requiredPermissions` and the predicate stay as they were, environments with the admin plugin (or SCIM, which turns it on) see no difference, and `create_user` and `impersonate_user` keep their admin-plugin gate (Set Password is released the same way, in its own note). + +`PUBLIC_AUTH_FEATURES.admin.gatedInputs` in `@objectstack/spec/kernel` no longer lists `sys_user.actions.unlock_user`, since it is no longer gated on that flag. diff --git a/.changeset/34130-set-password-without-admin-plugin.md b/.changeset/34130-set-password-without-admin-plugin.md new file mode 100644 index 00000000000..9e2c8554b70 --- /dev/null +++ b/.changeset/34130-set-password-without-admin-plugin.md @@ -0,0 +1,17 @@ +--- +'@objectstack/platform-objects': patch +'@objectstack/spec': patch +--- + +fix(platform-objects): Setup → Users offers Set Password on self-hosted environments without the better-auth admin plugin + +Clause-②: no (as #33989 and #34124 judge a gate drop) +Metadata-protocol: none + +`sys_user.set_user_password` no longer carries `requiresFeature: 'admin'`. Its door, `POST /api/v1/auth/admin/set-user-password`, is ObjectStack's own wrapper and already works without the better-auth admin plugin: it hashes and writes the password through better-auth's core, which every environment carries. The action was still hidden wherever `features.admin` is off, so a platform administrator there could not set or reset a person's password from the console. + +It is now offered to a platform administrator on every environment that runs without the admin plugin and is not cloud-managed. Its other rule is unchanged: it stays hidden on a cloud-managed environment, whose door refuses every target, and the door's own refusals (a pending person, SSO-only mode) answer as before. `create_user` and `impersonate_user` keep their admin-plugin gate. + +`PUBLIC_AUTH_FEATURES.admin.gatedInputs` in `@objectstack/spec/kernel` no longer lists `sys_user.actions.set_user_password`, since it is no longer gated on that flag. + +The `features.admin` description in `@objectstack/spec` (`AuthFeaturesConfigSchema`, and the generated auth-endpoints reference page) no longer says the console shows Unlock Account and Set Password only when it is true: whether the console offers banning, unbanning, unlocking or setting a password does not depend on it. diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index 0ec63634653..72889a5756a 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -1158,9 +1158,10 @@ new AuthPlugin({ ### Admin User Management -With `plugins: { admin: true }` (forced on when SCIM is enabled), platform -admins get email-independent account management on the Users list — the -`create_user` / `set_user_password` actions there drive these endpoints. All +Platform admins get email-independent account management on the Users list +— the `create_user` / `set_user_password` actions there drive these +endpoints. Creating a user needs `plugins: { admin: true }` (forced on when +SCIM is enabled); setting a password works with or without it. All three routes are gated server-side on the session's `isPlatformAdmin` — the `PLATFORM_ADMIN` standing of ADR-0095 D3 — with the legacy better-auth `role` scalar of `admin` still accepted as a back-compat fallback; the @@ -1545,7 +1546,7 @@ All endpoints are available under `/api/v1/auth/*`: - `POST /api/v1/auth/phone-number/request-password-reset` - Request an OTP-based password reset (requires an SMS service) - `POST /api/v1/auth/phone-number/reset-password` - Complete an OTP-based password reset -#### Admin User Management (requires `plugins.admin`; platform-admin gated) +#### Admin User Management (platform-admin gated) - `POST /api/v1/auth/admin/create-user` - Create a login-capable account (optional one-time temporary password + forced change) - `POST /api/v1/auth/admin/set-user-password` - Set/reset a user's password (also provisions a credential for SSO-onboarded users) @@ -1556,7 +1557,7 @@ All endpoints are available under `/api/v1/auth/*`: - `POST /api/v1/auth/admin/add-sso-user` - Add one pending person who signs in only through the hosting organisation's identity provider (cloud-managed environments only) - `POST /api/v1/auth/admin/import-sso-users` - Add pending people from a CSV or JSON rows (cloud-managed environments only; ≤500 rows, per-row results) -`ban-user`, `unban-user`, `add-sso-user` and `import-sso-users` answer without `plugins.admin` too. +`create-user` and `import-users` need `plugins.admin` (without it they answer `501 NOT_IMPLEMENTED`). `set-user-password`, `unlock-user`, `ban-user`, `unban-user`, `add-sso-user` and `import-sso-users` answer with or without it. #### Organization Membership (requires `plugins.organization`; platform-admin gated) diff --git a/content/docs/references/api/auth-endpoints.mdx b/content/docs/references/api/auth-endpoints.mdx index e31eff3e7ce..2a225128169 100644 --- a/content/docs/references/api/auth-endpoints.mdx +++ b/content/docs/references/api/auth-endpoints.mdx @@ -76,7 +76,7 @@ const result = AuthEndpointSchema.parse(data); | **degradedTenancy** | `boolean` | optional | Degraded tenancy: true when multi-organization isolation was requested but is not active (the deployment booted only because OS_ALLOW_DEGRADED_TENANCY=1), so no engine enforces organization boundaries; the console can raise an operator warning off it. A status signal, not a capability gate; absent means not degraded | | **oidcProvider** | `boolean` | optional | Embedded OIDC authorization server wired, from the same decision that mounts it, so OAuth applications can be registered and managed; on by default alongside the MCP surface. It says nothing about sign-in providers, which socialProviders lists; the flag is default-on, so absent reads as on | | **deviceAuthorization** | `boolean` | optional | Device authorization (browser-approved CLI login) wired, so the device-code endpoints answer; when false the console device-approval page says device authorization is not enabled instead of calling them. Absent means not wired | -| **admin** | `boolean` | optional | Admin plugin wired (forced on whenever SCIM is enabled), so creating and impersonating users is available; the console shows those actions only when it is true. Banning, unbanning, unlocking and setting a password answer without it; the console still shows its unlock and set-password actions only when it is true. Absent means not wired | +| **admin** | `boolean` | optional | Admin plugin wired (forced on whenever SCIM is enabled), so creating and impersonating users is available; the console shows those actions only when it is true. Banning, unbanning, unlocking and setting a password answer without it, and whether the console offers those actions does not depend on it. Absent means not wired | | **termsUrl** | `string` | optional | Terms-of-service link shown beneath the login and register cards: the trimmed OS_TERMS_URL value when set, otherwise the public ObjectStack terms page; absent when the operator set OS_TERMS_URL to an empty or blank (whitespace-only) value to suppress the link | | **privacyUrl** | `string` | optional | Privacy-policy link shown beneath the login and register cards: the trimmed OS_PRIVACY_URL value when set, otherwise the public ObjectStack privacy page; absent when the operator set OS_PRIVACY_URL to an empty or blank (whitespace-only) value to suppress the link | @@ -227,7 +227,7 @@ This schema accepts one of the following structures: | **degradedTenancy** | `boolean` | optional | Degraded tenancy: true when multi-organization isolation was requested but is not active (the deployment booted only because OS_ALLOW_DEGRADED_TENANCY=1), so no engine enforces organization boundaries; the console can raise an operator warning off it. A status signal, not a capability gate; absent means not degraded | | **oidcProvider** | `boolean` | optional | Embedded OIDC authorization server wired, from the same decision that mounts it, so OAuth applications can be registered and managed; on by default alongside the MCP surface. It says nothing about sign-in providers, which socialProviders lists; the flag is default-on, so absent reads as on | | **deviceAuthorization** | `boolean` | optional | Device authorization (browser-approved CLI login) wired, so the device-code endpoints answer; when false the console device-approval page says device authorization is not enabled instead of calling them. Absent means not wired | -| **admin** | `boolean` | optional | Admin plugin wired (forced on whenever SCIM is enabled), so creating and impersonating users is available; the console shows those actions only when it is true. Banning, unbanning, unlocking and setting a password answer without it; the console still shows its unlock and set-password actions only when it is true. Absent means not wired | +| **admin** | `boolean` | optional | Admin plugin wired (forced on whenever SCIM is enabled), so creating and impersonating users is available; the console shows those actions only when it is true. Banning, unbanning, unlocking and setting a password answer without it, and whether the console offers those actions does not depend on it. Absent means not wired | | **termsUrl** | `string` | optional | Terms-of-service link shown beneath the login and register cards: the trimmed OS_TERMS_URL value when set, otherwise the public ObjectStack terms page; absent when the operator set OS_TERMS_URL to an empty or blank (whitespace-only) value to suppress the link | | **privacyUrl** | `string` | optional | Privacy-policy link shown beneath the login and register cards: the trimmed OS_PRIVACY_URL value when set, otherwise the public ObjectStack privacy page; absent when the operator set OS_PRIVACY_URL to an empty or blank (whitespace-only) value to suppress the link | diff --git a/packages/platform-objects/src/identity/action-state-visibility.test.ts b/packages/platform-objects/src/identity/action-state-visibility.test.ts index 3e7ce069deb..5c74bb06194 100644 --- a/packages/platform-objects/src/identity/action-state-visibility.test.ts +++ b/packages/platform-objects/src/identity/action-state-visibility.test.ts @@ -84,15 +84,19 @@ 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. + * Ban / Unban / Unlock / Set Password are offered on a kernel WITHOUT the + * better-auth admin plugin: their doors (plugin-auth `admin/ban-user` / + * `admin/unban-user` / `admin/unlock-user` / `admin/set-user-password`) are + * mounted and work there too, so `features.admin` off, the flag every such + * kernel serves, managed or not, hides none of them (Set Password keeps its + * own hide-when-cloud-managed rule). The actions whose doors still need the + * plugin keep their `requiresFeature: 'admin'` gate. */ -describe('sys_user Ban / Unban are offered without the admin plugin', () => { +describe('sys_user Ban / Unban / Unlock / Set Password are offered without the admin plugin', () => { const ban = visibleOf(SysUser, 'ban_user'); const unban = visibleOf(SysUser, 'unban_user'); + const unlock = visibleOf(SysUser, 'unlock_user'); + const setPassword = visibleOf(SysUser, 'set_user_password'); /** 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 }, @@ -109,21 +113,36 @@ describe('sys_user Ban / Unban are offered without the admin plugin', () => { } }); + it('a locked or two-factor account is offered Unlock and one with neither is not, managed or not', () => { + for (const features of WITHOUT_PLUGIN) { + const where = JSON.stringify(features); + expect(offered(unlock, { locked_until: '2999-01-01T00:00:00.000Z', two_factor_enabled: false }, ADMIN, features), where).toBe(true); + expect(offered(unlock, { locked_until: null, two_factor_enabled: true }, ADMIN, features), where).toBe(true); + expect(offered(unlock, { locked_until: null, two_factor_enabled: false }, ADMIN, features), where).toBe(false); + } + }); + + it('Set Password is offered unmanaged and stays hidden managed, its own rule kept', () => { + const [unmanaged, managed] = WITHOUT_PLUGIN; + expect(offered(setPassword, { source: 'env_native' }, ADMIN, unmanaged!)).toBe(true); + expect(offered(setPassword, { source: 'env_native' }, ADMIN, managed!)).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); } + expect(offered(unlock, { locked_until: '2999-01-01T00:00:00.000Z', two_factor_enabled: true }, MEMBER, features)).toBe(false); + expect(offered(setPassword, { source: 'env_native' }, 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]> = [ - ['unlock_user', { locked_until: '2999-01-01T00:00:00.000Z', two_factor_enabled: true }], ['create_user', {}], - ['set_user_password', { source: 'env_native' }], ['impersonate_user', {}], ]; diff --git a/packages/platform-objects/src/identity/cloud-managed-visibility.test.ts b/packages/platform-objects/src/identity/cloud-managed-visibility.test.ts index cf214fa6366..f3574a6d8b7 100644 --- a/packages/platform-objects/src/identity/cloud-managed-visibility.test.ts +++ b/packages/platform-objects/src/identity/cloud-managed-visibility.test.ts @@ -15,9 +15,11 @@ * flag the payload lacks (`default-on` ones too), so that case is the * consumer's fault handling, the same for every flag. * - * Each of the six already carries another flag's gate (`organization` or - * `admin`) through `requiresFeature`, so the `cloudManaged` gate is written in - * `visible` and the two compose. The predicates are EVALUATED through the + * Five of the six also carry another flag's gate (`organization` or `admin`) + * through `requiresFeature`, so the `cloudManaged` gate is written in + * `visible` and the two compose. `set_user_password` carries none: its door + * works without the better-auth admin plugin (the admin block header in + * `sys-user.object.ts`), so `cloudManaged` is its only flag. The predicates are EVALUATED through the * canonical engine the console delegates to (`@objectstack/formula`), on the * parsed object, so the lowered envelope is what is judged; a string match * would stay green on a predicate that faults or never answers true. @@ -33,7 +35,7 @@ import { SysOrganization } from './sys-organization.object.js'; /** Holds every standing the six doors ask for: the platform-admin rung and the owner grade. */ const ADMIN = { id: 'u_admin', email: 'admin@example.com', positions: ['org_owner'], isPlatformAdmin: true }; -/** The other flags the six inputs are gated on, all on, so `cloudManaged` alone decides. */ +/** The other flags five of the six inputs are gated on, all on, so `cloudManaged` alone decides. */ const OTHER_FLAGS = { organization: true, admin: true }; const SIX: ReadonlyArray<[string, { actions?: unknown }, string]> = [ @@ -73,9 +75,18 @@ describe('features.cloudManaged hides the six doors that add people', () => { expect(offered(visibleOf(def, name), { ...OTHER_FLAGS, cloudManaged: false })).toBe(true); }); - it.each(SIX)('%s keeps its other flag: off hides it whatever cloudManaged says', (_site, def, name) => { + /** The five that carry another flag; `set_user_password` carries only `cloudManaged`. */ + const GATED_TWICE = SIX.filter(([site]) => site !== 'sys_user.set_user_password'); + + it.each(GATED_TWICE)('%s keeps its other flag: off hides it whatever cloudManaged says', (_site, def, name) => { expect(offered(visibleOf(def, name), { organization: false, admin: false, cloudManaged: false })).toBe(false); }); + + it('sys_user.set_user_password reads no other flag: offered with the admin plugin off, hidden managed', () => { + const source = visibleOf(SysUser, 'set_user_password'); + expect(offered(source, { organization: false, admin: false, cloudManaged: false })).toBe(true); + expect(offered(source, { organization: false, admin: false, cloudManaged: true })).toBe(false); + }); }); /** diff --git a/packages/platform-objects/src/identity/sys-user-set-manager-action.test.ts b/packages/platform-objects/src/identity/sys-user-set-manager-action.test.ts index 9d3a0efd015..651c18f2b75 100644 --- a/packages/platform-objects/src/identity/sys-user-set-manager-action.test.ts +++ b/packages/platform-objects/src/identity/sys-user-set-manager-action.test.ts @@ -198,9 +198,9 @@ describe('the visible predicate: offered on every row, the SCIM-held refusal is }); it('⛔ is NOT gated on features.admin, and that is deliberate', () => { - // The `admin` flag hides buttons whose endpoint is "only wired when - // `auth.plugins.admin` is enabled" — the 404-avoidance the block header on - // the admin actions states. This route is not one of those: it is an + // The `admin` flag hides buttons whose endpoint needs the better-auth + // admin plugin, so that the UI does not render buttons that 404 (the block + // header on the admin actions). This route is not one of those: it is an // ObjectStack mount registered unconditionally beside `unlock-user` and // authorized by the ADR-0068 platform-admin gate, so gating it would hide // a WORKING affordance on every host that never opted into that plugin — diff --git a/packages/platform-objects/src/identity/sys-user.object.ts b/packages/platform-objects/src/identity/sys-user.object.ts index 20c6594f6d3..1c836e0edfb 100644 --- a/packages/platform-objects/src/identity/sys-user.object.ts +++ b/packages/platform-objects/src/identity/sys-user.object.ts @@ -176,20 +176,26 @@ export const SysUser = ObjectSchema.create({ // ── Platform admin operations ─────────────────────────────────────── // - // `unlock_user`, `create_user` and the actions further down that carry - // `requiresFeature: 'admin'` (#2874) are gated on the better-auth `admin` + // `create_user` and `impersonate_user`, the actions here 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 + // Ban / Unban / Unlock / Set Password carry NO `requiresFeature: 'admin'`, + // deliberately. Their doors, plugin-auth's `admin/ban-user` / + // `admin/unban-user` / `admin/unlock-user` / `admin/set-user-password`, + // are ObjectStack mounts registered whether or not the vendor plugin is + // on. Without it the ban is written through the data engine and the + // session refusal answers `403 BANNED_USER` (`admin-ban-endpoints.ts`, + // `user-session-admission.ts`); the lockout is plugin-auth's own + // (ADR-0069 D2, stamped by its sign-in path), and the unlock clears it + // through the data engine; the password is hashed and written through + // better-auth's core `internalAdapter`, which every kernel carries. So + // `features.admin == true` would hide a working Deactivate / Reactivate / + // Unlock / Set Password on every kernel that runs without the plugin, + // managed environments included (Set Password keeps its own + // hide-when-cloud-managed rule). Pinned in // `action-state-visibility.test.ts` (the offer) and plugin-auth's // `pending-sso-users.test.ts` (the declared targets, driven live). // @@ -218,9 +224,11 @@ export const SysUser = ObjectSchema.create({ // list row the console projects every `record.` an object action's // predicate reads (objectui `listViewPredicates`), so the default Users // view carries `banned` without showing it; the record header reads the - // whole row. `banned` stays true past `ban_expires` until better-auth - // clears it at the user's next sign-in, so Unban is offered while the row - // says banned. Pinned in `action-state-visibility.test.ts`. + // whole row. `banned` stays true past `ban_expires` until the user's next + // sign-in clears it (better-auth's admin plugin where it is mounted, + // plugin-auth's `user-session-admission.ts` where it is not), so Unban is + // offered while the row says banned. Pinned in + // `action-state-visibility.test.ts`. { name: 'ban_user', label: 'Ban User', @@ -287,7 +295,8 @@ export const SysUser = ObjectSchema.create({ { // ADR-0069 D2 — clear a brute-force lockout early (locked_until auto- // expires, but an admin can release a user immediately). Hits the - // plugin-auth custom route, which is admin-guarded server-side. + // plugin-auth custom route, which is admin-guarded server-side and + // works without the better-auth admin plugin (block header above). name: 'unlock_user', label: 'Unlock Account', icon: 'lock-open', @@ -308,7 +317,6 @@ export const SysUser = ObjectSchema.create({ // `failed_login_count` at the threshold, so one more failure re-locks, // and Unlock is what resets that counter. visible: 'current_user.isPlatformAdmin == true && ((has(record.locked_until) && record.locked_until != null) || (has(record.two_factor_enabled) && record.two_factor_enabled == true))', - requiresFeature: 'admin', recordIdParam: 'userId', successMessage: 'Account unlocked', refreshAfter: true, @@ -564,11 +572,9 @@ export const SysUser = ObjectSchema.create({ // The door's platform-admin gate, declared where both action doors read it (#30771). requiredPermissions: [...PLATFORM_ADMIN_USERS_GATE], // Platform-admin standing (ADR-0068 D4) — see the block header above — - // and hidden while cloud-managed (`features.cloudManaged`, hide-when-on). - // Console only: the server keeps answering it on an `env_native` row, so - // the break-glass admin stays editable (ruling 6341690661, Q4 A). + // and hidden while cloud-managed (`features.cloudManaged`, hide-when-on): + // the door refuses every target there (plugin-auth `cloud-managed.ts`). visible: 'current_user.isPlatformAdmin == true && features.cloudManaged != true', - requiresFeature: 'admin', recordIdParam: 'userId', successMessage: 'Password updated', refreshAfter: false, diff --git a/packages/platform-objects/src/platform-objects.test.ts b/packages/platform-objects/src/platform-objects.test.ts index 55397b56017..342cb25e2a0 100644 --- a/packages/platform-objects/src/platform-objects.test.ts +++ b/packages/platform-objects/src/platform-objects.test.ts @@ -798,12 +798,13 @@ 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`). - // Ban / Unban carry no `admin` gate: their doors work without the plugin, - // so nothing is lowered onto the hand-written predicate. + // Ban / Unban / Unlock / Set Password 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, 'unlock_user', `${STANDING} && ((has(record.locked_until) && record.locked_until != null) || (has(record.two_factor_enabled) && record.two_factor_enabled == true))`], + ['SysUser', SysUser, 'set_user_password', `${STANDING} && ${MANAGED}`], ['SysUser', SysUser, 'impersonate_user', `(${STANDING}) && features.admin == true`], ['SysUser', SysUser, 'enable_two_factor', '(has(record.id) && record.id == ctx.user.id && has(record.two_factor_enabled) && record.two_factor_enabled != true) && features.twoFactor == true'], ['SysUser', SysUser, 'disable_two_factor', '(has(record.id) && record.id == ctx.user.id && has(record.two_factor_enabled) && record.two_factor_enabled == true) && features.twoFactor == true'], diff --git a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts index 9761d0ccf1a..bf31ae84dfc 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts @@ -309,7 +309,10 @@ export async function buildPluginList(this: PluginListHost): Promise { if (enabled.admin) { await this.addOptionalPlugin(plugins, 'admin', async () => { const { admin } = await import('better-auth/plugins/admin'); - // Platform admin: ban/unban, set-password, impersonate, set-role. + // The vendor admin plugin: what create-user and import-users drive, + // impersonation, and better-auth's own /admin/* routes (set-role, + // list-users, …). Ban/unban, unlock and set-password are ObjectStack + // mounts served with or without it (`plugins.admin` in auth-config.zod.ts). // Schema mapping ensures the plugin's added user/session columns // match ObjectStack's snake_case conventions (ban_reason, // ban_expires, impersonated_by). `role` and `banned` are already diff --git a/packages/plugins/plugin-auth/src/pending-sso-users.test.ts b/packages/plugins/plugin-auth/src/pending-sso-users.test.ts index 102a652d1e8..161b7f6e667 100644 --- a/packages/plugins/plugin-auth/src/pending-sso-users.test.ts +++ b/packages/plugins/plugin-auth/src/pending-sso-users.test.ts @@ -238,10 +238,12 @@ beforeAll(async () => { * staging gave, so no case sees another's writes. The tests switch the mode * on afterwards: every door under test reads the accessor per request. */ -async function stage(opts: { adminPlugin?: boolean; host?: EnvironmentUserHost | 'none'; tables?: Map } = {}) { +async function stage( + opts: { adminPlugin?: boolean; host?: EnvironmentUserHost | 'none'; tables?: Map; config?: Record } = {}, +) { const engine = createMemoryEngine(); for (const [name, rows] of structuredClone(opts.tables ?? staged.tables)) engine.tables.set(name, rows); - const manager = makeManager(engine, opts.adminPlugin ?? false); + const manager = makeManager(engine, opts.adminPlugin ?? false, opts.config); const told: Array<{ kind: string; event: EnvironmentUserEvent }> = []; const recordingHost: EnvironmentUserHost = { userAdded: (event) => void told.push({ kind: 'added', event }), @@ -1079,6 +1081,47 @@ describe('[#33186] the Setup → Users add actions reach the pending-person door }); }); +// ───────────────────────────────────────────────────────────────────────────── +// Setup → Users: the console's offer of a DECLARED action, and what it posts +// ───────────────────────────────────────────────────────────────────────────── +// +// Shared by the two describes below; the first one's header says how they judge. + +/** 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>, name: string, row: Record): 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: its constant `bodyExtra`, the record id + * under `recordIdParam`, then the collected params. + */ +function actionCall(name: string, userId: string, collected: Record = {}) { + 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); + const extra = ((action as { bodyExtra?: Record }).bodyExtra ?? {}); + return { path: target.slice(BASE.length), body: { ...extra, [String(action.recordIdParam)]: userId, ...collected } }; +} + // ───────────────────────────────────────────────────────────────────────────── // Setup → Users: Deactivate / Reactivate are offered without the admin plugin // ───────────────────────────────────────────────────────────────────────────── @@ -1093,37 +1136,6 @@ describe('[#33186] the Setup → Users add actions reach the pending-person door // `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>, name: string, row: Record): 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 = {}) { - 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], @@ -1160,3 +1172,158 @@ describe('[#33759] Ban / Unban are offered and work without the admin plugin', ( expect(offeredOn(on, 'impersonate_user', on.row(EMAILS.member)!)).toBe(true); }); }); + +// ───────────────────────────────────────────────────────────────────────────── +// Setup → Users: Unlock is offered and works without the admin plugin +// ───────────────────────────────────────────────────────────────────────────── +// +// `sys_user.unlock_user` posts to `admin/unlock-user`, an ObjectStack mount +// (ADR-0069 D2) whose handler clears the lockout through the data engine; the +// lockout itself (`sys_user.locked_until` / `failed_login_count`) is stamped by +// this plugin's own sign-in path, with no better-auth admin plugin involved. +// Each case locks the member the way the lockout locks anyone, by +// `lockoutThreshold` wrong passwords through the real sign-in, shows the right +// password refused while the lock holds, then judges and drives the DECLARED +// action against the door and signs in again. + +describe('[#34010] Unlock is offered and works without the admin plugin', () => { + const LOCKOUT = { lockoutThreshold: 3, lockoutDurationMinutes: 15 }; + const WRONG_PASSWORD = 'Wr0ng!Guess-34010'; + + /** Lock the member through the sign-in lockout itself, and show the lock holding against the right password. */ + async function lockMember(s: Awaited>): Promise { + for (let i = 0; i < LOCKOUT.lockoutThreshold; i++) { + expect((await s.signIn(EMAILS.member, WRONG_PASSWORD)).status, `wrong password ${i + 1}`).toBe(401); + } + const lockedUntil = new Date(s.row(EMAILS.member)!.locked_until).getTime(); + expect(lockedUntil, 'the lockout stamped a lock in the future').toBeGreaterThan(Date.now()); + const sessions = s.rowsOf('sys_session', s.ids.member).length; + const held = await verdict(await s.signIn(EMAILS.member)); + expect(held.status, held.text).toBe(401); + expect(s.rowsOf('sys_session', s.ids.member), 'the locked account got no session').toHaveLength(sessions); + } + + it.each([ + ['unmanaged', false], + ['managed', true], + ] as const)('%s kernel: a locked account is offered Unlock, the door releases it, and the next sign-in succeeds', async (_kind, managed) => { + const s = managed ? await managedStage({ config: LOCKOUT }) : await stage({ config: LOCKOUT }); + expect((s.manager.getPublicConfig() as any).features.admin, 'this kernel serves features.admin off').toBe(false); + await lockMember(s); + + expect(offeredOn(s, 'unlock_user', s.row(EMAILS.member)!)).toBe(true); + const unlock = actionCall('unlock_user', s.ids.member); + // The door's platform-admin gate holds without the plugin: a caller without + // the standing is refused and the lock stays. + const denied = await verdict(await s.fire(unlock.path, unlock.body, s.bearers.idp)); + expect(denied.status, denied.text).toBe(403); + expect(denied.code).toBe('PERMISSION_DENIED'); + expect(s.row(EMAILS.member)!.locked_until).toBeTruthy(); + + const res = await s.fire(unlock.path, unlock.body, s.bearers.admin); + expect(res.status, await res.clone().text()).toBe(200); + expect(s.row(EMAILS.member)!.locked_until ?? null).toBeNull(); + expect(Number(s.row(EMAILS.member)!.failed_login_count)).toBe(0); + expect((await s.signIn(EMAILS.member)).status).toBe(200); + }); + + it('CONTROL: with the plugin on, Unlock is offered and releases the account as before', async () => { + const s = await stage({ adminPlugin: true, config: LOCKOUT }); + expect((s.manager.getPublicConfig() as any).features.admin).toBe(true); + await lockMember(s); + + expect(offeredOn(s, 'unlock_user', s.row(EMAILS.member)!)).toBe(true); + const unlock = actionCall('unlock_user', s.ids.member); + const res = await s.fire(unlock.path, unlock.body, s.bearers.admin); + expect(res.status, await res.clone().text()).toBe(200); + expect(s.row(EMAILS.member)!.locked_until ?? null).toBeNull(); + expect((await s.signIn(EMAILS.member)).status).toBe(200); + }); +}); + +// ───────────────────────────────────────────────────────────────────────────── +// Setup → Users: Set Password is offered and works without the admin plugin +// ───────────────────────────────────────────────────────────────────────────── +// +// `sys_user.set_user_password` posts to `admin/set-user-password`, plugin-auth's +// wrapper registered ahead of the catch-all: it runs the platform-admin gate, +// then hashes through better-auth's core `internalAdapter`, which every kernel +// carries, with or without the vendor admin plugin. Each case judges the +// DECLARED action under the features the kernel serves, drives what it posts +// (its `bodyExtra`, `recordIdParam` and collected params), and signs in with +// the new password. The action's other rule is kept: it is hidden on a +// cloud-managed environment, whose door refuses every target. + +describe('[#34130] Set Password is offered and works without the admin plugin', () => { + const COLLECTED = { newPassword: NEW_PASSWORD, mustChangePassword: false, revokeSessionsAndKeys: false }; + + it('unmanaged kernel: Set Password is offered, the door sets the password, and the member signs in with it', async () => { + const s = await stage(); + const features = (s.manager.getPublicConfig() as any).features; + expect(features.admin, 'this kernel serves features.admin off').toBe(false); + expect(features.cloudManaged ?? false).toBe(false); + + expect(offeredOn(s, 'set_user_password', s.row(EMAILS.member)!)).toBe(true); + const call = actionCall('set_user_password', s.ids.member, COLLECTED); + // The door's platform-admin gate holds without the plugin: a caller without + // the standing is refused and the old password still signs in. + const denied = await verdict(await s.fire(call.path, call.body, s.bearers.idp)); + expect(denied.status, denied.text).toBe(403); + expect(denied.code).toBe('PERMISSION_DENIED'); + expect((await s.signIn(EMAILS.member, NEW_PASSWORD)).status).toBe(401); + + const res = await s.fire(call.path, call.body, s.bearers.admin); + expect(res.status, await res.clone().text()).toBe(200); + expect((await s.signIn(EMAILS.member, NEW_PASSWORD)).status).toBe(200); + expect((await s.signIn(EMAILS.member)).status).toBe(401); + }); + + it('unmanaged kernel: with the dialog defaults the door also flags the member and revokes their sessions', async () => { + const s = await stage(); + expect((s.manager.getPublicConfig() as any).features.admin).toBe(false); + // The values the dialog submits when the admin types only the password: + // every other declared param at its declared default. + const defaults = Object.fromEntries( + (declaredAction('set_user_password').params ?? []) + .filter((p) => p.defaultValue !== undefined) + .map((p) => [String(p.name ?? p.field), p.defaultValue]), + ); + expect(defaults).toEqual({ mustChangePassword: true, revokeSessionsAndKeys: true }); + expect(s.rowsOf('sys_session', s.ids.member).length, 'the member holds a session before').toBeGreaterThan(0); + + const call = actionCall('set_user_password', s.ids.member, { newPassword: NEW_PASSWORD, ...defaults }); + const v = await verdict(await s.fire(call.path, call.body, s.bearers.admin)); + expect(v.status, v.text).toBe(200); + const data = JSON.parse(v.text).data; + expect(data.mustChangePassword).toBe(true); + expect(data.revokeSessionsAndKeys).toBe(true); + expect(data.revoked?.complete).toBe(true); + expect(s.row(EMAILS.member)!.must_change_password).toBe(true); + // Revocation stamps each session row rather than deleting it. + const sessions = s.rowsOf('sys_session', s.ids.member); + expect(data.revoked.sessions).toBe(sessions.length); + for (const row of sessions) { + expect(row.revoke_reason).toBe('admin_password_reset'); + expect(new Date(row.expires_at).getTime()).toBeLessThanOrEqual(Date.now()); + } + expect((await s.signIn(EMAILS.member, NEW_PASSWORD)).status).toBe(200); + }); + + it('managed kernel: Set Password stays hidden, the rule kept beside the dropped gate', async () => { + const s = await managedStage(); + const features = (s.manager.getPublicConfig() as any).features; + expect(features.admin).toBe(false); + expect(features.cloudManaged).toBe(true); + expect(offeredOn(s, 'set_user_password', s.row(EMAILS.member)!)).toBe(false); + }); + + it('CONTROL: with the plugin on, Set Password is offered and sets the password as before', async () => { + const s = await stage({ adminPlugin: true }); + expect((s.manager.getPublicConfig() as any).features.admin).toBe(true); + expect(offeredOn(s, 'set_user_password', s.row(EMAILS.member)!)).toBe(true); + const call = actionCall('set_user_password', s.ids.member, COLLECTED); + const res = await s.fire(call.path, call.body, s.bearers.admin); + expect(res.status, await res.clone().text()).toBe(200); + expect((await s.signIn(EMAILS.member, NEW_PASSWORD)).status).toBe(200); + }); +}); diff --git a/packages/spec/src/api/auth-endpoints.zod.ts b/packages/spec/src/api/auth-endpoints.zod.ts index 7eaaa47eab3..9c113c944f5 100644 --- a/packages/spec/src/api/auth-endpoints.zod.ts +++ b/packages/spec/src/api/auth-endpoints.zod.ts @@ -367,7 +367,7 @@ export const AuthFeaturesConfigSchema = lazySchema(() => z.object({ ), admin: z.boolean().optional().describe( 'Admin plugin wired (forced on whenever SCIM is enabled), so creating and impersonating users is available; the console shows those actions only when it is true. ' - + 'Banning, unbanning, unlocking and setting a password answer without it; the console still shows its unlock and set-password actions only when it is true. Absent means not wired', + + 'Banning, unbanning, unlocking and setting a password answer without it, and whether the console offers those actions does not depend on it. Absent means not wired', ), termsUrl: z.string().optional().describe( 'Terms-of-service link shown beneath the login and register cards: the trimmed OS_TERMS_URL value when set, otherwise the public ObjectStack terms page; absent when the operator set OS_TERMS_URL to an empty or blank (whitespace-only) value to suppress the link', diff --git a/packages/spec/src/kernel/public-auth-features.ts b/packages/spec/src/kernel/public-auth-features.ts index 644544c4e24..315f3586e5b 100644 --- a/packages/spec/src/kernel/public-auth-features.ts +++ b/packages/spec/src/kernel/public-auth-features.ts @@ -257,11 +257,10 @@ export const PUBLIC_AUTH_FEATURES = { semantics: 'opt-in', gatedInputs: [ 'sys_user.actions.create_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', + // `ban_user` / `unban_user` / `unlock_user` / `set_user_password` are + // not booked: their doors are ObjectStack mounts that work without the + // admin plugin, so none is gated on this flag (see the admin block + // header in sys-user.object.ts). // 'sys_user.actions.set_user_role' retired (#9968) — see the removal // note beside `impersonate_user` in sys-user.object.ts. 'sys_user.actions.impersonate_user',