From a67c292bfd134f3e7aaa19cbe3a234f282a23cc0 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Mon, 9 Nov 2026 13:17:53 -0400 Subject: [PATCH 01/27] fix(FOUR-34260): store per-user random TOTP secrets for 2FA Stop deriving 2FA secrets from public uuid and username, which allowed anyone with those fields to forge valid codes. Generate secrets with TOTP::generate(), persist encrypted on users.two_factor_secret, and add regression tests for predictable-code rejection and normal 2FA flow. Existing Authenticator App enrollments must scan a new QR after deploy. https://processmaker.atlassian.net/browse/FOUR-34260 --- ProcessMaker/Models/User.php | 2 + ProcessMaker/TwoFactorAuthentication.php | 21 ++- ...0_add_two_factor_secret_to_users_table.php | 27 +++ .../Auth/TwoFactorPredictableSecretTest.php | 156 ++++++++++++++++++ .../TwoFactorAuthenticationTest.php | 108 ++++++++++++ 5 files changed, 308 insertions(+), 6 deletions(-) create mode 100644 database/migrations/2026_11_09_120000_add_two_factor_secret_to_users_table.php create mode 100644 tests/Feature/Auth/TwoFactorPredictableSecretTest.php create mode 100644 tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php diff --git a/ProcessMaker/Models/User.php b/ProcessMaker/Models/User.php index 5f15ac4e36..a32ffdcc3f 100644 --- a/ProcessMaker/Models/User.php +++ b/ProcessMaker/Models/User.php @@ -144,6 +144,7 @@ class User extends Authenticatable implements HasMedia 'loggedin_at' => 'datetime', 'schedule' => 'array', 'preferences_2fa' => 'array', + 'two_factor_secret' => 'encrypted', ]; /** @@ -238,6 +239,7 @@ public static function passwordRules(self $existing = null) */ protected $hidden = [ 'password', + 'two_factor_secret', 'groupMembersFromMemberable', 'permissions', ]; diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index 4fe8f04807..24d070cf77 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; @@ -45,17 +44,27 @@ 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) { - // Get secret - $secret = $this->generateSecret($user); + $secret = $this->getUserTotpSecret($user); // Config OTP $otp = TOTP::createFromSecret($secret); 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..2a4c89736d --- /dev/null +++ b/database/migrations/2026_11_09_120000_add_two_factor_secret_to_users_table.php @@ -0,0 +1,27 @@ +text('two_factor_secret')->nullable()->after('preferences_2fa'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('users', function (Blueprint $table) { + $table->dropColumn('two_factor_secret'); + }); + } +}; diff --git a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php new file mode 100644 index 0000000000..aa9b9714e1 --- /dev/null +++ b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php @@ -0,0 +1,156 @@ + 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 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..4ae213f5d2 --- /dev/null +++ b/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php @@ -0,0 +1,108 @@ +getMethod('getUserTotpSecret'); + $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 testValidateCodeRejectsCodeDerivedFromPublicIdentityOnly(): void + { + $user = User::factory()->create([ + 'uuid' => self::UUID, + 'username' => self::USERNAME, + ]); + + $this->invokeGetUserTotpSecret($user); + + $this->assertFalse( + (new TwoFactorAuthentication())->validateCode( + $user, + $this->codeFromPublicIdentity(self::UUID, self::USERNAME) + ) + ); + $this->assertFalse( + (new TwoFactorAuthentication())->validateCode( + $user, + $this->codeFromPublicIdentity(self::UUID, self::USERNAME, true) + ) + ); + } + + public function testValidateCodeAcceptsCodeFromStoredSecret(): void + { + $secret = TOTP::generate()->getSecret(); + $user = User::factory()->create([ + 'two_factor_secret' => $secret, + ]); + + $appCode = TOTP::createFromSecret($secret)->now(); + $this->assertTrue((new TwoFactorAuthentication())->validateCode($user, $appCode)); + + $emailOtp = TOTP::createFromSecret($secret); + $emailOtp->setDigest('sha512'); + $emailOtp->setDigits(8); + $emailOtp->setPeriod(300); + $this->assertTrue((new TwoFactorAuthentication())->validateCode($user, $emailOtp->now())); + } + + public function testValidateCodeRejectsRandomCode(): void + { + $user = User::factory()->create(); + + $this->assertFalse((new TwoFactorAuthentication())->validateCode($user, '000000')); + } +} From 51235c12b69c7f0e039e337cb7d6b538f1e533ed Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Mon, 9 Nov 2026 19:27:20 -0400 Subject: [PATCH 02/27] fix(FOUR-34260): use per-user TOTP secrets and reprovision legacy 2FA users Stop deriving 2FA codes from public uuid and username. Persist CSPRNG secrets encrypted on users.two_factor_secret, add regression tests, and on login route legacy users without a secret to QR (auth app only) or force a fresh email/SMS code. Run the migration on deploy. Authenticator App users must scan a new QR. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Auth/TwoFactorAuthController.php | 16 +++++++++-- .../Auth/TwoFactorPredictableSecretTest.php | 27 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index ed50fda849..d9ca2bfbaa 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -40,11 +40,22 @@ public function displayTwoFactorAuthForm(Request $request) return redirect()->route('login'); } + $user->refresh(); + if (empty($user->two_factor_secret)) { + $methods = $user->getValid2FAPreferences(); + if (in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) + && !in_array(TwoFactorAuthentication::EMAIL, $methods, true) + && !in_array(TwoFactorAuthentication::SMS, $methods, true) + ) { + return redirect()->route('2fa.auth_app_qr'); + } + } + // Send code if (!session()->has(self::TFA_ERROR) && !session()->has(self::TFA_MESSAGE)) { $this->twoFactorAuthentication->sendCode($user); } else { - if (!session()->has(self::TFA_MESSAGE)) { + if (!session()->has(self::TFA_MESSAGE) || empty($user->two_factor_secret)) { $this->twoFactorAuthentication->sendCode($user); } } @@ -153,7 +164,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 +248,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/tests/Feature/Auth/TwoFactorPredictableSecretTest.php b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php index aa9b9714e1..047373e94a 100644 --- a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php +++ b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php @@ -5,10 +5,12 @@ namespace Tests\Feature\Auth; use Illuminate\Support\Facades\Hash; +use Illuminate\Support\Facades\Notification; use OTPHP\TOTP; use ParagonIE\ConstantTime\Base32; use ProcessMaker\Http\Controllers\Auth\TwoFactorAuthController; use ProcessMaker\Models\User; +use ProcessMaker\Notifications\TwoFactorAuthNotification; use ProcessMaker\TwoFactorAuthentication; use Tests\TestCase; @@ -133,6 +135,31 @@ public function testVictimSessionRejectsEightDigitEmailModeCodeFromPublicIdentit $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')); + + 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); + $this->assertNotEmpty($emailUser->fresh()->two_factor_secret); + } + public function testVictimSessionAcceptsCodeFromStoredSecret(): void { $secret = TOTP::generate()->getSecret(); From daade4e33baba279f319072a3f3f5bab9d75180c Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Tue, 10 Nov 2026 11:34:59 -0400 Subject: [PATCH 03/27] fix(FOUR-34260): use __() for 2FA translations - TwoFactorAuthNotification mail subject and body line - TwoFactorAuthController invalid code errors Fixes sync mail send hanging on /2fa when subject used _(). https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Http/Controllers/Auth/TwoFactorAuthController.php | 4 ++-- ProcessMaker/Notifications/TwoFactorAuthNotification.php | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index d9ca2bfbaa..6f165289da 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -87,7 +87,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'); @@ -109,7 +109,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'; 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])); } From a046a925c688edad8c71cc38b1b893d3c4bf5ef7 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Tue, 10 Nov 2026 12:18:30 -0400 Subject: [PATCH 04/27] fix(FOUR-34260): align 2FA screens with shared auth Decisions layout Refactor otp and auth_app_qr to extend auth.layouts.auth instead of legacy standalone HTML, background assets, and inline CSS. Use existing skip-language- selector and skip-auth-language-scripts sections so 2FA matches password-reset branding without changing the auth layout. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../views/auth/2fa/auth_app_qr.blade.php | 145 +++------- resources/views/auth/2fa/otp.blade.php | 265 ++++++------------ 2 files changed, 121 insertions(+), 289 deletions(-) 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..eb3ddecf34 100644 --- a/resources/views/auth/2fa/otp.blade.php +++ b/resources/views/auth/2fa/otp.blade.php @@ -1,105 +1,88 @@ - - - - - - - - - - {{ __('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 +
+
+
+ +
+ @if (in_array(\ProcessMaker\TwoFactorAuthentication::AUTH_APP, + config('password-policies.2fa_method', []))) + + {{ __('Authenticator app') }} + +
+ @endif + + {{ __('Log in as another user') }} +
-
- +
+ +
+ +@endsection + +@push('scripts') - - +@endpush From 4a3f991da53037a62f27d92570db0d34bacc9e85 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Tue, 10 Nov 2026 12:23:18 -0400 Subject: [PATCH 05/27] fix(FOUR-34260): reload 2FA user without flushing permission caches Use fresh() instead of User::refresh() on /2fa display so two_factor_secret is read from the database without invalidating permissions cache. https://processmaker.atlassian.net/browse/FOUR-34260 --- ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index 6f165289da..06e43f6b76 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -40,7 +40,8 @@ public function displayTwoFactorAuthForm(Request $request) return redirect()->route('login'); } - $user->refresh(); + // Reload DB state without User::refresh() (clears permission caches). + $user = $user->fresh() ?? $user; if (empty($user->two_factor_secret)) { $methods = $user->getValid2FAPreferences(); if (in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) From f922d9697d400e4e5a8d89f4f28b085b140ac7ff Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Tue, 10 Nov 2026 12:58:08 -0400 Subject: [PATCH 06/27] fix(FOUR-34260): split 2FA secrets and harden authenticator QR enrollment Store email/SMS TOTP in two_factor_delivery_secret and authenticator TOTP in two_factor_secret. Gate /2fa/auth_app_qr on enabled Authenticator App and empty enrollment secret; reject six-digit codes unless the method is allowed. Extend the users migration, tighten OTP link visibility, and add unit/feature coverage for predictable-secret bypass and QR route access. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Auth/TwoFactorAuthController.php | 20 ++++- ProcessMaker/Models/User.php | 2 + ProcessMaker/TwoFactorAuthentication.php | 46 +++++++++- ...0_add_two_factor_secret_to_users_table.php | 3 +- resources/views/auth/2fa/otp.blade.php | 7 +- .../Auth/TwoFactorPredictableSecretTest.php | 31 ++++++- .../TwoFactorAuthenticationTest.php | 89 +++++++++++++++---- 7 files changed, 172 insertions(+), 26 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index 06e43f6b76..b70cf657c3 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -56,7 +56,12 @@ public function displayTwoFactorAuthForm(Request $request) if (!session()->has(self::TFA_ERROR) && !session()->has(self::TFA_MESSAGE)) { $this->twoFactorAuthentication->sendCode($user); } else { - if (!session()->has(self::TFA_MESSAGE) || empty($user->two_factor_secret)) { + $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); } } @@ -141,10 +146,21 @@ 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)) { + return redirect()->route('2fa'); + } + + if (!empty($user->two_factor_secret)) { + return redirect()->route('2fa'); + } + // Generate QR code $qrCode = $this->twoFactorAuthentication->generateQr($user); diff --git a/ProcessMaker/Models/User.php b/ProcessMaker/Models/User.php index a32ffdcc3f..68fe61ef04 100644 --- a/ProcessMaker/Models/User.php +++ b/ProcessMaker/Models/User.php @@ -145,6 +145,7 @@ class User extends Authenticatable implements HasMedia 'schedule' => 'array', 'preferences_2fa' => 'array', 'two_factor_secret' => 'encrypted', + 'two_factor_delivery_secret' => 'encrypted', ]; /** @@ -240,6 +241,7 @@ public static function passwordRules(self $existing = null) protected $hidden = [ 'password', 'two_factor_secret', + 'two_factor_delivery_secret', 'groupMembersFromMemberable', 'permissions', ]; diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index 24d070cf77..86e4f1fc5a 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -62,9 +62,29 @@ private function getUserTotpSecret(User $user): string return $secret; } + private function getUserDeliveryTotpSecret(User $user): string + { + if (!empty($user->two_factor_delivery_secret)) { + return $user->two_factor_delivery_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 createOtpInstance(User $user, bool $forGoogleAuthApp = false) { - $secret = $this->getUserTotpSecret($user); + $secret = $forGoogleAuthApp + ? $this->getUserTotpSecret($user) + : $this->getUserDeliveryTotpSecret($user); // Config OTP $otp = TOTP::createFromSecret($secret); @@ -91,11 +111,31 @@ private function getCodeForEmailSms(User $user): string public function validateCode(User $user, string $code) { + $methods = $user->getValid2FAPreferences(); + // The code is for Google Authenticator app? - $forGoogleAuthApp = strlen($code) === 6; + if (strlen($code) === 6) { + if (!in_array(self::AUTH_APP, $methods, true) || empty($user->two_factor_secret)) { + return false; + } + + // Create OTP instance + $otp = $this->createOtpInstance($user, true); + + // Validate code + return $otp->verify($code); + } + + if (!in_array(self::EMAIL, $methods, true) && !in_array(self::SMS, $methods, true)) { + return false; + } + + if (empty($user->two_factor_delivery_secret)) { + return false; + } // Create OTP instance - $otp = $this->createOtpInstance($user, $forGoogleAuthApp); + $otp = $this->createOtpInstance($user, false); // Validate code return $otp->verify($code); 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 index 2a4c89736d..87ef9ce8cf 100644 --- 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 @@ -12,6 +12,7 @@ public function up(): void { Schema::table('users', function (Blueprint $table) { $table->text('two_factor_secret')->nullable()->after('preferences_2fa'); + $table->text('two_factor_delivery_secret')->nullable()->after('two_factor_secret'); }); } @@ -21,7 +22,7 @@ public function up(): void public function down(): void { Schema::table('users', function (Blueprint $table) { - $table->dropColumn('two_factor_secret'); + $table->dropColumn(['two_factor_secret', 'two_factor_delivery_secret']); }); } }; diff --git a/resources/views/auth/2fa/otp.blade.php b/resources/views/auth/2fa/otp.blade.php index eb3ddecf34..190c804b79 100644 --- a/resources/views/auth/2fa/otp.blade.php +++ b/resources/views/auth/2fa/otp.blade.php @@ -57,8 +57,11 @@ class="form-control{{ $errors->has('code') ? ' is-invalid' : '' }}"
- @if (in_array(\ProcessMaker\TwoFactorAuthentication::AUTH_APP, - config('password-policies.2fa_method', []))) + @php + $twoFactorMethods = auth()->user()->getValid2FAPreferences(); + @endphp + @if (in_array(\ProcessMaker\TwoFactorAuthentication::AUTH_APP, $twoFactorMethods, true) + && empty(auth()->user()->two_factor_secret)) {{ __('Authenticator app') }} diff --git a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php index 047373e94a..1672d1d6b2 100644 --- a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php +++ b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php @@ -157,7 +157,36 @@ public function testLegacyUserProvisioningWhenSecretIsMissing(): void $this->actingAs($emailUser, 'web')->get(route('2fa'))->assertOk(); Notification::assertSentTo($emailUser, TwoFactorAuthNotification::class); - $this->assertNotEmpty($emailUser->fresh()->two_factor_secret); + $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 diff --git a/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php b/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php index 4ae213f5d2..57ae6a16d7 100644 --- a/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php +++ b/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php @@ -29,6 +29,15 @@ private function invokeGetUserTotpSecret(User $user): string 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), '='); @@ -59,49 +68,95 @@ public function testUserTotpSecretIsNotDerivedFromUuidAndUsername(): void $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->invokeGetUserTotpSecret($user); + $this->invokeGetUserDeliveryTotpSecret($user); + $service = new TwoFactorAuthentication(); $this->assertFalse( - (new TwoFactorAuthentication())->validateCode( - $user, - $this->codeFromPublicIdentity(self::UUID, self::USERNAME) - ) + $service->validateCode($user, $this->codeFromPublicIdentity(self::UUID, self::USERNAME)) ); $this->assertFalse( - (new TwoFactorAuthentication())->validateCode( - $user, - $this->codeFromPublicIdentity(self::UUID, self::USERNAME, true) - ) + $service->validateCode($user, $this->codeFromPublicIdentity(self::UUID, self::USERNAME, true)) ); } - public function testValidateCodeAcceptsCodeFromStoredSecret(): void + public function testValidateCodeAcceptsCodeFromStoredSecrets(): void { - $secret = TOTP::generate()->getSecret(); + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $authSecret = TOTP::generate()->getSecret(); + $deliverySecret = TOTP::generate()->getSecret(); $user = User::factory()->create([ - 'two_factor_secret' => $secret, + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => $authSecret, + 'two_factor_delivery_secret' => $deliverySecret, ]); - $appCode = TOTP::createFromSecret($secret)->now(); - $this->assertTrue((new TwoFactorAuthentication())->validateCode($user, $appCode)); + $service = new TwoFactorAuthentication(); - $emailOtp = TOTP::createFromSecret($secret); + $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((new TwoFactorAuthentication())->validateCode($user, $emailOtp->now())); + $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(); + $user = User::factory()->create([ + 'preferences_2fa' => [TwoFactorAuthentication::EMAIL], + ]); $this->assertFalse((new TwoFactorAuthentication())->validateCode($user, '000000')); } From ffea1a0ec9e06fb2c9db8a02a14e551ae0f430c1 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Tue, 10 Nov 2026 14:53:16 -0400 Subject: [PATCH 07/27] fix(FOUR-34260): reduce returns in displayAuthAppQr for Sonar S1142 Combine authenticator-method and existing-secret checks into one redirect to /2fa so displayAuthAppQr stays within the return-statement limit. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Http/Controllers/Auth/TwoFactorAuthController.php | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index b70cf657c3..d6149b6b70 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -153,11 +153,9 @@ public function displayAuthAppQr(Request $request) $user = $user->fresh() ?? $user; $methods = $user->getValid2FAPreferences(); - if (!in_array(TwoFactorAuthentication::AUTH_APP, $methods, true)) { - return redirect()->route('2fa'); - } - - if (!empty($user->two_factor_secret)) { + if (!in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) + || !empty($user->two_factor_secret) + ) { return redirect()->route('2fa'); } From 9b7085830aa891b87dd80e580d1ed061b3dbcfc2 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Tue, 10 Nov 2026 14:55:51 -0400 Subject: [PATCH 08/27] fix(FOUR-34260): lower cognitive complexity in displayTwoFactorAuthForm Extract authenticator QR redirect and send-code provisioning into private helpers so Sonar S3776 stays within the limit. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Auth/TwoFactorAuthController.php | 55 ++++++++++++------- 1 file changed, 35 insertions(+), 20 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index d6149b6b70..bd29b95331 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -42,29 +42,12 @@ public function displayTwoFactorAuthForm(Request $request) // Reload DB state without User::refresh() (clears permission caches). $user = $user->fresh() ?? $user; - if (empty($user->two_factor_secret)) { - $methods = $user->getValid2FAPreferences(); - if (in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) - && !in_array(TwoFactorAuthentication::EMAIL, $methods, true) - && !in_array(TwoFactorAuthentication::SMS, $methods, true) - ) { - return redirect()->route('2fa.auth_app_qr'); - } + if ($this->shouldRedirectToAuthenticatorQrEnrollment($user)) { + return redirect()->route('2fa.auth_app_qr'); } // Send code - if (!session()->has(self::TFA_ERROR) && !session()->has(self::TFA_MESSAGE)) { - $this->twoFactorAuthentication->sendCode($user); - } else { - $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); - } - } + $this->sendTwoFactorCodeForDisplay($user); // Set informative message $methodsNames = $this->twoFactorAuthentication->friendlyMethodsNames($user); @@ -166,6 +149,38 @@ 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; + } + + $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'); From f8319357b2550a66ab16ea9bce6612012651683e Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Tue, 10 Nov 2026 15:00:43 -0400 Subject: [PATCH 09/27] fix(FOUR-34260): use single return in validateCode for Sonar S1142 Accumulate validation in a $valid flag and return once so validateCode stays within the return-statement limit without changing 2FA verification behavior. https://processmaker.atlassian.net/browse/FOUR-34260 --- ProcessMaker/TwoFactorAuthentication.php | 32 +++++++++++------------- 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index 86e4f1fc5a..b4a2546278 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -112,33 +112,29 @@ private function getCodeForEmailSms(User $user): string public function validateCode(User $user, string $code) { $methods = $user->getValid2FAPreferences(); + $valid = false; // The code is for Google Authenticator app? if (strlen($code) === 6) { - if (!in_array(self::AUTH_APP, $methods, true) || empty($user->two_factor_secret)) { - return false; - } + if (in_array(self::AUTH_APP, $methods, true) && !empty($user->two_factor_secret)) { + // Create OTP instance + $otp = $this->createOtpInstance($user, true); + // Validate code + $valid = $otp->verify($code); + } + } 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, true); + $otp = $this->createOtpInstance($user, false); // Validate code - return $otp->verify($code); - } - - if (!in_array(self::EMAIL, $methods, true) && !in_array(self::SMS, $methods, true)) { - return false; + $valid = $otp->verify($code); } - if (empty($user->two_factor_delivery_secret)) { - return false; - } - - // Create OTP instance - $otp = $this->createOtpInstance($user, false); - - // Validate code - return $otp->verify($code); + return $valid; } /** From 0a72e9cbaf1df864c26dbfeca80930f3a2014658 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Tue, 10 Nov 2026 15:07:27 -0400 Subject: [PATCH 10/27] fix(FOUR-34260): keep authenticator secret in session until first valid code Defer persisting two_factor_secret until a six-digit code verifies. Store the QR provisioning secret in session so enrollment can be retried without locking users out of the authenticator link or QR page. https://processmaker.atlassian.net/browse/FOUR-34260 --- ProcessMaker/TwoFactorAuthentication.php | 47 +++++++++++++++---- resources/views/auth/2fa/otp.blade.php | 3 +- .../Auth/TwoFactorPredictableSecretTest.php | 7 +++ 3 files changed, 48 insertions(+), 9 deletions(-) diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index b4a2546278..7e9cca41f6 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -23,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 @@ -80,14 +82,19 @@ private function getUserDeliveryTotpSecret(User $user): string return $secret; } - private function createOtpInstance(User $user, bool $forGoogleAuthApp = false) + private function resolveAuthenticatorSecret(User $user): ?string { - $secret = $forGoogleAuthApp - ? $this->getUserTotpSecret($user) - : $this->getUserDeliveryTotpSecret($user); + if (!empty($user->two_factor_secret)) { + return $user->two_factor_secret; + } - // Config OTP - $otp = TOTP::createFromSecret($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); @@ -100,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 @@ -116,12 +135,18 @@ public function validateCode(User $user, string $code) // The code is for Google Authenticator app? if (strlen($code) === 6) { - if (in_array(self::AUTH_APP, $methods, true) && !empty($user->two_factor_secret)) { + $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)) @@ -199,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/resources/views/auth/2fa/otp.blade.php b/resources/views/auth/2fa/otp.blade.php index 190c804b79..d3d26e42a6 100644 --- a/resources/views/auth/2fa/otp.blade.php +++ b/resources/views/auth/2fa/otp.blade.php @@ -61,7 +61,8 @@ class="form-control{{ $errors->has('code') ? ' is-invalid' : '' }}" $twoFactorMethods = auth()->user()->getValid2FAPreferences(); @endphp @if (in_array(\ProcessMaker\TwoFactorAuthentication::AUTH_APP, $twoFactorMethods, true) - && empty(auth()->user()->two_factor_secret)) + && (empty(auth()->user()->two_factor_secret) + || session(\ProcessMaker\TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET))) {{ __('Authenticator app') }} diff --git a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php index 1672d1d6b2..051bcc82aa 100644 --- a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php +++ b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php @@ -148,6 +148,13 @@ public function testLegacyUserProvisioningWhenSecretIsMissing(): void ->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)); + config(['password-policies.2fa_method' => [TwoFactorAuthentication::EMAIL]]); $emailUser = User::factory()->create([ 'password' => Hash::make('password'), From 93531427b20fda8e5f91e6798dd593d6060b3a23 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Tue, 10 Nov 2026 16:07:30 -0400 Subject: [PATCH 11/27] fix(FOUR-34260): show OTP after QR when authenticator secret is pending Do not redirect authenticator-only users back to the QR page when PENDING_AUTHENTICATOR_SECRET is in session, so they can enter a code after scanning. Add a feature test that GET /2fa returns the OTP view after QR enrollment. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Http/Controllers/Auth/TwoFactorAuthController.php | 4 ++++ tests/Feature/Auth/TwoFactorPredictableSecretTest.php | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index bd29b95331..e0d0c8c478 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -155,6 +155,10 @@ private function shouldRedirectToAuthenticatorQrEnrollment(User $user): bool return false; } + if (session()->has(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET)) { + return false; + } + $methods = $user->getValid2FAPreferences(); return in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) diff --git a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php index 051bcc82aa..37959e69a3 100644 --- a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php +++ b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php @@ -155,6 +155,11 @@ public function testLegacyUserProvisioningWhenSecretIsMissing(): void $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'), From 4edefc5559e694748f831e55324b6bece9eca075 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 18 Nov 2026 16:37:30 -0400 Subject: [PATCH 12/27] feat(FOUR-34260): fix Sonar S1488 in createOtpInstance Return configureOtp result directly in TwoFactorAuthentication instead of assigning to $otp https://processmaker.atlassian.net/browse/FOUR-34260 --- ProcessMaker/TwoFactorAuthentication.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index 7e9cca41f6..6511b3f8ac 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -114,9 +114,7 @@ private function createOtpInstance(User $user, bool $forGoogleAuthApp = false) : $this->getUserDeliveryTotpSecret($user); // Config OTP - $otp = $this->configureOtp(TOTP::createFromSecret($secret), $user, $forGoogleAuthApp); - - return $otp; + return $this->configureOtp(TOTP::createFromSecret($secret), $user, $forGoogleAuthApp); } private function getCodeForEmailSms(User $user): string From 54197e4d3442829e94f15248b5e9859c26680eda Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 18 Nov 2026 16:48:03 -0400 Subject: [PATCH 13/27] refactor(FOUR-34260): remove unused getUserTotpSecret per Sonar S1144 Sonar flagged the private method as dead code after authenticator enrollment moved to pending session and resolveAuthenticatorSecret. Adjust unit test to assert stored secrets are not uuid/username-derived. https://processmaker.atlassian.net/browse/FOUR-34260 --- ProcessMaker/TwoFactorAuthentication.php | 18 ------------------ .../TwoFactorAuthenticationTest.php | 14 ++++---------- 2 files changed, 4 insertions(+), 28 deletions(-) diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index 6511b3f8ac..21494f50e9 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -46,24 +46,6 @@ public function sendCode(User $user): void } } - private function getUserTotpSecret(User $user): string - { - 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 $secret; - } - private function getUserDeliveryTotpSecret(User $user): string { if (!empty($user->two_factor_delivery_secret)) { diff --git a/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php b/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php index 57ae6a16d7..4bd8e3f272 100644 --- a/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php +++ b/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php @@ -20,15 +20,6 @@ class TwoFactorAuthenticationTest extends TestCase private const USERNAME = 'pmadmin'; - private function invokeGetUserTotpSecret(User $user): string - { - $class = new ReflectionClass(TwoFactorAuthentication::class); - $method = $class->getMethod('getUserTotpSecret'); - $method->setAccessible(true); - - return $method->invoke(new TwoFactorAuthentication(), $user); - } - private function invokeGetUserDeliveryTotpSecret(User $user): string { $class = new ReflectionClass(TwoFactorAuthentication::class); @@ -59,7 +50,10 @@ public function testUserTotpSecretIsNotDerivedFromUuidAndUsername(): void 'username' => self::USERNAME, ]); - $secret = $this->invokeGetUserTotpSecret($user); + $secret = TOTP::generate()->getSecret(); + $user->two_factor_secret = $secret; + $user->saveQuietly(); + $predictable = trim(Base32::encodeUpper(self::UUID . '_' . self::USERNAME), '='); $this->assertNotSame($predictable, $secret); From cd5ceca51843557820e4032551e4954aa432e657 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 18 Nov 2026 18:42:23 -0400 Subject: [PATCH 14/27] fix(FOUR-34260): block authenticator enrollment before delivery step-up Address Cursor Bugbot finding: do not mint or accept a session TOTP when email or SMS is enabled and users.two_factor_secret is null. Gate QR route, validateCode, and OTP link; add feature regression test. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Auth/TwoFactorAuthController.php | 4 +++ ProcessMaker/TwoFactorAuthentication.php | 5 +++ resources/views/auth/2fa/otp.blade.php | 5 +-- .../Auth/TwoFactorPredictableSecretTest.php | 32 +++++++++++++++++++ 4 files changed, 44 insertions(+), 2 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index e0d0c8c478..029bd789a3 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -136,8 +136,12 @@ public function displayAuthAppQr(Request $request) $user = $user->fresh() ?? $user; $methods = $user->getValid2FAPreferences(); + $hasDeliveryMethod = in_array(TwoFactorAuthentication::EMAIL, $methods, true) + || in_array(TwoFactorAuthentication::SMS, $methods, true); + if (!in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) || !empty($user->two_factor_secret) + || (empty($user->two_factor_secret) && $hasDeliveryMethod) ) { return redirect()->route('2fa'); } diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index 21494f50e9..884b7eee46 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -116,7 +116,12 @@ public function validateCode(User $user, string $code) // The code is for Google Authenticator app? if (strlen($code) === 6) { $authSecret = $this->resolveAuthenticatorSecret($user); + $hasDeliveryMethod = in_array(self::EMAIL, $methods, true) + || in_array(self::SMS, $methods, true); if (in_array(self::AUTH_APP, $methods, true) && $authSecret !== null) { + if (empty($user->two_factor_secret) && $hasDeliveryMethod) { + return false; + } // Create OTP instance $otp = $this->createOtpInstance($user, true); diff --git a/resources/views/auth/2fa/otp.blade.php b/resources/views/auth/2fa/otp.blade.php index d3d26e42a6..ddedf4f53d 100644 --- a/resources/views/auth/2fa/otp.blade.php +++ b/resources/views/auth/2fa/otp.blade.php @@ -61,8 +61,9 @@ class="form-control{{ $errors->has('code') ? ' is-invalid' : '' }}" $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))) + && empty(auth()->user()->two_factor_secret) + && !in_array(\ProcessMaker\TwoFactorAuthentication::EMAIL, $twoFactorMethods, true) + && !in_array(\ProcessMaker\TwoFactorAuthentication::SMS, $twoFactorMethods, true)) {{ __('Authenticator app') }} diff --git a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php index 37959e69a3..9c80673093 100644 --- a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php +++ b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php @@ -201,6 +201,38 @@ public function testAuthAppQrRouteRequiresAuthenticatorEnrollment(): void ->assertRedirect(route('2fa')); } + public function testCannotBypassDeliveryWithPendingAuthenticatorEnrollment(): void + { + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $user = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => null, + ]); + + $pendingSecret = TOTP::generate()->getSecret(); + session()->put(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET, $pendingSecret); + + $this->actingAs($user, 'web') + ->get(route('2fa.auth_app_qr')) + ->assertRedirect(route('2fa')); + + $this->postTwoFactorCode($user, TOTP::createFromSecret($pendingSecret)->now()) + ->assertRedirect(route('2fa')); + + $this->assertNotTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + $this->assertEmpty($user->fresh()->two_factor_secret); + } + public function testVictimSessionAcceptsCodeFromStoredSecret(): void { $secret = TOTP::generate()->getSecret(); From e84ffbd51db60af5d47dc07e87421b1ebafba347 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 18 Nov 2026 21:59:47 -0400 Subject: [PATCH 15/27] fix(FOUR-34260): allow authenticator enroll after delivery step-up Mixed-method users need a validated email/SMS code before QR enrollment. Keep blocking password-only session minting (Cursor Bugbot). https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Auth/TwoFactorAuthController.php | 6 +--- ProcessMaker/TwoFactorAuthentication.php | 30 ++++++++++++++-- resources/views/auth/2fa/otp.blade.php | 8 +---- .../Auth/TwoFactorPredictableSecretTest.php | 35 +++++++++++++++++++ 4 files changed, 64 insertions(+), 15 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index 029bd789a3..2ad52425c5 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -136,12 +136,8 @@ public function displayAuthAppQr(Request $request) $user = $user->fresh() ?? $user; $methods = $user->getValid2FAPreferences(); - $hasDeliveryMethod = in_array(TwoFactorAuthentication::EMAIL, $methods, true) - || in_array(TwoFactorAuthentication::SMS, $methods, true); - if (!in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) - || !empty($user->two_factor_secret) - || (empty($user->two_factor_secret) && $hasDeliveryMethod) + || !$this->twoFactorAuthentication->mayEnrollNewAuthenticator($user) ) { return redirect()->route('2fa'); } diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index 884b7eee46..ec4ac8dc15 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -25,6 +25,8 @@ class TwoFactorAuthentication public const PENDING_AUTHENTICATOR_SECRET = '2fa-pending-authenticator-secret'; + public const DELIVERY_STEP_UP = '2fa-delivery-step-up'; + public function sendCode(User $user): void { // Get methods to send the code @@ -75,6 +77,27 @@ private function resolveAuthenticatorSecret(User $user): ?string return !empty($pending) ? $pending : null; } + public function mayEnrollNewAuthenticator(User $user): bool + { + if (!empty($user->two_factor_secret)) { + return false; + } + + $methods = $user->getValid2FAPreferences(); + if (!in_array(self::AUTH_APP, $methods, true)) { + return false; + } + + $hasDeliveryMethod = in_array(self::EMAIL, $methods, true) + || in_array(self::SMS, $methods, true); + + if (!$hasDeliveryMethod) { + return true; + } + + return session()->get(self::DELIVERY_STEP_UP, false); + } + private function configureOtp(TOTP $otp, User $user, bool $forGoogleAuthApp): TOTP { $otp->setIssuer('ProcessMaker'); @@ -116,10 +139,8 @@ public function validateCode(User $user, string $code) // The code is for Google Authenticator app? if (strlen($code) === 6) { $authSecret = $this->resolveAuthenticatorSecret($user); - $hasDeliveryMethod = in_array(self::EMAIL, $methods, true) - || in_array(self::SMS, $methods, true); if (in_array(self::AUTH_APP, $methods, true) && $authSecret !== null) { - if (empty($user->two_factor_secret) && $hasDeliveryMethod) { + if (empty($user->two_factor_secret) && !$this->mayEnrollNewAuthenticator($user)) { return false; } // Create OTP instance @@ -142,6 +163,9 @@ public function validateCode(User $user, string $code) // Validate code $valid = $otp->verify($code); + if ($valid) { + session()->put(self::DELIVERY_STEP_UP, true); + } } return $valid; diff --git a/resources/views/auth/2fa/otp.blade.php b/resources/views/auth/2fa/otp.blade.php index ddedf4f53d..515c86fe47 100644 --- a/resources/views/auth/2fa/otp.blade.php +++ b/resources/views/auth/2fa/otp.blade.php @@ -57,13 +57,7 @@ class="form-control{{ $errors->has('code') ? ' is-invalid' : '' }}"
- @php - $twoFactorMethods = auth()->user()->getValid2FAPreferences(); - @endphp - @if (in_array(\ProcessMaker\TwoFactorAuthentication::AUTH_APP, $twoFactorMethods, true) - && empty(auth()->user()->two_factor_secret) - && !in_array(\ProcessMaker\TwoFactorAuthentication::EMAIL, $twoFactorMethods, true) - && !in_array(\ProcessMaker\TwoFactorAuthentication::SMS, $twoFactorMethods, true)) + @if (app(\ProcessMaker\TwoFactorAuthentication::class)->mayEnrollNewAuthenticator(auth()->user())) {{ __('Authenticator app') }} diff --git a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php index 9c80673093..e45f055a45 100644 --- a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php +++ b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php @@ -233,6 +233,41 @@ public function testCannotBypassDeliveryWithPendingAuthenticatorEnrollment(): vo $this->assertEmpty($user->fresh()->two_factor_secret); } + public function testMixedMethodsAllowAuthenticatorEnrollmentAfterDeliveryStepUp(): void + { + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $deliverySecret = TOTP::generate()->getSecret(); + $user = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => null, + 'two_factor_delivery_secret' => $deliverySecret, + ]); + + session()->put(TwoFactorAuthentication::DELIVERY_STEP_UP, true); + $pendingSecret = TOTP::generate()->getSecret(); + session()->put(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET, $pendingSecret); + + $this->actingAs($user, 'web') + ->get(route('2fa.auth_app_qr')) + ->assertOk(); + + $this->postTwoFactorCode($user, TOTP::createFromSecret($pendingSecret)->now()) + ->assertRedirect(route('login')); + + $this->assertTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + $this->assertSame($pendingSecret, $user->fresh()->two_factor_secret); + } + public function testVictimSessionAcceptsCodeFromStoredSecret(): void { $secret = TOTP::generate()->getSecret(); From c21c613bb51177f09912907aed91070033be2f16 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 18 Nov 2026 22:13:39 -0400 Subject: [PATCH 16/27] fix(FOUR-34260): guide mixed-method users through delivery then QR enroll Set DELIVERY_STEP_UP after a valid email/SMS code and gate new authenticator binding on mayEnrollNewAuthenticator. Redirect to the QR screen after delivery step-up so enrollment is reachable in the login flow (Cursor Bugbot). https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Auth/TwoFactorAuthController.php | 5 +++ .../Auth/TwoFactorPredictableSecretTest.php | 33 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index 2ad52425c5..29cb67f5d9 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -94,6 +94,11 @@ public function validateTwoFactorAuthCode(Request $request) session()->remove(self::TFA_ERROR); session()->remove(self::TFA_AUTH_APP); + $user = $user->fresh() ?? $user; + if (strlen($code) !== 6 && $this->twoFactorAuthentication->mayEnrollNewAuthenticator($user)) { + return redirect()->route('2fa.auth_app_qr'); + } + // Success $route = 'login'; } else { diff --git a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php index e45f055a45..90f1daa912 100644 --- a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php +++ b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php @@ -233,6 +233,39 @@ public function testCannotBypassDeliveryWithPendingAuthenticatorEnrollment(): vo $this->assertEmpty($user->fresh()->two_factor_secret); } + public function testMixedMethodsRedirectToQrAfterDeliveryCode(): void + { + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $deliverySecret = TOTP::generate()->getSecret(); + $user = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => null, + 'two_factor_delivery_secret' => $deliverySecret, + ]); + + $emailOtp = TOTP::createFromSecret($deliverySecret); + $emailOtp->setDigest('sha512'); + $emailOtp->setDigits(8); + $emailOtp->setPeriod(300); + + $this->actingAs($user, 'web') + ->post(route('2fa.validate'), ['code' => $emailOtp->now()]) + ->assertRedirect(route('2fa.auth_app_qr')); + + $this->assertTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + $this->assertTrue(session()->get(TwoFactorAuthentication::DELIVERY_STEP_UP)); + } + public function testMixedMethodsAllowAuthenticatorEnrollmentAfterDeliveryStepUp(): void { config([ From c91347149b0ce7b477db855929d3e2d5133bd912 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 18 Nov 2026 22:28:06 -0400 Subject: [PATCH 17/27] fix(FOUR-34260): harden mixed-method enrollment and preference bypass Snapshot challenge methods at login; block self-service API updates to preferences_2fa until TFA is validated. Gate authenticator enrollment on delivery step-up (session snapshot), redirect to QR after a valid delivery code, and clear 2FA session keys on logout. Address Cursor Bugbot findings. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Http/Controllers/Api/UserController.php | 12 +++++ .../Http/Controllers/Auth/LoginController.php | 15 ++++++ .../Auth/TwoFactorAuthController.php | 7 ++- ProcessMaker/TwoFactorAuthentication.php | 27 +++++++++-- .../Auth/TwoFactorPredictableSecretTest.php | 47 +++++++++++++++++++ 5 files changed, 102 insertions(+), 6 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Api/UserController.php b/ProcessMaker/Http/Controllers/Api/UserController.php index ee2acfa837..2a8748a05b 100644 --- a/ProcessMaker/Http/Controllers/Api/UserController.php +++ b/ProcessMaker/Http/Controllers/Api/UserController.php @@ -15,6 +15,7 @@ use ProcessMaker\Events\UserUpdated; use ProcessMaker\Exception\ReferentialIntegrityException; use ProcessMaker\Filters\SaveSession; +use ProcessMaker\Http\Controllers\Auth\TwoFactorAuthController; use ProcessMaker\Http\Controllers\Controller; use ProcessMaker\Http\Resources\ApiCollection; use ProcessMaker\Http\Resources\Users as UserResource; @@ -524,6 +525,17 @@ public function update(User $user, Request $request) if ($isSelfServiceUpdate) { $fields = $this->normalizeSelfServiceMeta($user, $fields); } + if (array_key_exists('preferences_2fa', $fields) + && $authenticatedUser->id === $user->id + && config('password-policies.2fa_enabled', false) + && !empty(config('password-policies.2fa_method', [])) + && !session()->get(TwoFactorAuthController::TFA_VALIDATED, false) + && TwoFactorAuthController::check2faByGroups() + ) { + return response()->json([ + 'message' => __('Two-factor authentication must be completed before updating 2FA preferences.'), + ], 422); + } if (isset($fields['password'])) { $fields['password'] = Hash::make($fields['password']); $fields['password_changed_at'] = Carbon::now()->toDateTimeString(); diff --git a/ProcessMaker/Http/Controllers/Auth/LoginController.php b/ProcessMaker/Http/Controllers/Auth/LoginController.php index 38b39fc9b6..894944f721 100644 --- a/ProcessMaker/Http/Controllers/Auth/LoginController.php +++ b/ProcessMaker/Http/Controllers/Auth/LoginController.php @@ -12,6 +12,7 @@ use Laravel\Passport\ApiTokenCookieFactory; use Laravel\Passport\Passport; use ProcessMaker\Events\Logout; +use ProcessMaker\Http\Controllers\Auth\TwoFactorAuthController; use ProcessMaker\Http\Controllers\Controller; use ProcessMaker\Managers\LoginManager; use ProcessMaker\Models\Setting; @@ -19,6 +20,7 @@ use ProcessMaker\Package\Auth\Database\Seeds\AuthDefaultSeeder; use ProcessMaker\Services\PermissionCacheService; use ProcessMaker\Traits\HasControllerAddons; +use ProcessMaker\TwoFactorAuthentication; class LoginController extends Controller { @@ -274,6 +276,16 @@ protected function authenticated(Request $request, $user) if (env('LOGOUT_OTHER_DEVICES', false)) { Auth::logoutOtherDevices($request->input('password')); } + + if (config('password-policies.2fa_enabled', false) + && !empty(config('password-policies.2fa_method', [])) + && TwoFactorAuthController::check2faByGroups() + ) { + session()->put( + TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT, + $user->getValid2FAPreferences() + ); + } } public function beforeLogout(Request $request) @@ -294,6 +306,9 @@ public function beforeLogout(Request $request) session()->remove(TwoFactorAuthController::TFA_VALIDATED); session()->remove(TwoFactorAuthController::TFA_MESSAGE); session()->remove(TwoFactorAuthController::TFA_ERROR); + session()->remove(TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT); + session()->remove(TwoFactorAuthentication::DELIVERY_STEP_UP); + session()->remove(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET); // Notify to listeners (package-auth, security logger) $eventResult = event(new Logout(Auth::user())); diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index 29cb67f5d9..d8d9de1ebb 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -42,6 +42,7 @@ public function displayTwoFactorAuthForm(Request $request) // Reload DB state without User::refresh() (clears permission caches). $user = $user->fresh() ?? $user; + $this->twoFactorAuthentication->rememberChallengeMethodsSnapshot($user); if ($this->shouldRedirectToAuthenticatorQrEnrollment($user)) { return redirect()->route('2fa.auth_app_qr'); } @@ -82,6 +83,8 @@ public function validateTwoFactorAuthCode(Request $request) return redirect()->route('2fa'); } + $this->twoFactorAuthentication->rememberChallengeMethodsSnapshot($user); + // Validate code $validated = $this->twoFactorAuthentication->validateCode($user, $code); @@ -139,6 +142,7 @@ public function displayAuthAppQr(Request $request) } $user = $user->fresh() ?? $user; + $this->twoFactorAuthentication->rememberChallengeMethodsSnapshot($user); $methods = $user->getValid2FAPreferences(); if (!in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) @@ -167,8 +171,7 @@ private function shouldRedirectToAuthenticatorQrEnrollment(User $user): bool $methods = $user->getValid2FAPreferences(); return in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) - && !in_array(TwoFactorAuthentication::EMAIL, $methods, true) - && !in_array(TwoFactorAuthentication::SMS, $methods, true); + && !$this->twoFactorAuthentication->challengeRequiresDeliveryStepUp(); } private function sendTwoFactorCodeForDisplay(User $user): void diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index ec4ac8dc15..80ef1f3cba 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -27,6 +27,8 @@ class TwoFactorAuthentication public const DELIVERY_STEP_UP = '2fa-delivery-step-up'; + public const CHALLENGE_METHODS_SNAPSHOT = '2fa-challenge-methods'; + public function sendCode(User $user): void { // Get methods to send the code @@ -77,6 +79,26 @@ private function resolveAuthenticatorSecret(User $user): ?string return !empty($pending) ? $pending : null; } + public function rememberChallengeMethodsSnapshot(User $user): void + { + if (session()->has(self::CHALLENGE_METHODS_SNAPSHOT)) { + return; + } + + session()->put( + self::CHALLENGE_METHODS_SNAPSHOT, + $user->getValid2FAPreferences() + ); + } + + public function challengeRequiresDeliveryStepUp(): bool + { + $methods = session()->get(self::CHALLENGE_METHODS_SNAPSHOT, []); + + return in_array(self::EMAIL, $methods, true) + || in_array(self::SMS, $methods, true); + } + public function mayEnrollNewAuthenticator(User $user): bool { if (!empty($user->two_factor_secret)) { @@ -88,10 +110,7 @@ public function mayEnrollNewAuthenticator(User $user): bool return false; } - $hasDeliveryMethod = in_array(self::EMAIL, $methods, true) - || in_array(self::SMS, $methods, true); - - if (!$hasDeliveryMethod) { + if (!$this->challengeRequiresDeliveryStepUp()) { return true; } diff --git a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php index 90f1daa912..511f9f0bec 100644 --- a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php +++ b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php @@ -219,6 +219,53 @@ public function testCannotBypassDeliveryWithPendingAuthenticatorEnrollment(): vo 'two_factor_secret' => null, ]); + session()->put(TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT, [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ]); + + $pendingSecret = TOTP::generate()->getSecret(); + session()->put(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET, $pendingSecret); + + $this->actingAs($user, 'web') + ->get(route('2fa.auth_app_qr')) + ->assertRedirect(route('2fa')); + + $this->postTwoFactorCode($user, TOTP::createFromSecret($pendingSecret)->now()) + ->assertRedirect(route('2fa')); + + $this->assertNotTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + $this->assertEmpty($user->fresh()->two_factor_secret); + } + + public function testNarrowedPreferencesCannotSkipDeliveryStepUpWhenPolicyRequiresIt(): void + { + Notification::fake(); + + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $user = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => null, + ]); + + session()->put(TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT, [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ]); + + $user->preferences_2fa = [TwoFactorAuthentication::AUTH_APP]; + $user->saveQuietly(); + $pendingSecret = TOTP::generate()->getSecret(); session()->put(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET, $pendingSecret); From e9d0f0f326035b70fab1d287e5404b884bce06f7 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 18 Nov 2026 22:38:34 -0400 Subject: [PATCH 18/27] fix(FOUR-34260): narrow API preferences guard to active web challenge Only block preferences_2fa when a login challenge snapshot exists and TFA is not validated; skip SSO and Bearer-only API profile updates. https://processmaker.atlassian.net/browse/FOUR-34260 --- ProcessMaker/Http/Controllers/Api/UserController.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Api/UserController.php b/ProcessMaker/Http/Controllers/Api/UserController.php index 2a8748a05b..d59bdd90fc 100644 --- a/ProcessMaker/Http/Controllers/Api/UserController.php +++ b/ProcessMaker/Http/Controllers/Api/UserController.php @@ -527,10 +527,9 @@ public function update(User $user, Request $request) } if (array_key_exists('preferences_2fa', $fields) && $authenticatedUser->id === $user->id - && config('password-policies.2fa_enabled', false) - && !empty(config('password-policies.2fa_method', [])) + && session()->has(TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT) && !session()->get(TwoFactorAuthController::TFA_VALIDATED, false) - && TwoFactorAuthController::check2faByGroups() + && session('sso_driver') === null ) { return response()->json([ 'message' => __('Two-factor authentication must be completed before updating 2FA preferences.'), From 467516557d2607967d506f5e6a39885e57babbba Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 18 Nov 2026 22:50:27 -0400 Subject: [PATCH 19/27] fix(FOUR-34260): bind preferences API gate to matching web session Ignore TFA_VALIDATED from another user's cookie when updating preferences_2fa via API (Cursor Bugbot). https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Http/Controllers/Api/UserController.php | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Api/UserController.php b/ProcessMaker/Http/Controllers/Api/UserController.php index d59bdd90fc..14b3c41cd0 100644 --- a/ProcessMaker/Http/Controllers/Api/UserController.php +++ b/ProcessMaker/Http/Controllers/Api/UserController.php @@ -525,15 +525,20 @@ public function update(User $user, Request $request) if ($isSelfServiceUpdate) { $fields = $this->normalizeSelfServiceMeta($user, $fields); } - if (array_key_exists('preferences_2fa', $fields) - && $authenticatedUser->id === $user->id - && session()->has(TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT) - && !session()->get(TwoFactorAuthController::TFA_VALIDATED, false) - && session('sso_driver') === null - ) { - return response()->json([ - 'message' => __('Two-factor authentication must be completed before updating 2FA preferences.'), - ], 422); + if (array_key_exists('preferences_2fa', $fields) && $authenticatedUser->id === $user->id) { + $webUserId = Auth::guard('web')->id(); + $twoFactorCompleteForPrincipal = $webUserId !== null + && (int) $webUserId === (int) $authenticatedUser->id + && session()->get(TwoFactorAuthController::TFA_VALIDATED, false); + + if (session()->has(TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT) + && session('sso_driver') === null + && !$twoFactorCompleteForPrincipal + ) { + return response()->json([ + 'message' => __('Two-factor authentication must be completed before updating 2FA preferences.'), + ], 422); + } } if (isset($fields['password'])) { $fields['password'] = Hash::make($fields['password']); From 7009dbecc73180a6729a200a91060377c1e51961 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 19 Nov 2026 11:44:54 -0400 Subject: [PATCH 20/27] fix(FOUR-34260): mitigate 2FA preference bypass in user update Gate self-service preferences_2fa updates on a completed web 2FA challenge bound to the authenticated user. Return 422 while the login challenge is pending, and skip the gate for SSO sessions. Refactor update() to a single response path so validation errors stop before any save or event dispatch. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Http/Controllers/Api/UserController.php | 130 ++++++++++-------- 1 file changed, 69 insertions(+), 61 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Api/UserController.php b/ProcessMaker/Http/Controllers/Api/UserController.php index 14b3c41cd0..b7b90a0f47 100644 --- a/ProcessMaker/Http/Controllers/Api/UserController.php +++ b/ProcessMaker/Http/Controllers/Api/UserController.php @@ -525,6 +525,19 @@ public function update(User $user, Request $request) if ($isSelfServiceUpdate) { $fields = $this->normalizeSelfServiceMeta($user, $fields); } + if (isset($fields['password'])) { + $fields['password'] = Hash::make($fields['password']); + $fields['password_changed_at'] = Carbon::now()->toDateTimeString(); + + // Remove login error message related to password expired if exists + session()->forget('login-error'); + } + $original = $user->getOriginal(); + $isLdapUser = isset($user->meta?->authenticationType) + && $user->meta->authenticationType === 'ldap'; + $user->fill($fields); + + $response = null; if (array_key_exists('preferences_2fa', $fields) && $authenticatedUser->id === $user->id) { $webUserId = Auth::guard('web')->id(); $twoFactorCompleteForPrincipal = $webUserId !== null @@ -535,36 +548,25 @@ public function update(User $user, Request $request) && session('sso_driver') === null && !$twoFactorCompleteForPrincipal ) { - return response()->json([ + $response = response()->json([ 'message' => __('Two-factor authentication must be completed before updating 2FA preferences.'), ], 422); } } - if (isset($fields['password'])) { - $fields['password'] = Hash::make($fields['password']); - $fields['password_changed_at'] = Carbon::now()->toDateTimeString(); - - // Remove login error message related to password expired if exists - session()->forget('login-error'); - } - $original = $user->getOriginal(); - $isLdapUser = isset($user->meta?->authenticationType) - && $user->meta->authenticationType === 'ldap'; - $user->fill($fields); - if (array_key_exists('cell', $fields)) { - $response = $this->validateCellPhoneNumber($user, $fields['cell']); - if ($response) { - return $response; + if ($response === null && array_key_exists('cell', $fields)) { + $cellValidation = $this->validateCellPhoneNumber($user, $fields['cell']); + if ($cellValidation) { + $response = $cellValidation; } } - if ($fields['email'] !== $original['email']) { + if ($response === null && $fields['email'] !== $original['email']) { $ssoUser = $isLdapUser; if (class_exists(SsoUser::class)) { // Check if the user is an SSO user (including SAML) $ssoUser = $ssoUser || SsoUser::where('user_id', $user->id)->exists(); } if ($ssoUser) { - return response([ + $response = response([ 'message' => __( "The email can't be edited. This action is only available for SSO-synced users." ), @@ -576,9 +578,8 @@ public function update(User $user, Request $request) ], ], ], 422); - } - if (!isset($fields['valpassword'])) { - return response([ + } elseif (!isset($fields['valpassword'])) { + $response = response([ 'message' => __( 'A valid authentication is required for for update the email.' ), @@ -591,57 +592,64 @@ public function update(User $user, Request $request) ], ], 422); } else { - $response = $this->validateBeforeChange(Auth::user(), $fields['valpassword']); - if ($response) { - return $response; + $emailAuthResponse = $this->validateBeforeChange(Auth::user(), $fields['valpassword']); + if ($emailAuthResponse) { + $response = $emailAuthResponse; } } } - if (Auth::user()->is_administrator && $request->has('is_administrator')) { - // user must be an admin to make another user an admin - $user->is_administrator = $request->get('is_administrator'); - } - - if (empty($fields['meta'])) { - $user->meta = null; - } - - try { - $user->saveOrFail(); - } catch (\Exception $e) { - $slackExceptionClass = 'ProcessMaker\Packages\Connectors\Slack\Exceptions\SlackConfigurationException'; + if ($response === null) { + if (Auth::user()->is_administrator && $request->has('is_administrator')) { + // user must be an admin to make another user an admin + $user->is_administrator = $request->get('is_administrator'); + } - if (class_exists($slackExceptionClass) && $e instanceof $slackExceptionClass) { - return response([ - 'message' => $e->getMessage(), - ], 422); + if (empty($fields['meta'])) { + $user->meta = null; } - throw $e; - } + try { + $user->saveOrFail(); + } catch (\Exception $e) { + $slackExceptionClass = 'ProcessMaker\Packages\Connectors\Slack\Exceptions\SlackConfigurationException'; + + if (class_exists($slackExceptionClass) && $e instanceof $slackExceptionClass) { + $response = response([ + 'message' => $e->getMessage(), + ], 422); + } else { + throw $e; + } + } - $changes = $user->getChanges(); + if ($response === null) { + $changes = $user->getChanges(); + + //Call new Event to store User Changes into LOG + UserUpdated::dispatch($user, $changes, $original); + try { + if ($request->has('avatar')) { + $this->uploadAvatar($user, $request); + } + } catch (\Exception $e) { + $response = response([ + 'message' => 'Error uploading avatar', + 'errors' => [ + 'avatar' => [ + $e->getMessage(), + ], + ], + ], 422); + } + } - //Call new Event to store User Changes into LOG - UserUpdated::dispatch($user, $changes, $original); - try { - if ($request->has('avatar')) { - $this->uploadAvatar($user, $request); + if ($response === null) { + RecommendationEngine::handleUserSettingChanges($user, $original); + $response = response([], 204); } - } catch (\Exception $e) { - return response([ - 'message' => 'Error uploading avatar', - 'errors' => [ - 'avatar' => [ - $e->getMessage(), - ], - ], - ], 422); } - RecommendationEngine::handleUserSettingChanges($user, $original); - - return response([], 204); + return $response; } /** From 82c94df03d9bc166ac1a7cb686d5e48766e0dd76 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 19 Nov 2026 12:07:48 -0400 Subject: [PATCH 21/27] fix(FOUR-34260): use random authenticator secrets instead of predictable ones Stop deriving TOTP secrets from the user UUID and username. Authenticator secrets are now random and stored in two_factor_secret. A new authenticator can only be enrolled after a delivery-code step-up when the policy requires one, and the enrollment snapshot is taken at login. Remove the predictable secret generator and the unused getUserTotpSecret helper (Sonar S1144). Simplify validateCode and createOtpInstance to satisfy S1142 and S1488. https://processmaker.atlassian.net/browse/FOUR-34260 --- ProcessMaker/TwoFactorAuthentication.php | 43 ++++++++++++++---------- 1 file changed, 25 insertions(+), 18 deletions(-) diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index 80ef1f3cba..16626c8bc1 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -158,25 +158,27 @@ public function validateCode(User $user, string $code) // 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) { - if (empty($user->two_factor_secret) && !$this->mayEnrollNewAuthenticator($user)) { - return false; - } - // 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); - } + $cannotUseAuthenticator = !in_array(self::AUTH_APP, $methods, true) || $authSecret === null; + $cannotEnroll = empty($user->two_factor_secret) && !$this->mayEnrollNewAuthenticator($user); + if ($cannotUseAuthenticator || $cannotEnroll) { + return false; + } + + // 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) - ) { + + return $valid; + } + + if ($this->hasDeliveryMethod($methods) && !empty($user->two_factor_delivery_secret)) { // Create OTP instance $otp = $this->createOtpInstance($user, false); @@ -190,6 +192,11 @@ public function validateCode(User $user, string $code) return $valid; } + private function hasDeliveryMethod(array $methods): bool + { + return in_array(self::EMAIL, $methods, true) || in_array(self::SMS, $methods, true); + } + /** * @param User $user * @param string $code From d40448c53f5f079a696e320411ca4d59f6188161 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 19 Nov 2026 12:10:16 -0400 Subject: [PATCH 22/27] fix(FOUR-34260): merge early exits in mayEnrollNewAuthenticator for Sonar S1142 Combine the existing-secret and missing AUTH_APP checks into one guard so the method stays within the three return-statement limit without changing enrollment behavior. https://processmaker.atlassian.net/browse/FOUR-34260 --- ProcessMaker/TwoFactorAuthentication.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index 16626c8bc1..80753b7cee 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -101,12 +101,8 @@ public function challengeRequiresDeliveryStepUp(): bool public function mayEnrollNewAuthenticator(User $user): bool { - if (!empty($user->two_factor_secret)) { - return false; - } - $methods = $user->getValid2FAPreferences(); - if (!in_array(self::AUTH_APP, $methods, true)) { + if (!empty($user->two_factor_secret) || !in_array(self::AUTH_APP, $methods, true)) { return false; } From 5631a2c71e02c2adac994188a3a45018d62f8a20 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 19 Nov 2026 12:25:12 -0400 Subject: [PATCH 23/27] fix(FOUR-34260): block self-service preferences_2fa update until web 2FA completes Reject PUT /api/1.0/users/{user} when the principal updates their own preferences_2fa while a login challenge snapshot is active, SSO is not in use, and the web session has not completed 2FA for the same user id. Prevents narrowing 2FA methods to skip delivery step-up during an in-progress challenge. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Http/Controllers/Api/UserController.php | 107 ++++++++---------- 1 file changed, 50 insertions(+), 57 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Api/UserController.php b/ProcessMaker/Http/Controllers/Api/UserController.php index b7b90a0f47..16954e5f89 100644 --- a/ProcessMaker/Http/Controllers/Api/UserController.php +++ b/ProcessMaker/Http/Controllers/Api/UserController.php @@ -537,7 +537,6 @@ public function update(User $user, Request $request) && $user->meta->authenticationType === 'ldap'; $user->fill($fields); - $response = null; if (array_key_exists('preferences_2fa', $fields) && $authenticatedUser->id === $user->id) { $webUserId = Auth::guard('web')->id(); $twoFactorCompleteForPrincipal = $webUserId !== null @@ -548,25 +547,25 @@ public function update(User $user, Request $request) && session('sso_driver') === null && !$twoFactorCompleteForPrincipal ) { - $response = response()->json([ + return response()->json([ 'message' => __('Two-factor authentication must be completed before updating 2FA preferences.'), ], 422); } } - if ($response === null && array_key_exists('cell', $fields)) { - $cellValidation = $this->validateCellPhoneNumber($user, $fields['cell']); - if ($cellValidation) { - $response = $cellValidation; + if (array_key_exists('cell', $fields)) { + $response = $this->validateCellPhoneNumber($user, $fields['cell']); + if ($response) { + return $response; } } - if ($response === null && $fields['email'] !== $original['email']) { + if ($fields['email'] !== $original['email']) { $ssoUser = $isLdapUser; if (class_exists(SsoUser::class)) { // Check if the user is an SSO user (including SAML) $ssoUser = $ssoUser || SsoUser::where('user_id', $user->id)->exists(); } if ($ssoUser) { - $response = response([ + return response([ 'message' => __( "The email can't be edited. This action is only available for SSO-synced users." ), @@ -578,8 +577,9 @@ public function update(User $user, Request $request) ], ], ], 422); - } elseif (!isset($fields['valpassword'])) { - $response = response([ + } + if (!isset($fields['valpassword'])) { + return response([ 'message' => __( 'A valid authentication is required for for update the email.' ), @@ -592,64 +592,57 @@ public function update(User $user, Request $request) ], ], 422); } else { - $emailAuthResponse = $this->validateBeforeChange(Auth::user(), $fields['valpassword']); - if ($emailAuthResponse) { - $response = $emailAuthResponse; + $response = $this->validateBeforeChange(Auth::user(), $fields['valpassword']); + if ($response) { + return $response; } } } - if ($response === null) { - if (Auth::user()->is_administrator && $request->has('is_administrator')) { - // user must be an admin to make another user an admin - $user->is_administrator = $request->get('is_administrator'); - } + if (Auth::user()->is_administrator && $request->has('is_administrator')) { + // user must be an admin to make another user an admin + $user->is_administrator = $request->get('is_administrator'); + } - if (empty($fields['meta'])) { - $user->meta = null; - } + if (empty($fields['meta'])) { + $user->meta = null; + } - try { - $user->saveOrFail(); - } catch (\Exception $e) { - $slackExceptionClass = 'ProcessMaker\Packages\Connectors\Slack\Exceptions\SlackConfigurationException'; - - if (class_exists($slackExceptionClass) && $e instanceof $slackExceptionClass) { - $response = response([ - 'message' => $e->getMessage(), - ], 422); - } else { - throw $e; - } - } + try { + $user->saveOrFail(); + } catch (\Exception $e) { + $slackExceptionClass = 'ProcessMaker\Packages\Connectors\Slack\Exceptions\SlackConfigurationException'; - if ($response === null) { - $changes = $user->getChanges(); - - //Call new Event to store User Changes into LOG - UserUpdated::dispatch($user, $changes, $original); - try { - if ($request->has('avatar')) { - $this->uploadAvatar($user, $request); - } - } catch (\Exception $e) { - $response = response([ - 'message' => 'Error uploading avatar', - 'errors' => [ - 'avatar' => [ - $e->getMessage(), - ], - ], - ], 422); - } + if (class_exists($slackExceptionClass) && $e instanceof $slackExceptionClass) { + return response([ + 'message' => $e->getMessage(), + ], 422); } - if ($response === null) { - RecommendationEngine::handleUserSettingChanges($user, $original); - $response = response([], 204); + throw $e; + } + + $changes = $user->getChanges(); + + //Call new Event to store User Changes into LOG + UserUpdated::dispatch($user, $changes, $original); + try { + if ($request->has('avatar')) { + $this->uploadAvatar($user, $request); } + } catch (\Exception $e) { + return response([ + 'message' => 'Error uploading avatar', + 'errors' => [ + 'avatar' => [ + $e->getMessage(), + ], + ], + ], 422); } - return $response; + RecommendationEngine::handleUserSettingChanges($user, $original); + + return response([], 204); } /** From 562b39a8abaa48f36162a1be7401a7c4faafbd0f Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 19 Nov 2026 12:28:06 -0400 Subject: [PATCH 24/27] fix(FOUR-34260): satisfy Sonar S1142 in validateTwoFactorAuthCode Use a single final redirect with a $route variable instead of a separate return for authenticator QR enrollment, preserving mixed-method flow behavior. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Http/Controllers/Auth/TwoFactorAuthController.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index d8d9de1ebb..4e7883941f 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -98,12 +98,10 @@ public function validateTwoFactorAuthCode(Request $request) session()->remove(self::TFA_AUTH_APP); $user = $user->fresh() ?? $user; + $route = 'login'; if (strlen($code) !== 6 && $this->twoFactorAuthentication->mayEnrollNewAuthenticator($user)) { - return redirect()->route('2fa.auth_app_qr'); + $route = '2fa.auth_app_qr'; } - - // Success - $route = 'login'; } else { // Set error message session()->put(self::TFA_ERROR, __('Invalid code.')); From 4badbbc78da60d018632bfc00ca8a98e3f92784e Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 19 Nov 2026 12:49:24 -0400 Subject: [PATCH 25/27] refactor(FOUR-34260): extract UserController::update helpers for Sonar S1142 and S3776 Address Sonar findings on UserController::update(): rule S1142 (too many return statements) and rule S3776 (cognitive complexity above the allowed threshold). Move post-fill validation and persistence into private helpers without changing behavior. The 2FA preferences_2fa gate, cell validation, email change checks, and save/avatar flow remain the same as before this refactor. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Http/Controllers/Api/UserController.php | 248 ++++++++++-------- ProcessMaker/TwoFactorAuthentication.php | 53 ++-- 2 files changed, 170 insertions(+), 131 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Api/UserController.php b/ProcessMaker/Http/Controllers/Api/UserController.php index 16954e5f89..603ba0853d 100644 --- a/ProcessMaker/Http/Controllers/Api/UserController.php +++ b/ProcessMaker/Http/Controllers/Api/UserController.php @@ -537,112 +537,18 @@ public function update(User $user, Request $request) && $user->meta->authenticationType === 'ldap'; $user->fill($fields); - if (array_key_exists('preferences_2fa', $fields) && $authenticatedUser->id === $user->id) { - $webUserId = Auth::guard('web')->id(); - $twoFactorCompleteForPrincipal = $webUserId !== null - && (int) $webUserId === (int) $authenticatedUser->id - && session()->get(TwoFactorAuthController::TFA_VALIDATED, false); - - if (session()->has(TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT) - && session('sso_driver') === null - && !$twoFactorCompleteForPrincipal - ) { - return response()->json([ - 'message' => __('Two-factor authentication must be completed before updating 2FA preferences.'), - ], 422); - } - } - if (array_key_exists('cell', $fields)) { - $response = $this->validateCellPhoneNumber($user, $fields['cell']); - if ($response) { - return $response; - } - } - if ($fields['email'] !== $original['email']) { - $ssoUser = $isLdapUser; - if (class_exists(SsoUser::class)) { - // Check if the user is an SSO user (including SAML) - $ssoUser = $ssoUser || SsoUser::where('user_id', $user->id)->exists(); - } - if ($ssoUser) { - return response([ - 'message' => __( - "The email can't be edited. This action is only available for SSO-synced users." - ), - 'errors' => [ - 'email' => [ - __( - "The email can't be edited. This action is only available for SSO-synced users." - ), - ], - ], - ], 422); - } - if (!isset($fields['valpassword'])) { - return response([ - 'message' => __( - 'A valid authentication is required for for update the email.' - ), - 'errors' => [ - 'email' => [ - __( - 'The password is required.' - ), - ], - ], - ], 422); - } else { - $response = $this->validateBeforeChange(Auth::user(), $fields['valpassword']); - if ($response) { - return $response; - } - } + $validationResponse = $this->resolveUserUpdateValidationResponse( + $authenticatedUser, + $user, + $fields, + $original, + $isLdapUser + ); + if ($validationResponse !== null) { + return $validationResponse; } - if (Auth::user()->is_administrator && $request->has('is_administrator')) { - // user must be an admin to make another user an admin - $user->is_administrator = $request->get('is_administrator'); - } - - if (empty($fields['meta'])) { - $user->meta = null; - } - - try { - $user->saveOrFail(); - } catch (\Exception $e) { - $slackExceptionClass = 'ProcessMaker\Packages\Connectors\Slack\Exceptions\SlackConfigurationException'; - - if (class_exists($slackExceptionClass) && $e instanceof $slackExceptionClass) { - return response([ - 'message' => $e->getMessage(), - ], 422); - } - throw $e; - } - - $changes = $user->getChanges(); - - //Call new Event to store User Changes into LOG - UserUpdated::dispatch($user, $changes, $original); - try { - if ($request->has('avatar')) { - $this->uploadAvatar($user, $request); - } - } catch (\Exception $e) { - return response([ - 'message' => 'Error uploading avatar', - 'errors' => [ - 'avatar' => [ - $e->getMessage(), - ], - ], - ], 422); - } - - RecommendationEngine::handleUserSettingChanges($user, $original); - - return response([], 204); + return $this->completeUserUpdate($user, $request, $fields, $original); } /** @@ -698,6 +604,140 @@ private function normalizeSelfServiceMeta(User $user, array $fields): array return $fields; } + private function resolveUserUpdateValidationResponse( + User $authenticatedUser, + User $user, + array $fields, + array $original, + bool $isLdapUser + ) { + $response = $this->preferences2faUpdateBlockedResponse($authenticatedUser, $user, $fields); + if ($response === null && array_key_exists('cell', $fields)) { + $response = $this->validateCellPhoneNumber($user, $fields['cell']) ?: null; + } + if ($response === null && $fields['email'] !== $original['email']) { + $response = $this->validateEmailChangeForUpdate($user, $fields, $isLdapUser); + } + + return $response; + } + + private function preferences2faUpdateBlockedResponse(User $authenticatedUser, User $user, array $fields) + { + if (!array_key_exists('preferences_2fa', $fields) || $authenticatedUser->id !== $user->id) { + return null; + } + + $webUserId = Auth::guard('web')->id(); + $twoFactorCompleteForPrincipal = $webUserId !== null + && (int) $webUserId === (int) $authenticatedUser->id + && session()->get(TwoFactorAuthController::TFA_VALIDATED, false); + + if (session()->has(TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT) + && session('sso_driver') === null + && !$twoFactorCompleteForPrincipal + ) { + return response()->json([ + 'message' => __('Two-factor authentication must be completed before updating 2FA preferences.'), + ], 422); + } + + return null; + } + + private function validateEmailChangeForUpdate(User $user, array $fields, bool $isLdapUser) + { + $response = null; + $ssoUser = $isLdapUser; + if (class_exists(SsoUser::class)) { + // Check if the user is an SSO user (including SAML) + $ssoUser = $ssoUser || SsoUser::where('user_id', $user->id)->exists(); + } + if ($ssoUser) { + $response = response([ + 'message' => __( + "The email can't be edited. This action is only available for SSO-synced users." + ), + 'errors' => [ + 'email' => [ + __( + "The email can't be edited. This action is only available for SSO-synced users." + ), + ], + ], + ], 422); + } elseif (!isset($fields['valpassword'])) { + $response = response([ + 'message' => __( + 'A valid authentication is required for for update the email.' + ), + 'errors' => [ + 'email' => [ + __( + 'The password is required.' + ), + ], + ], + ], 422); + } else { + $emailAuthResponse = $this->validateBeforeChange(Auth::user(), $fields['valpassword']); + if ($emailAuthResponse) { + $response = $emailAuthResponse; + } + } + + return $response; + } + + private function completeUserUpdate(User $user, Request $request, array $fields, array $original) + { + if (Auth::user()->is_administrator && $request->has('is_administrator')) { + // user must be an admin to make another user an admin + $user->is_administrator = $request->get('is_administrator'); + } + + if (empty($fields['meta'])) { + $user->meta = null; + } + + try { + $user->saveOrFail(); + } catch (\Exception $e) { + $slackExceptionClass = 'ProcessMaker\Packages\Connectors\Slack\Exceptions\SlackConfigurationException'; + + if (class_exists($slackExceptionClass) && $e instanceof $slackExceptionClass) { + return response([ + 'message' => $e->getMessage(), + ], 422); + } + + throw $e; + } + + $changes = $user->getChanges(); + + //Call new Event to store User Changes into LOG + UserUpdated::dispatch($user, $changes, $original); + try { + if ($request->has('avatar')) { + $this->uploadAvatar($user, $request); + } + } catch (\Exception $e) { + return response([ + 'message' => 'Error uploading avatar', + 'errors' => [ + 'avatar' => [ + $e->getMessage(), + ], + ], + ], 422); + } + + RecommendationEngine::handleUserSettingChanges($user, $original); + + return response([], 204); + } + /** * Validate the phone number for SMS two-factor authentication. * diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index 80753b7cee..7c5ab90a81 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -149,40 +149,39 @@ private function getCodeForEmailSms(User $user): string public function validateCode(User $user, string $code) { $methods = $user->getValid2FAPreferences(); - $valid = false; - // The code is for Google Authenticator app? if (strlen($code) === 6) { - $authSecret = $this->resolveAuthenticatorSecret($user); - $cannotUseAuthenticator = !in_array(self::AUTH_APP, $methods, true) || $authSecret === null; - $cannotEnroll = empty($user->two_factor_secret) && !$this->mayEnrollNewAuthenticator($user); - if ($cannotUseAuthenticator || $cannotEnroll) { - return false; - } - - // Create OTP instance - $otp = $this->createOtpInstance($user, true); + return $this->verifyAuthenticatorCode($user, $code, $methods); + } - // 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); - } + if (!$this->hasDeliveryMethod($methods) || empty($user->two_factor_delivery_secret)) { + return false; + } - return $valid; + $otp = $this->createOtpInstance($user, false); + $valid = $otp->verify($code); + if ($valid) { + session()->put(self::DELIVERY_STEP_UP, true); } - if ($this->hasDeliveryMethod($methods) && !empty($user->two_factor_delivery_secret)) { - // Create OTP instance - $otp = $this->createOtpInstance($user, false); + return $valid; + } + + private function verifyAuthenticatorCode(User $user, string $code, array $methods): bool + { + $authSecret = $this->resolveAuthenticatorSecret($user); + $cannotUseAuthenticator = !in_array(self::AUTH_APP, $methods, true) || $authSecret === null; + $cannotEnroll = empty($user->two_factor_secret) && !$this->mayEnrollNewAuthenticator($user); + if ($cannotUseAuthenticator || $cannotEnroll) { + return false; + } - // Validate code - $valid = $otp->verify($code); - if ($valid) { - session()->put(self::DELIVERY_STEP_UP, true); - } + $otp = $this->createOtpInstance($user, true); + $valid = $otp->verify($code); + if ($valid && empty($user->two_factor_secret)) { + $user->two_factor_secret = $authSecret; + $user->saveQuietly(); + session()->forget(self::PENDING_AUTHENTICATOR_SECRET); } return $valid; From 3e855dd7fa6d382f1e0a5c2cbeb58ae91cf7cfad Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 19 Nov 2026 14:48:15 -0400 Subject: [PATCH 26/27] fix(FOUR-34260): block stateless API preferences_2fa updates without validated web session Require web guard and TFA_VALIDATED for self-service preferences_2fa when global 2FA applies. Extract UserController::update validation helpers for Sonar S1142 and S3776. Add feature test with a valid update payload asserting the 2FA guard message. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Http/Controllers/Api/UserController.php | 19 ++++--- .../Auth/TwoFactorPredictableSecretTest.php | 49 +++++++++++++++++++ 2 files changed, 60 insertions(+), 8 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Api/UserController.php b/ProcessMaker/Http/Controllers/Api/UserController.php index 603ba0853d..fd599bc450 100644 --- a/ProcessMaker/Http/Controllers/Api/UserController.php +++ b/ProcessMaker/Http/Controllers/Api/UserController.php @@ -628,21 +628,24 @@ private function preferences2faUpdateBlockedResponse(User $authenticatedUser, Us return null; } + if (session('sso_driver') !== null + || !config('password-policies.2fa_enabled', false) + || empty(config('password-policies.2fa_method', [])) + || !TwoFactorAuthController::check2faByGroups() + ) { + return null; + } + $webUserId = Auth::guard('web')->id(); $twoFactorCompleteForPrincipal = $webUserId !== null && (int) $webUserId === (int) $authenticatedUser->id && session()->get(TwoFactorAuthController::TFA_VALIDATED, false); - if (session()->has(TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT) - && session('sso_driver') === null - && !$twoFactorCompleteForPrincipal - ) { - return response()->json([ + return $twoFactorCompleteForPrincipal + ? null + : response()->json([ 'message' => __('Two-factor authentication must be completed before updating 2FA preferences.'), ], 422); - } - - return null; } private function validateEmailChangeForUpdate(User $user, array $fields, bool $isLdapUser) diff --git a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php index 511f9f0bec..17d933d861 100644 --- a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php +++ b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php @@ -201,6 +201,50 @@ public function testAuthAppQrRouteRequiresAuthenticatorEnrollment(): void ->assertRedirect(route('2fa')); } + /** + * Stateless auth:api must not narrow preferences_2fa before the same principal + * completes web 2FA (blocks Bearer PUT bypass of delivery step-up). + */ + public function testStatelessApiCannotUpdatePreferences2faBeforeWebTwoFactorValidated(): void + { + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $user = User::factory()->create([ + 'is_administrator' => true, + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => null, + ]); + + $payload = [ + 'username' => $user->username, + 'firstname' => $user->firstname, + 'lastname' => $user->lastname, + 'email' => $user->email, + 'status' => $user->status, + 'preferences_2fa' => [TwoFactorAuthentication::AUTH_APP], + ]; + + $this->actingAs($user, 'api') + ->putJson('/api/1.0/users/' . $user->id, $payload) + ->assertStatus(422) + ->assertJsonPath( + 'message', + __('Two-factor authentication must be completed before updating 2FA preferences.') + ); + + $freshPreferences = $user->fresh()->preferences_2fa; + $this->assertContains(TwoFactorAuthentication::EMAIL, $freshPreferences); + $this->assertContains(TwoFactorAuthentication::AUTH_APP, $freshPreferences); + } + public function testCannotBypassDeliveryWithPendingAuthenticatorEnrollment(): void { config([ @@ -238,6 +282,10 @@ public function testCannotBypassDeliveryWithPendingAuthenticatorEnrollment(): vo $this->assertEmpty($user->fresh()->two_factor_secret); } + /** + * Enrollment still requires delivery when the login snapshot includes it, even if + * stored preferences were narrowed outside the API (historical bypass shape). + */ public function testNarrowedPreferencesCannotSkipDeliveryStepUpWhenPolicyRequiresIt(): void { Notification::fake(); @@ -263,6 +311,7 @@ public function testNarrowedPreferencesCannotSkipDeliveryStepUpWhenPolicyRequire TwoFactorAuthentication::EMAIL, ]); + // Simulates narrowed prefs without going through UserController (not the API guard). $user->preferences_2fa = [TwoFactorAuthentication::AUTH_APP]; $user->saveQuietly(); From 5bc0a820ea2e945240d2731c6fa314562a3fb2dc Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 19 Nov 2026 18:59:23 -0400 Subject: [PATCH 27/27] fix(OUR-34260): block OTP destination changes until web 2FA is validated Reject self-service PUT updates to preferences_2fa, email, and cell when global 2FA applies and the principal has not completed the web session challenge (TFA_VALIDATED), closing Bearer and password-only API bypasses of delivery step-up. Snapshot challenge delivery email and cell at login and send OTP to those targets. Add feature tests for stateless API preferences and email changes. https://processmaker.atlassian.net/browse/FOUR-34260 --- .../Http/Controllers/Api/UserController.php | 57 ++++++++++++++----- .../Http/Controllers/Auth/LoginController.php | 7 +-- ProcessMaker/TwoFactorAuthentication.php | 32 ++++++++++- .../Auth/TwoFactorPredictableSecretTest.php | 39 +++++++++++++ 4 files changed, 115 insertions(+), 20 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Api/UserController.php b/ProcessMaker/Http/Controllers/Api/UserController.php index fd599bc450..aa8d9eb5ae 100644 --- a/ProcessMaker/Http/Controllers/Api/UserController.php +++ b/ProcessMaker/Http/Controllers/Api/UserController.php @@ -611,7 +611,12 @@ private function resolveUserUpdateValidationResponse( array $original, bool $isLdapUser ) { - $response = $this->preferences2faUpdateBlockedResponse($authenticatedUser, $user, $fields); + $response = $this->selfServiceTwoFactorSensitiveUpdateBlocked( + $authenticatedUser, + $user, + $fields, + $original + ); if ($response === null && array_key_exists('cell', $fields)) { $response = $this->validateCellPhoneNumber($user, $fields['cell']) ?: null; } @@ -622,30 +627,54 @@ private function resolveUserUpdateValidationResponse( return $response; } - private function preferences2faUpdateBlockedResponse(User $authenticatedUser, User $user, array $fields) - { - if (!array_key_exists('preferences_2fa', $fields) || $authenticatedUser->id !== $user->id) { + private function selfServiceTwoFactorSensitiveUpdateBlocked( + User $authenticatedUser, + User $user, + array $fields, + array $original + ) { + if ($authenticatedUser->id !== $user->id || !$this->touchesTwoFactorDestinations($fields, $original)) { + return null; + } + + if (!$this->selfServiceTwoFactorCompletionPending($authenticatedUser)) { return null; } + return response()->json([ + 'message' => __('Two-factor authentication must be completed before updating 2FA preferences.'), + ], 422); + } + + private function touchesTwoFactorDestinations(array $fields, array $original): bool + { + if (array_key_exists('preferences_2fa', $fields)) { + return true; + } + + if (array_key_exists('cell', $fields) && ($fields['cell'] ?? null) !== ($original['cell'] ?? null)) { + return true; + } + + return array_key_exists('email', $fields) + && ($fields['email'] ?? null) !== ($original['email'] ?? null); + } + + private function selfServiceTwoFactorCompletionPending(User $authenticatedUser): bool + { if (session('sso_driver') !== null || !config('password-policies.2fa_enabled', false) || empty(config('password-policies.2fa_method', [])) || !TwoFactorAuthController::check2faByGroups() ) { - return null; + return false; } $webUserId = Auth::guard('web')->id(); - $twoFactorCompleteForPrincipal = $webUserId !== null - && (int) $webUserId === (int) $authenticatedUser->id - && session()->get(TwoFactorAuthController::TFA_VALIDATED, false); - - return $twoFactorCompleteForPrincipal - ? null - : response()->json([ - 'message' => __('Two-factor authentication must be completed before updating 2FA preferences.'), - ], 422); + + return $webUserId === null + || (int) $webUserId !== (int) $authenticatedUser->id + || !session()->get(TwoFactorAuthController::TFA_VALIDATED, false); } private function validateEmailChangeForUpdate(User $user, array $fields, bool $isLdapUser) diff --git a/ProcessMaker/Http/Controllers/Auth/LoginController.php b/ProcessMaker/Http/Controllers/Auth/LoginController.php index 894944f721..0c8b31ba9e 100644 --- a/ProcessMaker/Http/Controllers/Auth/LoginController.php +++ b/ProcessMaker/Http/Controllers/Auth/LoginController.php @@ -281,10 +281,7 @@ protected function authenticated(Request $request, $user) && !empty(config('password-policies.2fa_method', [])) && TwoFactorAuthController::check2faByGroups() ) { - session()->put( - TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT, - $user->getValid2FAPreferences() - ); + (new TwoFactorAuthentication())->rememberChallengeMethodsSnapshot($user); } } @@ -307,6 +304,8 @@ public function beforeLogout(Request $request) session()->remove(TwoFactorAuthController::TFA_MESSAGE); session()->remove(TwoFactorAuthController::TFA_ERROR); session()->remove(TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT); + session()->remove(TwoFactorAuthentication::CHALLENGE_DELIVERY_EMAIL); + session()->remove(TwoFactorAuthentication::CHALLENGE_DELIVERY_CELL); session()->remove(TwoFactorAuthentication::DELIVERY_STEP_UP); session()->remove(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET); diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index 7c5ab90a81..d5841bdd4d 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -29,10 +29,15 @@ class TwoFactorAuthentication public const CHALLENGE_METHODS_SNAPSHOT = '2fa-challenge-methods'; + public const CHALLENGE_DELIVERY_EMAIL = '2fa-challenge-delivery-email'; + + public const CHALLENGE_DELIVERY_CELL = '2fa-challenge-delivery-cell'; + public function sendCode(User $user): void { // Get methods to send the code $methods = $user->getValid2FAPreferences(); + $deliveryUser = $this->userForDeliveryChallenge($user); if (in_array(self::EMAIL, $methods) || in_array(self::SMS, $methods)) { // Get code @@ -40,10 +45,10 @@ public function sendCode(User $user): void // Send OTP if (in_array(self::EMAIL, $methods)) { - Notification::send($user, new TwoFactorAuthNotification($user, $code)); + Notification::send($deliveryUser, new TwoFactorAuthNotification($deliveryUser, $code)); } if (in_array(self::SMS, $methods)) { - $this->sendSms($user, $code); + $this->sendSms($deliveryUser, $code); } } elseif (in_array(self::AUTH_APP, $methods)) { session()->put('2fa-auth-app', true); @@ -89,6 +94,29 @@ public function rememberChallengeMethodsSnapshot(User $user): void self::CHALLENGE_METHODS_SNAPSHOT, $user->getValid2FAPreferences() ); + session()->put(self::CHALLENGE_DELIVERY_EMAIL, $user->email); + session()->put(self::CHALLENGE_DELIVERY_CELL, $user->cell); + } + + private function userForDeliveryChallenge(User $user): User + { + $email = session()->get(self::CHALLENGE_DELIVERY_EMAIL); + $cell = session()->get(self::CHALLENGE_DELIVERY_CELL); + if ($email === null && $cell === null) { + return $user; + } + + $deliveryUser = $user->replicate(); + $deliveryUser->exists = true; + $deliveryUser->id = $user->id; + if ($email !== null) { + $deliveryUser->email = $email; + } + if ($cell !== null) { + $deliveryUser->cell = $cell; + } + + return $deliveryUser; } public function challengeRequiresDeliveryStepUp(): bool diff --git a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php index 17d933d861..5834f95fee 100644 --- a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php +++ b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php @@ -245,6 +245,45 @@ public function testStatelessApiCannotUpdatePreferences2faBeforeWebTwoFactorVali $this->assertContains(TwoFactorAuthentication::AUTH_APP, $freshPreferences); } + public function testStatelessApiCannotChangeEmailBeforeWebTwoFactorValidated(): void + { + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $user = User::factory()->create([ + 'is_administrator' => true, + 'password' => Hash::make('password'), + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => null, + ]); + + $payload = [ + 'username' => $user->username, + 'firstname' => $user->firstname, + 'lastname' => $user->lastname, + 'email' => 'attacker-' . $user->email, + 'status' => $user->status, + 'valpassword' => 'password', + ]; + + $this->actingAs($user, 'api') + ->putJson('/api/1.0/users/' . $user->id, $payload) + ->assertStatus(422) + ->assertJsonPath( + 'message', + __('Two-factor authentication must be completed before updating 2FA preferences.') + ); + + $this->assertSame($user->email, $user->fresh()->email); + } + public function testCannotBypassDeliveryWithPendingAuthenticatorEnrollment(): void { config([