From 7c901afe31b4381e1465a740aa6f847d27bec95a Mon Sep 17 00:00:00 2001 From: romanetar Date: Wed, 18 Nov 2026 15:43:16 +0100 Subject: [PATCH 1/2] feat(2fa): guard group-enforced users and lock the row in disableTwoFactor Builds on the disableTwoFactor service method (#169): - refuse a user or administrator actor on a group-enforced user, as the enforcement is derived from group membership (User::isTwoFactorEnforcedByGroup()); the console path (null actor) stays allowed for manual recovery - self-service: with a password it must match; a social-only account is accepted inside the recovery enrollment window instead - take the users-row lock before mutating, so it serializes with a concurrent regenerate/enroll, and clear recovery_codes_acknowledged_at - the service writes no enrollment/settings audit event: recording it is the caller's responsibility; it keeps one device_revoked event per revoked device --- app/Services/Auth/IRecoveryCodeService.php | 37 +++--- app/Services/Auth/RecoveryCodeService.php | 35 +++++- app/libs/Auth/Models/User.php | 18 ++- tests/DisableTwoFactorIntegrationTest.php | 18 ++- ...ecoveryCodeServiceDisableTwoFactorTest.php | 106 ++++++++++++++---- 5 files changed, 161 insertions(+), 53 deletions(-) diff --git a/app/Services/Auth/IRecoveryCodeService.php b/app/Services/Auth/IRecoveryCodeService.php index f59d52aa..50b80382 100644 --- a/app/Services/Auth/IRecoveryCodeService.php +++ b/app/Services/Auth/IRecoveryCodeService.php @@ -107,34 +107,35 @@ public function countUnusedRecoveryCodes(User $user): int; public function getStatus(User $user): RecoveryCodesStatus; /** - * Disables 2FA for the user: clears two_factor_enabled and two_factor_enforced_at, - * deletes every recovery code and revokes every trusted device, all in a single - * transaction. A device_revoked audit event is recorded best-effort afterwards. + * Disables 2FA for the user: clears two_factor_enabled, two_factor_enforced_at and + * recovery_codes_acknowledged_at, deletes every recovery code and revokes every + * trusted device, all in a single transaction under the users-row lock. A + * device_revoked audit event per revoked device is recorded best-effort afterwards. + * The service writes no enrollment/settings audit event: recording it is the caller's + * responsibility (idp:reset-2fa writes settings_changed; the self-service and admin + * paths write enrollment_changed with {enabled: false, actor_id, reason}), so a + * caller never records it twice. * * $actor identifies who performs the operation: - * - null: a system/console operation (e.g. idp:reset-2fa), no password is required; - * - the same user: self-service, $currentPassword must match; + * - null: a system/console operation (e.g. idp:reset-2fa), nothing is required; + * - the same user: self-service. With a password, $currentPassword must match. + * Without one (social-only, !hasPasswordSet()) the session must be inside the + * recovery enrollment window (isWithinEnrollmentWindow()); * - another user: an administrator acting on the account, no password is required. * Authorizing the administrator is the caller's responsibility. * - * Passwordless users (social-only accounts, !$user->hasPasswordSet()) can never - * pass the self-service password check, as User::checkPassword() returns false - * for an empty password, so self-service always throws for them. Such a caller - * must first require another proof of identity (under SDS rev 2.5, a recent 2FA - * challenge: MFAConstants::SESSION_KEY_COMPLETED_AT) and only then invoke this - * method on the user's behalf with $actor = null. - * - * The caller is responsible for emitting the settings_changed audit event, as only - * it knows the context (reason, actor, operator). - * - * Group-enforced users are still required to complete 2FA at login afterwards, - * as enforcement is derived from group membership (User::shouldRequire2FA()). + * Group-enforced users cannot be disabled by a user or an administrator: enforcement + * is derived from group membership (User::isTwoFactorEnforcedByGroup()), so the call + * is refused. The console path is allowed (manual recovery); such a user is still + * challenged at login afterwards. * * @param User $user * @param string|null $currentPassword * @param User|null $actor * @return void - * @throws ValidationException if the actor is the user and $currentPassword does not match + * @throws ValidationException if the user is enforced by group and $actor is not null, if + * the actor is the user and the password does not match, or the user has no password + * and the session is outside the enrollment window */ public function disableTwoFactor(User $user, ?string $currentPassword, ?User $actor): void; } diff --git a/app/Services/Auth/RecoveryCodeService.php b/app/Services/Auth/RecoveryCodeService.php index c554d968..2e93fa24 100644 --- a/app/Services/Auth/RecoveryCodeService.php +++ b/app/Services/Auth/RecoveryCodeService.php @@ -237,18 +237,39 @@ private function logCodesGenerated(User $user, RecoveryCodesBatch $batch): void */ public function disableTwoFactor(User $user, ?string $currentPassword, ?User $actor): void { - // self-service requires the current password; console and admin - // operations do not (see IRecoveryCodeService::disableTwoFactor) - if (!is_null($actor) && $actor->getId() === $user->getId() - && !$user->checkPassword(trim((string)$currentPassword))) { - throw new ValidationException('current_password is not correct.'); + // Group enforcement does not depend on the stored flag: disabling would only + // delete the recovery codes and trusted devices of a user who is still + // challenged at login. The console (null actor) is the manual recovery path + // (idp:reset-2fa) and stays allowed. + if (!is_null($actor) && $user->isTwoFactorEnforcedByGroup()) { + throw new ValidationException('Two-factor authentication is enforced by group membership and cannot be disabled.'); + } + + $is_self = !is_null($actor) && $actor->getId() === $user->getId(); + + if ($is_self) { + if ($user->hasPasswordSet()) { + if (!$user->checkPassword(trim((string)$currentPassword))) { + throw new ValidationException('current_password is not correct.'); + } + } elseif (!$this->isWithinEnrollmentWindow($user)) { + // Social-only account: no password to confirm. Proof of identity is a + // real 2FA challenge completed moments ago in this session. + throw new ValidationException( + 'Sign out and sign in again, then turn off two-factor authentication right after the sign-in.' + ); + } } // a single transaction() call: nesting another one (e.g. through the audit // service) inside it would let an inner failure close the entity manager // under this still-running outer transaction $revoked_devices = $this->tx_service->transaction(function () use ($user) { + // serializes with a concurrent regenerate: it also deletes and inserts + // codes. The lock re-hydrates $user, so it must precede disable2FA(). + $this->repository->lockUserRow($user); $user->disable2FA(); + $user->setRecoveryCodesAcknowledgedAt(null); $this->user_repository->add($user, false); $this->repository->deleteAllForUser($user); return $this->trusted_device_repository->revokeAllActiveForUser($user); @@ -257,7 +278,9 @@ public function disableTwoFactor(User $user, ?string $currentPassword, ?User $ac // Best-effort: 2FA is already disabled and the codes and devices are gone, // an audit-logging failure must not make the caller believe it did not happen. // One device_revoked event per device actually revoked, with its device_id - // (same semantics as DeviceTrustService::removeTrustedDevices). + // (same semantics as DeviceTrustService::removeTrustedDevices). The + // enrollment_changed / settings_changed event is the caller's: only it + // knows the actor and the reason. foreach ($revoked_devices as $device) { try { $this->audit_service->log( diff --git a/app/libs/Auth/Models/User.php b/app/libs/Auth/Models/User.php index 8da14ee8..b4137fcb 100644 --- a/app/libs/Auth/Models/User.php +++ b/app/libs/Auth/Models/User.php @@ -2459,13 +2459,27 @@ public function shouldRequire2FA(): bool if (!config('two_factor.enabled', true)) { return false; } + if ($this->isTwoFactorEnforcedByGroup()) { + return true; + } + return (bool) $this->two_factor_enabled; + } + + /** + * Whether the user belongs to any of the groups listed in + * config('two_factor.enforced_groups'). Group enforcement does not depend on the + * stored two_factor_enabled flag, so it cannot be switched off by disabling it. + * Unlike shouldRequire2FA() this ignores the global two_factor.enabled kill-switch. + */ + public function isTwoFactorEnforcedByGroup(): bool + { $enforcedGroups = config('two_factor.enforced_groups', []); foreach ($enforcedGroups as $slug) { - if($this->belongToGroup($slug)) { + if ($this->belongToGroup($slug)) { return true; } } - return (bool) $this->two_factor_enabled; + return false; } /** diff --git a/tests/DisableTwoFactorIntegrationTest.php b/tests/DisableTwoFactorIntegrationTest.php index e4ba09eb..b9ac4cab 100644 --- a/tests/DisableTwoFactorIntegrationTest.php +++ b/tests/DisableTwoFactorIntegrationTest.php @@ -57,11 +57,22 @@ private function userRow(): object return DB::table('users')->where('id', $this->user->getId())->first(); } + private function enrollmentEventCount(): int + { + return DB::table('two_factor_audit_log') + ->where('user_id', $this->user->getId()) + ->whereIn('event_type', [TwoFactorAuditLog::EventEnrollmentChanged, TwoFactorAuditLog::EventSettingsChanged]) + ->count(); + } + public function testDisableClearsEverything(): void { $this->assertSame(1, (int)$this->userRow()->two_factor_enabled); $this->assertSame(10, DB::table('user_recovery_codes')->where('user_id', $this->user->getId())->count()); + // enrolling in setUp already wrote its own enrollment_changed (enabled: true) + $events_before = $this->enrollmentEventCount(); + $this->service->disableTwoFactor($this->user, null, null); $row = $this->userRow(); @@ -80,11 +91,8 @@ public function testDisableClearsEverything(): void ->where('user_id', $this->user->getId()) ->where('event_type', TwoFactorAuditLog::EventDeviceRevoked) ->count()); - // settings_changed is the caller's responsibility - $this->assertSame(0, DB::table('two_factor_audit_log') - ->where('user_id', $this->user->getId()) - ->where('event_type', TwoFactorAuditLog::EventSettingsChanged) - ->count()); + // the service writes no enrollment/settings event: that is the caller's responsibility + $this->assertSame($events_before, $this->enrollmentEventCount()); } public function testSelfServiceWithWrongPasswordLeavesStateUntouched(): void diff --git a/tests/unit/RecoveryCodeServiceDisableTwoFactorTest.php b/tests/unit/RecoveryCodeServiceDisableTwoFactorTest.php index 18d68233..34f4ba42 100644 --- a/tests/unit/RecoveryCodeServiceDisableTwoFactorTest.php +++ b/tests/unit/RecoveryCodeServiceDisableTwoFactorTest.php @@ -20,6 +20,8 @@ use Auth\Repositories\IUserRepository; use Auth\Repositories\IUserTrustedDeviceRepository; use Auth\User; +use Auth\MFAConstants; +use Illuminate\Support\Facades\Session; use Mockery; use models\exceptions\ValidationException; use Tests\BrowserKitTestCase; @@ -75,17 +77,21 @@ protected function tearDown(): void parent::tearDown(); } - private function buildUser(int $id): \Mockery\MockInterface + private function buildUser(int $id, bool $enforced = false, bool $hasPassword = true): \Mockery\MockInterface { $user = Mockery::mock(User::class); $user->shouldReceive('getId')->andReturn($id); $user->shouldReceive('getTwoFactorMethod')->andReturn(User::MFAMethod_OTP); + $user->shouldReceive('isTwoFactorEnforcedByGroup')->andReturn($enforced); + $user->shouldReceive('hasPasswordSet')->andReturn($hasPassword); return $user; } private function expectFullDisable(\Mockery\MockInterface $user): void { - $user->shouldReceive('disable2FA')->once(); + $this->code_repo->shouldReceive('lockUserRow')->once()->with($user)->ordered(); + $user->shouldReceive('disable2FA')->once()->ordered(); + $user->shouldReceive('setRecoveryCodesAcknowledgedAt')->once()->with(null); $this->user_repo->shouldReceive('add')->once()->with($user, false); $this->code_repo->shouldReceive('deleteAllForUser')->once()->with($user)->andReturn(10); $this->device_repo->shouldReceive('revokeAllActiveForUser')->once()->with($user) @@ -95,6 +101,15 @@ private function expectFullDisable(\Mockery\MockInterface $user): void ->with($user, TwoFactorAuditLog::EventDeviceRevoked, User::MFAMethod_OTP, Mockery::type('string'), Mockery::type('array')); } + private function expectNothingChanges(\Mockery\MockInterface $user): void + { + $user->shouldNotReceive('disable2FA'); + $this->tx_service->shouldNotReceive('transaction'); + $this->code_repo->shouldNotReceive('deleteAllForUser'); + $this->device_repo->shouldNotReceive('revokeAllActiveForUser'); + $this->audit_service->shouldNotReceive('log'); + } + public function testConsoleActorNeedsNoPassword(): void { $user = $this->buildUser(1); @@ -104,6 +119,14 @@ public function testConsoleActorNeedsNoPassword(): void $this->service->disableTwoFactor($user, null, null); } + public function testConsoleActorMayResetAGroupEnforcedUser(): void + { + $user = $this->buildUser(1, true); + $this->expectFullDisable($user); + + $this->service->disableTwoFactor($user, null, null); + } + public function testAdminActorNeedsNoPassword(): void { $user = $this->buildUser(1); @@ -114,6 +137,16 @@ public function testAdminActorNeedsNoPassword(): void $this->service->disableTwoFactor($user, null, $admin); } + public function testAdminActorCannotDisableAGroupEnforcedUser(): void + { + $user = $this->buildUser(1, true); + $admin = $this->buildUser(2); + $this->expectNothingChanges($user); + + $this->expectException(ValidationException::class); + $this->service->disableTwoFactor($user, null, $admin); + } + public function testSelfServiceWithCorrectPassword(): void { $user = $this->buildUser(1); @@ -127,52 +160,79 @@ public function testSelfServiceWithWrongPasswordChangesNothing(): void { $user = $this->buildUser(1); $user->shouldReceive('checkPassword')->once()->andReturn(false); - $user->shouldNotReceive('disable2FA'); - $this->tx_service->shouldNotReceive('transaction'); - $this->code_repo->shouldNotReceive('deleteAllForUser'); - $this->device_repo->shouldNotReceive('revokeAllActiveForUser'); - $this->audit_service->shouldNotReceive('log'); + $this->expectNothingChanges($user); $this->expectException(ValidationException::class); $this->service->disableTwoFactor($user, 'wrong', $user); } - public function testSelfServiceWithoutPasswordIsRejected(): void + public function testSelfServiceOnAGroupEnforcedUserIsRefusedBeforeCheckingThePassword(): void { - $user = $this->buildUser(1); - $user->shouldReceive('checkPassword')->once()->with('')->andReturn(false); - $user->shouldNotReceive('disable2FA'); + $user = $this->buildUser(1, true); + $user->shouldNotReceive('checkPassword'); + $this->expectNothingChanges($user); + + $this->expectException(ValidationException::class); + $this->service->disableTwoFactor($user, 'secret', $user); + } + + public function testSelfServiceWithoutPasswordOutsideTheEnrollmentWindowIsRejected(): void + { + Session::forget(MFAConstants::SESSION_KEY_COMPLETED_AT); + $user = $this->buildUser(1, false, false); + $user->shouldNotReceive('checkPassword'); + $this->expectNothingChanges($user); + + $this->expectException(ValidationException::class); + $this->service->disableTwoFactor($user, null, $user); + } + + public function testSelfServiceWithoutPasswordInsideTheEnrollmentWindow(): void + { + Session::put(MFAConstants::SESSION_KEY_COMPLETED_AT, ['user_id' => 1, 'at' => time() - 30]); + $user = $this->buildUser(1, false, false); + $user->shouldNotReceive('checkPassword'); + $this->expectFullDisable($user); + + $this->service->disableTwoFactor($user, null, $user); + } + + public function testSelfServiceWithoutPasswordAndAWindowOfAnotherUserIsRejected(): void + { + Session::put(MFAConstants::SESSION_KEY_COMPLETED_AT, ['user_id' => 99, 'at' => time() - 30]); + $user = $this->buildUser(1, false, false); + $this->expectNothingChanges($user); $this->expectException(ValidationException::class); $this->service->disableTwoFactor($user, null, $user); } /** - * A passwordless (social-only) user can never satisfy the self-service - * password check: checkPassword() is false for an empty password, whatever - * is supplied. The caller must obtain another proof of identity (a recent - * 2FA challenge) and call this service as console/admin instead. - * See the IRecoveryCodeService::disableTwoFactor PHPDoc. + * The users-row lock is the first thing taken inside the transaction: when it + * cannot be acquired nothing is mutated (it serializes with a concurrent + * regenerate/enroll, which also deletes and inserts codes). */ - public function testSelfServiceForPasswordlessUserIsRejectedAndChangesNothing(): void + public function testNothingIsMutatedWhenTheUserRowLockFails(): void { $user = $this->buildUser(1); - $user->shouldReceive('hasPasswordSet')->andReturn(false); - $user->shouldReceive('checkPassword')->once()->andReturn(false); + $this->code_repo->shouldReceive('lockUserRow')->once()->with($user) + ->andThrow(new \RuntimeException('lock wait timeout')); $user->shouldNotReceive('disable2FA'); - $this->tx_service->shouldNotReceive('transaction'); + $user->shouldNotReceive('setRecoveryCodesAcknowledgedAt'); $this->code_repo->shouldNotReceive('deleteAllForUser'); $this->device_repo->shouldNotReceive('revokeAllActiveForUser'); $this->audit_service->shouldNotReceive('log'); - $this->expectException(ValidationException::class); - $this->service->disableTwoFactor($user, 'anything', $user); + $this->expectException(\RuntimeException::class); + $this->service->disableTwoFactor($user, null, null); } public function testNoActiveDevicesLogsNoDeviceRevokedEvent(): void { $user = $this->buildUser(1); + $this->code_repo->shouldReceive('lockUserRow')->once(); $user->shouldReceive('disable2FA')->once(); + $user->shouldReceive('setRecoveryCodesAcknowledgedAt')->once()->with(null); $this->user_repo->shouldReceive('add')->once(); $this->code_repo->shouldReceive('deleteAllForUser')->once()->andReturn(0); $this->device_repo->shouldReceive('revokeAllActiveForUser')->once()->andReturn([]); @@ -184,7 +244,9 @@ public function testNoActiveDevicesLogsNoDeviceRevokedEvent(): void public function testAuditFailureDoesNotFailTheOperation(): void { $user = $this->buildUser(1); + $this->code_repo->shouldReceive('lockUserRow')->once(); $user->shouldReceive('disable2FA')->once(); + $user->shouldReceive('setRecoveryCodesAcknowledgedAt')->once(); $this->user_repo->shouldReceive('add')->once(); $this->code_repo->shouldReceive('deleteAllForUser')->once()->andReturn(0); $this->device_repo->shouldReceive('revokeAllActiveForUser')->once()->andReturn([new UserTrustedDevice()]); From d6015f9709baf1fe9a05a7256a2766afffa4b964 Mon Sep 17 00:00:00 2001 From: romanetar Date: Wed, 18 Nov 2026 17:12:25 +0100 Subject: [PATCH 2/2] test(2fa): prove disableTwoFactor clears recovery_codes_acknowledged_at The integration test now acknowledges the enrolled batch in setUp, asserts the column is set before disableTwoFactor() and NULL after it. The unit test orders setRecoveryCodesAcknowledgedAt(null) after lockUserRow(), so moving it before the lock (where HINT_REFRESH would re-hydrate the user and drop it) no longer passes. --- tests/DisableTwoFactorIntegrationTest.php | 7 ++++++- tests/unit/RecoveryCodeServiceDisableTwoFactorTest.php | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/DisableTwoFactorIntegrationTest.php b/tests/DisableTwoFactorIntegrationTest.php index b9ac4cab..b8e9e1bc 100644 --- a/tests/DisableTwoFactorIntegrationTest.php +++ b/tests/DisableTwoFactorIntegrationTest.php @@ -46,7 +46,10 @@ protected function setUp(): void $this->user = $user; // enrolled, with a code batch and two trusted devices - $this->service->enableTwoFactorAndGenerateCodes($user, User::MFAMethod_OTP); + $batch = $this->service->enableTwoFactorAndGenerateCodes($user, User::MFAMethod_OTP); + // the user confirmed the batch: recovery_codes_acknowledged_at is set, so the + // disable test can prove it is cleared (enrolling alone leaves it NULL) + $this->assertTrue($this->service->acknowledgeRecoveryCodes($user, $batch->getBatchId())); $devices = $this->app->make(IDeviceTrustService::class); $devices->trustDevice($user, 'agent-a', '127.0.0.1'); $devices->trustDevice($user, 'agent-b', '127.0.0.1'); @@ -69,6 +72,7 @@ public function testDisableClearsEverything(): void { $this->assertSame(1, (int)$this->userRow()->two_factor_enabled); $this->assertSame(10, DB::table('user_recovery_codes')->where('user_id', $this->user->getId())->count()); + $this->assertNotNull($this->userRow()->recovery_codes_acknowledged_at); // enrolling in setUp already wrote its own enrollment_changed (enabled: true) $events_before = $this->enrollmentEventCount(); @@ -78,6 +82,7 @@ public function testDisableClearsEverything(): void $row = $this->userRow(); $this->assertSame(0, (int)$row->two_factor_enabled); $this->assertNull($row->two_factor_enforced_at); + $this->assertNull($row->recovery_codes_acknowledged_at); $this->assertSame(0, DB::table('user_recovery_codes')->where('user_id', $this->user->getId())->count()); $devices = DB::table('user_trusted_devices')->where('user_id', $this->user->getId())->get(); diff --git a/tests/unit/RecoveryCodeServiceDisableTwoFactorTest.php b/tests/unit/RecoveryCodeServiceDisableTwoFactorTest.php index 34f4ba42..c30a14e0 100644 --- a/tests/unit/RecoveryCodeServiceDisableTwoFactorTest.php +++ b/tests/unit/RecoveryCodeServiceDisableTwoFactorTest.php @@ -91,7 +91,7 @@ private function expectFullDisable(\Mockery\MockInterface $user): void { $this->code_repo->shouldReceive('lockUserRow')->once()->with($user)->ordered(); $user->shouldReceive('disable2FA')->once()->ordered(); - $user->shouldReceive('setRecoveryCodesAcknowledgedAt')->once()->with(null); + $user->shouldReceive('setRecoveryCodesAcknowledgedAt')->once()->with(null)->ordered(); $this->user_repo->shouldReceive('add')->once()->with($user, false); $this->code_repo->shouldReceive('deleteAllForUser')->once()->with($user)->andReturn(10); $this->device_repo->shouldReceive('revokeAllActiveForUser')->once()->with($user)