diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index ed50fda849..e0d0c8c478 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -40,15 +40,15 @@ public function displayTwoFactorAuthForm(Request $request) return redirect()->route('login'); } - // Send code - if (!session()->has(self::TFA_ERROR) && !session()->has(self::TFA_MESSAGE)) { - $this->twoFactorAuthentication->sendCode($user); - } else { - if (!session()->has(self::TFA_MESSAGE)) { - $this->twoFactorAuthentication->sendCode($user); - } + // Reload DB state without User::refresh() (clears permission caches). + $user = $user->fresh() ?? $user; + if ($this->shouldRedirectToAuthenticatorQrEnrollment($user)) { + return redirect()->route('2fa.auth_app_qr'); } + // Send code + $this->sendTwoFactorCodeForDisplay($user); + // Set informative message $methodsNames = $this->twoFactorAuthentication->friendlyMethodsNames($user); $message = __('Enter the security code from :methods. If incorrect, please retry with the latest code provided.', @@ -76,7 +76,7 @@ public function validateTwoFactorAuthCode(Request $request) // If empty code return error message if (empty($code)) { // Set error message - session()->put(self::TFA_ERROR, _('Invalid code.')); + session()->put(self::TFA_ERROR, __('Invalid code.')); // Return to 2fa page return redirect()->route('2fa'); @@ -98,7 +98,7 @@ public function validateTwoFactorAuthCode(Request $request) $route = 'login'; } else { // Set error message - session()->put(self::TFA_ERROR, _('Invalid code.')); + session()->put(self::TFA_ERROR, __('Invalid code.')); // Return to 2fa page $route = '2fa'; @@ -129,10 +129,19 @@ public function displayAuthAppQr(Request $request) $user = $request->user(); // If not user not authenticated, redirect to login page - if (empty($user)) { + if (empty($user) || !config('password-policies.2fa_enabled', false)) { return redirect()->route('login'); } + $user = $user->fresh() ?? $user; + $methods = $user->getValid2FAPreferences(); + + if (!in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) + || !empty($user->two_factor_secret) + ) { + return redirect()->route('2fa'); + } + // Generate QR code $qrCode = $this->twoFactorAuthentication->generateQr($user); @@ -140,6 +149,42 @@ public function displayAuthAppQr(Request $request) return view('auth.2fa.auth_app_qr', compact('qrCode')); } + private function shouldRedirectToAuthenticatorQrEnrollment(User $user): bool + { + if (!empty($user->two_factor_secret)) { + return false; + } + + if (session()->has(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET)) { + return false; + } + + $methods = $user->getValid2FAPreferences(); + + return in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) + && !in_array(TwoFactorAuthentication::EMAIL, $methods, true) + && !in_array(TwoFactorAuthentication::SMS, $methods, true); + } + + private function sendTwoFactorCodeForDisplay(User $user): void + { + if (!session()->has(self::TFA_ERROR) && !session()->has(self::TFA_MESSAGE)) { + $this->twoFactorAuthentication->sendCode($user); + + return; + } + + $methods = $user->getValid2FAPreferences(); + $needsProvisioning = in_array(TwoFactorAuthentication::EMAIL, $methods, true) + || in_array(TwoFactorAuthentication::SMS, $methods, true) + ? empty($user->two_factor_delivery_secret) + : empty($user->two_factor_secret); + + if (!session()->has(self::TFA_MESSAGE) || $needsProvisioning) { + $this->twoFactorAuthentication->sendCode($user); + } + } + public function testSettings(Request $request) { $enabled = $request->json('enabled'); @@ -153,7 +198,7 @@ public function testSettings(Request $request) if (count($enabled) === 0) { $message = [ 'status' => 'error', - 'message' => __('The two-step method must be selected.') + 'message' => __('The two-step method must be selected.'), ]; $status = 500; } @@ -237,6 +282,7 @@ public static function check2faByGroups() { try { $user = Auth::user(); + return $user->in2FAGroupOrIndependent(); } catch (Exception $e) { session()->put(self::TFA_ERROR, $e->getMessage()); diff --git a/ProcessMaker/Models/User.php b/ProcessMaker/Models/User.php index 5f15ac4e36..68fe61ef04 100644 --- a/ProcessMaker/Models/User.php +++ b/ProcessMaker/Models/User.php @@ -144,6 +144,8 @@ class User extends Authenticatable implements HasMedia 'loggedin_at' => 'datetime', 'schedule' => 'array', 'preferences_2fa' => 'array', + 'two_factor_secret' => 'encrypted', + 'two_factor_delivery_secret' => 'encrypted', ]; /** @@ -238,6 +240,8 @@ public static function passwordRules(self $existing = null) */ protected $hidden = [ 'password', + 'two_factor_secret', + 'two_factor_delivery_secret', 'groupMembersFromMemberable', 'permissions', ]; diff --git a/ProcessMaker/Notifications/TwoFactorAuthNotification.php b/ProcessMaker/Notifications/TwoFactorAuthNotification.php index 2b36e3953a..35204ba566 100644 --- a/ProcessMaker/Notifications/TwoFactorAuthNotification.php +++ b/ProcessMaker/Notifications/TwoFactorAuthNotification.php @@ -19,7 +19,7 @@ class TwoFactorAuthNotification extends Notification /** * Create a new notification instance. * - * @param \ProcessMaker\Models\User $user + * @param User $user * @param string $code */ public function __construct(User $user, string $code) @@ -43,12 +43,12 @@ public function via($notifiable) * Get the mail representation of the notification. * * @param mixed $notifiable - * @return \Illuminate\Notifications\Messages\MailMessage + * @return MailMessage */ public function toMail($notifiable) { return (new MailMessage) - ->subject(_('Security Code')) + ->subject(__('Security Code')) ->greeting($this->user->username) ->line(__('This is your security code: :code', ['code' => $this->code])); } diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index 4fe8f04807..7e9cca41f6 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -8,7 +8,6 @@ use BaconQrCode\Writer; use Illuminate\Support\Facades\Notification; use OTPHP\TOTP; -use ParagonIE\ConstantTime\Base32; use ProcessMaker\Models\User; use ProcessMaker\Notifications\TwoFactorAuthNotification; use Twilio\Exceptions\TwilioException; @@ -24,6 +23,8 @@ class TwoFactorAuthentication const ERROR_INVALID_TO_NUMBER = 21211; + public const PENDING_AUTHENTICATOR_SECRET = '2fa-pending-authenticator-secret'; + public function sendCode(User $user): void { // Get methods to send the code @@ -45,20 +46,55 @@ public function sendCode(User $user): void } } - private function generateSecret(User $user): string + private function getUserTotpSecret(User $user): string { - $base = $user->uuid . '_' . $user->username; + if (!empty($user->two_factor_secret)) { + return $user->two_factor_secret; + } + + $secret = TOTP::generate()->getSecret(); + + if ($user->exists) { + $user->two_factor_secret = $secret; + $user->saveQuietly(); + } else { + $user->setAttribute('two_factor_secret', $secret); + } - return trim(Base32::encodeUpper($base), '='); + return $secret; } - private function createOtpInstance(User $user, bool $forGoogleAuthApp = false) + private function getUserDeliveryTotpSecret(User $user): string { - // Get secret - $secret = $this->generateSecret($user); + if (!empty($user->two_factor_delivery_secret)) { + return $user->two_factor_delivery_secret; + } - // Config OTP - $otp = TOTP::createFromSecret($secret); + $secret = TOTP::generate()->getSecret(); + + if ($user->exists) { + $user->two_factor_delivery_secret = $secret; + $user->saveQuietly(); + } else { + $user->setAttribute('two_factor_delivery_secret', $secret); + } + + return $secret; + } + + private function resolveAuthenticatorSecret(User $user): ?string + { + if (!empty($user->two_factor_secret)) { + return $user->two_factor_secret; + } + + $pending = session()->get(self::PENDING_AUTHENTICATOR_SECRET); + + return !empty($pending) ? $pending : null; + } + + private function configureOtp(TOTP $otp, User $user, bool $forGoogleAuthApp): TOTP + { $otp->setIssuer('ProcessMaker'); $otp->setLabel($user->username); @@ -71,6 +107,18 @@ private function createOtpInstance(User $user, bool $forGoogleAuthApp = false) return $otp; } + private function createOtpInstance(User $user, bool $forGoogleAuthApp = false) + { + $secret = $forGoogleAuthApp + ? $this->resolveAuthenticatorSecret($user) + : $this->getUserDeliveryTotpSecret($user); + + // Config OTP + $otp = $this->configureOtp(TOTP::createFromSecret($secret), $user, $forGoogleAuthApp); + + return $otp; + } + private function getCodeForEmailSms(User $user): string { // Create OTP instance @@ -82,14 +130,36 @@ private function getCodeForEmailSms(User $user): string public function validateCode(User $user, string $code) { - // The code is for Google Authenticator app? - $forGoogleAuthApp = strlen($code) === 6; + $methods = $user->getValid2FAPreferences(); + $valid = false; - // Create OTP instance - $otp = $this->createOtpInstance($user, $forGoogleAuthApp); + // The code is for Google Authenticator app? + if (strlen($code) === 6) { + $authSecret = $this->resolveAuthenticatorSecret($user); + if (in_array(self::AUTH_APP, $methods, true) && $authSecret !== null) { + // Create OTP instance + $otp = $this->createOtpInstance($user, true); + + // Validate code + $valid = $otp->verify($code); + if ($valid && empty($user->two_factor_secret)) { + $user->two_factor_secret = $authSecret; + $user->saveQuietly(); + session()->forget(self::PENDING_AUTHENTICATOR_SECRET); + } + } + } elseif ( + (in_array(self::EMAIL, $methods, true) || in_array(self::SMS, $methods, true)) + && !empty($user->two_factor_delivery_secret) + ) { + // Create OTP instance + $otp = $this->createOtpInstance($user, false); + + // Validate code + $valid = $otp->verify($code); + } - // Validate code - return $otp->verify($code); + return $valid; } /** @@ -154,7 +224,13 @@ private function sendSms(User $user, string $code) public function generateQr(User $user) { - $otp = $this->createOtpInstance($user, true); + $secret = session()->get(self::PENDING_AUTHENTICATOR_SECRET); + if (empty($secret)) { + $secret = TOTP::generate()->getSecret(); + session()->put(self::PENDING_AUTHENTICATOR_SECRET, $secret); + } + + $otp = $this->configureOtp(TOTP::createFromSecret($secret), $user, true); $g2faUrl = $otp->getProvisioningUri(); diff --git a/database/migrations/2026_11_09_120000_add_two_factor_secret_to_users_table.php b/database/migrations/2026_11_09_120000_add_two_factor_secret_to_users_table.php new file mode 100644 index 0000000000..87ef9ce8cf --- /dev/null +++ b/database/migrations/2026_11_09_120000_add_two_factor_secret_to_users_table.php @@ -0,0 +1,28 @@ +text('two_factor_secret')->nullable()->after('preferences_2fa'); + $table->text('two_factor_delivery_secret')->nullable()->after('two_factor_secret'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('users', function (Blueprint $table) { + $table->dropColumn(['two_factor_secret', 'two_factor_delivery_secret']); + }); + } +}; diff --git a/resources/views/auth/2fa/auth_app_qr.blade.php b/resources/views/auth/2fa/auth_app_qr.blade.php index 8e047304ed..da71c9f7b1 100644 --- a/resources/views/auth/2fa/auth_app_qr.blade.php +++ b/resources/views/auth/2fa/auth_app_qr.blade.php @@ -1,75 +1,42 @@ - - - - - - - - - - {{ __('Configure the authenticator app') }} - @vite('resources/sass/app.scss') - - - -
-
-
-
-
- @php - $isMobile = ( - isset($_SERVER['HTTP_USER_AGENT']) - && \ProcessMaker\Helpers\MobileHelper::isMobile($_SERVER['HTTP_USER_AGENT']) - ) ? true : false; - @endphp - @if (!$isMobile) -
- ProcessMaker - -
- @endif -
-
-
-
- @component('components.logo') - @endcomponent -

