Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 19 additions & 18 deletions app/Services/Auth/IRecoveryCodeService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
35 changes: 29 additions & 6 deletions app/Services/Auth/RecoveryCodeService.php
Original file line number Diff line number Diff line change
Expand Up @@ -237,18 +237,39 @@ private function logCodesGenerated(User $user, RecoveryCodesBatch $batch): void
*/
public function disableTwoFactor(User $user, ?string $currentPassword, ?User $actor): void
Comment thread
smarcet marked this conversation as resolved.
Resolved
{
// 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.');
Comment thread
smarcet marked this conversation as resolved.
Resolved
}

$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);
Expand All @@ -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(
Expand Down
18 changes: 16 additions & 2 deletions app/libs/Auth/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
25 changes: 19 additions & 6 deletions tests/DisableTwoFactorIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -57,16 +60,29 @@ 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());
$this->assertNotNull($this->userRow()->recovery_codes_acknowledged_at);

// enrolling in setUp already wrote its own enrollment_changed (enabled: true)
$events_before = $this->enrollmentEventCount();

$this->service->disableTwoFactor($this->user, null, null);
Comment thread
smarcet marked this conversation as resolved.
Resolved

$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();
Expand All @@ -80,11 +96,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
Expand Down
106 changes: 84 additions & 22 deletions tests/unit/RecoveryCodeServiceDisableTwoFactorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)->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)
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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([]);
Expand All @@ -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()]);
Expand Down
Loading