Skip to content

Commit 9afcd6a

Browse files
fix(plugin-auth)!: an organization cannot require MFA while two-factor enrollment is off (#30201) (#30293)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg1aFpHahTsprKPd3uPCkQ3d)_ domain:server#2 · os-bill · session_01Utp6Cbvcmv8YWFhFJwzjKL ## 维护者速读 - 改了什么:两步验证(twoFactor)没开时,组织上的「强制多因素认证」(`require_mfa`)不能从关改成开(新建即开同样不行),返回 400 并说明原因和出路(先开两步验证;环境变量没把它钉成关时,也可以开全局的 `auth.mfa_required`,它会连同注册入口一起打开)。已经存了开的组织行原样回存照常放行,不挡这一行的其它编辑。同时 MFA 闸门只拦「能去注册的人」:两步验证关着时,任何 MFA 要求都不拦人、不启动宽限期倒计时,服务端只打一条带修法的警告。 - 为什么改:之前管理员在 Setup 勾上这个框就能存,宽限期一过,全组织所有人(包括所有者)都被 403 MFA_REQUIRED 拦住并被引去注册,而注册接口 `POST /api/v1/auth/two-factor/enable` 因为插件没开直接 404;Setup 本身也在同一道闸后面,产品里没人能撤回,整个租户锁死。全局开关一直把「要求」和「注册入口」作为一整块打开,组织字段没有这层配对。 - 风险与回滚:这是一次收窄(Clause-② `no (narrowing)`):两步验证关着的部署上,以前能存的 `require_mfa = true` 现在被拒。已经存了 `true` 的旧组织行不改动、也不再锁人;一旦打开两步验证,它就开始照常要求未注册成员(宽限期从那时起算)。两步验证开着的部署行为完全不变。回滚即撤本 PR。 - 先看:`packages/plugins/plugin-auth/src/organization-mfa-enrollment-guard.ts`(拒存规则与文案);`auth-manager-password-session-policy.ts` 里 `resolveUserAuthGates` 的 MFA 分支(两步验证关时不拦、不盖戳);`auth-manager.ts` 的 `resolveTwoFactorEnabled`(插件列表、`features.twoFactor`、闸门、拒存四处同一个答案)。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run src/organization-mfa-enrollment-guard.test.ts`,预期 29/29 通过,其中端到端一组断言「两步验证关:注册接口 404,会话不被 MFA_REQUIRED 拦住」。 - 需要你做的:无,席位落地。界面半边(Setup 文案、注册失败的本地化提示)不在本卡,已列给席位另立。 Fixes #30201 Clause-②: no (narrowing) — while the two-factor feature is off, a write that turns `sys_organization.require_mfa` on (an insert with it on, or an update of a row that stores it off) is refused `400 VALIDATION_FAILED`, a value an administrator could save before; re-saving a row that already stores it on passes. No published export, error code or settings key is added; nothing is widened. Metadata-protocol: none Skills-docs: follow-up owed — `content/docs/permissions/authentication.mdx` (the `mfa_required` row says `require_mfa` is settable per organization with no condition; it needs two-factor on). Not edited here: outside this card's file surface. ## Why `sys_organization.require_mfa` is a generically editable extension column, so an administrator could tick Require Multi-Factor Auth on an organization's edit form and it saved, with two-factor off (the default, `features.twoFactor: false`). Once the grace period ended, the ADR-0069 D3 gate held every unenrolled member `403 MFA_REQUIRED` and sent them to enroll, and the enrollment endpoint (`POST /api/v1/auth/two-factor/enable`) answered 404 because the twoFactor plugin that serves it was never wired. Every member, the owner included, was locked out, and nobody could undo it from inside the product, because Setup sits behind the same gate. The global `auth.mfa_required` setting never had this hole: its settings piece applies `{ mfaRequired: true, plugins: { twoFactor: true } }` as one refusable patch. The organization column had no such pairing. ## What changes - **The refusal (route b).** A new `beforeInsert` / `beforeUpdate` hook on `sys_organization` (`organization-mfa-enrollment-guard.ts`, priority 15, right after the ADR-0092 D2 identity write guard at 10) refuses, while two-factor is off, a write that turns `require_mfa` on: an insert with it on, or an update of a row whose stored value is off. `validationFailure` from `@objectstack/types`, `400 VALIDATION_FAILED`, one `fields[]` entry `{ field: 'require_mfa', code: 'invalid_value' }` (the closed ADR-0114 catalog). The message says what was refused, why, who would have been locked out (every member, the owner included) and the ways forward; the `auth.mfa_required` remedy is offered only "unless `OS_AUTH_TWO_FACTOR` is set to false", because the env var outranks the settings. It is judged for every write context, the system's included (the lockout does not depend on who wrote the row). The stored value is the update context's `previous`, which the engine binds before `beforeUpdate` on both update paths (the by-id row it read, and one per-row context per matched row on a multi-row update, before anything is written), so a multi-row update is judged row by row and one row turning it on refuses the whole write with nothing written. An update context without a `previous` is judged as a change. Re-sending `require_mfa: true` for a row that already stores it (a whole-row SDK or MCP update, an import re-run, a save with no change) passes, so the row's other edits are not blocked; the gate does not enforce that stored value while two-factor is off anyway. Clearing the column and writing other columns pass untouched. Two-factor state is read per write from the live `AuthManager`, so a settings pass that turns two-factor on admits the next write with no restart. - **Why refuse rather than pair (route a was measured and not taken).** The twoFactor plugin's switch is process configuration: the settings pass and the `OS_AUTH_TWO_FACTOR` env, re-applied at every boot and read by the plugin-list builder. An organization row is data. Turning the plugin on from an organization write would hold only in the process that took the write, would not survive a restart or reach another node (nothing that builds the plugin list reads organization rows), and turning it back off when the last organization clears the column would silently drop every enrolled member's second factor. So the card's fallback is taken; the global switch keeps its existing pairing. - **The gate fail-safe (ADR-0069 D3).** `resolveUserAuthGates` now holds a user for MFA only while they can enroll. With two-factor off, an MFA requirement (an organization's `require_mfa`, `auth.mfa_required` under an `OS_AUTH_TWO_FACTOR=false` pin, or a host config with `mfaRequired` but no `plugins.twoFactor`) yields no `MFA_REQUIRED` and stamps no `mfa_required_at`; the manager logs one warning per process naming the remedy. An organization row stored `require_mfa = true` before this lands therefore locks nobody out. Enrolled users were never held and still are not. - **One answer for "is two-factor on".** `resolveTwoFactorEnabled` (env `OS_AUTH_TWO_FACTOR`, then `plugins.twoFactor`, then off) is now the single decision point for the better-auth plugin list, `features.twoFactor` in `/api/v1/auth/config`, the gate and the refusal; the two copies of the env read it replaces are gone. It is not re-exported from `index.ts`. The live reading is `AuthManager.isTwoFactorEnabled()`, a new public method on an exported class, marked `@internal` (read by the gate and by the guard `AuthPlugin` registers; not a supported entry point). - **Registration.** `AuthPlugin` registers the guard in the `kernel:ready` identity-guard block, right after `registerApiKeyRestoreGuard`. This hunk is far from the `email_password_enabled` settings apply that #30202 edits. - **Existing tests that relied on the dead end.** Tests that turned on `mfaRequired` without `plugins.twoFactor` (two `auth-manager.test.ts` helpers, the impersonation policy fixture, and two `packages/verify` held-session pins) now set `plugins: { twoFactor: true }`, which is the only configuration in which the hold they pin can be complied with. In `held-session-vendor-admin-doors`, the block whose hold only the session's organization declares turns two-factor on in its own `beforeAll` (and puts it back after) instead of inheriting it from the held state that ran before; run alone it now passes 4/4, and without that line its organization write is refused by the guard. `held-session-platform-admin` already set `OS_AUTH_TWO_FACTOR=true`. - Changeset `.changeset/30201-org-mfa-needs-enrollment.md` (`patch`, `!` summary, **BREAKING** accept-set banner, ADR-0087 `not-required (no-migration-prescription)` marker). ## Tests - `organization-mfa-enrollment-guard.test.ts` (new, 29 tests): - the rule on a capture engine: registration options, the off/on predicate (`false`, `0`, `'0'`, `'false'`, `null`, `undefined` are off), refusal while off, admission while on, an update refused for a row stored off or with no `previous`, re-sending it for a row already on admitted (an insert never is), other writes never judged, the message's facts (the conditional settings remedy included) and no tracker number; - `AuthPlugin` registration: `kernel:ready` registers both hooks on `sys_organization` above D2's priority, and the captured handler refuses while two-factor is off and admits after `applyConfigPatch({ plugins: { twoFactor: true } })`; - a real SQLite ObjectQL engine with `SysOrganization` and the D2 guard: the administrator's by-id save is refused and the row keeps its value, admitted once two-factor is on, refused for a system write, a multi-row update and an insert; a row that already requires MFA re-saved with it and another column passes while two-factor is off (the row stored off is still refused); a multi-row update over one row on and one off is refused with nothing written, and over rows all on it lands; other writes pass; - end to end on real better-auth: an organization stored `require_mfa = true`, a member past the grace window, `active_organization_id` set. Two-factor off: `POST /two-factor/enable` answers 404, the session's `authGate` is not `MFA_REQUIRED`, `resolveUserAuthGates` returns `[]`, the warning fires once and the clock is not restamped. Two-factor on: `authGate` is `MFA_REQUIRED` and `/two-factor/enable` answers 200 with a `totpURI`. - `auth-manager.test.ts`: "only a user who can enroll is held" (no hold, no stamp, one warning per manager whose settings remedy is conditional on the env var; an `OS_AUTH_TWO_FACTOR=false` pin outranks `plugins.twoFactor` and `features.twoFactor` reads false; control with two-factor on), plus the per-org case (no block and no clock while off). - **Ablations** on `9b256807` (every negative pin, via `scripts/ablation-replace.mjs` in wrap mode, each restore proven blob == HEAD; plugin-auth tests import their source, so no build sits between mutation and run): - A, guard `throw` deleted: 5 red (the rule's refusal, the registration pin, the real-engine admin, system and multi-row refusals). - B, gate fail-safe neutralized: 4 red, including the end-to-end pin `expected 'MFA_REQUIRED' not to be 'MFA_REQUIRED'`. - C, registration in `auth-plugin.ts` deleted: the registration pin red (`expected [] to deeply equal [[beforeInsert…],[beforeUpdate…]]`). - D, env precedence dropped from `resolveTwoFactorEnabled`: the env-pin test red (`expected true to be false`). - **Ablations, review round** on `f643025e`, same method: - F, the unchanged-value pass deleted: 3 red (the rule's re-send case, the real-engine re-save, the multi-row case's landing half). - G, a context without `previous` treated as already on: 3 red (`the write was admitted`). - H, the settings remedy made unconditional: the message pin red. - E, the organization block's own two-factor arming deleted (`packages/verify`, run alone): its `beforeAll` fails on the guard's `ValidationError`, 28 skipped. ## Acceptance notes - **The `domain:ui` half is not here** (the UI lane is off duty): the Setup copy on the organization form (who is affected, when the block starts), and a localized enrollment refusal saying what to do. The server's refusal text above is what the form shows until then. - Under an `OS_AUTH_TWO_FACTOR=false` pin, the settings console still shows `auth.mfa_required` as saved; the gate now does not enforce it (and says so in the log). Before this PR such a deployment held users it could not enroll. - A user whose `mfa_required_at` was stamped before this lands, on a deployment that later turns two-factor on, is held as soon as it is on, because the stamp is older than the grace window. They can enroll at that point, which is the difference from today. - This relaxes a security hold on deployments where two-factor is off: a configured MFA requirement is no longer enforced there. That is deliberate (the dispatch's fail-safe): the hold could not be complied with and locked the tenant out; the warning names the remedy. ## Verification Suites, typecheck, gates and the full dogfood battery ran on the final tree, head `05e6e0bd` (the review fixes `f643025e` merged with `main` at `8b117c0e`; neither `main` merge touched a file in `plugin-auth` or `packages/verify`). The first-round ablations ran on `9b256807`, the review-round ones on `f643025e`. <details><summary>Suites and typecheck (head 05e6e0b, under scripts/pm/os-verify-lock.sh)</summary> - `pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2`: Test Files 221 passed (221), Tests 3909 passed, 10 skipped. VERDICT command-exit 0. - `pnpm --filter @objectstack/plugin-auth typecheck`: VERDICT command-exit 0 (the test-typecheck ratchet holds). - `pnpm --filter @objectstack/verify exec vitest run` on `held-session-impersonation-target`, `held-session-vendor-admin-doors` and `held-session-platform-admin`: Test Files 3 passed, Tests 49 passed. VERDICT command-exit 0. The organization-declared block alone (`-t 'organization declares'`): 4 passed, 24 skipped. </details> <details><summary>Full dogfood battery (owed by the narrowing arm)</summary> `pnpm --filter @objectstack/dogfood test` on `05e6e0bd`, under `scripts/pm/os-verify-lock.sh`: VERDICT command-exit 0 (held the lock 1182s, shared box); Test Files 419 passed, 3 skipped (422); Tests 3492 passed, 36 skipped (3528); no failure. The one red the first round saw on `8c4430f5` (`permission-set-clone-door.dogfood.test.ts`, from #30222's `member_default` grant, measured green with that file put back) is gone: `main` reverted #30222 (#30262) and this head carries the revert. </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` on `05e6e0bd`: 64 derived, each run with its exit code recorded before any pipe. A session restart cut the first pass after 60 (all exit 0); the other 4 were re-run: `check:type-check-debt` exit 0 under the lock, `check:undeclared-dep-imports` and `check:where-matcher` exit 0, and `check:watch-hint-literal` exit 1 on a `packages/spec/tsup.config.bundled_*.mjs` temp file that the concurrent locked build wrote and removed mid-scan (ENOENT), then exit 0 re-run with no build in flight. `--ran` over the final record: 64 derived, 64 run, 0 NOT-MEASURED, 0 UNRUN, exit 0. `pnpm lint` exit 0. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic (`packages/spec` not touched). - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes (reading under Verification). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: n/a. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English (the 维护者速读 block is Chinese by the Communication rule). --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CYRZxPEjGeTbGfW4YC)_ <!-- signed: domain:server#2 · os-bill · session_01Utp6Cbvcmv8YWFhFJwzjKL --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1c53783 commit 9afcd6a

10 files changed

Lines changed: 794 additions & 12 deletions
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth)!: an organization cannot require multi-factor authentication while two-factor enrollment is off, and the MFA gate never holds a user who has no way to enroll (#30201)
6+
7+
Clause-②: no (narrowing) — while the two-factor feature is off, a write that turns `sys_organization.require_mfa` on (an insert with it on, or an update of a row that stores it off) is refused `400 VALIDATION_FAILED`, a value an administrator could save before; re-saving a row that already stores it on passes. No published export, error code or settings key is added; nothing is widened.
8+
Metadata-protocol: none
9+
Skills-docs: follow-up owed — content/docs/permissions/authentication.mdx (the `mfa_required` row says `require_mfa` is settable per organization with no condition; it needs two-factor on)
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No metadata moves: no spec key, authorable spelling, export or stored shape is removed, renamed or re-shaped, and no stored row is read, rewritten, converted or dropped, so there is nothing for `objectstack migrate meta` to rewrite. What narrows is a runtime accept set on one platform-owned data column, `sys_organization.require_mfa`, judged against the deployment's two-factor state at write time; the remedy is a deployment or settings change (turn two-factor on), which no ledger entry can derive. The other categories are closed on facts: the bumped package publishes (not unpublished); no ADR-0087 id covers this column and this diff adds none (not registered, not already-registered); no published export is added, removed or retyped, so no interface or type narrows (not runtime-export-retired, runtime-interface-only or type-surface-only). -->
12+
13+
**BREAKING** accept-set narrowing on `sys_organization.require_mfa` writes, served by every data door (the organization's edit form, REST, MCP), on a deployment where two-factor is off.
14+
15+
- **Before.** An administrator could tick Require Multi-Factor Auth on an organization while two-factor was off (the default, `features.twoFactor: false`), and it saved. Once the grace period ended, every member, the owner included, was held `403 MFA_REQUIRED` and sent to enroll, and the enrollment endpoint (`POST /api/v1/auth/two-factor/enable`) answered 404: the twoFactor plugin that serves it was never turned on. Nobody could undo it from inside the product, because Setup sits behind the same gate. The global switch never had this hole: the `auth.mfa_required` setting turns the requirement and the plugin on as one piece.
16+
- **Now.** While two-factor is off, a write that turns `require_mfa` on is refused: an insert with it on, or an update of a row whose stored value is off. The refusal carries one `fields[]` entry on `require_mfa` (`invalid_value`) saying why, who would have been locked out, and the ways forward. It applies to every write context, the system's included, on the by-id door, an insert, and a multi-row update, which is judged row by row (one row turning it on refuses the whole write, with nothing written). Re-sending `require_mfa: true` for a row that already stores it (a whole-row update, an import re-run, a save with no change) passes, so other edits of that row are not blocked. Clearing the column and writing other columns pass as before, and every write passes once two-factor is on (read per write, so no restart is needed).
17+
- **The gate.** ADR-0069 D3's MFA gate holds a user only while they can enroll. With two-factor off, an MFA requirement (an organization's `require_mfa`, or `auth.mfa_required` under an `OS_AUTH_TWO_FACTOR=false` pin, or a host that sets `mfaRequired` without `plugins.twoFactor`) holds nobody and starts no grace clock, and the server says so once in a warning with the remedy. An organization row stored with `require_mfa = true` before this release therefore locks no one out; it starts holding unenrolled members once two-factor is turned on.
18+
- **One answer.** Whether two-factor is on is decided in one place, the same `OS_AUTH_TWO_FACTOR` env, then `plugins.twoFactor`, then off, for the plugin list, `features.twoFactor` in `/api/v1/auth/config`, the gate and the write refusal.
19+
- **Unchanged.** An enrolled user is never held. With two-factor on, the requirement and its grace period behave exactly as before. The `auth.mfa_required` setting still turns two-factor on with the requirement.
20+
21+
**The remedy.** To require multi-factor authentication for one organization, turn two-factor enrollment on for the deployment first, with `OS_AUTH_TWO_FACTOR=true`, and then tick the organization's box. Unless `OS_AUTH_TWO_FACTOR` is set to `false` (the env var outranks the settings), turning on the `auth.mfa_required` setting instead also works: it requires multi-factor authentication for every organization and turns enrollment on with it.

‎packages/plugins/plugin-auth/src/auth-manager-password-session-policy.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ export interface PasswordSessionPolicyHost {
6262
_orgMfaCache: AuthManager['_orgMfaCache'];
6363
_orgMfaRefreshing: AuthManager['_orgMfaRefreshing'];
6464
getDataEngine: AuthManager['getDataEngine'];
65+
isTwoFactorEnabled: AuthManager['isTwoFactorEnabled'];
6566
logDurabilityDegradation: AuthManager['logDurabilityDegradation'];
67+
noteMfaRequirementWithoutEnrollment: AuthManager['noteMfaRequirementWithoutEnrollment'];
6668
parseHashes: AuthManager['parseHashes'];
6769
refreshMustChangeCacheIfStale: AuthManager['refreshMustChangeCacheIfStale'];
6870
refreshOrgMfaCacheIfStale: AuthManager['refreshOrgMfaCacheIfStale'];
@@ -136,7 +138,7 @@ export function refreshOrgMfaCacheIfStale(this: Pick<PasswordSessionPolicyHost,
136138

137139
/** The body of `AuthManager#resolveUserAuthGates`; the method's docblock there is its contract. */
138140
export async function resolveUserAuthGates(
139-
this: Pick<PasswordSessionPolicyHost, '_mustChangeCache' | '_orgMfaCache' | 'config' | 'getDataEngine' | 'refreshMustChangeCacheIfStale' | 'refreshOrgMfaCacheIfStale'>,
141+
this: Pick<PasswordSessionPolicyHost, '_mustChangeCache' | '_orgMfaCache' | 'config' | 'getDataEngine' | 'isTwoFactorEnabled' | 'noteMfaRequirementWithoutEnrollment' | 'refreshMustChangeCacheIfStale' | 'refreshOrgMfaCacheIfStale'>,
140142
userId: string,
141143
options: { organizationId?: string } = {},
142144
): Promise<AuthGate[]> {
@@ -205,7 +207,21 @@ export async function resolveUserAuthGates(
205207
// A user without TOTP enrolled is blocked once their grace window
206208
// elapses. The clock (`mfa_required_at`) starts the first time we see
207209
// them required-but-unenrolled (stamped lazily, best-effort).
208-
if (mfaRequired && !(u?.two_factor_enabled === true || u?.two_factor_enabled === 1)) {
210+
//
211+
// [#30201] Only while they CAN enroll. The twoFactor plugin's
212+
// `/two-factor/*` endpoints are the one enrollment path; with the plugin
213+
// off, a hold here answers `MFA_REQUIRED` to a user whose remediation
214+
// endpoint does not exist, which locks every member of the organization
215+
// out, the owner included, behind the very gate that guards Setup. So an
216+
// unenrollable requirement is not enforced (no hold, and no grace clock
217+
// started: the window opens when enrollment does) and is reported once.
218+
// The `require_mfa` write guard refuses a new requirement in that state
219+
// (`organization-mfa-enrollment-guard.ts`); this covers rows stored before
220+
// it, and an `OS_AUTH_TWO_FACTOR=false` pin under the global setting.
221+
const unenrolled = !(u?.two_factor_enabled === true || u?.two_factor_enabled === 1);
222+
if (mfaRequired && unenrolled && !this.isTwoFactorEnabled()) {
223+
this.noteMfaRequirementWithoutEnrollment();
224+
} else if (mfaRequired && unenrolled) {
209225
const graceDays = Math.max(0, Math.floor(Number(this.config.mfaGracePeriodDays ?? 7)));
210226
let requiredAt = u?.mfa_required_at;
211227
if (!requiredAt) {

‎packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ import {
7171
resolveDcrEnabled,
7272
resolveOidcProviderEnabled,
7373
resolveScimEnabled,
74+
resolveTwoFactorEnabled,
7475
type AuthManager,
7576
} from './auth-manager.js';
7677
import {
@@ -188,11 +189,13 @@ export async function buildPluginList(this: PluginListHost): Promise<any[]> {
188189
// better-auth build would otherwise mount SCIM with its ADR-0134
189190
// deprovisioning path silently declined.
190191
assertScimAdminCoherence(pluginConfig);
191-
const twoFactorFromEnv = readBooleanEnv('OS_AUTH_TWO_FACTOR');
192192
const hibpFromEnv = readBooleanEnv('OS_AUTH_PASSWORD_REJECT_BREACHED');
193193
const enabled = {
194194
organization: pluginConfig.organization ?? true,
195-
twoFactor: twoFactorFromEnv ?? pluginConfig.twoFactor ?? false,
195+
// [#30201] Shared decision point (env → config), see
196+
// resolveTwoFactorEnabled — the MFA gate and the require_mfa write guard
197+
// ask the same question, so a requirement is never enforced unenrollable.
198+
twoFactor: resolveTwoFactorEnabled(pluginConfig),
196199
passwordRejectBreached: hibpFromEnv ?? pluginConfig.passwordRejectBreached ?? false,
197200
passkeys: pluginConfig.passkeys ?? false,
198201
magicLink: pluginConfig.magicLink ?? false,

‎packages/plugins/plugin-auth/src/auth-manager.test.ts‎

Lines changed: 79 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3876,7 +3876,8 @@ describe('AuthManager', () => {
38763876
const IMPERSONATION = { impersonatedBy: 'u-admin' };
38773877
// Every posture computable at once: enforced MFA with no grace, and a
38783878
// one-day expiry. Each row below decides which postures its user holds.
3879-
const POLICY = { mfaRequired: true, mfaGracePeriodDays: 0, passwordExpiryDays: 1 };
3879+
// [#30201] Two-factor on: the gate holds a user for MFA only while they can enroll.
3880+
const POLICY = { mfaRequired: true, mfaGracePeriodDays: 0, passwordExpiryDays: 1, plugins: { twoFactor: true } };
38803881
const sessionGateFor = async (row: Record<string, unknown>, session: Record<string, unknown>) => {
38813882
const engine = makeDataEngine({ platformAdmin: false });
38823883
// The block's double, its `findOne` answering the posture read of the user row.
@@ -4695,9 +4696,13 @@ describe('AuthManager', () => {
46954696
}),
46964697
update: vi.fn(async () => ({})),
46974698
});
4699+
// [#30201] Two-factor on by default here: the gate holds a user for MFA only
4700+
// while they can enroll. The cases that turn it off say so (`plugins: {}`).
46984701
const mgr = (engine: any, extra: any = {}) => {
46994702
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
4700-
const m = new AuthManager({ secret: SECRET, baseUrl: 'http://localhost:3000', dataEngine: engine, ...extra });
4703+
const m = new AuthManager({
4704+
secret: SECRET, baseUrl: 'http://localhost:3000', dataEngine: engine, plugins: { twoFactor: true }, ...extra,
4705+
});
47014706
warn.mockRestore();
47024707
return m;
47034708
};
@@ -4749,6 +4754,63 @@ describe('AuthManager', () => {
47494754
const g = await (m as any).computeAuthGate('u1', undefined, false);
47504755
expect(g?.code).toBe('MFA_REQUIRED');
47514756
});
4757+
4758+
// [#30201] The twoFactor plugin's endpoints are the only enrollment path.
4759+
// A hold while it is off answers MFA_REQUIRED to a user whose remediation
4760+
// endpoint answers 404 — the whole-tenant lockout the card measured.
4761+
describe('only a user who can enroll is held (#30201)', () => {
4762+
const OLD = () => new Date(Date.now() - 30 * 86_400_000).toISOString();
4763+
const logger = () => ({ warn: vi.fn(), info: vi.fn() });
4764+
4765+
it('two-factor off: no hold and no grace clock started, said once with the remedy', async () => {
4766+
const log = logger();
4767+
const lapsed = makeEngine({ id: 'u1', two_factor_enabled: false, mfa_required_at: OLD() });
4768+
const m = mgr(lapsed, { mfaRequired: true, mfaGracePeriodDays: 0, plugins: {}, logger: log });
4769+
expect(m.isTwoFactorEnabled()).toBe(false);
4770+
await expect((m as any).computeAuthGate('u1', undefined, false)).resolves.toBeUndefined();
4771+
expect(await m.resolveUserAuthGates('u1')).toEqual([]);
4772+
const fresh = makeEngine({ id: 'u2', two_factor_enabled: false, mfa_required_at: null });
4773+
const m2 = mgr(fresh, { mfaRequired: true, plugins: {}, logger: log });
4774+
expect(await m2.resolveUserAuthGates('u2')).toEqual([]);
4775+
// The window opens when enrollment does, not before.
4776+
expect(fresh.update).not.toHaveBeenCalled();
4777+
// Once per manager, however many requests ask.
4778+
expect(log.warn).toHaveBeenCalledTimes(2);
4779+
expect(String(log.warn.mock.calls[0][0])).toMatch(/NOT enforced/);
4780+
expect(String(log.warn.mock.calls[0][0])).toMatch(/OS_AUTH_TWO_FACTOR=true/);
4781+
// The settings remedy is conditional: the env var outranks it.
4782+
expect(String(log.warn.mock.calls[0][0])).toMatch(/unless OS_AUTH_TWO_FACTOR is set to false/);
4783+
});
4784+
4785+
it('an OS_AUTH_TWO_FACTOR=false pin outranks plugins.twoFactor, so the requirement is not enforced', async () => {
4786+
const prior = process.env.OS_AUTH_TWO_FACTOR;
4787+
process.env.OS_AUTH_TWO_FACTOR = 'false';
4788+
try {
4789+
const m = mgr(makeEngine({ id: 'u1', two_factor_enabled: false, mfa_required_at: OLD() }), {
4790+
mfaRequired: true, mfaGracePeriodDays: 0, logger: logger(),
4791+
});
4792+
expect(m.isTwoFactorEnabled()).toBe(false);
4793+
// The one answer: what is wired, what is advertised, what the gate asks.
4794+
expect(m.getPublicConfig().features.twoFactor).toBe(false);
4795+
expect(await m.resolveUserAuthGates('u1')).toEqual([]);
4796+
} finally {
4797+
if (prior === undefined) delete process.env.OS_AUTH_TWO_FACTOR;
4798+
else process.env.OS_AUTH_TWO_FACTOR = prior;
4799+
}
4800+
});
4801+
4802+
it('control: the same user is held once two-factor is on, and an enrolled user never is', async () => {
4803+
const m = mgr(makeEngine({ id: 'u1', two_factor_enabled: false, mfa_required_at: OLD() }), {
4804+
mfaRequired: true, mfaGracePeriodDays: 0,
4805+
});
4806+
expect(m.isTwoFactorEnabled()).toBe(true);
4807+
expect((await m.resolveUserAuthGates('u1')).map((g) => g.code)).toEqual(['MFA_REQUIRED']);
4808+
const enrolled = mgr(makeEngine({ id: 'u1', two_factor_enabled: true, mfa_required_at: OLD() }), {
4809+
mfaRequired: true, mfaGracePeriodDays: 0, plugins: {},
4810+
});
4811+
expect(await enrolled.resolveUserAuthGates('u1')).toEqual([]);
4812+
});
4813+
});
47524814
});
47534815

47544816
// ADR-0069 D3 — per-org MFA tightening (an org may require MFA above the
@@ -4766,9 +4828,12 @@ describe('AuthManager', () => {
47664828
update: vi.fn(async () => ({})),
47674829
count: vi.fn(async () => 1),
47684830
});
4831+
// [#30201] Two-factor on by default, as in the block above.
47694832
const mgr = (engine: any, extra: any = {}) => {
47704833
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
4771-
const m = new AuthManager({ secret: SECRET, baseUrl: 'http://localhost:3000', dataEngine: engine, ...extra });
4834+
const m = new AuthManager({
4835+
secret: SECRET, baseUrl: 'http://localhost:3000', dataEngine: engine, plugins: { twoFactor: true }, ...extra,
4836+
});
47724837
warn.mockRestore();
47734838
return m;
47744839
};
@@ -4803,6 +4868,17 @@ describe('AuthManager', () => {
48034868
await expect((m as any).computeAuthGate('u1', 'org1', false)).resolves.toBeUndefined();
48044869
});
48054870

4871+
it('[#30201] does NOT block for the active org\'s require_mfa while two-factor is off, nor start the clock', async () => {
4872+
const engine = makeEngine(
4873+
{ id: 'u1', two_factor_enabled: false, mfa_required_at: null },
4874+
{ id: 'org1', require_mfa: true },
4875+
);
4876+
const m = mgr(engine, { mfaRequired: false, mfaGracePeriodDays: 0, plugins: {}, logger: { warn: vi.fn() } });
4877+
(m as any)._orgMfaCache = { value: true, at: Date.now() };
4878+
await expect((m as any).computeAuthGate('u1', 'org1', false)).resolves.toBeUndefined();
4879+
expect(engine.update).not.toHaveBeenCalled();
4880+
});
4881+
48064882
it('is a no-op when no org requires MFA and there is no active org', async () => {
48074883
const engine = makeEngine({ id: 'u1', two_factor_enabled: false }, null);
48084884
const m = mgr(engine, { mfaRequired: false });

0 commit comments

Comments
 (0)