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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions app/Http/Controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<string,int> 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
Expand Down
5 changes: 4 additions & 1 deletion app/Validators/CustomValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions resources/js/login/components/recovery_code_form.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
};

Expand Down
3 changes: 3 additions & 0 deletions resources/js/login/components/two_factor_form.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
};

Expand Down
115 changes: 79 additions & 36 deletions resources/js/login/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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
}
/>
)}
</Typography>
{showTwoFactorForm && (
{showTwoFactorForm && !this.state.lowRecoveryCodesWarning && (
<TwoFactorForm
otpCode={this.state.twoFactorCode}
otpError={this.state.errors.twofactor}
Expand Down Expand Up @@ -1006,8 +1045,9 @@ class LoginPage extends React.Component {
onCancel={this.resetToPasswordFlow}
/>
)}
{showRecoveryForm && this.state.lowRecoveryCodesWarning && (
{this.state.lowRecoveryCodesWarning && (
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
romanetar marked this conversation as resolved.
Resolved
<div
role="alert"
className={recoveryCodesStyles.low_code_warning}
data-testid="low-recovery-codes-warning"
>
Expand All @@ -1018,6 +1058,9 @@ class LoginPage extends React.Component {
locked out.
</Typography>
<Button
// The verify form that held focus unmounts when the warning
// appears; move keyboard focus to the only way forward.
autoFocus
variant="contained"
color="primary"
onClick={this.onContinueAfterLowRecoveryCodes}
Expand Down
71 changes: 71 additions & 0 deletions tests/TwoFactorLoginFlowTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -669,10 +669,31 @@ public function testSuccessfulOTPVerificationCompletesLogin(): void
$this->assertStringStartsWith('http', $payload['redirect_url']);
$this->assertTrue(Auth::check());

// Same recovery-codes standing as verify2FARecovery() so the login page can warn
// about low codes after an email OTP sign-in (RecoveryCodesStatus::toArray()).
$this->assertSame(0, $payload['recovery_codes_remaining'] ?? null);
$this->assertSame((int) Config::get('auth.recovery_codes.count'), $payload['recovery_codes_total'] ?? null);
$this->assertSame((int) Config::get('auth.recovery_codes.low_threshold'), $payload['recovery_codes_low_threshold'] ?? null);

$admin = $this->user(self::ADMIN_EMAIL);
$this->assertGreaterThan(0, $this->countAudit($admin->getId(), TwoFactorAuditLog::EventChallengeSucceeded));
}

public function testOTPVerificationReportsUnusedRecoveryCodesRemaining(): void
{
$admin = $this->user(self::ADMIN_EMAIL);
$this->createRecoveryCode($admin, 'UNUSEDCODEONE', false);
$this->createRecoveryCode($admin, 'UNUSEDCODETWO', false);
$this->createRecoveryCode($admin, 'BURNEDCODE', true);

$this->postLogin(self::ADMIN_EMAIL, self::SEED_PASSWORD);
$response = $this->verify($this->latestOtpCode(self::ADMIN_EMAIL));

$this->assertResponseStatus(200);
$payload = json_decode($response->getContent(), true);
$this->assertSame(2, $payload['recovery_codes_remaining'] ?? null, 'used codes must not be counted');
}

public function testFailedOTPVerificationReturnsErrorAndIncrementsCounter(): void
{
$this->postLogin(self::ADMIN_EMAIL, self::SEED_PASSWORD);
Expand Down Expand Up @@ -1397,6 +1418,56 @@ public function testRecoveryAuditFailureDoesNotBlockLogin(): void
$this->assertTrue(Auth::check(), 'session must be established despite the audit failure');
}

public function testRecoveryCodesStatusFailureDoesNotBlockOTPLogin(): void
{
// The recovery-codes standing is best-effort: it is read after the OTP is
// redeemed and the session established, so a failure must NOT 500 the
// user - the response still carries redirect_url, just without the status.
$this->failRecoveryCodesStatus();

$this->postLogin(self::ADMIN_EMAIL, self::SEED_PASSWORD);
$response = $this->verify($this->latestOtpCode(self::ADMIN_EMAIL));

$this->assertEquals(200, $response->getStatusCode(), 'a recovery-codes status failure must not fail the login');
$this->assertTrue(Auth::check(), 'session must be established despite the status failure');
$payload = json_decode($response->getContent(), true);
$this->assertStringStartsWith('http', $payload['redirect_url'] ?? '');
$this->assertArrayNotHasKey('recovery_codes_remaining', $payload);
}

public function testRecoveryCodesStatusFailureDoesNotBlockRecoveryLogin(): void
{
$admin = $this->user(self::ADMIN_EMAIL);
$plain = 'RECOVERYSTATUSFAIL' . strtoupper(uniqid());
$this->createRecoveryCode($admin, $plain, false);
$this->failRecoveryCodesStatus();

$this->postLogin(self::ADMIN_EMAIL, self::SEED_PASSWORD);
$response = $this->recovery($plain);

$this->assertEquals(200, $response->getStatusCode(), 'a recovery-codes status failure must not fail the login');
$this->assertTrue(Auth::check(), 'session must be established despite the status failure');
$payload = json_decode($response->getContent(), true);
$this->assertStringStartsWith('http', $payload['redirect_url'] ?? '');
$this->assertArrayNotHasKey('recovery_codes_remaining', $payload);
}

private function failRecoveryCodesStatus(): void
{
// Only getStatus() fails: the login flow itself also depends on this service
// (e.g. MFAGateService::requiresRecoveryCodeEnrollment()), so every other
// method passes through to the real implementation (final, so no partial mock).
$real = $this->app->make(IRecoveryCodeService::class);
$mock = \Mockery::mock(IRecoveryCodeService::class);
foreach ((new \ReflectionClass(IRecoveryCodeService::class))->getMethods() as $method) {
$name = $method->getName();
if ($name === 'getStatus') continue;
$mock->shouldReceive($name)->andReturnUsing(fn (...$args) => $real->{$name}(...$args));
}
$mock->shouldReceive('getStatus')->andThrow(new \RuntimeException('recovery codes store unavailable'));
$this->app->instance(IRecoveryCodeService::class, $mock);
}

public function testDeviceTrustFailureDoesNotBlockLogin(): void
{
// Device-trust enrollment is best-effort: by the time it runs the OTP is
Expand Down
11 changes: 11 additions & 0 deletions tests/js/login/components/recovery-code-form.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,17 @@ describe('RecoveryCodeForm', () => {
expect(baseProps.onBackToOtp).not.toHaveBeenCalled();
});

it('"Cancel" is ignored while a verification is in flight, and works again once it ends', () => {
const onCancel = jest.fn();
const { rerender } = render(<RecoveryCodeForm {...baseProps} onCancel={onCancel} disableInput={true} />);
fireEvent.click(screen.getByTestId('cancel-link'));
expect(onCancel).not.toHaveBeenCalled();

rerender(<RecoveryCodeForm {...baseProps} onCancel={onCancel} disableInput={false} />);
fireEvent.click(screen.getByTestId('cancel-link'));
expect(onCancel).toHaveBeenCalledTimes(1);
});

it('typing in the field reports the raw value to the parent', () => {
// Normalization lives in LoginPage.onRecoveryCodeChange(); the form must
// hand over the untouched event so that stays the single source of truth.
Expand Down
11 changes: 11 additions & 0 deletions tests/js/login/components/two-factor-form.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@ describe('TwoFactorForm', () => {
expect(screen.queryByText(/Code expires in/)).not.toBeInTheDocument();
});

it('"Cancel" is ignored while a verification is in flight, and works again once it ends', () => {
const onCancel = jest.fn();
const { rerender } = render(<TwoFactorForm {...baseProps} onCancel={onCancel} disableInput={true} />);
fireEvent.click(screen.getByTestId('cancel-link'));
expect(onCancel).not.toHaveBeenCalled();

rerender(<TwoFactorForm {...baseProps} onCancel={onCancel} disableInput={false} />);
fireEvent.click(screen.getByTestId('cancel-link'));
expect(onCancel).toHaveBeenCalledTimes(1);
});

it('VERIFY button is disabled when otpCode is empty', () => {
render(<TwoFactorForm {...baseProps} otpCode="" />);
// MUI Button spreads unknown props to its root <button>; disabled is set on the native element.
Expand Down
Loading
Loading