Skip to content

Commit 1aa1a1d

Browse files
committed
wip(plugin-auth): tests and changeset for the organization MFA enrollment guard
Claude-Session: https://claude.ai/code/session_01Utp6CYRZxPEjGeTbGfW4YC Co-authored-by: Claude <noreply@anthropic.com>
1 parent 004729a commit 1aa1a1d

5 files changed

Lines changed: 419 additions & 5 deletions

File tree

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

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

Lines changed: 77 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,61 @@ 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+
});
4782+
4783+
it('an OS_AUTH_TWO_FACTOR=false pin outranks plugins.twoFactor, so the requirement is not enforced', async () => {
4784+
const prior = process.env.OS_AUTH_TWO_FACTOR;
4785+
process.env.OS_AUTH_TWO_FACTOR = 'false';
4786+
try {
4787+
const m = mgr(makeEngine({ id: 'u1', two_factor_enabled: false, mfa_required_at: OLD() }), {
4788+
mfaRequired: true, mfaGracePeriodDays: 0, logger: logger(),
4789+
});
4790+
expect(m.isTwoFactorEnabled()).toBe(false);
4791+
// The one answer: what is wired, what is advertised, what the gate asks.
4792+
expect(m.getPublicConfig().features.twoFactor).toBe(false);
4793+
expect(await m.resolveUserAuthGates('u1')).toEqual([]);
4794+
} finally {
4795+
if (prior === undefined) delete process.env.OS_AUTH_TWO_FACTOR;
4796+
else process.env.OS_AUTH_TWO_FACTOR = prior;
4797+
}
4798+
});
4799+
4800+
it('control: the same user is held once two-factor is on, and an enrolled user never is', async () => {
4801+
const m = mgr(makeEngine({ id: 'u1', two_factor_enabled: false, mfa_required_at: OLD() }), {
4802+
mfaRequired: true, mfaGracePeriodDays: 0,
4803+
});
4804+
expect(m.isTwoFactorEnabled()).toBe(true);
4805+
expect((await m.resolveUserAuthGates('u1')).map((g) => g.code)).toEqual(['MFA_REQUIRED']);
4806+
const enrolled = mgr(makeEngine({ id: 'u1', two_factor_enabled: true, mfa_required_at: OLD() }), {
4807+
mfaRequired: true, mfaGracePeriodDays: 0, plugins: {},
4808+
});
4809+
expect(await enrolled.resolveUserAuthGates('u1')).toEqual([]);
4810+
});
4811+
});
47524812
});
47534813

47544814
// ADR-0069 D3 — per-org MFA tightening (an org may require MFA above the
@@ -4766,9 +4826,12 @@ describe('AuthManager', () => {
47664826
update: vi.fn(async () => ({})),
47674827
count: vi.fn(async () => 1),
47684828
});
4829+
// [#30201] Two-factor on by default, as in the block above.
47694830
const mgr = (engine: any, extra: any = {}) => {
47704831
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
4771-
const m = new AuthManager({ secret: SECRET, baseUrl: 'http://localhost:3000', dataEngine: engine, ...extra });
4832+
const m = new AuthManager({
4833+
secret: SECRET, baseUrl: 'http://localhost:3000', dataEngine: engine, plugins: { twoFactor: true }, ...extra,
4834+
});
47724835
warn.mockRestore();
47734836
return m;
47744837
};
@@ -4803,6 +4866,17 @@ describe('AuthManager', () => {
48034866
await expect((m as any).computeAuthGate('u1', 'org1', false)).resolves.toBeUndefined();
48044867
});
48054868

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

0 commit comments

Comments
 (0)