Skip to content

Commit f643025

Browse files
committed
fix(plugin-auth): refuse only turning require_mfa on, and say when the settings remedy works
Contract review follow-ups: - The guard judges the change, not the payload: an update is refused only for a row whose stored value (the engine's `previous`, bound on the by-id and the per-row multi-row paths) is off. Re-sending `require_mfa: true` for a row that already stores it passes, so a whole-row update, an import re-run or a save with no change no longer blocks the row's other edits. A multi-row update is judged row by row; a context with no `previous` is judged as a change. - The refusal and the gate's warning offer the `auth.mfa_required` remedy only where it can work: the OS_AUTH_TWO_FACTOR env var outranks it. - AuthManager.isTwoFactorEnabled is marked @internal. - The organization-declared held-session block turns two-factor on itself instead of inheriting it from the held state that ran before. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Utp6CYRZxPEjGeTbGfW4YC
1 parent 8c4430f commit f643025

6 files changed

Lines changed: 127 additions & 25 deletions

File tree

‎.changeset/30201-org-mfa-needs-enrollment.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
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)
66

7-
Clause-②: no (narrowing) — a write that turns `sys_organization.require_mfa` on is refused `400 VALIDATION_FAILED` while the two-factor feature is off, a value an administrator could save before. Nothing is widened.
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.
88
Metadata-protocol: none
99
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)
1010

@@ -13,9 +13,9 @@ Skills-docs: follow-up owed — content/docs/permissions/authentication.mdx (the
1313
**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.
1414

1515
- **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.** A write whose payload turns `require_mfa` on is refused while two-factor is off, with one `fields[]` entry on `require_mfa` (`invalid_value`) saying why, who would have been locked out, and the two ways forward. It applies to every write context, the system's included, on the by-id door, a multi-row update and an insert. 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).
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).
1717
- **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.
1818
- **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.
1919
- **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.
2020

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. Turning on the `auth.mfa_required` setting instead requires it for every organization and turns enrollment on with it.
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.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4778,6 +4778,8 @@ describe('AuthManager', () => {
47784778
expect(log.warn).toHaveBeenCalledTimes(2);
47794779
expect(String(log.warn.mock.calls[0][0])).toMatch(/NOT enforced/);
47804780
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/);
47814783
});
47824784

