From 8dbc467e398f511da253aceb7bb8b113472b56d1 Mon Sep 17 00:00:00 2001 From: Brian Date: Fri, 2 Oct 2026 21:57:15 +0000 Subject: [PATCH] add fallback feature and error page --- CLI/class-two-factor-cli-command.php | 2 +- TESTS.md | 3 +- class-two-factor-core.php | 210 ++++++++++++--------- readme.txt | 6 +- tests/class-two-factor-core.php | 159 ++++++++++++++++ tests/cli/class-two-factor-cli-command.php | 25 +++ 6 files changed, 317 insertions(+), 88 deletions(-) diff --git a/CLI/class-two-factor-cli-command.php b/CLI/class-two-factor-cli-command.php index 7aba2a50c..37f3ec07e 100644 --- a/CLI/class-two-factor-cli-command.php +++ b/CLI/class-two-factor-cli-command.php @@ -130,7 +130,7 @@ public function status( $args, $assoc_args ) { 'user_id' => $user->ID, 'user_login' => $user->user_login, 'using_2fa' => $using_2fa ? 'true' : 'false', - 'primary_provider' => $primary ? $primary->get_key() : '', + 'primary_provider' => $primary && ! is_wp_error( $primary ) ? $primary->get_key() : '', 'enabled_providers' => implode( ', ', $enabled_providers ), 'backup_codes_remaining' => $backup_codes_remaining, ), diff --git a/TESTS.md b/TESTS.md index d2d3b0746..893ec0160 100644 --- a/TESTS.md +++ b/TESTS.md @@ -86,6 +86,7 @@ The largest test file. Covers the full authentication lifecycle managed by `Two_ - Hook registration (`add_hooks`) - Provider registration and retrieval (`get_providers`, `get_enabled_providers_for_user`, `get_available_providers_for_user`, `get_primary_provider_for_user`) +- Fail-closed fallback when a user's stored providers are unregistered or can't be used (used-up recovery codes, missing TOTP secret): emailed codes, or a lockout when email is turned off - Login interception (`filter_authenticate`, `show_two_factor_login`, `process_provider`) - Login nonce creation, verification, and deletion - Rate limiting (`get_user_time_delay`, `is_user_rate_limited`, `clear_login_rate_limit`) @@ -202,7 +203,7 @@ Tests `Two_Factor_Dummy_Secure` (a fixture that always _fails_ authentication, u Tests the `Two_Factor_CLI_Command` WP-CLI command class. The WP-CLI runtime is not loaded during PHPUnit, so the suite loads lightweight test doubles for `WP_CLI`, `WP_CLI_Command`, and the `WP_CLI\Utils` helpers (see Test Helpers) that capture output for assertions and throw on `error()`/`confirm()`: - User resolution by ID, login, and email; "user not found" errors -- `status` — output for users with and without 2FA, backup-code count, `--format` passthrough +- `status` — output for users with and without 2FA, locked-out users, backup-code count, `--format` passthrough - `list-providers` — registered providers listed, `--format` passthrough - `enable` — enabling secret-free providers; session destruction on change; refusing TOTP (no stale "Phase 3" pointer) and backup codes; unknown provider and missing-argument errors - `disable` (single provider) — removal leaves others intact, session destruction on change, idempotent no-op, confirmation required without `--yes` diff --git a/class-two-factor-core.php b/class-two-factor-core.php index 42ef1a85b..1016bf6c0 100644 --- a/class-two-factor-core.php +++ b/class-two-factor-core.php @@ -723,10 +723,10 @@ public static function get_enabled_providers_for_user( $user = null ) { * @see Two_Factor_Core::get_enabled_providers_for_user() * * @param int|WP_User $user Optional. User ID, or WP_User object of the the user. Defaults to current user. - * @return Two_Factor_Provider[]|WP_Error List of provider instances, or a WP_Error if the user's stored - * providers are no longer registered and the fallback provider - * (`Two_Factor_Email` by default, see `two_factor_fallback_provider_for_user`) - * doesn't resolve to a registered, available provider. + * @return Two_Factor_Provider[]|WP_Error List of provider instances, or a WP_Error if none of the user's stored + * providers can be used and the fallback provider (`Two_Factor_Email` by + * default, see `two_factor_fallback_provider_for_user`) doesn't resolve + * to a registered, available provider. */ public static function get_available_providers_for_user( $user = null ) { $user = self::fetch_user( $user ); @@ -739,82 +739,120 @@ public static function get_available_providers_for_user( $user = null ) { $configured_providers = array(); $stored_providers = self::get_stored_provider_keys_for_user( $user ); + foreach ( $providers as $provider_key => $provider ) { + if ( in_array( $provider_key, $enabled_providers, true ) && $provider->is_available_for_user( $user ) ) { + $configured_providers[ $provider_key ] = $provider; + } + } + + // Without providers stored in meta the user never set up two-factor, so there's nothing to fall back from. + if ( ! empty( $configured_providers ) || empty( $stored_providers ) ) { + return $configured_providers; + } + /** - * If the user has providers stored in meta but none of them are still registered, force - * emailed codes on where available so removed or deprecated providers can't drop the user - * to single-factor auth ('failing open'). + * The user has providers stored in meta but none of them can be used. Force emailed codes on where + * available so the user can't drop to single-factor auth ('failing open'). This covers: * - * "No longer registered" is deliberately cause-agnostic: a provider dropped by plugin - * deactivation, by the site-wide settings, or by `two_factor_providers_for_user` is treated - * identically, because the outcome for the user is identical. + * - 'unregistered': none of the stored providers are still registered. A provider dropped by + * plugin deactivation, by the site-wide settings, or by `two_factor_providers_for_user` is + * treated identically, because the outcome for the user is identical. + * - 'unavailable': the enabled providers are registered but not available for the user, such + * as recovery codes that have all been used, or an authenticator app with no secret stored. * * If any stored provider IS still registered, an empty enabled list means * `two_factor_enabled_providers_for_user` cleared it on purpose, and that must be respected. */ - if ( empty( $enabled_providers ) && ! empty( $stored_providers ) ) { - $still_registered = array_intersect( $stored_providers, array_keys( $providers ) ); - - if ( empty( $still_registered ) ) { - /** - * Filter the provider forced on when none of a user's stored providers are still registered. - * - * Returning a key that is not registered, or that the provider itself reports as unavailable - * for this user, is treated as "no fallback": the method returns a `no_available_2fa_methods` - * WP_Error rather than allowing the user through with one factor. - * - * The returned provider must be usable without any prior per-user setup (like the email - * provider is), since the user has no working provider left to configure it through: - * - * add_filter( 'two_factor_fallback_provider_for_user', function() { - * return 'Two_Factor_Backup_Codes'; // Wrong: requires codes to already be generated. - * } ); - * - * A fallback that is not already available for the user resolves to the WP_Error branch, - * not to a silent single-factor login. - * - * @since 0.17.0 - * - * @param string $fallback_provider Provider key to force on. Default 'Two_Factor_Email'. - * @param int $user_id The user ID. - * @param string[] $stored_providers Provider keys stored for the user, none of which are registered. - */ - $fallback_provider = apply_filters( - 'two_factor_fallback_provider_for_user', - 'Two_Factor_Email', - $user->ID, - $stored_providers - ); + if ( ! empty( $enabled_providers ) ) { + $reason = 'unavailable'; + } elseif ( empty( array_intersect( $stored_providers, array_keys( $providers ) ) ) ) { + $reason = 'unregistered'; + } else { + return $configured_providers; + } - if ( - is_string( $fallback_provider ) - && isset( $providers[ $fallback_provider ] ) - && $providers[ $fallback_provider ]->is_available_for_user( $user ) - ) { - // Force the fallback provider to 'on'. - $enabled_providers[] = $fallback_provider; - } else { - // Fail closed: an invalid, unregistered, or unavailable fallback locks the user - // out pending admin intervention, rather than letting them through with one factor. - return new WP_Error( - 'no_available_2fa_methods', - __( 'Error: You have Two Factor method(s) enabled, but the provider(s) no longer exist. Please contact a site administrator for assistance.', 'two-factor' ), - array( - 'user_providers_raw' => $stored_providers, - 'available_providers' => array_keys( $providers ), - 'fallback_provider' => $fallback_provider, - ) - ); - } - } + /** + * Filter the provider forced on when none of a user's stored providers can be used. + * + * Returning a key that is not registered, or that the provider itself reports as unavailable + * for this user, is treated as "no fallback": the method returns a `no_available_2fa_methods` + * or `no_usable_2fa_methods` WP_Error rather than allowing the user through with one factor. + * + * The returned provider must be usable without any prior per-user setup (like the email + * provider is), since the user has no working provider left to configure it through: + * + * add_filter( 'two_factor_fallback_provider_for_user', function() { + * return 'Two_Factor_Backup_Codes'; // Wrong: requires codes to already be generated. + * } ); + * + * A fallback that is not already available for the user resolves to the WP_Error branch, + * not to a silent single-factor login. + * + * @since 0.17.0 + * @since 0.18.0 Also applied when the enabled providers are registered but unavailable, and added `$reason`. + * + * @param string $fallback_provider Provider key to force on. Default 'Two_Factor_Email'. + * @param int $user_id The user ID. + * @param string[] $stored_providers Provider keys stored for the user. + * @param string $reason 'unregistered' if none of the stored providers are still registered, + * 'unavailable' if the enabled providers aren't available for the user. + */ + $fallback_provider = apply_filters( + 'two_factor_fallback_provider_for_user', + 'Two_Factor_Email', + $user->ID, + $stored_providers, + $reason + ); + + if ( + is_string( $fallback_provider ) + && isset( $providers[ $fallback_provider ] ) + && $providers[ $fallback_provider ]->is_available_for_user( $user ) + ) { + // Force the fallback provider to 'on'. + return array( $fallback_provider => $providers[ $fallback_provider ] ); + } + + // Fail closed: an invalid, unregistered, or unavailable fallback locks the user + // out pending admin intervention, rather than letting them through with one factor. + $error_data = array( + 'user_providers_raw' => $stored_providers, + 'available_providers' => array_keys( $providers ), + 'fallback_provider' => $fallback_provider, + ); + + if ( 'unregistered' === $reason ) { + return new WP_Error( + 'no_available_2fa_methods', + __( 'Error: You have Two Factor method(s) enabled, but the provider(s) no longer exist. Please contact a site administrator for assistance.', 'two-factor' ), + $error_data + ); } - foreach ( $providers as $provider_key => $provider ) { - if ( in_array( $provider_key, $enabled_providers, true ) && $provider->is_available_for_user( $user ) ) { - $configured_providers[ $provider_key ] = $provider; + if ( in_array( 'Two_Factor_Backup_Codes', $enabled_providers, true ) ) { + $message = __( 'Error: You have used all of your recovery codes. Please ask a site administrator to generate new ones.', 'two-factor' ); + } else { + $labels = array(); + foreach ( $enabled_providers as $provider_key ) { + $labels[] = isset( $providers[ $provider_key ] ) ? $providers[ $provider_key ]->get_label() : $provider_key; } + + $message = sprintf( + /* translators: %s: comma-separated list of two-factor method names. */ + _n( + 'Error: Your two-factor method (%s) is not set up. Please ask a site administrator to reset it.', + 'Error: Your two-factor methods (%s) are not set up. Please ask a site administrator to reset them.', + count( $labels ), + 'two-factor' + ), + implode( ', ', $labels ) + ); } - return $configured_providers; + $error_data['enabled_providers'] = $enabled_providers; + + return new WP_Error( 'no_usable_2fa_methods', $message, $error_data ); } /** @@ -825,7 +863,7 @@ public static function get_available_providers_for_user( $user = null ) { * @param int|WP_User $user Optional. User ID, or WP_User object of the the user. Defaults to current user. * @param null|string|object $preferred_provider Optional. The name of the provider, the provider, or empty. * @return null|object|WP_Error The provider, null if none is available, or a WP_Error if the user has - * provider(s) enabled that are no longer registered (see + * provider(s) enabled but none can be used (see * Two_Factor_Core::get_primary_provider_for_user()). */ public static function get_provider_for_user( $user = null, $preferred_provider = null ) { @@ -892,7 +930,7 @@ private static function get_primary_provider_key_selected_for_user( $user ) { * * @param int|WP_User $user Optional. User ID, or WP_User object of the the user. Defaults to current user. * @return object|null|WP_Error Provider instance, null if the user has none configured, or a WP_Error if the - * user has provider(s) enabled that are no longer registered. Callers that render + * user has provider(s) enabled but none can be used. Callers that render * shared admin UI (e.g. list tables) must not `wp_die()` on the WP_Error case, since * that would break the page for everyone, not just the affected user. */ @@ -906,7 +944,7 @@ public static function get_primary_provider_for_user( $user = null ) { $available_providers = self::get_available_providers_for_user( $user ); if ( is_wp_error( $available_providers ) ) { - // The user's configured methods don't exist, and there was no replacement to swap in. Bubble the + // None of the user's methods can be used, and there was no replacement to swap in. Bubble the // error up instead of dying here — this can run from contexts (like the Users list table) where // killing the whole request would break the page for an admin who isn't even the affected user. return $available_providers; @@ -971,9 +1009,9 @@ public static function is_user_using_two_factor( $user = null ) { * @param bool $is_required Whether two-factor is required for the user. Default true when the user has a primary provider. * @param WP_User $user The user being checked. */ - // A WP_Error means the user has a provider enabled that's no longer registered. Still treat them as - // "using" two-factor so the login requirement isn't dropped (failing open) just because their specific - // method disappeared. WP_Error is a non-null object, so !empty() already covers it. + // A WP_Error means the user has providers enabled but none can be used. Still treat them as "using" + // two-factor so the login requirement isn't dropped (failing open) just because their methods + // disappeared or can't be used. WP_Error is a non-null object, so !empty() already covers it. return (bool) apply_filters( 'two_factor_is_required_for_user', ! empty( $provider ), $user ); } @@ -1251,7 +1289,7 @@ public static function clear_password_reset_notice( $user ) { public static function login_html( $user, $login_nonce, $redirect_to, $error_msg = '', $provider = null, $action = 'validate_2fa' ) { $provider = self::get_provider_for_user( $user, $provider ); if ( is_wp_error( $provider ) ) { - // The user's configured methods don't exist, and there was no replacement to swap in. This is the + // None of the user's methods can be used, and there was no replacement to swap in. This is the // user's own login screen, so it's appropriate to stop here with a specific, actionable message. wp_die( esc_html( $provider->get_error_message() ) ); } @@ -1263,7 +1301,7 @@ public static function login_html( $user, $login_nonce, $redirect_to, $error_msg $available_providers = self::get_available_providers_for_user( $user ); if ( is_wp_error( $available_providers ) ) { - // If it returned an error, the configured methods don't exist, and it couldn't swap in a replacement. + // If it returned an error, none of the methods can be used, and it couldn't swap in a replacement. wp_die( esc_html( $available_providers->get_error_message() ) ); } @@ -1890,7 +1928,7 @@ public static function validate_login_form_2fa( $user, $nonce = '', $provider = $provider = self::get_provider_for_user( $user, $provider ); if ( is_wp_error( $provider ) ) { - // The user's configured methods don't exist, and there was no replacement to swap in. This is the + // None of the user's methods can be used, and there was no replacement to swap in. This is the // user's own login attempt, so it's appropriate to stop here with a specific, actionable message. wp_die( esc_html( $provider->get_error_message() ) ); } @@ -2090,7 +2128,7 @@ public static function revalidate_login_form_2fa( $nonce = '', $provider = '', $ $provider = self::get_provider_for_user( $user, $provider ); if ( is_wp_error( $provider ) ) { - // The user's configured methods don't exist, and there was no replacement to swap in. This is the + // None of the user's methods can be used, and there was no replacement to swap in. This is the // user's own session revalidation, so it's appropriate to stop here with a specific, actionable message. wp_die( esc_html( $provider->get_error_message() ) ); } @@ -2441,10 +2479,14 @@ public static function manage_users_custom_column( $output, $column_name, $user_ $provider = self::get_primary_provider_for_user( $user_id ); if ( is_wp_error( $provider ) ) { - // The user has a provider enabled that's no longer registered on the site. Show a clear, - // non-fatal indicator instead of erroring out — this must never wp_die(), since that would - // truncate the Users list table for every admin viewing the page, not just this one user's row. - return sprintf( '%s', esc_html__( 'Error: legacy 2FA method', 'two-factor' ) ); + // None of the user's methods can be used. Show a clear, non-fatal indicator instead of + // erroring out — this must never wp_die(), since that would truncate the Users list table + // for every admin viewing the page, not just this one user's row. + $label = 'no_usable_2fa_methods' === $provider->get_error_code() + ? __( 'Error: no usable 2FA method', 'two-factor' ) + : __( 'Error: legacy 2FA method', 'two-factor' ); + + return sprintf( '%s', esc_html( $label ) ); } if ( ! $provider ) { @@ -2471,8 +2513,8 @@ public static function user_two_factor_options( $user ) { $available_providers_or_error = self::get_available_providers_for_user( $user ); if ( is_wp_error( $available_providers_or_error ) ) { - // The user has provider(s) enabled that are no longer registered on the site. Surface the existing - // admin-contact message on their own profile screen (where they can act on it) rather than crashing. + // None of the user's methods can be used and there's no fallback. Surface the admin-contact + // message on their own profile screen (where they can act on it) rather than crashing. self::add_error( $available_providers_or_error ); $enabled_providers = array(); } else { diff --git a/readme.txt b/readme.txt index 504c6689f..4ed48596f 100644 --- a/readme.txt +++ b/readme.txt @@ -93,7 +93,7 @@ Here is a list of action and filter hooks provided by the plugin: - `two_factor_providers_for_user` filter overrides the available two-factor providers for a specific user. Array values are instances of provider classes and the user object `WP_User` is available as the second argument. - `two_factor_enabled_providers_for_user` filter overrides the list of two-factor providers enabled for a user. First argument is an array of enabled provider classnames as values, the second argument is the user ID. - `two_factor_is_required_for_user` filter controls whether two-factor authentication is required for a user. Return `false` to bypass the two-factor flow (e.g. for trusted IP addresses). First argument is a boolean (whether the user has a primary provider configured), the second argument is the `WP_User` object. -- `two_factor_fallback_provider_for_user` filter overrides the provider forced on when none of a user's stored two-factor providers are still registered (e.g. after a provider plugin is deactivated). Defaults to `Two_Factor_Email`. First argument is the provider classname, the second is the user ID, the third is the array of provider classnames that were stored for the user but are no longer registered. The returned provider must be registered and available to the user (`is_available_for_user()`), or the user is shown an error instead of being let through with a fallback. +- `two_factor_fallback_provider_for_user` filter overrides the provider forced on when none of a user's stored two-factor providers can be used, either because they are no longer registered (e.g. after a provider plugin is deactivated) or because they aren't available for the user (e.g. all recovery codes have been used). Defaults to `Two_Factor_Email`. First argument is the provider classname, the second is the user ID, the third is the array of provider classnames stored for the user, and the fourth is the reason: `unregistered` or `unavailable`. The returned provider must be registered and available to the user (`is_available_for_user()`), or the user is shown an error instead of being let through with a fallback. - `two_factor_user_authenticated` action which receives the logged in `WP_User` object as the first argument for determining the logged in user right after the authentication workflow. - `two_factor_user_api_login_enable` filter restricts authentication for REST API and XML-RPC to application passwords only. Provides the user ID as the second argument. - `two_factor_email_token_ttl` filter overrides the time interval in seconds that an email token is considered after generation. Accepts the time in seconds as the first argument and the ID of the `WP_User` object being authenticated. @@ -147,7 +147,9 @@ To report a security issue, please visit the [WordPress HackerOne](https://hacke = What if I lose access to all my authentication methods? = -If you have backup codes enabled, you can use one of those to regain access. If you don't have backup codes or have used them all, you'll need to contact your site administrator to reset your account. This is why it's important to always enable backup codes and keep them in a secure location. +If you have backup codes enabled, you can use one of those to regain access. If you don't have backup codes, you'll need to contact your site administrator to reset your account. This is why it's important to always enable backup codes and keep them in a secure location. + +If none of your two-factor methods can be used anymore, for example because you have used all your backup codes, you'll be sent a code by email instead. If the site has turned off the email method, you'll need to contact your site administrator to generate new backup codes or reset your account. = Why do I need to re-verify my two-factor method when changing two-factor settings? = diff --git a/tests/class-two-factor-core.php b/tests/class-two-factor-core.php index 7545a543d..153fc9e12 100644 --- a/tests/class-two-factor-core.php +++ b/tests/class-two-factor-core.php @@ -3680,6 +3680,165 @@ public function test_get_available_providers_for_user_fails_closed_on_invalid_fa } } + /** + * Ensure a user whose only method is recovery codes keeps a second factor once all codes are used, + * and that a session that never passed two-factor can't change their two-factor settings. + * + * @covers Two_Factor_Core::get_available_providers_for_user + * @covers Two_Factor_Core::is_user_using_two_factor + * @covers Two_Factor_Core::current_user_can_update_two_factor_options + */ + public function test_get_available_providers_for_user_falls_back_when_recovery_codes_are_used_up() { + $user = self::factory()->user->create_and_get(); + $backup_codes = Two_Factor_Backup_Codes::get_instance(); + $codes = $backup_codes->generate_codes( $user, array( 'number' => 1 ) ); + Two_Factor_Core::enable_provider_for_user( $user->ID, 'Two_Factor_Backup_Codes' ); + + $this->assertArrayHasKey( 'Two_Factor_Backup_Codes', Two_Factor_Core::get_available_providers_for_user( $user->ID ), 'Recovery codes are available while codes remain' ); + + $this->assertTrue( $backup_codes->validate_code( $user, $codes[0] ) ); + + $this->assertSame( + array( 'Two_Factor_Email' ), + array_keys( Two_Factor_Core::get_available_providers_for_user( $user->ID ) ), + 'Emailed codes are forced on once all recovery codes are used' + ); + $this->assertSame( 'Two_Factor_Email', Two_Factor_Core::get_primary_provider_for_user( $user->ID )->get_key() ); + $this->assertTrue( Two_Factor_Core::is_user_using_two_factor( $user->ID ), 'The user still needs a second factor to log in' ); + + // The WP test framework blocks cookies at priority 10, so check for the plugin's block at PHP_INT_MAX. + $this->assertFalse( has_filter( 'send_auth_cookies', '__return_false', PHP_INT_MAX ) ); + Two_Factor_Core::filter_authenticate( $user ); + $this->assertTrue( has_filter( 'send_auth_cookies', '__return_false', PHP_INT_MAX ), 'The password alone does not set auth cookies' ); + + // A session from a password-only login has no two-factor data. + wp_set_current_user( $user->ID ); + wp_set_auth_cookie( $user->ID ); + $this->assertFalse( Two_Factor_Core::is_current_user_session_two_factor() ); + $this->assertFalse( Two_Factor_Core::current_user_can_update_two_factor_options( 'save' ), 'A session without two-factor cannot change two-factor settings' ); + + wp_set_current_user( 0 ); + } + + /** + * Ensure a user with an authenticator app enabled but no secret stored gets the email fallback. + * + * @covers Two_Factor_Core::get_available_providers_for_user + */ + public function test_get_available_providers_for_user_falls_back_when_totp_secret_is_missing() { + $user = self::factory()->user->create_and_get(); + + update_user_meta( $user->ID, Two_Factor_Core::ENABLED_PROVIDERS_USER_META_KEY, array( 'Two_Factor_Totp' ) ); + + $this->assertSame( + array( 'Two_Factor_Email' ), + array_keys( Two_Factor_Core::get_available_providers_for_user( $user->ID ) ), + 'Emailed codes are forced on when the authenticator app has no secret' + ); + $this->assertTrue( Two_Factor_Core::is_user_using_two_factor( $user->ID ) ); + } + + /** + * Ensure the user is locked out with a specific message when all recovery codes are used and the + * email method is turned off site-wide. + * + * @covers Two_Factor_Core::get_available_providers_for_user + * @covers Two_Factor_Core::manage_users_custom_column + */ + public function test_get_available_providers_for_user_fails_closed_when_recovery_codes_are_used_up_and_email_is_disabled() { + $user = self::factory()->user->create_and_get(); + + update_user_meta( $user->ID, Two_Factor_Core::ENABLED_PROVIDERS_USER_META_KEY, array( 'Two_Factor_Backup_Codes' ) ); + update_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Totp', 'Two_Factor_Backup_Codes' ) ); + + try { + $result = Two_Factor_Core::get_available_providers_for_user( $user->ID ); + + $this->assertInstanceOf( WP_Error::class, $result ); + $this->assertSame( 'no_usable_2fa_methods', $result->get_error_code() ); + $this->assertSame( 'Error: You have used all of your recovery codes. Please ask a site administrator to generate new ones.', $result->get_error_message() ); + $this->assertSame( array( 'Two_Factor_Backup_Codes' ), $result->get_error_data()['enabled_providers'] ); + $this->assertTrue( Two_Factor_Core::is_user_using_two_factor( $user->ID ), 'User is still treated as using two-factor (fail closed)' ); + $this->assertStringContainsString( 'no usable 2FA method', Two_Factor_Core::manage_users_custom_column( '', 'two-factor', $user->ID ) ); + } finally { + delete_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ); + } + } + + /** + * Ensure the lockout message names the method when it isn't recovery codes. + * + * @covers Two_Factor_Core::get_available_providers_for_user + */ + public function test_get_available_providers_for_user_fails_closed_when_totp_secret_is_missing_and_email_is_disabled() { + $user = self::factory()->user->create_and_get(); + + update_user_meta( $user->ID, Two_Factor_Core::ENABLED_PROVIDERS_USER_META_KEY, array( 'Two_Factor_Totp' ) ); + update_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Totp', 'Two_Factor_Backup_Codes' ) ); + + try { + $result = Two_Factor_Core::get_available_providers_for_user( $user->ID ); + + $this->assertInstanceOf( WP_Error::class, $result ); + $this->assertSame( 'no_usable_2fa_methods', $result->get_error_code() ); + $this->assertSame( 'Error: Your two-factor method (Authenticator App) is not set up. Please ask a site administrator to reset it.', $result->get_error_message() ); + } finally { + delete_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ); + } + } + + /** + * Ensure the fallback filter is told why it runs, and that its return value is used. + * + * @covers Two_Factor_Core::get_available_providers_for_user + */ + public function test_fallback_provider_filter_receives_reason() { + $user = self::factory()->user->create_and_get(); + $args = array(); + + $filter = function ( $fallback_provider, $user_id, $stored_providers, $reason ) use ( &$args ) { + $args = array( $user_id, $stored_providers, $reason ); + + return 'Two_Factor_Dummy'; + }; + + add_filter( 'two_factor_fallback_provider_for_user', $filter, 10, 4 ); + + try { + update_user_meta( $user->ID, Two_Factor_Core::ENABLED_PROVIDERS_USER_META_KEY, array( 'Two_Factor_Backup_Codes' ) ); + $this->assertSame( array( 'Two_Factor_Dummy' ), array_keys( Two_Factor_Core::get_available_providers_for_user( $user->ID ) ) ); + $this->assertSame( array( $user->ID, array( 'Two_Factor_Backup_Codes' ), 'unavailable' ), $args ); + + update_user_meta( $user->ID, Two_Factor_Core::ENABLED_PROVIDERS_USER_META_KEY, array( 'Two_Factor_Missing' ) ); + $this->assertSame( array( 'Two_Factor_Dummy' ), array_keys( Two_Factor_Core::get_available_providers_for_user( $user->ID ) ) ); + $this->assertSame( array( $user->ID, array( 'Two_Factor_Missing' ), 'unregistered' ), $args ); + } finally { + remove_filter( 'two_factor_fallback_provider_for_user', $filter, 10 ); + } + } + + /** + * Ensure providers added by a filter for a user who never set up two-factor don't trigger the fallback. + * + * @covers Two_Factor_Core::get_available_providers_for_user + */ + public function test_get_available_providers_for_user_ignores_unconfigured_providers_added_by_filter() { + $user = self::factory()->user->create_and_get(); + + $filter = function () { + return array( 'Two_Factor_Totp' ); + }; + + add_filter( 'two_factor_enabled_providers_for_user', $filter ); + + try { + $this->assertSame( array(), Two_Factor_Core::get_available_providers_for_user( $user->ID ) ); + $this->assertFalse( Two_Factor_Core::is_user_using_two_factor( $user->ID ) ); + } finally { + remove_filter( 'two_factor_enabled_providers_for_user', $filter ); + } + } + /** * Verify process_provider() returns WP_Error when no provider is given. * diff --git a/tests/cli/class-two-factor-cli-command.php b/tests/cli/class-two-factor-cli-command.php index 2885e13c7..9f9b8d7f4 100644 --- a/tests/cli/class-two-factor-cli-command.php +++ b/tests/cli/class-two-factor-cli-command.php @@ -269,6 +269,31 @@ public function test_status_reports_backup_code_count() { $this->assertSame( 4, $this->last_format()['items'][0]['backup_codes_remaining'] ); } + /** + * A user locked out because none of their methods can be used is reported without a fatal error. + * + * @covers Two_Factor_CLI_Command::status + */ + public function test_status_for_locked_out_user() { + update_user_meta( $this->user->ID, Two_Factor_Core::ENABLED_PROVIDERS_USER_META_KEY, array( 'Two_Factor_Totp' ) ); + + $filter = function () { + return 'Two_Factor_Nonexistent'; + }; + + add_filter( 'two_factor_fallback_provider_for_user', $filter ); + + try { + $this->command->status( array( 'cli_test_user' ), array() ); + } finally { + remove_filter( 'two_factor_fallback_provider_for_user', $filter ); + } + + $item = $this->last_format()['items'][0]; + $this->assertSame( 'true', $item['using_2fa'] ); + $this->assertSame( '', $item['primary_provider'] ); + } + /* * --------------------------------------------------------------------- * list-providers