diff --git a/src/js/_enqueues/lib/auth-check.js b/src/js/_enqueues/lib/auth-check.js index f05d6643bf776..c60c6dfeee6d9 100644 --- a/src/js/_enqueues/lib/auth-check.js +++ b/src/js/_enqueues/lib/auth-check.js @@ -51,6 +51,7 @@ if ( height ) { if ( body && body.hasClass( 'interim-login-success' ) ) { + adoptRefreshNonce( body ); hide(); } else { parent.css( 'max-height', height + 40 + 'px' ); @@ -90,6 +91,27 @@ } } + /** + * Adopts the Heartbeat refresh nonce handed over by a successful interim login. + * + * Logging in again starts a new session, and nonces are tied to the session, + * so the refresh nonce this page was rendered with can no longer renew its + * nonces. The login success page carries one for the new session; the next + * Heartbeat exchanges it for fresh nonces. + * + * @since 7.2.0 + * @private + * + * @param {jQuery} body The body of the interim login frame. + */ + function adoptRefreshNonce( body ) { + var refreshNonce = body.find( '#wp-auth-check-heartbeat-refresh-nonce' ).val(); + + if ( refreshNonce && typeof window.heartbeatSettings === 'object' ) { + window.heartbeatSettings.refreshNonce = refreshNonce; + } + } + /** * Hides the authentication form popup. * diff --git a/src/js/_enqueues/wp/heartbeat.js b/src/js/_enqueues/wp/heartbeat.js index 6f89e1db47b6c..cae57154dd7b7 100644 --- a/src/js/_enqueues/wp/heartbeat.js +++ b/src/js/_enqueues/wp/heartbeat.js @@ -429,6 +429,7 @@ data: heartbeatData, interval: settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000, _nonce: typeof window.heartbeatSettings === 'object' ? window.heartbeatSettings.nonce : '', + refresh_nonce: typeof window.heartbeatSettings === 'object' ? window.heartbeatSettings.refreshNonce : '', action: 'heartbeat', screen_id: settings.screenId, has_focus: settings.hasFocus @@ -475,9 +476,23 @@ delete response.heartbeat_nonce; } - // Update the Rest API nonce if set and wp-api loaded. - if ( response.rest_nonce && typeof window.wpApiSettings === 'object' ) { - window.wpApiSettings.nonce = response.rest_nonce; + // Update the heartbeat refresh nonce if set. + if ( response.heartbeat_refresh_nonce && typeof window.heartbeatSettings === 'object' ) { + window.heartbeatSettings.refreshNonce = response.heartbeat_refresh_nonce; + delete response.heartbeat_refresh_nonce; + } + + if ( response.rest_nonce ) { + // Update the Rest API nonce if set and wp-api loaded. + if ( typeof window.wpApiSettings === 'object' ) { + window.wpApiSettings.nonce = response.rest_nonce; + } + + // Update the nonce used by wp.apiFetch, for example in the block editor. + if ( window.wp && wp.apiFetch && wp.apiFetch.nonceMiddleware ) { + wp.apiFetch.nonceMiddleware.nonce = response.rest_nonce; + } + // This nonce is required for api-fetch through heartbeat.tick. // delete response.rest_nonce; } diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index 076549b218b82..b36e5923ca5c7 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -3466,6 +3466,19 @@ function wp_ajax_heartbeat() { $data = wp_unslash( (array) $_POST['data'] ); } + if ( false === $nonce_state ) { + /* + * The Heartbeat nonce has expired. Only hand out fresh nonces in exchange + * for a valid long-lived refresh nonce, which can only be obtained from a + * page rendered by the server. Otherwise the client has to reload. + */ + $refresh_nonce = ! empty( $_POST['refresh_nonce'] ) ? $_POST['refresh_nonce'] : ''; + + if ( ! wp_verify_nonce( $refresh_nonce, 'heartbeat-refresh-nonce' ) ) { + wp_send_json( array( 'nonces_expired' => true ) ); + } + } + if ( 1 !== $nonce_state ) { /** * Filters the nonces to send to the New/Edit Post screen. @@ -3479,8 +3492,7 @@ function wp_ajax_heartbeat() { $response = apply_filters( 'wp_refresh_nonces', $response, $data, $screen_id ); if ( false === $nonce_state ) { - // User is logged in but nonces have expired. - $response['nonces_expired'] = true; + // Nonces were refreshed with the refresh nonce, skip processing the stale request data. wp_send_json( $response ); } } diff --git a/src/wp-admin/includes/misc.php b/src/wp-admin/includes/misc.php index 0b412dd56511f..6543967dac24e 100644 --- a/src/wp-admin/includes/misc.php +++ b/src/wp-admin/includes/misc.php @@ -1378,6 +1378,7 @@ function wp_refresh_metabox_loader_nonces( $response, $data ) { * Adds the latest Heartbeat and REST API nonce to the Heartbeat response. * * @since 5.0.0 + * @since 7.2.0 Added the Heartbeat refresh nonce. * * @param array $response The Heartbeat response. * @return array The Heartbeat response. @@ -1389,6 +1390,9 @@ function wp_refresh_heartbeat_nonces( $response ) { // Refresh the Heartbeat nonce. $response['heartbeat_nonce'] = wp_create_nonce( 'heartbeat-nonce' ); + // Rotate the long-lived Heartbeat refresh nonce. + $response['heartbeat_refresh_nonce'] = wp_create_nonce( 'heartbeat-refresh-nonce' ); + return $response; } diff --git a/src/wp-includes/default-filters.php b/src/wp-includes/default-filters.php index 3c1234f9cfa8e..756fc13ac67d0 100644 --- a/src/wp-includes/default-filters.php +++ b/src/wp-includes/default-filters.php @@ -520,6 +520,7 @@ // Default settings for heartbeat. add_filter( 'heartbeat_settings', 'wp_heartbeat_settings' ); +add_filter( 'nonce_life', 'wp_heartbeat_refresh_nonce_life', 10, 2 ); // Check if the user is logged out. add_action( 'admin_enqueue_scripts', 'wp_auth_check_load' ); diff --git a/src/wp-includes/general-template.php b/src/wp-includes/general-template.php index bfb400cbda4cd..76532a5701cdd 100644 --- a/src/wp-includes/general-template.php +++ b/src/wp-includes/general-template.php @@ -5767,6 +5767,7 @@ function wp_required_field_message() { * Outputs the nonce used in the heartbeat XHR. * * @since 3.6.0 + * @since 7.2.0 Added the `refreshNonce` setting. * * @param array $settings * @return array Heartbeat settings. @@ -5777,8 +5778,32 @@ function wp_heartbeat_settings( $settings ) { } if ( is_user_logged_in() ) { - $settings['nonce'] = wp_create_nonce( 'heartbeat-nonce' ); + $settings['nonce'] = wp_create_nonce( 'heartbeat-nonce' ); + $settings['refreshNonce'] = wp_create_nonce( 'heartbeat-refresh-nonce' ); } return $settings; } + +/** + * Sets the lifespan of the Heartbeat refresh nonce. + * + * The refresh nonce works like an OAuth refresh token: it cannot authorize any + * action by itself, it can only be exchanged through Heartbeat for fresh nonces + * once the regular nonces have expired, for example after a device slept or a + * browser tab was suspended. Like all nonces it is tied to the session token, + * so it stops working when the user logs out. + * + * @since 7.2.0 + * + * @param int $lifespan Lifespan of nonces in seconds. + * @param string|int $action The nonce action. + * @return int Lifespan of the nonce in seconds. + */ +function wp_heartbeat_refresh_nonce_life( $lifespan, $action = -1 ) { + if ( 'heartbeat-refresh-nonce' === $action ) { + return 2 * WEEK_IN_SECONDS; + } + + return $lifespan; +} diff --git a/src/wp-login.php b/src/wp-login.php index 5a8df12b01c5e..f89276c04c988 100644 --- a/src/wp-login.php +++ b/src/wp-login.php @@ -1309,6 +1309,20 @@ function wp_login_viewport_meta() { $reauth = ! empty( $_REQUEST['reauth'] ); + /* + * Remember the logged-in cookie of the session an interim login starts, + * so the success page can create nonces for that session. + */ + $interim_logged_in_cookie = ''; + if ( $interim_login ) { + add_action( + 'set_logged_in_cookie', + static function ( $logged_in_cookie ) use ( &$interim_logged_in_cookie ) { + $interim_logged_in_cookie = $logged_in_cookie; + } + ); + } + $user = wp_signon( array(), $secure_cookie ); if ( empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) { @@ -1354,6 +1368,23 @@ function wp_login_viewport_meta() { $interim_login = 'success'; login_header( '', $message ); + if ( $interim_logged_in_cookie ) { + /* + * Nonces are tied to the session token, and logging in again + * starts a new session, so the page behind the login dialog + * now holds a Heartbeat refresh nonce nothing will accept. + * Hand it one for the new session: the page reads it from this + * same-origin frame and exchanges it for fresh nonces. + */ + $_COOKIE[ LOGGED_IN_COOKIE ] = $interim_logged_in_cookie; + wp_set_current_user( $user->ID ); + + printf( + '', + esc_attr( wp_create_nonce( 'heartbeat-refresh-nonce' ) ) + ); + } + ?> assertNotFalse( wp_verify_nonce( $result['rest_nonce'], 'wp_rest' ), 'The rest_nonce should be valid for "wp_rest".' ); $this->assertNotFalse( wp_verify_nonce( $result['heartbeat_nonce'], 'heartbeat-nonce' ), 'The heartbeat_nonce should be valid for "heartbeat-nonce".' ); + $this->assertNotFalse( wp_verify_nonce( $result['heartbeat_refresh_nonce'], 'heartbeat-refresh-nonce' ), 'The heartbeat_refresh_nonce should be valid for "heartbeat-refresh-nonce".' ); } /** diff --git a/tests/phpunit/tests/ajax/wpAjaxHeartbeat.php b/tests/phpunit/tests/ajax/wpAjaxHeartbeat.php index 87d49987b5752..32e6b942494ef 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHeartbeat.php +++ b/tests/phpunit/tests/ajax/wpAjaxHeartbeat.php @@ -164,4 +164,148 @@ public function test_with_invalid_nonce() { $this->assertNotEmpty( $response['wp_autosave'] ); $this->assertFalse( $response['wp_autosave']['success'] ); } + + public function tear_down() { + unset( $_COOKIE[ LOGGED_IN_COOKIE ] ); + parent::tear_down(); + } + + /** + * Tests that an expired Heartbeat nonce without a refresh nonce does not return fresh nonces. + */ + public function test_expired_nonce_without_refresh_nonce_returns_nonces_expired_only() { + wp_set_current_user( self::$admin_id ); + + $_POST = array( + 'action' => 'heartbeat', + '_nonce' => 'expired123', + ); + + $response = $this->make_heartbeat_request(); + + $this->assertSame( array( 'nonces_expired' => true ), $response ); + } + + /** + * Tests that an expired Heartbeat nonce with an invalid refresh nonce does not return fresh nonces. + */ + public function test_expired_nonce_with_invalid_refresh_nonce_returns_nonces_expired_only() { + wp_set_current_user( self::$admin_id ); + + $_POST = array( + 'action' => 'heartbeat', + '_nonce' => 'expired123', + 'refresh_nonce' => 'invalid123', + ); + + $response = $this->make_heartbeat_request(); + + $this->assertSame( array( 'nonces_expired' => true ), $response ); + } + + /** + * Tests that an expired Heartbeat nonce with a valid refresh nonce returns fresh nonces. + */ + public function test_expired_nonce_with_valid_refresh_nonce_returns_fresh_nonces() { + wp_set_current_user( self::$admin_id ); + + $_POST = array( + 'action' => 'heartbeat', + '_nonce' => 'expired123', + 'refresh_nonce' => wp_create_nonce( 'heartbeat-refresh-nonce' ), + ); + + $response = $this->make_heartbeat_request(); + + $this->assertArrayNotHasKey( 'nonces_expired', $response, 'Nonces should have been refreshed.' ); + $this->assertSame( 1, wp_verify_nonce( $response['rest_nonce'], 'wp_rest' ), 'The REST API nonce should be fresh.' ); + $this->assertSame( 1, wp_verify_nonce( $response['heartbeat_nonce'], 'heartbeat-nonce' ), 'The Heartbeat nonce should be fresh.' ); + $this->assertSame( 1, wp_verify_nonce( $response['heartbeat_refresh_nonce'], 'heartbeat-refresh-nonce' ), 'The refresh nonce should be rotated.' ); + } + + /** + * Tests that a refresh nonce belonging to another user does not return fresh nonces. + */ + public function test_expired_nonce_with_other_users_refresh_nonce_returns_nonces_expired_only() { + wp_set_current_user( self::$editor_id ); + $refresh_nonce = wp_create_nonce( 'heartbeat-refresh-nonce' ); + + wp_set_current_user( self::$admin_id ); + + $_POST = array( + 'action' => 'heartbeat', + '_nonce' => 'expired123', + 'refresh_nonce' => $refresh_nonce, + ); + + $response = $this->make_heartbeat_request(); + + $this->assertSame( array( 'nonces_expired' => true ), $response ); + } + + /** + * Tests that nonces from before an interim login need the refresh nonce of the new session. + * + * Logging in again through the interim login dialog starts a new session. + * The page behind the dialog keeps the nonces of the old one, so its own + * refresh nonce can no longer renew them; the login success page hands it a + * refresh nonce for the new session instead. + */ + public function test_expired_session_nonces_renew_with_refresh_nonce_of_new_session() { + wp_set_current_user( self::$admin_id ); + + $this->use_session( self::$admin_id ); + $stale_heartbeat_nonce = wp_create_nonce( 'heartbeat-nonce' ); + $stale_refresh_nonce = wp_create_nonce( 'heartbeat-refresh-nonce' ); + + // The interim login starts a new session. + $this->use_session( self::$admin_id ); + + $_POST = array( + 'action' => 'heartbeat', + '_nonce' => $stale_heartbeat_nonce, + 'refresh_nonce' => $stale_refresh_nonce, + ); + + $this->assertSame( + array( 'nonces_expired' => true ), + $this->make_heartbeat_request(), + 'A refresh nonce from the previous session should not renew nonces.' + ); + + $_POST['refresh_nonce'] = wp_create_nonce( 'heartbeat-refresh-nonce' ); + $this->_last_response = ''; + + $response = $this->make_heartbeat_request(); + + $this->assertArrayNotHasKey( 'nonces_expired', $response, 'Nonces should have been refreshed.' ); + $this->assertSame( 1, wp_verify_nonce( $response['heartbeat_nonce'], 'heartbeat-nonce' ), 'The Heartbeat nonce should belong to the new session.' ); + $this->assertSame( 1, wp_verify_nonce( $response['rest_nonce'], 'wp_rest' ), 'The REST API nonce should belong to the new session.' ); + } + + /** + * Points the logged-in cookie at a new session for a user. + * + * @param int $user_id User ID. + */ + private function use_session( $user_id ) { + $expiration = time() + DAY_IN_SECONDS; + $token = WP_Session_Tokens::get_instance( $user_id )->create( $expiration ); + $_COOKIE[ LOGGED_IN_COOKIE ] = wp_generate_auth_cookie( $user_id, $expiration, 'logged_in', $token ); + } + + /** + * Makes a Heartbeat request and returns the decoded response. + * + * @return array The decoded Heartbeat response. + */ + private function make_heartbeat_request() { + try { + $this->_handleAjax( 'heartbeat' ); + } catch ( WPAjaxDieContinueException $e ) { + unset( $e ); + } + + return json_decode( $this->_last_response, true ); + } } diff --git a/tests/phpunit/tests/general/wpHeartbeatRefreshNonceLife.php b/tests/phpunit/tests/general/wpHeartbeatRefreshNonceLife.php new file mode 100644 index 0000000000000..56216542fec11 --- /dev/null +++ b/tests/phpunit/tests/general/wpHeartbeatRefreshNonceLife.php @@ -0,0 +1,25 @@ +assertSame( 2 * WEEK_IN_SECONDS, apply_filters( 'nonce_life', DAY_IN_SECONDS, 'heartbeat-refresh-nonce' ) ); + } + + /** + * Tests that other nonces keep their lifespan. + */ + public function test_other_nonce_life_is_unchanged() { + $this->assertSame( DAY_IN_SECONDS, apply_filters( 'nonce_life', DAY_IN_SECONDS, 'heartbeat-nonce' ) ); + $this->assertSame( DAY_IN_SECONDS, apply_filters( 'nonce_life', DAY_IN_SECONDS, 'wp_rest' ) ); + } +}