-

-
- {{__('Configure the authenticator app')}} -
-
- {{__('1.- Download the Google Authenticator App')}} -
-
- {{__('2.- On the Google Authenticator app click on the + icon')}} -
-
- {{__('3.- Select "Scan QR code" option')}} -
-
- QR -
- -
- -
-
-
-
-
+@extends('auth.layouts.auth') + +@section('skip-language-selector', 'skip') +@section('skip-auth-language-scripts', 'skip') + +@section('title') +{{ __('Configure the authenticator app') }} +@endsection + +@section('content') +
+
+ {{__('Configure the authenticator app')}}
+
+ {{__('1.- Download the Google Authenticator App')}} +
+
+ {{__('2.- On the Google Authenticator app click on the + icon')}} +
+
+ {{__('3.- Select "Scan QR code" option')}} +
+
+QR + +
+
- +@endsection + +@push('scripts') - - +@endpush diff --git a/resources/views/auth/2fa/otp.blade.php b/resources/views/auth/2fa/otp.blade.php index aba8a68b26..d3d26e42a6 100644 --- a/resources/views/auth/2fa/otp.blade.php +++ b/resources/views/auth/2fa/otp.blade.php @@ -1,105 +1,92 @@ - - - - - - - - - - {{ __('Enter Security Code') }} - @vite('resources/sass/app.scss') - - - -
-
-
-
-
- @php - $isMobile = ( - isset($_SERVER['HTTP_USER_AGENT']) - && \ProcessMaker\Helpers\MobileHelper::isMobile($_SERVER['HTTP_USER_AGENT']) - ) ? true : false; - @endphp - @if (!$isMobile) -
- ProcessMaker - -
- @endif -
-
-
-
- @component('components.logo') - @endcomponent -
-
- @if (session()->has('2fa-message') && !session()->has('2fa-error')) -
{{ session()->get('2fa-message')}}
- @endif - @if (session()->has('2fa-error')) -
{{ session()->get('2fa-error')}}
- @endif +@extends('auth.layouts.auth') -
- -
- - - @if ($errors->has('code')) - - {{ $errors->first('code') }} - - @endif -
-
-
- -
- @if (in_array(\ProcessMaker\TwoFactorAuthentication::AUTH_APP, - config('password-policies.2fa_method', []))) - - {{ __('Authenticator app') }} - -
- @endif - - {{ __('Log in as another user') }} - -
-
-
- -
-
-
-
-
+@section('skip-language-selector', 'skip') +@section('skip-auth-language-scripts', 'skip') + +@section('title') +{{ __('Enter Security Code') }} +@endsection + +@section('css') + +@endsection + +@section('content') +
+ @if (session()->has('2fa-message') && !session()->has('2fa-error')) +
{{ session()->get('2fa-message')}}
+ @endif + @if (session()->has('2fa-error')) +
{{ session()->get('2fa-error')}}
+ @endif + +
+ +
+ + + @if ($errors->has('code')) + + {{ $errors->first('code') }} + + @endif +
+
+
+ +
+ @php + $twoFactorMethods = auth()->user()->getValid2FAPreferences(); + @endphp + @if (in_array(\ProcessMaker\TwoFactorAuthentication::AUTH_APP, $twoFactorMethods, true) + && (empty(auth()->user()->two_factor_secret) + || session(\ProcessMaker\TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET))) + + {{ __('Authenticator app') }} + +
+ @endif + + {{ __('Log in as another user') }} +
-
- +
+ +
+ +@endsection + +@push('scripts') - - +@endpush diff --git a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php new file mode 100644 index 0000000000..37959e69a3 --- /dev/null +++ b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php @@ -0,0 +1,224 @@ + true, + 'password-policies.2fa_method' => [TwoFactorAuthentication::AUTH_APP], + ]); + } + + private function codeFromPublicIdentity(string $uuid, string $username, string $mode = 'app'): string + { + $secret = trim(Base32::encodeUpper($uuid . '_' . $username), '='); + $otp = TOTP::createFromSecret($secret); + + if ($mode === 'email') { + $otp->setDigest('sha512'); + $otp->setDigits(8); + $otp->setPeriod(300); + } + + return $otp->now(); + } + + private function victimAtTwoFactorGate(): User + { + return User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::AUTH_APP], + ]); + } + + private function postTwoFactorCode(User $sessionUser, string $code) + { + return $this->actingAs($sessionUser, 'web') + ->post(route('2fa.validate'), ['code' => $code]); + } + + public function testProtectedRouteRedirectsToTwoFactorUntilValidated(): void + { + $victim = $this->victimAtTwoFactorGate(); + + $this->actingAs($victim, 'web') + ->get(route('about.index')) + ->assertRedirect(route('2fa')); + } + + public function testWrongCodeDoesNotClearTwoFactorGate(): void + { + $victim = $this->victimAtTwoFactorGate(); + + $this->postTwoFactorCode($victim, '000000') + ->assertRedirect(route('2fa')); + + $this->assertNotTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + + $this->actingAs($victim, 'web') + ->get(route('about.index')) + ->assertRedirect(route('2fa')); + } + + public function testCodeDerivedFromAnotherUsersPublicIdentityDoesNotValidateVictimSession(): void + { + $victim = $this->victimAtTwoFactorGate(); + $attacker = User::factory()->create(); + + $codeForAttacker = $this->codeFromPublicIdentity($attacker->uuid, $attacker->username); + + $this->postTwoFactorCode($victim, $codeForAttacker) + ->assertRedirect(route('2fa')); + + $this->assertNotTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + } + + public function testVictimSessionRejectsCodeComputedFromPublicUuidAndUsernameOnly(): void + { + $victim = $this->victimAtTwoFactorGate(); + $attacker = User::factory()->create(); + + $harvested = User::query() + ->whereKey($victim->id) + ->first(['uuid', 'username']); + + $this->assertNotSame($attacker->uuid, $harvested->uuid); + + $code = $this->codeFromPublicIdentity($harvested->uuid, $harvested->username); + + $this->postTwoFactorCode($victim, $code) + ->assertRedirect(route('2fa')); + + $this->assertNotTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + + $this->actingAs($victim, 'web') + ->get(route('about.index')) + ->assertRedirect(route('2fa')); + } + + public function testVictimSessionRejectsEightDigitEmailModeCodeFromPublicIdentity(): void + { + config([ + 'password-policies.2fa_method' => [TwoFactorAuthentication::EMAIL], + ]); + + $victim = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::EMAIL], + ]); + + $code = $this->codeFromPublicIdentity($victim->uuid, $victim->username, 'email'); + + $this->postTwoFactorCode($victim, $code) + ->assertRedirect(route('2fa')); + + $this->assertNotTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + } + + public function testLegacyUserProvisioningWhenSecretIsMissing(): void + { + Notification::fake(); + + $authOnly = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::AUTH_APP], + 'two_factor_secret' => null, + ]); + $this->actingAs($authOnly, 'web') + ->get(route('2fa')) + ->assertRedirect(route('2fa.auth_app_qr')); + + $this->actingAs($authOnly, 'web') + ->get(route('2fa.auth_app_qr')) + ->assertOk(); + + $this->assertEmpty($authOnly->fresh()->two_factor_secret); + $this->assertNotEmpty(session(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET)); + + $this->actingAs($authOnly, 'web') + ->get(route('2fa')) + ->assertOk() + ->assertViewIs('auth.2fa.otp'); + + config(['password-policies.2fa_method' => [TwoFactorAuthentication::EMAIL]]); + $emailUser = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::EMAIL], + 'two_factor_secret' => null, + ]); + $this->actingAs($emailUser, 'web')->get(route('2fa'))->assertOk(); + + Notification::assertSentTo($emailUser, TwoFactorAuthNotification::class); + $emailUser->refresh(); + $this->assertNotEmpty($emailUser->two_factor_delivery_secret); + $this->assertEmpty($emailUser->two_factor_secret); + } + + public function testAuthAppQrRouteRequiresAuthenticatorEnrollment(): void + { + config(['password-policies.2fa_method' => [TwoFactorAuthentication::EMAIL]]); + + $emailUser = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::EMAIL], + ]); + + $this->actingAs($emailUser, 'web') + ->get(route('2fa.auth_app_qr')) + ->assertRedirect(route('2fa')); + + $secret = TOTP::generate()->getSecret(); + $authUser = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::AUTH_APP], + 'two_factor_secret' => $secret, + ]); + + config(['password-policies.2fa_method' => [TwoFactorAuthentication::AUTH_APP]]); + + $this->actingAs($authUser, 'web') + ->get(route('2fa.auth_app_qr')) + ->assertRedirect(route('2fa')); + } + + public function testVictimSessionAcceptsCodeFromStoredSecret(): void + { + $secret = TOTP::generate()->getSecret(); + $victim = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::AUTH_APP], + 'two_factor_secret' => $secret, + ]); + + $code = TOTP::createFromSecret($secret)->now(); + + $this->postTwoFactorCode($victim, $code) + ->assertRedirect(route('login')); + + $this->assertTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + + $this->actingAs($victim, 'web') + ->get(route('about.index')) + ->assertOk(); + } +} diff --git a/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php b/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php new file mode 100644 index 0000000000..57ae6a16d7 --- /dev/null +++ b/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php @@ -0,0 +1,163 @@ +getMethod('getUserTotpSecret'); + $method->setAccessible(true); + + return $method->invoke(new TwoFactorAuthentication(), $user); + } + + private function invokeGetUserDeliveryTotpSecret(User $user): string + { + $class = new ReflectionClass(TwoFactorAuthentication::class); + $method = $class->getMethod('getUserDeliveryTotpSecret'); + $method->setAccessible(true); + + return $method->invoke(new TwoFactorAuthentication(), $user); + } + + private function codeFromPublicIdentity(string $uuid, string $username, bool $emailMode = false): string + { + $secret = trim(Base32::encodeUpper($uuid . '_' . $username), '='); + $otp = TOTP::createFromSecret($secret); + + if ($emailMode) { + $otp->setDigest('sha512'); + $otp->setDigits(8); + $otp->setPeriod(300); + } + + return $otp->now(); + } + + public function testUserTotpSecretIsNotDerivedFromUuidAndUsername(): void + { + $user = User::factory()->create([ + 'uuid' => self::UUID, + 'username' => self::USERNAME, + ]); + + $secret = $this->invokeGetUserTotpSecret($user); + $predictable = trim(Base32::encodeUpper(self::UUID . '_' . self::USERNAME), '='); + + $this->assertNotSame($predictable, $secret); + + $user->refresh(); + $this->assertSame($secret, $user->two_factor_secret); + } + + public function testUserDeliveryTotpSecretIsNotDerivedFromUuidAndUsername(): void + { + $user = User::factory()->create([ + 'uuid' => self::UUID, + 'username' => self::USERNAME, + ]); + + $secret = $this->invokeGetUserDeliveryTotpSecret($user); + $predictable = trim(Base32::encodeUpper(self::UUID . '_' . self::USERNAME), '='); + + $this->assertNotSame($predictable, $secret); + + $user->refresh(); + $this->assertSame($secret, $user->two_factor_delivery_secret); + $this->assertEmpty($user->two_factor_secret); + } + + public function testValidateCodeRejectsCodeDerivedFromPublicIdentityOnly(): void + { + $user = User::factory()->create([ + 'uuid' => self::UUID, + 'username' => self::USERNAME, + 'preferences_2fa' => [TwoFactorAuthentication::EMAIL], + ]); + + $this->invokeGetUserDeliveryTotpSecret($user); + + $service = new TwoFactorAuthentication(); + $this->assertFalse( + $service->validateCode($user, $this->codeFromPublicIdentity(self::UUID, self::USERNAME)) + ); + $this->assertFalse( + $service->validateCode($user, $this->codeFromPublicIdentity(self::UUID, self::USERNAME, true)) + ); + } + + public function testValidateCodeAcceptsCodeFromStoredSecrets(): void + { + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $authSecret = TOTP::generate()->getSecret(); + $deliverySecret = TOTP::generate()->getSecret(); + $user = User::factory()->create([ + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => $authSecret, + 'two_factor_delivery_secret' => $deliverySecret, + ]); + + $service = new TwoFactorAuthentication(); + + $appCode = TOTP::createFromSecret($authSecret)->now(); + $this->assertTrue($service->validateCode($user, $appCode)); + + $emailOtp = TOTP::createFromSecret($deliverySecret); + $emailOtp->setDigest('sha512'); + $emailOtp->setDigits(8); + $emailOtp->setPeriod(300); + $this->assertTrue($service->validateCode($user, $emailOtp->now())); + } + + public function testValidateCodeRejectsSixDigitForEmailOnlyUser(): void + { + config(['password-policies.2fa_method' => [TwoFactorAuthentication::EMAIL]]); + + $deliverySecret = TOTP::generate()->getSecret(); + $authSecret = TOTP::generate()->getSecret(); + $user = User::factory()->create([ + 'preferences_2fa' => [TwoFactorAuthentication::EMAIL], + 'two_factor_secret' => $authSecret, + 'two_factor_delivery_secret' => $deliverySecret, + ]); + + $sixDigitFromAuthSecret = TOTP::createFromSecret($authSecret)->now(); + $this->assertFalse((new TwoFactorAuthentication())->validateCode($user, $sixDigitFromAuthSecret)); + } + + public function testValidateCodeRejectsRandomCode(): void + { + $user = User::factory()->create([ + 'preferences_2fa' => [TwoFactorAuthentication::EMAIL], + ]); + + $this->assertFalse((new TwoFactorAuthentication())->validateCode($user, '000000')); + } +}