From 7f074e5d25e103c0a71bb3611bfd2faef6610064 Mon Sep 17 00:00:00 2001 From: Brian Date: Sat, 17 Oct 2026 21:40:34 +0200 Subject: [PATCH 1/3] Make Two-Factor provider settings network-wide on Multisite MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On Multisite, the enabled providers are now a network option managed by super admins under Network Admin → Settings → Two-Factor, and they apply to every site. Sites show the selection read-only. The main site's saved selection is carried over once; values saved on other sites are ignored. Single site installs are unchanged. --- AGENTS.md | 7 +- TESTS.md | 25 + class-two-factor-core.php | 117 ++- readme.txt | 4 +- settings/class-two-factor-settings.php | 198 ++++- tests/class-two-factor-core.php | 8 +- .../class-two-factor-settings-multisite.php | 686 ++++++++++++++++++ tests/settings/class-two-factor-settings.php | 254 +++++++ two-factor.php | 46 +- 9 files changed, 1302 insertions(+), 43 deletions(-) create mode 100644 tests/settings/class-two-factor-settings-multisite.php create mode 100644 tests/settings/class-two-factor-settings.php diff --git a/AGENTS.md b/AGENTS.md index 0ac2249e..531f0203 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,10 +47,10 @@ The plugin follows a provider pattern. `Two_Factor_Core` owns the login intercep ### Core Files -- **`two-factor.php`** — Entry point. Defines `TWO_FACTOR_DIR` and `TWO_FACTOR_VERSION`, loads all core files (including the settings class), instantiates `Two_Factor_Compat`, and calls `Two_Factor_Core::add_hooks()`. Also registers the wp-admin settings page (Settings → Two-Factor) and the filter callbacks that enforce the site-wide enabled-providers option (`two_factor_filter_enabled_providers`, `two_factor_filter_enabled_providers_for_user`). +- **`two-factor.php`** — Entry point. Defines `TWO_FACTOR_DIR` and `TWO_FACTOR_VERSION`, loads all core files (including the settings class), instantiates `Two_Factor_Compat`, and calls `Two_Factor_Core::add_hooks()`. Also registers the settings page (Settings → Two-Factor; Network Admin → Settings → Two-Factor on multisite) and the filter callbacks that enforce the enabled-providers setting (`two_factor_filter_enabled_providers`, `two_factor_filter_enabled_providers_for_user`). - **`class-two-factor-core.php`** — Central class. Owns the login flow, user meta, nonce management, rate limiting, session tracking, REST API endpoints, and the user profile settings UI. - **`class-two-factor-compat.php`** — Compatibility shims for third-party plugins (currently: Jetpack SSO). New integrations go here; the goal is to avoid any plugin-specific logic outside this file. -- **`settings/class-two-factor-settings.php`** — `Two_Factor_Settings`, renders the site-wide settings screen (Settings → Two-Factor, requires `manage_options`) where admins choose which providers are available on the site. Saving writes the `two_factor_enabled_providers` option; enforcement happens via the filters registered in `two-factor.php`, not in this class. +- **`settings/class-two-factor-settings.php`** — `Two_Factor_Settings`, renders the settings screen where admins choose which providers are available: Settings → Two-Factor (`manage_options`) on single site, Network Admin → Settings → Two-Factor (`manage_network_options`) on multisite, where the setting applies to every site and each site's Settings → Two-Factor shows it read-only (`render_network_managed_page()`). Reads and writes go through `Two_Factor_Core::get_enabled_providers_policy()` and `update_enabled_providers_policy()`; on multisite the form is saved by `save_network_settings()` on `network_admin_edit_two_factor_settings`, which keeps only registered providers and refuses an empty selection. Enforcement happens via the filters registered in `two-factor.php`, not in this class. - **`providers/class-two-factor-provider.php`** — Abstract base class all providers extend. Defines the required interface: `get_label()`, `is_available_for_user()`, `authentication_page()`, `validate_authentication()`, and optional hooks for REST routes, settings UI, and uninstall cleanup. - **`providers/`** — Concrete providers: `class-two-factor-totp.php`, `class-two-factor-email.php`, `class-two-factor-backup-codes.php`, `class-two-factor-dummy.php`. - **`includes/`** — Custom `login_header()` and `login_footer()` template functions that replace the WordPress core versions with additional filter hooks. Excluded from PHPCS because they intentionally deviate from core function signatures. Do not modify files in includes/ directly. They are intentionally kept close to WordPress core function signatures to ease future merging into Core. Any functional changes should go through the filter hooks they expose instead. @@ -102,7 +102,8 @@ New providers should follow this pattern rather than registering hooks from outs | Constant | Option Key | Purpose | |---|---|---| -| `ENABLED_PROVIDERS_OPTION_KEY` | `two_factor_enabled_providers` | Provider class names enabled site-wide via the settings page; never saved means all providers are allowed. | +| `ENABLED_PROVIDERS_OPTION_KEY` | `two_factor_enabled_providers` | Provider class names enabled via the settings page; never saved means all providers are allowed. A network option on multisite (per-site values are ignored there), a site option otherwise. | +| `ENABLED_PROVIDERS_MIGRATED_OPTION_KEY` | `two_factor_enabled_providers_migrated` | Multisite network option recording that the main site's per-site value was carried over to the network option, so that happens only once. | ### REST API diff --git a/TESTS.md b/TESTS.md index d2d3b074..1091fec1 100644 --- a/TESTS.md +++ b/TESTS.md @@ -65,6 +65,7 @@ npm run composer -- test -- --group backup-codes npm run composer -- test -- --group providers npm run composer -- test -- --group core npm run composer -- test -- --group cli +npm run composer -- test -- --group settings # Run a single file npm run composer -- test -- tests/providers/class-two-factor-totp.php @@ -210,6 +211,30 @@ Tests the `Two_Factor_CLI_Command` WP-CLI command class. The WP-CLI runtime is n - `backup-codes generate` — default and `--count` code counts, regeneration replaces the set, enables the provider so codes are usable at login, session destruction when first enabled, unknown-action and missing-argument errors - `unlock` — clears the login throttle for a rate-limited user; no-op message otherwise +### Settings — `tests/settings/class-two-factor-settings.php` + +**Class:** `Tests_Two_Factor_Settings` · **Group:** `settings` + +Tests the enabled-providers setting in both suites: + +- `two_factor_get_enabled_providers_option()` matching `Two_Factor_Core::get_enabled_providers_policy()`, and normalization on save +- Uninstall removing the setting as a site option and as a network option +- Failing closed when the setting leaves none of a user's providers registered +- Single site only (skipped on multisite): `manage_options` capability, plain site option, saving from the settings screen, editors can't save, page registered under Settings + +### Network Settings — `tests/settings/class-two-factor-settings-multisite.php` + +**Class:** `Tests_Two_Factor_Settings_Multisite` · **Groups:** `settings`, `multisite` + +Multisite only (skipped on single site): + +- Per-site values are ignored; a sub-site administrator can't change the setting through the per-site form or the network save handler +- The network setting applies on every site; super admins save it from the network admin, with a valid nonce, keeping only registered providers, and never with an empty selection +- Carrying the main site's per-site value over to the network option, once +- Pages registered under Network Admin → Settings (`manage_network_options`) and, read-only, under Settings (`manage_options`); all providers listed on the network screen only +- The read-only site page: no form, nothing saved, a link to the network settings for network admins only +- Plugin action link pointing to the network settings + ## Test Helpers - **`tests/bootstrap.php`** — Locates the WordPress test library (via `WP_TESTS_DIR` env var, relative path, or `/tmp/wordpress-tests-lib`), loads the plugin via `muplugins_loaded`, then boots the WP test environment. diff --git a/class-two-factor-core.php b/class-two-factor-core.php index 42ef1a85..5b81a319 100644 --- a/class-two-factor-core.php +++ b/class-two-factor-core.php @@ -37,6 +37,16 @@ class Two_Factor_Core { */ const ENABLED_PROVIDERS_OPTION_KEY = 'two_factor_enabled_providers'; + /** + * The network option key recording that the enabled providers were carried over from + * the main site to the network-wide setting on multisite. + * + * @since 0.18.0 + * + * @type string + */ + const ENABLED_PROVIDERS_MIGRATED_OPTION_KEY = 'two_factor_enabled_providers_migrated'; + /** * The user meta nonce key. * @@ -160,7 +170,9 @@ public static function add_hooks( $compat ) { add_filter( 'two_factor_providers', array( __CLASS__, 'enable_dummy_method_for_debug' ) ); // Add Settings link to plugin action links. - add_filter( 'plugin_action_links_' . plugin_basename( TWO_FACTOR_DIR . 'two-factor.php' ), array( __CLASS__, 'add_settings_action_link' ) ); + $plugin_basename = plugin_basename( TWO_FACTOR_DIR . 'two-factor.php' ); + add_filter( 'plugin_action_links_' . $plugin_basename, array( __CLASS__, 'add_settings_action_link' ) ); + add_filter( 'network_admin_plugin_action_links_' . $plugin_basename, array( __CLASS__, 'add_settings_action_link' ) ); $compat->init(); } @@ -254,6 +266,10 @@ public static function uninstall() { delete_option( $option_key ); } + // The enabled providers are a network option on multisite; on single site this deletes the same option again. + delete_network_option( null, self::ENABLED_PROVIDERS_OPTION_KEY ); + delete_network_option( null, self::ENABLED_PROVIDERS_MIGRATED_OPTION_KEY ); + foreach ( $user_meta_keys as $meta_key ) { delete_metadata( 'user', 0, $meta_key, '', true ); } @@ -399,6 +415,99 @@ public static function enable_dummy_method_for_debug( $methods ) { return $methods; } + /** + * Get the providers enabled in the plugin settings. + * + * On multisite this is a network-wide setting, stored as a network option; values saved + * per site are ignored. On single site installs it is a regular option. + * + * @since 0.18.0 + * + * @return array|null Enabled provider keys, possibly empty, or null when the setting has never + * been saved, meaning all providers are allowed. + */ + public static function get_enabled_providers_policy() { + if ( is_multisite() ) { + $enabled = get_network_option( null, self::ENABLED_PROVIDERS_OPTION_KEY, null ); + + if ( null === $enabled && self::maybe_migrate_enabled_providers_policy() ) { + $enabled = get_network_option( null, self::ENABLED_PROVIDERS_OPTION_KEY, null ); + } + } else { + $enabled = get_option( self::ENABLED_PROVIDERS_OPTION_KEY, null ); + } + + if ( null === $enabled ) { + return null; // Never saved — allow everything. + } + + return is_array( $enabled ) ? $enabled : array(); + } + + /** + * Save the providers enabled in the plugin settings. + * + * @since 0.18.0 + * + * @param array $providers Provider keys to enable. + * @return bool True if the value was updated, false otherwise. + */ + public static function update_enabled_providers_policy( array $providers ) { + $providers = array_values( array_unique( array_filter( $providers, 'is_string' ) ) ); + + if ( ! is_multisite() ) { + return update_option( self::ENABLED_PROVIDERS_OPTION_KEY, $providers ); + } + + // A saved network setting takes precedence over anything left to carry over from the main site. + update_network_option( null, self::ENABLED_PROVIDERS_MIGRATED_OPTION_KEY, 1 ); + + return update_network_option( null, self::ENABLED_PROVIDERS_OPTION_KEY, $providers ); + } + + /** + * Get the capability required to view and change the plugin settings. + * + * @since 0.18.0 + * + * @return string + */ + public static function policy_capability() { + return is_multisite() ? 'manage_network_options' : 'manage_options'; + } + + /** + * Carry the main site's enabled providers over to the network-wide setting, once. + * + * Before 0.18.0 the enabled providers were saved per site on multisite, too. Only the main + * site's value is carried over; values saved on other sites are ignored. + * + * @since 0.18.0 + * + * @return bool True if the network setting was saved from the main site's value. + */ + private static function maybe_migrate_enabled_providers_policy() { + if ( get_network_option( null, self::ENABLED_PROVIDERS_MIGRATED_OPTION_KEY ) ) { + return false; + } + + update_network_option( null, self::ENABLED_PROVIDERS_MIGRATED_OPTION_KEY, 1 ); + + // Without a main site, get_blog_option() would read the current site's value instead. + $main_site_id = get_main_site_id(); + if ( ! $main_site_id ) { + return false; + } + + $main_site_enabled = get_blog_option( $main_site_id, self::ENABLED_PROVIDERS_OPTION_KEY, null ); + + if ( ! is_array( $main_site_enabled ) ) { + return false; + } + + return self::update_enabled_providers_policy( $main_site_enabled ); + } + /** * Add Plugin and User Settings link to the plugin action links on the Plugins screen. * @@ -408,7 +517,9 @@ public static function enable_dummy_method_for_debug( $methods ) { * @return string[] Modified array with the User Settings link added. */ public static function add_settings_action_link( $links ) { - $plugin_settings_url = admin_url( 'options-general.php?page=two-factor-settings' ); + $plugin_settings_url = is_multisite() + ? network_admin_url( 'settings.php?page=two-factor-settings' ) + : admin_url( 'options-general.php?page=two-factor-settings' ); $plugin_settings_link = sprintf( '%s', esc_url( $plugin_settings_url ), @@ -425,7 +536,7 @@ public static function add_settings_action_link( $links ) { // Show plugin settings first, then user settings. array_unshift( $links, $user_settings_link ); - if ( current_user_can( 'manage_options' ) ) { + if ( current_user_can( self::policy_capability() ) ) { array_unshift( $links, $plugin_settings_link ); } diff --git a/readme.txt b/readme.txt index 13db7cf2..27b2a002 100644 --- a/readme.txt +++ b/readme.txt @@ -31,7 +31,7 @@ The Two-Factor plugin adds an extra layer of security to your WordPress login by ### For Site Administrators -- **Plugin settings**: The plugin provides a settings page under "Settings → Two-Factor" to configure which providers should be disabled site-wide. +- **Plugin settings**: The plugin provides a settings page under "Settings → Two-Factor" to configure which providers should be disabled site-wide. On Multisite, super admins find it under "Network Admin → Settings → Two-Factor", and it applies to every site in the network; "Settings → Two-Factor" on each site shows it read-only. - **User management**: Administrators can configure 2FA for other users by editing their profiles - **Security recommendations**: Encourage users to enable backup methods to prevent account lockouts @@ -165,7 +165,7 @@ Yes. For passkeys and hardware security keys, you can install the [Two-Factor Pr = Does this plugin work on WordPress Multisite? = -Yes. The Two-Factor plugin is compatible with WordPress Multisite. Each user configures their own 2FA settings via their profile, and because authentication codes are stored in WordPress user meta, the configuration is tied to the user account and valid across all sites in the network. However, there are no network-wide settings — a super admin cannot enforce or configure 2FA globally from the Network Admin dashboard. To manage 2FA for a specific user, edit their profile on any site where they have an account. +Yes. The Two-Factor plugin is compatible with WordPress Multisite. Each user configures their own 2FA settings via their profile, and because authentication codes are stored in WordPress user meta, the configuration is tied to the user account and valid across all sites in the network. Which two-factor providers are available is a network-wide setting as well: super admins choose them under Network Admin → Settings → Two-Factor, and the choice applies to every site. There is no network-wide setting to enforce 2FA for users. To manage 2FA for a specific user, edit their profile on any site where they have an account. = How do I disable 2FA for a user who is locked out? = diff --git a/settings/class-two-factor-settings.php b/settings/class-two-factor-settings.php index b8fc4733..e0a79925 100644 --- a/settings/class-two-factor-settings.php +++ b/settings/class-two-factor-settings.php @@ -1,7 +1,7 @@

' . esc_html__( 'Settings saved.', 'two-factor' ) . '

'; + } - update_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array_values( array_unique( $enabled ) ) ); + // Saved by save_network_settings(), which redirects back here. + if ( is_multisite() ) { + $error = isset( $_GET['error'] ) ? sanitize_key( wp_unslash( $_GET['error'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only displays a notice; no state change occurs here. - echo '

' . esc_html__( 'Settings saved.', 'two-factor' ) . '

'; + if ( 'no_providers' === $error ) { + echo '

' . esc_html__( 'At least one provider must be enabled. No changes were saved.', 'two-factor' ) . '

'; + } elseif ( isset( $_GET['updated'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only displays a notice; no state change occurs here. + echo '

' . esc_html__( 'Settings saved.', 'two-factor' ) . '

'; + } } // Build provider list for display using public core API. @@ -59,15 +66,80 @@ static function ( $value ) { // Default to all providers enabled when the option has never been saved. $all_provider_keys = array_keys( $provider_instances ); - $saved_enabled = get_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, $all_provider_keys ); + $saved_enabled = Two_Factor_Core::get_enabled_providers_policy(); + if ( null === $saved_enabled ) { + $saved_enabled = $all_provider_keys; + } + + if ( is_multisite() ) { + $description = __( 'Choose which Two-Factor providers are available on all sites in this network. All providers are enabled by default.', 'two-factor' ); + $form_action = network_admin_url( 'edit.php?action=' . self::NETWORK_SAVE_ACTION ); + } else { + $description = __( 'Choose which Two-Factor providers are available on this site. All providers are enabled by default.', 'two-factor' ); + $form_action = ''; + } echo '
'; echo '

' . esc_html__( 'Two-Factor Settings', 'two-factor' ) . '

'; echo '

' . esc_html__( 'Enabled Providers', 'two-factor' ) . '

'; - echo '

' . esc_html__( 'Choose which Two-Factor providers are available on this site. All providers are enabled by default.', 'two-factor' ) . '

'; - echo '
'; + echo '

' . esc_html( $description ) . '

'; + echo ''; wp_nonce_field( 'two_factor_save_settings', 'two_factor_settings_nonce' ); + self::render_providers_fieldset( $provider_instances, $saved_enabled, false ); + + submit_button( __( 'Save Settings', 'two-factor' ), 'primary', 'two_factor_settings_submit' ); + echo '
'; + + echo '
'; + } + + /** + * Render the settings read-only, for the sites of a multisite network. + * + * On multisite the settings apply to the whole network and can only be changed in the network admin. + * + * @since 0.18.0 + * + * @return void + */ + public static function render_network_managed_page() { + if ( ! current_user_can( 'manage_options' ) ) { + return; + } + + $provider_instances = self::get_all_providers(); + $enabled = Two_Factor_Core::get_enabled_providers_policy(); + if ( null === $enabled ) { + $enabled = array_keys( $provider_instances ); + } + + echo '
'; + echo '

' . esc_html__( 'Two-Factor Settings', 'two-factor' ) . '

'; + echo '

' . esc_html__( 'The Two-Factor providers are managed for all sites in this network by the network administrators.', 'two-factor' ) . '

'; + + if ( current_user_can( Two_Factor_Core::policy_capability() ) ) { + echo '

' . esc_html__( 'Change the network settings', 'two-factor' ) . '

'; + } + + echo '

' . esc_html__( 'Enabled Providers', 'two-factor' ) . '

'; + + self::render_providers_fieldset( $provider_instances, $enabled, true ); + + echo '
'; + } + + /** + * Render the provider checkboxes. + * + * @since 0.18.0 + * + * @param Two_Factor_Provider[] $provider_instances Providers to list, indexed by provider key. + * @param array $enabled Keys of the enabled providers. + * @param bool $read_only Whether to render disabled checkboxes that aren't submitted. + * @return void + */ + private static function render_providers_fieldset( $provider_instances, $enabled, $read_only ) { echo '
' . esc_html__( 'Providers', 'two-factor' ) . ''; echo ''; @@ -81,7 +153,7 @@ static function ( $value ) { $label = method_exists( $instance, 'get_label' ) ? $instance->get_label() : $provider_key; echo '

'; } @@ -92,10 +164,86 @@ static function ( $value ) { echo '
'; echo '
'; + } - submit_button( __( 'Save Settings', 'two-factor' ), 'primary', 'two_factor_settings_submit' ); - echo ''; + /** + * Save the settings submitted from the network admin, then redirect back to the settings page. + * + * Runs on the `network_admin_edit_two_factor_settings` action. + * + * @since 0.18.0 + * + * @return void + */ + public static function save_network_settings() { + if ( ! current_user_can( Two_Factor_Core::policy_capability() ) ) { + wp_die( esc_html__( 'Sorry, you are not allowed to manage these settings.', 'two-factor' ), 403 ); + } - echo ''; + check_admin_referer( 'two_factor_save_settings', 'two_factor_settings_nonce' ); + + // Only keep registered providers, including those the current settings disable. + $enabled = array_values( array_intersect( self::get_posted_providers(), array_keys( self::get_all_providers() ) ) ); + $redirect = array( 'page' => 'two-factor-settings' ); + + // Without any provider, every user with two-factor enabled would be locked out of the network. + if ( empty( $enabled ) ) { + $redirect['error'] = 'no_providers'; + } else { + Two_Factor_Core::update_enabled_providers_policy( $enabled ); + $redirect['updated'] = 'true'; + } + + wp_safe_redirect( add_query_arg( $redirect, network_admin_url( 'settings.php' ) ) ); + exit; + } + + /** + * Get all registered providers, including those disabled in the settings. + * + * @since 0.18.0 + * + * @return Two_Factor_Provider[] Provider instances indexed by provider key. + */ + private static function get_all_providers() { + $priority = has_filter( 'two_factor_providers', 'two_factor_filter_enabled_providers' ); + + if ( false === $priority ) { + return Two_Factor_Core::get_providers(); + } + + remove_filter( 'two_factor_providers', 'two_factor_filter_enabled_providers', (int) $priority ); + + try { + return Two_Factor_Core::get_providers(); + } finally { + add_filter( 'two_factor_providers', 'two_factor_filter_enabled_providers', (int) $priority ); + } + } + + /** + * Get the provider keys submitted with the settings form. + * + * The caller must verify the nonce first. + * + * @since 0.18.0 + * + * @return string[] + */ + private static function get_posted_providers() { + $posted = isset( $_POST['two_factor_enabled_providers'] ) && is_array( $_POST['two_factor_enabled_providers'] ) ? wp_unslash( $_POST['two_factor_enabled_providers'] ) : array(); // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce verified by the caller; array values sanitized immediately below. + + // Sanitize posted values immediately. + $posted = array_map( 'sanitize_text_field', (array) $posted ); + + // Remove empty values. + return array_values( + array_filter( + $posted, + static function ( $value ) { + return '' !== $value; + } + ) + ); } } diff --git a/tests/class-two-factor-core.php b/tests/class-two-factor-core.php index 7545a543..f70ce004 100644 --- a/tests/class-two-factor-core.php +++ b/tests/class-two-factor-core.php @@ -3983,6 +3983,12 @@ public function test_wp_login_non_two_factor_user() { public function test_add_settings_action_link() { $old_user_id = get_current_user_id(); $admin = self::factory()->user->create_and_get( array( 'role' => 'administrator' ) ); + + // On multisite the plugin settings are network-wide and reserved for network super admins. + if ( is_multisite() ) { + grant_super_admin( $admin->ID ); + } + wp_set_current_user( $admin->ID ); $links = array( 'deactivate' => 'Deactivate' ); @@ -3995,6 +4001,6 @@ public function test_add_settings_action_link() { $first = reset( $result ); $this->assertStringContainsString( 'assertStringContainsString( 'Settings', $first ); - $this->assertStringContainsString( 'options-general.php', $first ); + $this->assertStringContainsString( is_multisite() ? 'network/settings.php' : 'options-general.php', $first ); } } diff --git a/tests/settings/class-two-factor-settings-multisite.php b/tests/settings/class-two-factor-settings-multisite.php new file mode 100644 index 00000000..bf89c648 --- /dev/null +++ b/tests/settings/class-two-factor-settings-multisite.php @@ -0,0 +1,686 @@ +user->create( array( 'role' => 'administrator' ) ); + grant_super_admin( self::$super_admin_id ); + + self::$site_admin_id = $factory->user->create(); + self::$blog_id = $factory->blog->create( array( 'user_id' => self::$site_admin_id ) ); + + self::$member_id = $factory->user->create(); + add_user_to_blog( self::$blog_id, self::$member_id, 'editor' ); + } + + /** + * Clean up test fixtures. + */ + public static function wpTearDownAfterClass() { + if ( ! is_multisite() ) { + return; + } + + revoke_super_admin( self::$super_admin_id ); + wp_delete_site( self::$blog_id ); + } + + /** + * Skip on single site. + */ + public function set_up() { + parent::set_up(); + + $this->skipWithoutMultisite(); + } + + /** + * Clean up the simulated request after each test. + */ + public function tear_down() { + unset( + $_GET['page'], + $_GET['updated'], + $_GET['error'], + $_POST['two_factor_settings_submit'], + $_POST['two_factor_settings_nonce'], + $_POST['two_factor_enabled_providers'], + $_REQUEST['two_factor_settings_nonce'] + ); + + parent::tear_down(); + } + + /** + * Configure TOTP as the only provider for a user. + * + * @param int $user_id User ID. + */ + private function enable_totp_only( $user_id ) { + Two_Factor_Totp::get_instance()->set_user_totp_key( $user_id, Two_Factor_Totp::generate_key() ); + update_user_meta( $user_id, Two_Factor_Core::ENABLED_PROVIDERS_USER_META_KEY, array( 'Two_Factor_Totp' ) ); + update_user_meta( $user_id, Two_Factor_Core::PROVIDER_USER_META_KEY, 'Two_Factor_Totp' ); + } + + /** + * Configure both emailed codes and TOTP for a user. + * + * @param int $user_id User ID. + */ + private function enable_email_and_totp( $user_id ) { + Two_Factor_Totp::get_instance()->set_user_totp_key( $user_id, Two_Factor_Totp::generate_key() ); + update_user_meta( $user_id, Two_Factor_Core::ENABLED_PROVIDERS_USER_META_KEY, array( 'Two_Factor_Email', 'Two_Factor_Totp' ) ); + } + + /** + * Populate the request with a settings form submission for the current user. + * + * @param string[] $providers Provider keys to submit. + */ + private function set_settings_form_post( array $providers ) { + $nonce = wp_create_nonce( 'two_factor_save_settings' ); + + $_POST['two_factor_settings_submit'] = 'Save Settings'; + $_POST['two_factor_settings_nonce'] = $nonce; + $_REQUEST['two_factor_settings_nonce'] = $nonce; + $_POST['two_factor_enabled_providers'] = $providers; + } + + /** + * Submit the settings form to the settings page callback and return its output. + * + * @param string[] $providers Provider keys to submit. + * @return string + */ + private function submit_settings_page( array $providers ) { + $this->set_settings_form_post( $providers ); + + ob_start(); + + try { + two_factor_render_settings_page(); + } finally { + $output = ob_get_clean(); + } + + return $output; + } + + /** + * Run a callback that redirects and exits, and return the redirect location. + * + * @param callable $callback Code that calls wp_safe_redirect() and exits. + * @return string|null The redirect location, or null if there was no redirect. + */ + private function capture_redirect( callable $callback ) { + $redirect_filter = static function ( $location ) { + throw new Two_Factor_Redirect_Exception( $location ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped + }; + + add_filter( 'wp_redirect', $redirect_filter, PHP_INT_MAX ); + + try { + $callback(); + } catch ( Two_Factor_Redirect_Exception $e ) { + return $e->getMessage(); + } finally { + remove_filter( 'wp_redirect', $redirect_filter, PHP_INT_MAX ); + } + + return null; + } + + /** + * Run a callback that is expected to call wp_die(). + * + * @param callable $callback Code expected to die. + * @return bool Whether wp_die() was called. + */ + private function did_die( callable $callback ) { + try { + $this->capture_redirect( $callback ); + } catch ( WPDieException $e ) { + return true; + } + + return false; + } + + /** + * Register settings pages and return the capability of each page under a parent menu. + * + * @param string $parent_slug Parent menu slug. + * @param callable $register Callback that registers the pages. + * @return string[] Capabilities indexed by page slug. + */ + private function get_registered_page_capabilities( $parent_slug, callable $register ) { + global $submenu, $_registered_pages, $_parent_pages; + + $backup = array( $submenu, $_registered_pages, $_parent_pages ); + + try { + $register(); + + return wp_list_pluck( isset( $submenu[ $parent_slug ] ) ? $submenu[ $parent_slug ] : array(), 1, 2 ); + } finally { + list( $submenu, $_registered_pages, $_parent_pages ) = $backup; + } + } + + /** + * Values saved per site before the setting became network-wide are ignored. + * + * @covers Two_Factor_Core::get_enabled_providers_policy + * @covers ::two_factor_filter_enabled_providers + */ + public function test_legacy_subsite_value_is_ignored() { + $this->enable_totp_only( self::$super_admin_id ); + update_blog_option( self::$blog_id, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Email' ) ); + + switch_to_blog( self::$blog_id ); + $provider = Two_Factor_Core::get_primary_provider_for_user( self::$super_admin_id ); + restore_current_blog(); + + $this->assertInstanceOf( Two_Factor_Totp::class, $provider, 'The per-site value does not change the provider on the sub-site' ); + } + + /** + * A sub-site administrator submitting the per-site settings form changes nothing. + * + * @covers Two_Factor_Settings::render_network_managed_page + * @covers ::two_factor_render_settings_page + */ + public function test_subsite_admin_cannot_change_policy() { + $this->enable_totp_only( self::$super_admin_id ); + + switch_to_blog( self::$blog_id ); + wp_set_current_user( self::$site_admin_id ); + + $this->assertTrue( current_user_can( 'manage_options' ), 'The site administrator manages the sub-site options' ); + + $output = $this->submit_settings_page( array( 'Two_Factor_Email' ) ); + $policy = two_factor_get_enabled_providers_option(); + $provider = Two_Factor_Core::get_primary_provider_for_user( self::$super_admin_id ); + + restore_current_blog(); + + $this->assertStringNotContainsString( 'Settings saved.', $output, 'Nothing was saved' ); + $this->assertNull( $policy, 'No provider restriction applies on the sub-site' ); + $this->assertInstanceOf( Two_Factor_Totp::class, $provider, 'The provider used on the sub-site is unchanged' ); + $this->assertNull( + get_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, null ), + 'No network option was written' + ); + } + + /** + * A sub-site administrator can't save the network-wide settings. + * + * @covers Two_Factor_Settings::save_network_settings + */ + public function test_subsite_admin_cannot_save_network_settings() { + switch_to_blog( self::$blog_id ); + wp_set_current_user( self::$site_admin_id ); + $this->set_settings_form_post( array( 'Two_Factor_Email' ) ); + restore_current_blog(); + + $this->assertTrue( + $this->did_die( array( 'Two_Factor_Settings', 'save_network_settings' ) ), + 'Saving was refused' + ); + $this->assertNull( + get_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, null ), + 'No network option was written' + ); + } + + /** + * Saving the network-wide settings requires a valid nonce. + * + * @covers Two_Factor_Settings::save_network_settings + */ + public function test_network_settings_require_valid_nonce() { + wp_set_current_user( self::$super_admin_id ); + $this->set_settings_form_post( array( 'Two_Factor_Email' ) ); + + $_POST['two_factor_settings_nonce'] = 'invalid'; + $_REQUEST['two_factor_settings_nonce'] = 'invalid'; + + $this->assertTrue( + $this->did_die( array( 'Two_Factor_Settings', 'save_network_settings' ) ), + 'Saving was refused' + ); + $this->assertNull( + get_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, null ), + 'No network option was written' + ); + } + + /** + * Saving the network-wide settings with no provider enabled is refused. + * + * @covers Two_Factor_Settings::save_network_settings + */ + public function test_network_settings_refuse_empty_selection() { + update_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Totp' ) ); + wp_set_current_user( self::$super_admin_id ); + + $expected_redirect = add_query_arg( + array( + 'page' => 'two-factor-settings', + 'error' => 'no_providers', + ), + network_admin_url( 'settings.php' ) + ); + + // Nothing ticked: browsers don't submit the field at all. + $this->set_settings_form_post( array() ); + unset( $_POST['two_factor_enabled_providers'] ); + + $this->assertSame( $expected_redirect, $this->capture_redirect( array( 'Two_Factor_Settings', 'save_network_settings' ) ), 'An empty selection is refused' ); + + // Only keys that aren't registered providers. + $this->set_settings_form_post( array( 'Not_A_Provider' ) ); + + $this->assertSame( $expected_redirect, $this->capture_redirect( array( 'Two_Factor_Settings', 'save_network_settings' ) ), 'A selection without registered providers is refused' ); + $this->assertSame( + array( 'Two_Factor_Totp' ), + get_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ), + 'The network setting is unchanged' + ); + } + + /** + * Only registered providers are saved, including ones the current setting disables. + * + * @covers Two_Factor_Settings::save_network_settings + */ + public function test_network_settings_save_only_registered_providers() { + // TOTP is currently disabled, so it isn't among the providers in effect. + update_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Email' ) ); + + wp_set_current_user( self::$super_admin_id ); + $this->set_settings_form_post( array( 'Two_Factor_Totp', 'Not_A_Provider', 'Two_Factor_Backup_Codes' ) ); + + $this->capture_redirect( array( 'Two_Factor_Settings', 'save_network_settings' ) ); + + $this->assertSame( + array( 'Two_Factor_Totp', 'Two_Factor_Backup_Codes' ), + get_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ), + 'Unknown keys are dropped, and a disabled provider can be enabled again' + ); + $this->assertNotFalse( + has_filter( 'two_factor_providers', 'two_factor_filter_enabled_providers' ), + 'The setting is enforced again after saving' + ); + } + + /** + * The network-wide setting applies on every site. + * + * @covers Two_Factor_Core::get_enabled_providers_policy + * @covers ::two_factor_filter_enabled_providers + * @covers ::two_factor_filter_enabled_providers_for_user + */ + public function test_network_policy_applies_on_every_site() { + $this->enable_email_and_totp( self::$member_id ); + update_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Totp', 'Two_Factor_Backup_Codes' ) ); + + foreach ( array( get_main_site_id(), self::$blog_id ) as $blog_id ) { + switch_to_blog( $blog_id ); + $enabled = Two_Factor_Core::get_enabled_providers_for_user( self::$member_id ); + $available = Two_Factor_Core::get_available_providers_for_user( self::$member_id ); + restore_current_blog(); + + $this->assertNotContains( 'Two_Factor_Email', $enabled, "Emailed codes are not enabled on site {$blog_id}" ); + $this->assertSame( array( 'Two_Factor_Totp' ), array_keys( $available ), "Only TOTP is available on site {$blog_id}" ); + } + } + + /** + * A super admin saves the network-wide setting and it applies on every site. + * + * @covers Two_Factor_Settings::save_network_settings + * @covers Two_Factor_Core::update_enabled_providers_policy + */ + public function test_super_admin_can_set_network_policy() { + $this->enable_email_and_totp( self::$member_id ); + + wp_set_current_user( self::$super_admin_id ); + $this->set_settings_form_post( array( 'Two_Factor_Totp', 'Two_Factor_Backup_Codes' ) ); + + $redirect = $this->capture_redirect( array( 'Two_Factor_Settings', 'save_network_settings' ) ); + + $this->assertSame( + add_query_arg( + array( + 'page' => 'two-factor-settings', + 'updated' => 'true', + ), + network_admin_url( 'settings.php' ) + ), + $redirect, + 'Redirects back to the network settings screen' + ); + $this->assertSame( + array( 'Two_Factor_Totp', 'Two_Factor_Backup_Codes' ), + get_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ), + 'The network option was written' + ); + + foreach ( array( get_main_site_id(), self::$blog_id ) as $blog_id ) { + switch_to_blog( $blog_id ); + $enabled = Two_Factor_Core::get_enabled_providers_for_user( self::$member_id ); + restore_current_blog(); + + $this->assertSame( array( 'Two_Factor_Totp' ), array_values( $enabled ), "The setting applies on site {$blog_id}" ); + } + } + + /** + * The main site's saved value is carried over to the network setting once. + * + * @covers Two_Factor_Core::get_enabled_providers_policy + */ + public function test_main_site_value_is_migrated_once() { + delete_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_MIGRATED_OPTION_KEY ); + update_blog_option( get_main_site_id(), Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Totp', 'Two_Factor_Backup_Codes' ) ); + update_blog_option( self::$blog_id, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Email' ) ); + + // The first read happens on the sub-site, which must still use the main site's value. + switch_to_blog( self::$blog_id ); + $policy = Two_Factor_Core::get_enabled_providers_policy(); + restore_current_blog(); + + $this->assertSame( array( 'Two_Factor_Totp', 'Two_Factor_Backup_Codes' ), $policy, 'The main site value is carried over' ); + $this->assertSame( $policy, get_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ), 'The value was saved as the network setting' ); + + update_blog_option( get_main_site_id(), Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Email' ) ); + + $this->assertSame( + array( 'Two_Factor_Totp', 'Two_Factor_Backup_Codes' ), + Two_Factor_Core::get_enabled_providers_policy(), + 'Later per-site changes are ignored' + ); + + delete_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ); + + $this->assertNull( + Two_Factor_Core::get_enabled_providers_policy(), + 'Clearing the network setting does not bring back the per-site value' + ); + } + + /** + * Without a value on the main site there is nothing to carry over, now or later. + * + * @covers Two_Factor_Core::get_enabled_providers_policy + */ + public function test_migration_without_main_site_value_runs_once() { + delete_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_MIGRATED_OPTION_KEY ); + + $this->assertNull( Two_Factor_Core::get_enabled_providers_policy(), 'All providers are allowed' ); + + update_blog_option( get_main_site_id(), Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Email' ) ); + + $this->assertNull( Two_Factor_Core::get_enabled_providers_policy(), 'A per-site value saved later is ignored' ); + } + + /** + * Saving the network setting completes the migration. + * + * @covers Two_Factor_Core::update_enabled_providers_policy + */ + public function test_saving_network_setting_completes_migration() { + delete_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_MIGRATED_OPTION_KEY ); + update_blog_option( get_main_site_id(), Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Email' ) ); + + Two_Factor_Core::update_enabled_providers_policy( array( 'Two_Factor_Totp' ) ); + delete_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ); + + $this->assertNull( Two_Factor_Core::get_enabled_providers_policy(), 'The main site value is not carried over afterwards' ); + } + + /** + * Only network administrators can manage the setting. + * + * @covers Two_Factor_Core::policy_capability + */ + public function test_policy_capability_is_network_wide() { + $this->assertSame( 'manage_network_options', Two_Factor_Core::policy_capability() ); + } + + /** + * The settings page is registered in the network admin, and sites get the read-only page. + * + * @covers ::two_factor_register_admin_hooks + * @covers ::two_factor_add_network_settings_page + * @covers ::two_factor_add_settings_page + */ + public function test_settings_pages_are_registered() { + set_current_screen( 'dashboard-network' ); + wp_set_current_user( self::$super_admin_id ); + + two_factor_register_admin_hooks(); + + $this->assertNotFalse( has_action( 'network_admin_menu', 'two_factor_add_network_settings_page' ), 'Network admin page is registered' ); + $this->assertNotFalse( + has_action( 'network_admin_edit_two_factor_settings', array( 'Two_Factor_Settings', 'save_network_settings' ) ), + 'Network admin save handler is registered' + ); + $this->assertNotFalse( has_action( 'admin_menu', 'two_factor_add_settings_page' ), 'Read-only site page is registered' ); + + $network_pages = $this->get_registered_page_capabilities( 'settings.php', 'two_factor_add_network_settings_page' ); + $site_pages = $this->get_registered_page_capabilities( 'options-general.php', 'two_factor_add_settings_page' ); + + $this->assertArrayHasKey( 'two-factor-settings', $network_pages ); + $this->assertSame( 'manage_network_options', $network_pages['two-factor-settings'] ); + $this->assertArrayHasKey( 'two-factor-settings', $site_pages ); + $this->assertSame( 'manage_options', $site_pages['two-factor-settings'] ); + } + + /** + * Sites show the network-wide setting read-only, and submitting the page saves nothing. + * + * @covers ::two_factor_render_settings_page + * @covers Two_Factor_Settings::render_network_managed_page + */ + public function test_site_settings_page_is_read_only() { + update_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Totp' ) ); + + switch_to_blog( self::$blog_id ); + wp_set_current_user( self::$site_admin_id ); + set_current_screen( 'settings_page_two-factor-settings' ); + + $output = $this->submit_settings_page( array( 'Two_Factor_Email' ) ); + $site_option = get_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ); + + restore_current_blog(); + + $this->assertStringContainsString( 'managed for all sites in this network', $output, 'Explains where the setting is managed' ); + $this->assertStringNotContainsString( 'assertStringNotContainsString( 'name="two_factor_enabled_providers[]"', $output, 'The checkboxes are not submitted' ); + $this->assertMatchesRegularExpression( '/id="provider_Two_Factor_Totp"[^>]*checked=\'checked\'[^>]*disabled=\'disabled\'/', $output, 'TOTP is shown as enabled' ); + $this->assertMatchesRegularExpression( '/id="provider_Two_Factor_Email"(?![^>]*checked)[^>]*disabled=\'disabled\'/', $output, 'Emailed codes are shown as disabled' ); + $this->assertStringNotContainsString( 'page=two-factor-settings', $output, 'Site administrators get no link to the network settings' ); + $this->assertFalse( $site_option, 'Nothing was saved for the site' ); + $this->assertSame( + array( 'Two_Factor_Totp' ), + get_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ), + 'The network setting is unchanged' + ); + } + + /** + * On a site's read-only page, network administrators get a link to the network settings. + * + * @covers Two_Factor_Settings::render_network_managed_page + */ + public function test_site_settings_page_links_network_admins_to_network_settings() { + switch_to_blog( self::$blog_id ); + wp_set_current_user( self::$super_admin_id ); + + ob_start(); + two_factor_render_settings_page(); + $output = ob_get_clean(); + + restore_current_blog(); + + $this->assertStringContainsString( esc_url( network_admin_url( 'settings.php?page=two-factor-settings' ) ), $output ); + } + + /** + * The network settings page explains a refused empty selection. + * + * @covers Two_Factor_Settings::render_settings_page + */ + public function test_network_settings_page_shows_empty_selection_error() { + wp_set_current_user( self::$super_admin_id ); + set_current_screen( 'settings_page_two-factor-settings-network' ); + $_GET['page'] = 'two-factor-settings'; + $_GET['error'] = 'no_providers'; + + ob_start(); + two_factor_render_settings_page(); + $output = ob_get_clean(); + + $this->assertStringContainsString( 'At least one provider must be enabled. No changes were saved.', $output ); + $this->assertStringNotContainsString( 'Settings saved.', $output ); + } + + /** + * The network settings page submits to the network admin save handler, and a submission + * to the page itself saves nothing. + * + * @covers Two_Factor_Settings::render_settings_page + */ + public function test_network_settings_page_renders_network_form() { + update_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Totp' ) ); + + wp_set_current_user( self::$super_admin_id ); + set_current_screen( 'settings_page_two-factor-settings-network' ); + $_GET['page'] = 'two-factor-settings'; + $_GET['updated'] = 'true'; + + $output = $this->submit_settings_page( array( 'Two_Factor_Email' ) ); + + $this->assertStringContainsString( + 'action="' . esc_url( network_admin_url( 'edit.php?action=two_factor_settings' ) ) . '"', + $output, + 'The form submits to the network admin save handler' + ); + $this->assertStringContainsString( 'Settings saved.', $output, 'The notice shows after the redirect back' ); + $this->assertStringContainsString( 'value="Two_Factor_Email"', $output, 'Disabled providers are listed' ); + $this->assertSame( + array( 'Two_Factor_Totp' ), + get_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ), + 'The submission to the page itself was not saved' + ); + } + + /** + * The network settings screen lists every provider so disabled ones can be turned back on, + * while the page parameter alone doesn't lift the restriction elsewhere. + * + * @covers ::two_factor_filter_enabled_providers + */ + public function test_network_settings_screen_lists_all_providers() { + update_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Totp' ) ); + $_GET['page'] = 'two-factor-settings'; + + set_current_screen( 'settings_page_two-factor-settings-network' ); + $network_screen_providers = array_keys( Two_Factor_Core::get_providers() ); + + set_current_screen( 'profile' ); + $site_screen_providers = array_keys( Two_Factor_Core::get_providers() ); + + $this->assertContains( 'Two_Factor_Email', $network_screen_providers, 'All providers are listed on the network settings screen' ); + $this->assertSame( array( 'Two_Factor_Totp' ), $site_screen_providers, 'The setting applies on other screens' ); + } + + /** + * The plugin action link points to the network settings, for network administrators only. + * + * @covers Two_Factor_Core::add_settings_action_link + */ + public function test_settings_action_link_points_to_network_settings() { + $links = array( 'deactivate' => 'Deactivate' ); + + wp_set_current_user( self::$super_admin_id ); + $super_admin_links = Two_Factor_Core::add_settings_action_link( $links ); + + switch_to_blog( self::$blog_id ); + wp_set_current_user( self::$site_admin_id ); + $site_admin_links = Two_Factor_Core::add_settings_action_link( $links ); + restore_current_blog(); + + $this->assertCount( 3, $super_admin_links ); + $this->assertStringContainsString( + esc_url( network_admin_url( 'settings.php?page=two-factor-settings' ) ), + reset( $super_admin_links ), + 'Network administrators get a link to the network settings' + ); + $this->assertCount( 2, $site_admin_links, 'Site administrators only get the user settings link' ); + $this->assertNotFalse( + has_filter( + 'network_admin_plugin_action_links_' . plugin_basename( TWO_FACTOR_DIR . 'two-factor.php' ), + array( 'Two_Factor_Core', 'add_settings_action_link' ) + ), + 'The link is added on the network plugins screen' + ); + } +} diff --git a/tests/settings/class-two-factor-settings.php b/tests/settings/class-two-factor-settings.php new file mode 100644 index 00000000..7f267836 --- /dev/null +++ b/tests/settings/class-two-factor-settings.php @@ -0,0 +1,254 @@ +user->create( array( 'role' => 'administrator' ) ); + self::$editor_id = $factory->user->create( array( 'role' => 'editor' ) ); + } + + /** + * Clean up the simulated request after each test. + */ + public function tear_down() { + unset( + $_POST['two_factor_settings_submit'], + $_POST['two_factor_settings_nonce'], + $_POST['two_factor_enabled_providers'], + $_REQUEST['two_factor_settings_nonce'] + ); + + parent::tear_down(); + } + + /** + * Submit the settings form to the settings page callback and return its output. + * + * @param string[] $providers Provider keys to submit. + * @return string + */ + private function submit_settings_page( array $providers ) { + $nonce = wp_create_nonce( 'two_factor_save_settings' ); + + $_POST['two_factor_settings_submit'] = 'Save Settings'; + $_POST['two_factor_settings_nonce'] = $nonce; + $_REQUEST['two_factor_settings_nonce'] = $nonce; + $_POST['two_factor_enabled_providers'] = $providers; + + ob_start(); + + try { + two_factor_render_settings_page(); + } finally { + $output = ob_get_clean(); + } + + return $output; + } + + /** + * Register settings pages and return the capability of each page under a parent menu. + * + * @param string $parent_slug Parent menu slug. + * @param callable $register Callback that registers the pages. + * @return string[] Capabilities indexed by page slug. + */ + private function get_registered_page_capabilities( $parent_slug, callable $register ) { + global $submenu, $_registered_pages, $_parent_pages; + + $backup = array( $submenu, $_registered_pages, $_parent_pages ); + + try { + $register(); + + return wp_list_pluck( isset( $submenu[ $parent_slug ] ) ? $submenu[ $parent_slug ] : array(), 1, 2 ); + } finally { + list( $submenu, $_registered_pages, $_parent_pages ) = $backup; + } + } + + /** + * The legacy helper returns the same value as the core accessor. + * + * @covers ::two_factor_get_enabled_providers_option + * @covers Two_Factor_Core::get_enabled_providers_policy + */ + public function test_enabled_providers_option_helper_matches_policy() { + $this->assertNull( two_factor_get_enabled_providers_option(), 'Never saved means all providers are allowed' ); + $this->assertNull( Two_Factor_Core::get_enabled_providers_policy(), 'Never saved means all providers are allowed' ); + + Two_Factor_Core::update_enabled_providers_policy( array( 'Two_Factor_Totp' ) ); + + $this->assertSame( array( 'Two_Factor_Totp' ), two_factor_get_enabled_providers_option() ); + $this->assertSame( array( 'Two_Factor_Totp' ), Two_Factor_Core::get_enabled_providers_policy() ); + } + + /** + * Saved provider keys are de-duplicated, and anything but strings is dropped. + * + * @covers Two_Factor_Core::update_enabled_providers_policy + */ + public function test_update_policy_normalizes_providers() { + Two_Factor_Core::update_enabled_providers_policy( + array( 'Two_Factor_Totp', 'Two_Factor_Totp', array( 'Two_Factor_Dummy' ), 'Two_Factor_Email' ) + ); + + $this->assertSame( array( 'Two_Factor_Totp', 'Two_Factor_Email' ), Two_Factor_Core::get_enabled_providers_policy() ); + } + + /** + * Uninstall removes the setting whether it was saved per site or network-wide. + * + * @covers Two_Factor_Core::uninstall + */ + public function test_uninstall_removes_policy_in_both_scopes() { + update_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Email' ) ); + update_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Email' ) ); + update_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_MIGRATED_OPTION_KEY, 1 ); + + Two_Factor_Core::uninstall(); + + $this->assertFalse( get_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ), 'The site option was deleted' ); + $this->assertFalse( get_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ), 'The network option was deleted' ); + $this->assertFalse( get_network_option( null, Two_Factor_Core::ENABLED_PROVIDERS_MIGRATED_OPTION_KEY ), 'The migration flag was deleted' ); + } + + /** + * Narrowing the setting so a user has no usable provider left locks them out instead of + * letting them in with only their password. + * + * @covers Two_Factor_Core::get_available_providers_for_user + * @covers Two_Factor_Core::is_user_using_two_factor + */ + public function test_policy_without_usable_provider_fails_closed() { + $user_id = self::factory()->user->create(); + Two_Factor_Totp::get_instance()->set_user_totp_key( $user_id, Two_Factor_Totp::generate_key() ); + update_user_meta( $user_id, Two_Factor_Core::ENABLED_PROVIDERS_USER_META_KEY, array( 'Two_Factor_Totp' ) ); + + Two_Factor_Core::update_enabled_providers_policy( array( 'Two_Factor_Backup_Codes' ) ); + + $available = Two_Factor_Core::get_available_providers_for_user( $user_id ); + + $this->assertWPError( $available, 'No provider is available' ); + $this->assertSame( 'no_available_2fa_methods', $available->get_error_code() ); + $this->assertTrue( Two_Factor_Core::is_user_using_two_factor( $user_id ), 'Two-factor is still required for the user' ); + } + + /** + * Single site: the setting is managed with `manage_options`. + * + * @covers Two_Factor_Core::policy_capability + */ + public function test_single_site_policy_capability() { + $this->skipWithMultisite(); + + $this->assertSame( 'manage_options', Two_Factor_Core::policy_capability() ); + } + + /** + * Single site: the setting is a regular option. + * + * @covers ::two_factor_get_enabled_providers_option + * @covers ::two_factor_filter_enabled_providers + */ + public function test_single_site_policy_is_a_site_option() { + $this->skipWithMultisite(); + + update_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, array( 'Two_Factor_Totp' ) ); + + $this->assertSame( array( 'Two_Factor_Totp' ), two_factor_get_enabled_providers_option() ); + $this->assertSame( array( 'Two_Factor_Totp' ), array_keys( Two_Factor_Core::get_providers() ) ); + } + + /** + * Single site: an administrator saves the settings from the settings screen. + * + * @covers Two_Factor_Settings::render_settings_page + * @covers ::two_factor_render_settings_page + */ + public function test_single_site_admin_can_save_settings() { + $this->skipWithMultisite(); + + wp_set_current_user( self::$admin_id ); + + $output = $this->submit_settings_page( array( 'Two_Factor_Totp', 'Two_Factor_Totp', '', 'Two_Factor_Backup_Codes' ) ); + + $this->assertStringContainsString( 'Settings saved.', $output ); + $this->assertSame( array( 'Two_Factor_Totp', 'Two_Factor_Backup_Codes' ), get_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ) ); + } + + /** + * Single site: users without `manage_options` can't save the settings. + * + * @covers Two_Factor_Settings::render_settings_page + * @covers ::two_factor_render_settings_page + */ + public function test_single_site_editor_cannot_save_settings() { + $this->skipWithMultisite(); + + wp_set_current_user( self::$editor_id ); + + $output = $this->submit_settings_page( array( 'Two_Factor_Email' ) ); + + $this->assertSame( '', $output, 'Nothing is rendered' ); + $this->assertFalse( get_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ), 'Nothing was saved' ); + } + + /** + * Single site: the settings screen is registered under Settings. + * + * @covers ::two_factor_register_admin_hooks + * @covers ::two_factor_add_settings_page + */ + public function test_single_site_settings_page_is_registered_under_settings() { + $this->skipWithMultisite(); + + set_current_screen( 'dashboard' ); + wp_set_current_user( self::$admin_id ); + + two_factor_register_admin_hooks(); + + $this->assertNotFalse( has_action( 'admin_menu', 'two_factor_add_settings_page' ) ); + $this->assertFalse( has_action( 'network_admin_menu', 'two_factor_add_network_settings_page' ) ); + + $pages = $this->get_registered_page_capabilities( 'options-general.php', 'two_factor_add_settings_page' ); + + $this->assertArrayHasKey( 'two-factor-settings', $pages ); + $this->assertSame( 'manage_options', $pages['two-factor-settings'] ); + } +} diff --git a/two-factor.php b/two-factor.php index 61ddff57..7f93d7b2 100644 --- a/two-factor.php +++ b/two-factor.php @@ -72,6 +72,12 @@ function two_factor_register_admin_hooks() { if ( is_admin() ) { add_action( 'admin_menu', 'two_factor_add_settings_page' ); + + // On multisite the settings are network-wide and changed in the network admin; sites show them read-only. + if ( is_multisite() ) { + add_action( 'network_admin_menu', 'two_factor_add_network_settings_page' ); + add_action( 'network_admin_edit_' . Two_Factor_Settings::NETWORK_SAVE_ACTION, array( 'Two_Factor_Settings', 'save_network_settings' ) ); + } } // Load settings page assets when in admin. @@ -99,6 +105,22 @@ function two_factor_add_settings_page() { ); } +/** + * Add the Two Factor settings page under Settings in the network admin. + * + * @since 0.18.0 + */ +function two_factor_add_network_settings_page() { + add_submenu_page( + 'settings.php', + __( 'Two-Factor Settings', 'two-factor' ), + __( 'Two-Factor', 'two-factor' ), + Two_Factor_Core::policy_capability(), + 'two-factor-settings', + 'two_factor_render_settings_page' + ); +} + /** * Render the settings page via the settings class if available. @@ -106,7 +128,13 @@ function two_factor_add_settings_page() { * @since 0.16 */ function two_factor_render_settings_page() { - if ( ! current_user_can( 'manage_options' ) ) { + // On multisite, sites only show the network-wide settings. + if ( is_multisite() && ! is_network_admin() ) { + Two_Factor_Settings::render_network_managed_page(); + return; + } + + if ( ! current_user_can( Two_Factor_Core::policy_capability() ) ) { return; } @@ -123,20 +151,18 @@ function two_factor_render_settings_page() { /** - * Helper: retrieve the site-enabled providers option. + * Helper: retrieve the enabled providers setting, network-wide on multisite. * Returns null when the option has never been saved (meaning all providers are allowed). * Returns an array (possibly empty) when the admin has explicitly saved a selection. * * @since 0.16 * + * @see Two_Factor_Core::get_enabled_providers_policy() + * * @return array|null */ function two_factor_get_enabled_providers_option() { - $enabled = get_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY, null ); - if ( null === $enabled ) { - return null; // Never saved — allow everything. - } - return is_array( $enabled ) ? $enabled : array(); + return Two_Factor_Core::get_enabled_providers_policy(); } @@ -158,8 +184,10 @@ function two_factor_filter_enabled_providers( $providers ) { } // On the settings page itself, show all providers so admins can change the selection. - $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the current admin page slug only; no state change occurs here. - if ( is_admin() && 'two-factor-settings' === $page ) { + // On multisite that page is only in the network admin. + $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the current admin page slug only; no state change occurs here. + $on_settings_screen = is_multisite() ? is_network_admin() : is_admin(); + if ( $on_settings_screen && 'two-factor-settings' === $page ) { return $providers; } From a50a337d0575adab0cad293fd938b895937c6917 Mon Sep 17 00:00:00 2001 From: Brian Date: Fri, 13 Nov 2026 09:52:59 +0900 Subject: [PATCH 2/3] align equal sign --- two-factor.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/two-factor.php b/two-factor.php index c4f0856e..c548cf0d 100644 --- a/two-factor.php +++ b/two-factor.php @@ -184,7 +184,7 @@ function two_factor_filter_enabled_providers( $providers ) { } // On the settings page itself, show all providers so admins can change the selection. - $current_screen = is_admin() ? get_current_screen() : false; + $current_screen = is_admin() ? get_current_screen() : false; $settings_screen = is_multisite() ? 'settings_page_two-factor-settings-network' : 'settings_page_two-factor-settings'; if ( $current_screen && $settings_screen === $current_screen->base ) { return $providers; From 2ea4dee18b99e8d82cf7f64f93d7d63acffd688f Mon Sep 17 00:00:00 2001 From: masteradhoc <6242098+masteradhoc@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:14:28 +0000 Subject: [PATCH 3/3] Fix conflicting settings test classes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- TESTS.md | 4 ++-- tests/class-two-factor-settings.php | 4 ++++ ...ctor-settings.php => class-two-factor-settings-policy.php} | 4 ++-- 3 files changed, 8 insertions(+), 4 deletions(-) rename tests/settings/{class-two-factor-settings.php => class-two-factor-settings-policy.php} (98%) diff --git a/TESTS.md b/TESTS.md index fba9f814..3698109d 100644 --- a/TESTS.md +++ b/TESTS.md @@ -213,9 +213,9 @@ Tests the `Two_Factor_CLI_Command` WP-CLI command class. The WP-CLI runtime is n - `backup-codes generate` — default and `--count` code counts, regeneration replaces the set, enables the provider so codes are usable at login, session destruction when first enabled, unknown-action and missing-argument errors - `unlock` — clears the login throttle for a rate-limited user; no-op message otherwise -### Settings — `tests/settings/class-two-factor-settings.php` +### Settings Policy — `tests/settings/class-two-factor-settings-policy.php` -**Class:** `Tests_Two_Factor_Settings` · **Group:** `settings` +**Class:** `Tests_Two_Factor_Settings_Policy` · **Group:** `settings` Tests the enabled-providers setting in both suites: diff --git a/tests/class-two-factor-settings.php b/tests/class-two-factor-settings.php index 6c4c7160..59aa3cff 100644 --- a/tests/class-two-factor-settings.php +++ b/tests/class-two-factor-settings.php @@ -31,6 +31,10 @@ public function set_up() { parent::set_up(); $this->old_pagenow = isset( $GLOBALS['pagenow'] ) ? $GLOBALS['pagenow'] : null; + + // On multisite the setting is network-wide; see Tests_Two_Factor_Settings_Multisite. + $this->skipWithMultisite(); + delete_option( Two_Factor_Core::ENABLED_PROVIDERS_OPTION_KEY ); $this->clear_settings_request(); } diff --git a/tests/settings/class-two-factor-settings.php b/tests/settings/class-two-factor-settings-policy.php similarity index 98% rename from tests/settings/class-two-factor-settings.php rename to tests/settings/class-two-factor-settings-policy.php index 7f267836..4c103c98 100644 --- a/tests/settings/class-two-factor-settings.php +++ b/tests/settings/class-two-factor-settings-policy.php @@ -6,12 +6,12 @@ */ /** - * Class Tests_Two_Factor_Settings + * Class Tests_Two_Factor_Settings_Policy * * @package Two_Factor * @group settings */ -class Tests_Two_Factor_Settings extends WP_UnitTestCase { +class Tests_Two_Factor_Settings_Policy extends WP_UnitTestCase { /** * Administrator user ID.