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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/js/_enqueues/lib/auth-check.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@

if ( height ) {
if ( body && body.hasClass( 'interim-login-success' ) ) {
adoptRefreshNonce( body );
hide();
} else {
parent.css( 'max-height', height + 40 + 'px' );
Expand Down Expand Up @@ -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.
*
Expand Down
21 changes: 18 additions & 3 deletions src/js/_enqueues/wp/heartbeat.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
}
Expand Down
16 changes: 14 additions & 2 deletions src/wp-admin/includes/ajax-actions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 );
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/wp-admin/includes/misc.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
}

Expand Down
1 change: 1 addition & 0 deletions src/wp-includes/default-filters.php
Original file line number Diff line number Diff line change
Expand Up @@ -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' );
Expand Down
27 changes: 26 additions & 1 deletion src/wp-includes/general-template.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
}
31 changes: 31 additions & 0 deletions src/wp-login.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 ] ) ) {
Expand Down Expand Up @@ -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(
'<input type="hidden" id="wp-auth-check-heartbeat-refresh-nonce" value="%s" />',
esc_attr( wp_create_nonce( 'heartbeat-refresh-nonce' ) )
);
}

?>
</div>
<?php
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public function test_wp_refresh_heartbeat_nonces() {

$this->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".' );
}

/**
Expand Down
144 changes: 144 additions & 0 deletions tests/phpunit/tests/ajax/wpAjaxHeartbeat.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
}
}
25 changes: 25 additions & 0 deletions tests/phpunit/tests/general/wpHeartbeatRefreshNonceLife.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

/**
* @group general
* @group template
*
* @covers ::wp_heartbeat_refresh_nonce_life
*/
class Tests_General_wpHeartbeatRefreshNonceLife extends WP_UnitTestCase {

/**
* Tests that the refresh nonce lives longer than other nonces.
*/
public function test_refresh_nonce_life() {
$this->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' ) );
}
}
Loading