diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index f765b5c6..cec3b3ba 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -820,7 +820,7 @@ public function verify2FA() // must send this one. 'csrf_token' => csrf_token(), ], - $this->recovery_code_service->getStatus($user)->toArray() + $this->recoveryCodesStatusOrEmpty($user) )); } catch (ValidationException $ex) { Log::warning($ex); @@ -928,7 +928,7 @@ public function verify2FARecovery() // must send this one. 'csrf_token' => csrf_token(), ], - $this->recovery_code_service->getStatus($user)->toArray() + $this->recoveryCodesStatusOrEmpty($user) )); } catch (ValidationException $ex) { Log::warning($ex); @@ -1036,6 +1036,26 @@ private function mfaSessionExpired() return $this->unauthorized(['error_code' => MFAConstants::ERROR_CODE_SESSION_EXPIRED]); } + /** + * Recovery-codes standing for the post-verification response, best-effort. + * Callers only reach this once the second factor is redeemed, the session is + * established and postLogin() may already have consumed the OAuth2 memento, + * so a failure here must not turn the sign-in into a 500 that drops + * redirect_url. The login page navigates directly when the fields are absent. + * + * @param User $user + * @return array RecoveryCodesStatus::toArray(), or [] on failure + */ + private function recoveryCodesStatusOrEmpty(User $user): array + { + try { + return $this->recovery_code_service->getStatus($user)->toArray(); + } catch (\Throwable $ex) { + Log::warning($ex); + return []; + } + } + /** * Clears the UI-restoration session keys written when a challenge is * issued (see postLogin()'s mfa_required branch). Companion to diff --git a/app/Validators/CustomValidator.php b/app/Validators/CustomValidator.php index e8c8f1ad..71f38c71 100644 --- a/app/Validators/CustomValidator.php +++ b/app/Validators/CustomValidator.php @@ -225,7 +225,10 @@ private function loadRSAKey(?string $pem, $password = false) if (is_null($pem)) return null; try { $key = PublicKeyLoader::load($pem, $password); - } catch (NoKeyLoadedException $ex) { + } catch (NoKeyLoadedException | \ValueError $ex) { + // ValueError: decrypting with a wrong password can, by chance (~1/256, valid padding), + // produce garbage that phpseclib's ASN.1 parser rejects with a ValueError instead of + // a NoKeyLoadedException return null; } // only RSA keys are valid here (phpseclib 2 RSA::loadKey() also accepted EC keys) diff --git a/resources/js/login/components/recovery_code_form.js b/resources/js/login/components/recovery_code_form.js index 7f54642c..568a72eb 100644 --- a/resources/js/login/components/recovery_code_form.js +++ b/resources/js/login/components/recovery_code_form.js @@ -27,6 +27,9 @@ const RecoveryCodeForm = ({ const handleCancel = (ev) => { ev.preventDefault(); + // A verification is in flight: the sign-in may already be completing + // server-side, so leaving now would strand its late response. + if (disableInput) return; onCancel(); }; diff --git a/resources/js/login/components/two_factor_form.js b/resources/js/login/components/two_factor_form.js index 73ec092b..92baeacb 100644 --- a/resources/js/login/components/two_factor_form.js +++ b/resources/js/login/components/two_factor_form.js @@ -70,6 +70,9 @@ const TwoFactorForm = ({ const handleCancel = (ev) => { ev.preventDefault(); + // A verification is in flight: the sign-in may already be completing + // server-side, so leaving now would strand its late response. + if (disableInput) return; onCancel(); }; diff --git a/resources/js/login/login.js b/resources/js/login/login.js index 1923a6f3..4dbd9c85 100644 --- a/resources/js/login/login.js +++ b/resources/js/login/login.js @@ -143,6 +143,7 @@ class LoginPage extends React.Component { this.onVerify2FA = this.onVerify2FA.bind(this); this.onResend2FA = this.onResend2FA.bind(this); this.onVerifyRecovery = this.onVerifyRecovery.bind(this); + this.proceedAfterVerifiedLogin = this.proceedAfterVerifiedLogin.bind(this); this.onContinueAfterLowRecoveryCodes = this.onContinueAfterLowRecoveryCodes.bind(this); this.onAcknowledgeRecoveryCodes = this.onAcknowledgeRecoveryCodes.bind(this); this.onGenerateNewRecoveryCodes = this.onGenerateNewRecoveryCodes.bind(this); @@ -448,14 +449,12 @@ class LoginPage extends React.Component { // data (never a redirect for this XHR to follow) - a real top-level navigation // to it lets the browser complete any further hop natively, cross-origin // included, which this XHR never could. + // The recovery-codes standing rides along: warn before navigating when + // the user is running low (see proceedAfterVerifiedLogin()). A user with + // no unused codes here most likely never generated any, so 0 is not + // "running low" on this path - that case belongs to enrollment, not here. const { response } = payload; - const redirectUrl = - (response && response.redirect_url) || window.location.href; - if (response && response.recovery_codes_enrollment_required === true) { - this.startRecoveryEnrollment(redirectUrl, response.csrf_token); - return; - } - window.location.href = redirectUrl; + this.proceedAfterVerifiedLogin(response, { warnWhenNoneLeft: false }); }, (error) => { this.handleMfaError(error, "twofactor"); @@ -556,31 +555,8 @@ class LoginPage extends React.Component { verifyRecoveryCode(recoveryCode, this.props.token).then( (payload) => { const { response } = payload; - const redirectUrl = - (response && response.redirect_url) || window.location.href; - // The enrollment modal replaces the low-code banner: a user who has to - // enroll gets a fresh batch instead of a warning about the old one. - if (response && response.recovery_codes_enrollment_required === true) { - this.startRecoveryEnrollment(redirectUrl, response.csrf_token); - return; - } - const remaining = response && response.recovery_codes_remaining; - const threshold = - (response && response.recovery_codes_low_threshold) ?? - DEFAULT_RECOVERY_CODES_LOW_THRESHOLD; - const alreadyDismissed = - sessionStorage.getItem(RECOVERY_CODES_LOW_WARNING_DISMISSED_KEY) === "1"; - - if (typeof remaining === "number" && remaining < threshold && !alreadyDismissed) { - this.setState({ - ...this.state, - lowRecoveryCodesWarning: { remaining, redirectUrl }, - }); - return; - } - - // See onVerify2FA() for rationale on using a real top-level navigation. - window.location.href = redirectUrl; + // The user just burned a code, so 0 left means they used their last one. + this.proceedAfterVerifiedLogin(response, { warnWhenNoneLeft: true }); }, (error) => { this.handleMfaError(error, "recovery"); @@ -701,8 +677,61 @@ class LoginPage extends React.Component { this.startRecoveryEnrollment(enrollment.redirectUrl, enrollment.csrfToken); } + /** + * Shared tail of every successful 2FA verification (email OTP and recovery + * code): show the "running low on recovery codes" warning once per browser + * session, otherwise navigate to the post-login destination. + * + * @param {object} response verification response (redirect_url + recovery-codes standing) + * @param {{warnWhenNoneLeft: boolean}} options whether 0 unused codes should warn + */ + proceedAfterVerifiedLogin(response, { warnWhenNoneLeft }) { + const redirectUrl = + (response && response.redirect_url) || window.location.href; + // The enrollment modal replaces the low-code banner: a user who has to + // enroll gets a fresh batch instead of a warning about the old one. + if (response && response.recovery_codes_enrollment_required === true) { + this.startRecoveryEnrollment(redirectUrl, response.csrf_token); + return; + } + const remaining = response && response.recovery_codes_remaining; + const threshold = + (response && response.recovery_codes_low_threshold) ?? + DEFAULT_RECOVERY_CODES_LOW_THRESHOLD; + // Storage can throw (e.g. site data blocked); the sign-in already completed + // server-side, so treat that as "not dismissed" and never skip navigation. + let alreadyDismissed = false; + try { + alreadyDismissed = + sessionStorage.getItem(RECOVERY_CODES_LOW_WARNING_DISMISSED_KEY) === "1"; + } catch (e) { + alreadyDismissed = false; + } + + const isLow = + typeof remaining === "number" && + remaining < threshold && + (warnWhenNoneLeft || remaining > 0); + + if (isLow && !alreadyDismissed) { + this.setState({ + ...this.state, + lowRecoveryCodesWarning: { remaining, redirectUrl }, + }); + return; + } + + // Real top-level navigation: the backend returns the destination as data so the + // browser completes any cross-origin hop natively (an XHR could not). + window.location.href = redirectUrl; + } + onContinueAfterLowRecoveryCodes() { - sessionStorage.setItem(RECOVERY_CODES_LOW_WARNING_DISMISSED_KEY, "1"); + try { + sessionStorage.setItem(RECOVERY_CODES_LOW_WARNING_DISMISSED_KEY, "1"); + } catch (e) { + // Best-effort: the warning may show again this session, but Continue must navigate. + } window.location.href = this.state.lowRecoveryCodesWarning.redirectUrl; } @@ -974,11 +1003,21 @@ class LoginPage extends React.Component { variant="outlined" className={styles.valid_user_name_chip} label={this.state.user_name} - onDelete={this.handleDelete} + // Switching accounts is not allowed while a verification is + // in flight (disableInput) - its late response would land on + // the password step or navigate somewhere the user already + // left - nor once the low recovery-codes warning is pending, + // since the sign-in already completed server-side and a + // switch would only strand the user beside a stale redirect. + onDelete={ + this.state.lowRecoveryCodesWarning || this.state.disableInput + ? undefined + : this.handleDelete + } /> )} - {showTwoFactorForm && ( + {showTwoFactorForm && !this.state.lowRecoveryCodesWarning && ( )} - {showRecoveryForm && this.state.lowRecoveryCodesWarning && ( + {this.state.lowRecoveryCodesWarning && (
@@ -1018,6 +1058,9 @@ class LoginPage extends React.Component { locked out.