47834785
it('an OS_AUTH_TWO_FACTOR=false pin outranks plugins.twoFactor, so the requirement is not enforced', async () => {

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

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5254,6 +5254,9 @@ export class AuthManager {
52545254
}
52555255

52565256
/**
5257+
* @internal Package-internal: read by the MFA gate and by the organization
5258+
* MFA enrollment guard `AuthPlugin` registers; not a supported entry point.
5259+
*
52575260
* [#30201] Can a user enroll a second factor on this deployment right now —
52585261
* is the twoFactor plugin wired? {@link resolveTwoFactorEnabled} over the
52595262
* live config, the one answer `buildPluginList()` and `features.twoFactor`
@@ -5278,9 +5281,10 @@ export class AuthManager {
52785281
this.config.logger?.warn(
52795282
'[auth] multi-factor authentication is required (the auth.mfa_required setting, or an organization\'s ' +
52805283
'require_mfa) but is NOT enforced: the two-factor feature is off, so nobody can enroll an authenticator ' +
5281-
'app, and holding them would lock every affected member out, the owner included. Remedy: turn two-factor ' +
5282-
'on (OS_AUTH_TWO_FACTOR=true, or the auth.mfa_required setting, which turns it on with the requirement); ' +
5283-
'or clear require_mfa on the organization.',
5284+
'app, and holding them would lock every affected member out, the owner included. Remedy: set ' +
5285+
'OS_AUTH_TWO_FACTOR=true; or, unless OS_AUTH_TWO_FACTOR is set to false (it overrides the settings), turn ' +
5286+
'on the auth.mfa_required setting, which turns two-factor on with the requirement; or clear require_mfa on ' +
5287+
'the organization.',
52845288
);
52855289
}
52865290

‎packages/plugins/plugin-auth/src/organization-mfa-enrollment-guard.test.ts‎

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,16 @@ function captureEngine() {
6767
};
6868
}
6969

70-
/** Run every registered handler for `event` over a payload; returns the thrown error, or null. */
70+
/**
71+
* Run every registered handler for `event` over a payload, with the stored row
72+
* as `previous` when given (the engine binds it on every update path); returns
73+
* the thrown error, or null.
74+
*/
7175
async function judge(
7276
enrollable: boolean,
7377
event: 'beforeInsert' | 'beforeUpdate',
7478
data: Record<string, unknown>,
79+
previous?: Record<string, unknown>,
7580
): Promise<any> {
7681
const engine = captureEngine();
7782
registerOrganizationMfaEnrollmentGuard(engine, {
@@ -80,7 +85,10 @@ async function judge(
8085
});
8186
try {
8287
for (const r of engine.registrations.filter((x) => x.event === event)) {
83-
await r.handler({ object: 'sys_organization', event, input: { id: 'org_1', data } });
88+
await r.handler({
89+
object: 'sys_organization', event, input: { id: 'org_1', data },
90+
...(previous ? { previous } : {}),
91+
});
8492
}
8593
return null;
8694
} catch (e) {
@@ -121,6 +129,22 @@ describe('organization MFA enrollment guard — the rule', () => {
121129
}
122130
});
123131

132+
it('refuses an update that turns it on for a row stored off, and one with no stored row to prove otherwise', async () => {
133+
expectRequireMfaRefusal(await judge(false, 'beforeUpdate', { require_mfa: true }, { require_mfa: false }));
134+
expectRequireMfaRefusal(await judge(false, 'beforeUpdate', { require_mfa: true }, { require_mfa: null }));
135+
expectRequireMfaRefusal(await judge(false, 'beforeUpdate', { require_mfa: true }, { name: 'Acme' }));
136+
// No `previous` at all: an unproven prior state is judged as a change.
137+
expectRequireMfaRefusal(await judge(false, 'beforeUpdate', { require_mfa: true }));
138+
});
139+
140+
it('admits re-sending it for a row that already stores it on: the write turns nothing on', async () => {
141+
// A whole-row SDK/MCP update, an import re-run, a save with no change.
142+
expect(await judge(false, 'beforeUpdate', { require_mfa: true }, { require_mfa: true })).toBeNull();
143+
expect(await judge(false, 'beforeUpdate', { require_mfa: 1, name: 'Acme' }, { require_mfa: 1 })).toBeNull();
144+
// An insert has no stored value to keep: a `previous` there changes nothing.
145+
expectRequireMfaRefusal(await judge(false, 'beforeInsert', { require_mfa: true }, { require_mfa: true }));
146+
});
147+
124148
it('never judges a write that clears the requirement or leaves it alone', async () => {
125149
for (const event of ['beforeInsert', 'beforeUpdate'] as const) {
126150
expect(await judge(false, event, { require_mfa: false })).toBeNull();
@@ -138,6 +162,8 @@ describe('organization MFA enrollment guard — the rule', () => {
138162
expect(err.message).toMatch(/owner included/);
139163
expect(err.message).toMatch(/OS_AUTH_TWO_FACTOR=true/);
140164
expect(err.message).toMatch(/auth\.mfa_required/);
165+
// The env var outranks the settings: the settings remedy is offered only where it can work.
166+
expect(err.message).toMatch(/Unless OS_AUTH_TWO_FACTOR is set to false/);
141167
expect(err.message).not.toMatch(/#\d/);
142168
expect(err.fields[0].message).toBe(err.message);
143169
});
@@ -273,6 +299,40 @@ describe('organization MFA enrollment guard — on a real engine', () => {
273299
expect(await engine.findOne('sys_organization', { where: { id: 'org_c' }, ...SYSTEM })).toBeNull();
274300
});
275301

302+
it('admits re-saving a row that already requires MFA, so its other edits are not blocked', async () => {
303+
const enrollable = { value: true };
304+
const engine = await bootOrganizationEngine(enrollable);
305+
await engine.update('sys_organization', { id: 'org_a', require_mfa: true }, ADMIN);
306+
// Two-factor goes off afterwards (an env pin, a settings change).
307+
enrollable.value = false;
308+
// A door that sends the whole editable record re-sends the stored `true`.
309+
await engine.update('sys_organization', { id: 'org_a', require_mfa: true, timezone: 'Asia/Shanghai' }, ADMIN);
310+
await engine.update('sys_organization', { id: 'org_a', require_mfa: true }, SYSTEM);
311+
const row: any = await engine.findOne('sys_organization', { where: { id: 'org_a' }, ...SYSTEM });
312+
expect(row.timezone).toBe('Asia/Shanghai');
313+
expect(row.require_mfa).toBe(true);
314+
// Control: the other row, stored off, is still refused.
315+
expectRequireMfaRefusal(await caught(engine.update('sys_organization', { id: 'org_b', require_mfa: true }, ADMIN)));
316+
});
317+
318+
it('judges a multi-row update row by row: one row turning it on refuses the whole write, with nothing written', async () => {
319+
const enrollable = { value: true };
320+
const engine = await bootOrganizationEngine(enrollable);
321+
await engine.update('sys_organization', { id: 'org_a', require_mfa: true }, ADMIN);
322+
enrollable.value = false;
323+
// org_a already requires it, org_b does not: the batch turns it on for org_b.
324+
expectRequireMfaRefusal(await caught(
325+
engine.update('sys_organization', { require_mfa: true, timezone: 'UTC' }, { ...SYSTEM, where: {}, multi: true } as any),
326+
));
327+
expect(await storedRequireMfa(engine, 'org_b')).toBe(false);
328+
const a: any = await engine.findOne('sys_organization', { where: { id: 'org_a' }, ...SYSTEM });
329+
expect(a.timezone).not.toBe('UTC');
330+
// Every matched row already requires it: the batch turns nothing on and lands.
331+
await engine.update('sys_organization', { require_mfa: true, timezone: 'UTC' }, { ...SYSTEM, where: { slug: 'acme' }, multi: true } as any);
332+
const a2: any = await engine.findOne('sys_organization', { where: { id: 'org_a' }, ...SYSTEM });
333+
expect(a2.timezone).toBe('UTC');
334+
});
335+
276336
it('leaves every other organization write alone while two-factor is off', async () => {
277337
const engine = await bootOrganizationEngine({ value: false });
278338
await engine.update('sys_organization', { id: 'org_a', timezone: 'Asia/Shanghai' }, ADMIN);

‎packages/plugins/plugin-auth/src/organization-mfa-enrollment-guard.ts‎

Lines changed: 46 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -35,20 +35,34 @@
3535
*
3636
* ## The rule
3737
*
38-
* A write to `sys_organization` whose payload sets `require_mfa` to anything
39-
* but an explicit off value is refused while {@link
40-
* OrganizationMfaEnrollmentGuardOptions.isTwoFactorEnabled} answers false —
38+
* While {@link OrganizationMfaEnrollmentGuardOptions.isTwoFactorEnabled}
39+
* answers false, a write that TURNS the requirement on is refused —
4140
* `400 VALIDATION_FAILED` with one `fields[]` entry, `require_mfa` /
42-
* `invalid_value` (the closed ADR-0114 catalog), built by `validationFailure`.
43-
* Clearing the column, writing other columns, and every write while two-factor
44-
* is on pass untouched.
41+
* `invalid_value` (the closed ADR-0114 catalog), built by `validationFailure`:
42+
*
43+
* - an insert whose payload sets `require_mfa` to anything but an explicit
44+
* off value;
45+
* - an update whose payload does so for a row whose stored value is off.
46+
*
47+
* Clearing the column, writing other columns, re-sending `require_mfa: true`
48+
* for a row that already stores it (a whole-row SDK or MCP update, an import
49+
* re-run, a save with no change), and every write while two-factor is on pass
50+
* untouched. Refusing the unchanged value would block every other edit of
51+
* that row through a door that sends the whole record, for a value the gate
52+
* already does not enforce (below).
53+
*
54+
* The stored value is the update context's `previous`, which the engine binds
55+
* before `beforeUpdate` on BOTH update paths: the by-id write binds the row it
56+
* read, and a multi-row update fans out one context per matched row, each
57+
* with that row's `previous` and the one shared payload, before anything is
58+
* written. So a multi-row update is judged row by row, and one row turning
59+
* the requirement on refuses the whole write, rows that already stored it
60+
* included, with nothing written. An update context WITHOUT a `previous` is
61+
* judged as a change (refused): no engine path produces one, and an unproven
62+
* prior state is not evidence the value was already on.
4563
*
4664
* Judged for EVERY write context, the system's included, like the last-admin
47-
* guard: the lockout does not depend on who wrote the row. And judged on the
48-
* payload, not on the stored row, so it covers the by-id path, a multi-row
49-
* update (whose per-row contexts share one payload) and an insert alike; a
50-
* form that re-sends `require_mfa: true` for a row stored before this guard is
51-
* told the requirement is not enforceable, which is true.
65+
* guard: the lockout does not depend on who wrote the row.
5266
*
5367
* Rows stored before this guard are not touched. The gate itself does not
5468
* enforce a requirement nobody can comply with (`resolveUserAuthGates`), so
@@ -98,26 +112,41 @@ export function turnsMfaRequirementOn(value: unknown): boolean {
98112
return !OFF_VALUES.has(value);
99113
}
100114

101-
/** The refusal: what was refused, why, who it would have locked out, and the two ways forward. */
115+
/**
116+
* The refusal: what was refused, why, who it would have locked out, and the
117+
* ways forward. The second way is conditional because it is: the
118+
* `OS_AUTH_TWO_FACTOR` env var outranks the settings (`resolveTwoFactorEnabled`),
119+
* so under an `OS_AUTH_TWO_FACTOR=false` pin turning `auth.mfa_required` on
120+
* does not turn enrollment on.
121+
*/
102122
export function organizationMfaWithoutEnrollmentRefusal(): Error {
103123
const message =
104124
'This organization cannot require multi-factor authentication yet: two-factor enrollment is off on this ' +
105125
'deployment, so once the grace period ended every member, the owner included, would be blocked with no way ' +
106126
'to enroll an authenticator app. Turn two-factor on first, then require it here: set OS_AUTH_TWO_FACTOR=true ' +
107-
'on the deployment, or turn on the auth.mfa_required setting, which requires multi-factor authentication for ' +
108-
'every organization and turns enrollment on with it.';
127+
'on the deployment. Unless OS_AUTH_TWO_FACTOR is set to false there (it overrides the settings), turning on ' +
128+
'the auth.mfa_required setting also works: it requires multi-factor authentication for every organization ' +
129+
'and turns enrollment on with it.';
109130
return validationFailure(message, [{ field: REQUIRE_MFA_FIELD, code: 'invalid_value', message }]);
110131
}
111132

133+
/** True when an update context proves the row already stores the requirement on. */
134+
function alreadyRequiresMfa(ctx: any): boolean {
135+
const previous = ctx?.previous as Record<string, unknown> | undefined;
136+
return !!previous && typeof previous === 'object' && turnsMfaRequirementOn(previous[REQUIRE_MFA_FIELD]);
137+
}
138+
112139
/** Register the guard's insert and update hooks on `sys_organization`. */
113140
export function registerOrganizationMfaEnrollmentGuard(
114141
engine: OrganizationMfaEnrollmentGuardEngine,
115142
opts: OrganizationMfaEnrollmentGuardOptions,
116143
): void {
117-
const judge = async (ctx: any): Promise<void> => {
144+
const judge = (isUpdate: boolean) => async (ctx: any): Promise<void> => {
118145
const data = ctx?.input?.data as Record<string, unknown> | undefined;
119146
if (!data || typeof data !== 'object' || !(REQUIRE_MFA_FIELD in data)) return;
120147
if (!turnsMfaRequirementOn(data[REQUIRE_MFA_FIELD])) return;
148+
// Unchanged: the row already stores it on, so this write turns nothing on.
149+
if (isUpdate && alreadyRequiresMfa(ctx)) return;
121150
if (opts.isTwoFactorEnabled()) return;
122151
throw organizationMfaWithoutEnrollmentRefusal();
123152
};
@@ -126,6 +155,6 @@ export function registerOrganizationMfaEnrollmentGuard(
126155
priority: ORGANIZATION_MFA_ENROLLMENT_GUARD_PRIORITY,
127156
packageId: opts.packageId,
128157
};
129-
engine.registerHook('beforeInsert', judge, options);
130-
engine.registerHook('beforeUpdate', judge, options);
158+
engine.registerHook('beforeInsert', judge(false), options);
159+
engine.registerHook('beforeUpdate', judge(true), options);
131160
}

‎packages/verify/src/held-session-vendor-admin-doors.pin.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,10 +332,16 @@ for (const state of HELD_STATES) {
332332

333333
describe("a hold only the session's organization declares (MFA required by the organization)", () => {
334334
let organizationId: string | undefined;
335+
let twoFactorBefore: boolean | undefined;
335336

336337
beforeAll(async () => {
337338
organizationId = (await sessionOf(await stack.signIn())).organizationId;
338339
if (!organizationId) throw new Error('the platform admin session operates in no organization');
340+
// Two-factor on, by this block itself: an organization cannot require MFA
341+
// while nobody can enroll (the write is refused), and the gate holds no one
342+
// then. Not inherited from whichever held state ran before.
343+
twoFactorBefore = auth.isTwoFactorEnabled();
344+
auth.applyConfigPatch({ plugins: { twoFactor: true } });
339345
await ql.update('sys_organization', { id: organizationId, require_mfa: true }, SYS);
340346
// The 60-second "does any organization require MFA" cache, primed as the
341347
// background refresh would after this write.
@@ -348,6 +354,7 @@ describe("a hold only the session's organization declares (MFA required by the o
348354
afterAll(async () => {
349355
if (organizationId) await ql.update('sys_organization', { id: organizationId, require_mfa: false }, SYS);
350356
auth._orgMfaCache = { value: false, at: Date.now() };
357+
if (twoFactorBefore === false) auth.applyConfigPatch({ plugins: { twoFactor: false } });
351358
});
352359

353360
it('holds the admin in that organization and in no other reading (the floor holds no one)', async () => {

0 commit comments

Comments
 (0)