Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/wp-remote-users-sync/functions.php
+++ b/wp-remote-users-sync/functions.php
@@ -48,7 +48,7 @@
if ( empty( $wp_hasher ) ) {
require_once ABSPATH . WPINC . '/class-phpass.php';
- $wp_hasher = new PasswordHash( 8, true ); // @codingStandardsIgnoreLine
+ $wp_hasher = new PasswordHash( 8, true ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
}
do_action( 'wprus_password', $password );
--- a/wp-remote-users-sync/inc/api/admin/class-wprus-admin-meta.php
+++ b/wp-remote-users-sync/inc/api/admin/class-wprus-admin-meta.php
@@ -0,0 +1,166 @@
+<?php
+/**
+ * Handle administrative metadata-setting requests.
+ *
+ * @package Wprus
+ */
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+/** Retrieve and validate outgoing metadata settings. */
+class Wprus_Admin_Meta {
+
+ /**
+ * Administrative endpoint transport.
+ *
+ * @var Wprus_Api_Admin
+ */
+ protected $api;
+
+ /**
+ * Plugin settings.
+ *
+ * @var Wprus_Settings
+ */
+ protected $settings;
+
+ /**
+ * Store the shared endpoint transport and settings.
+ *
+ * @param Wprus_Api_Admin $api Administrative endpoint transport.
+ * @param Wprus_Settings $settings Plugin settings.
+ * @param bool $init_hooks Whether to register WordPress hooks.
+ */
+ public function __construct( $api, $settings, $init_hooks = false ) {
+ $this->api = $api;
+ $this->settings = $settings;
+
+ if ( $init_hooks ) {
+ add_action( 'wp_ajax_wprus_admin_notify_outgoing_meta_remote', array( $this, 'notify_outgoing_meta_remote' ), 10, 0 );
+ }
+ }
+
+ /**
+ * Register the outgoing metadata handler.
+ *
+ * @param array $handlers Registered administrative handlers.
+ * @return array Registered administrative handlers.
+ */
+ public function register_handler( $handlers ) {
+ $handlers['outgoing_meta'] = array( $this, 'handle_outgoing_meta_notification' );
+
+ return $handlers;
+ }
+
+ /**
+ * Return outgoing metadata keys configured for the requesting site.
+ *
+ * @param array $data Administrative action data.
+ * @return array|WP_Error Configured keys or an error.
+ */
+ public function handle_outgoing_meta_notification( $data ) {
+
+ if ( ! is_array( $data ) || empty( $data['base_url'] ) || ! is_string( $data['base_url'] ) ) {
+ return new WP_Error( 'wprus_invalid_outgoing_meta_request', __( 'Invalid outgoing metadata request.', 'wprus' ), array( 'status' => 400 ) );
+ }
+
+ $site = $this->settings->get_site( $data['base_url'] );
+
+ if ( ! $site || ! isset( $site['url'] ) || untrailingslashit( $site['url'] ) !== untrailingslashit( $data['base_url'] ) ) {
+ return new WP_Error( 'wprus_unknown_outgoing_meta_site', __( 'The requesting site is not configured.', 'wprus' ), array( 'status' => 400 ) );
+ }
+
+ return isset( $site['outgoing_meta'] ) && is_array( $site['outgoing_meta'] )
+ ? array_values( $site['outgoing_meta'] )
+ : array();
+ }
+
+ /**
+ * Retrieve and validate a connected site's outgoing metadata keys.
+ *
+ * @return void This method sends a JSON response and ends the request.
+ */
+ public function notify_outgoing_meta_remote() {
+ $this->api->authorize_local_ajax_request();
+
+ $url = filter_input( INPUT_POST, 'site_url', FILTER_VALIDATE_URL );
+ $site = is_string( $url ) ? $this->settings->get_site( $url ) : false;
+
+ if ( ! $site || ! isset( $site['url'] ) || untrailingslashit( $site['url'] ) !== untrailingslashit( $url ) ) {
+ wp_send_json_error( __( 'The remote site is not configured.', 'wprus' ), 400 );
+ }
+
+ $user = wp_get_current_user();
+
+ if ( ! $user->exists() || '' === $user->user_login ) {
+ wp_send_json_error( __( 'Unable to identify the current user.', 'wprus' ), 403 );
+ }
+
+ $payload = array(
+ 'username' => $user->user_login,
+ 'action' => 'outgoing_meta',
+ 'data' => array( 'base_url' => get_option( 'home' ) ),
+ );
+ $response = $this->api->fire_action( $site['url'], $payload, true, 5 );
+ $decoded = json_decode( $response['body'], true );
+
+ if (
+ 200 !== absint( $response['response_code'] ) ||
+ JSON_ERROR_NONE !== json_last_error() ||
+ ! is_array( $decoded ) ||
+ true !== ( $decoded['success'] ?? null ) ||
+ ! isset( $decoded['data'] ) ||
+ ! is_array( $decoded['data'] )
+ ) {
+ $message = ( is_array( $decoded ) && isset( $decoded['data'] ) && is_string( $decoded['data'] ) )
+ ? $decoded['data']
+ : __( 'Unable to retrieve outgoing metadata from the remote site.', 'wprus' );
+
+ wp_send_json_error( $message );
+ }
+
+ $keys = $decoded['data'];
+
+ if ( array_keys( $keys ) !== array_keys( array_values( $keys ) ) ) {
+ wp_send_json_error( __( 'The remote site returned invalid metadata.', 'wprus' ) );
+ }
+
+ wp_send_json_success( $this->filter_outgoing_meta_keys( $keys ) );
+ }
+
+ /**
+ * Keep only remote metadata keys permitted by this site.
+ *
+ * @param array $keys Raw metadata keys returned by the remote site.
+ * @return array Accepted metadata keys.
+ */
+ protected function filter_outgoing_meta_keys( $keys ) {
+ require_once WPRUS_PLUGIN_PATH . 'inc/api/class-wprus-api-meta.php';
+
+ $meta_handler = new Wprus_Api_Meta( 'meta', $this->settings, false );
+ $accepted = array();
+
+ foreach ( $keys as $meta_key ) {
+
+ if (
+ ! is_string( $meta_key ) ||
+ '' === $meta_key ||
+ trim( $meta_key ) !== $meta_key ||
+ wp_unslash( $meta_key ) !== $meta_key ||
+ sanitize_key( $meta_key ) !== $meta_key
+ ) {
+ continue;
+ }
+
+ if ( $meta_handler->is_excluded_meta_key( $meta_key ) ) {
+ continue;
+ }
+
+ $accepted[] = $meta_key;
+ }
+
+ return array_values( array_unique( $accepted ) );
+ }
+}
--- a/wp-remote-users-sync/inc/api/admin/class-wprus-admin-test.php
+++ b/wp-remote-users-sync/inc/api/admin/class-wprus-admin-test.php
@@ -0,0 +1,224 @@
+<?php
+/**
+ * Handle administrative connection tests.
+ *
+ * @package Wprus
+ */
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+/** Compare action settings and send connection tests. */
+class Wprus_Admin_Test {
+
+ /**
+ * Administrative endpoint transport.
+ *
+ * @var Wprus_Api_Admin
+ */
+ protected $api;
+
+ /**
+ * Plugin settings.
+ *
+ * @var Wprus_Settings
+ */
+ protected $settings;
+
+ /**
+ * Store the shared endpoint transport and settings.
+ *
+ * @param Wprus_Api_Admin $api Administrative endpoint transport.
+ * @param Wprus_Settings $settings Plugin settings.
+ * @param bool $init_hooks Whether to register WordPress hooks.
+ */
+ public function __construct( $api, $settings, $init_hooks = false ) {
+ $this->api = $api;
+ $this->settings = $settings;
+
+ if ( $init_hooks ) {
+ add_action( 'wp_ajax_wprus_admin_notify_test_remote', array( $this, 'notify_test_remote' ), 10, 0 );
+ }
+ }
+
+ /**
+ * Register the connection-test handler.
+ *
+ * @param array $handlers Registered administrative handlers.
+ * @return array Registered administrative handlers.
+ */
+ public function register_handler( $handlers ) {
+ $handlers['test'] = array( $this, 'handle_test_notification' );
+
+ return $handlers;
+ }
+
+ /**
+ * Compare every Action setting with the requesting site.
+ *
+ * @param array $data Complete Action settings from the requesting site.
+ * @return array|WP_Error Test result or configuration differences.
+ */
+ public function handle_test_notification( $data ) {
+ $site = is_array( $data ) && ! empty( $data['base_url'] ) ? $this->settings->get_site( $data['base_url'] ) : false;
+
+ if (
+ ! $site ||
+ ! isset( $data['actions']['incoming'], $data['actions']['outgoing'] ) ||
+ ! is_array( $data['actions']['incoming'] ) ||
+ ! is_array( $data['actions']['outgoing'] )
+ ) {
+ return new WP_Error( 'wprus_invalid_test', __( 'Invalid connection test request.', 'wprus' ), array( 'status' => 400 ) );
+ }
+
+ $failures = array();
+ $actions = array_keys(
+ apply_filters(
+ 'wprus_actions',
+ array(
+ 'login' => __( 'Login', 'wprus' ),
+ 'logout' => __( 'Logout', 'wprus' ),
+ 'create' => __( 'Create', 'wprus' ),
+ 'update' => __( 'Update', 'wprus' ),
+ 'delete' => __( 'Delete', 'wprus' ),
+ 'password' => __( 'Password', 'wprus' ),
+ 'role' => __( 'Roles', 'wprus' ),
+ 'meta' => __( 'Metadata', 'wprus' ),
+ )
+ )
+ );
+ $actions = array_unique( array_merge( $actions, array_keys( $data['actions']['incoming'] ), array_keys( $data['actions']['outgoing'] ) ) );
+
+ foreach (
+ array(
+ 'incoming' => 'outgoing',
+ 'outgoing' => 'incoming',
+ ) as $local_direction => $remote_direction
+ ) {
+
+ foreach ( $actions as $action ) {
+ $local_enabled = ! empty( $data['actions'][ $local_direction ][ $action ] );
+ $remote_enabled = ! empty( $site[ $remote_direction . '_actions' ][ $action ] );
+
+ if ( $local_enabled !== $remote_enabled ) {
+ $failures[] = array(
+ 'action' => $action,
+ 'direction' => $local_direction,
+ 'local_enabled' => $local_enabled,
+ );
+ }
+ }
+ }
+
+ if ( $failures ) {
+ return new WP_Error(
+ 'wprus_configuration_mismatch',
+ __( 'Action settings differ between the two sites.', 'wprus' ),
+ array(
+ 'status' => 409,
+ 'details' => array( 'failures' => $failures ),
+ )
+ );
+ }
+
+ return array( 'failures' => array() );
+ }
+
+ /**
+ * Send one request that tests every Action setting.
+ *
+ * @return void This method sends a JSON response and ends the request.
+ */
+ public function notify_test_remote() {
+ $this->api->authorize_local_ajax_request();
+
+ $url = filter_input( INPUT_POST, 'site_url', FILTER_VALIDATE_URL );
+ $data = filter_input( INPUT_POST, 'data', FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY );
+ $success = false;
+ $payload = false;
+
+ if (
+ ! $url || ! is_array( $data ) ||
+ ! isset( $data['username'], $data['actions']['incoming'], $data['actions']['outgoing'] ) ||
+ ! is_string( $data['username'] ) ||
+ '' === $data['username'] ||
+ ! is_array( $data['actions']['incoming'] ) ||
+ ! is_array( $data['actions']['outgoing'] )
+ ) {
+ wp_send_json_error( __( 'Malformed data - the test request was received but the data could not be extracted.', 'wprus' ), 400 );
+ }
+
+ $payload = array(
+ 'username' => $data['username'],
+ 'action' => 'test',
+ 'data' => array(
+ 'base_url' => get_option( 'home' ),
+ 'actions' => $data['actions'],
+ ),
+ );
+ $response = $this->api->fire_action( $url, $payload, true, 5 );
+
+ do_action( 'wprus_test_fired', $payload['data'], $response );
+
+ if ( ! empty( $response['body'] ) ) {
+ $data = json_decode( $response['body'], true );
+
+ if ( JSON_ERROR_NONE !== json_last_error() ) {
+ $payload = __( 'Error contacting the remote site: ', 'wprus' );
+ $payload .= __( 'Payload error - ' ) . json_last_error_msg();
+ } elseif ( is_array( $data ) && isset( $data['success'], $data['data'] ) ) {
+
+ if ( 200 === absint( $response['response_code'] ) && true === $data['success'] ) {
+ $success = true;
+ }
+
+ $payload = $data['data'];
+ }
+ }
+
+ if ( ! $success && ! $payload ) {
+ $payload = __( 'Error contacting the remote site: ', 'wprus' );
+
+ if (
+ ! empty( $response['response_code'] ) &&
+ 200 !== $response['response_code'] &&
+ ! empty( $response['response_message'] )
+ ) {
+ $payload .= $response['response_code'] . ' - ' . $response['response_message'];
+ } else {
+ // translators: %s is the error code.
+ $payload .= ( ! empty( $response['response_code'] ) ) ? sprintf( __( ' - code: %s - ', 'wprus' ), $response['response_code'] ) : '';
+ $payload .= __( 'an undefined error occured. Please make sure the address is correct and try again.', 'wprus' );
+ $payload .= "n";
+ $payload .= __( 'On the remote site, please make sure the plugin is activated and that the permalinks are up to date by visiting the permalinks settings page.', 'wprus' );
+ }
+
+ if ( 404 === absint( $response['response_code'] ) ) {
+ $payload .= "n";
+ $payload .= __( 'On the remote site, please make sure the permalinks are not using the "Plain" option.', 'wprus' );
+ }
+ }
+
+ $log_type = ( $success ) ? 'success' : 'alert';
+
+ Wprus_Logger::log( $payload, $log_type, 'db_log' );
+
+ if ( ! $success ) {
+ Wprus_Logger::log(
+ array(
+ 'message' => 'Response data received from the remote site: ',
+ $response,
+ ),
+ 'info',
+ 'db_log'
+ );
+ }
+
+ if ( $success ) {
+ wp_send_json_success( $payload );
+ }
+
+ wp_send_json_error( $payload );
+ }
+}
--- a/wp-remote-users-sync/inc/api/admin/class-wprus-api-admin.php
+++ b/wp-remote-users-sync/inc/api/admin/class-wprus-api-admin.php
@@ -0,0 +1,162 @@
+<?php
+/**
+ * Route permanent administrative requests.
+ *
+ * @package Wprus
+ */
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+/** Dispatch administrative requests through the shared WPRUS transport. */
+class Wprus_Api_Admin extends Wprus_Api_Abstract {
+
+ /**
+ * Included administrative handlers.
+ *
+ * @var array
+ */
+ protected $handlers = array();
+
+ /**
+ * Create the administrative handlers and register local requests.
+ *
+ * @param string $endpoint Endpoint name.
+ * @param Wprus_Settings $settings Plugin settings.
+ * @param bool $init_hooks Whether to register WordPress hooks.
+ */
+ public function __construct( $endpoint, $settings, $init_hooks = false ) {
+ parent::__construct( $endpoint, $settings, $init_hooks );
+
+ $init_handler_hooks = $init_hooks && ! $this->doing_remote_action;
+
+ /**
+ * Lets another plugin load files containing administrative handler classes.
+ *
+ * @param Wprus_Api_Admin $api Administrative endpoint transport.
+ */
+ do_action( 'wprus_require_admin_handler_files', $this );
+
+ foreach ( (array) glob( __DIR__ . '/class-wprus-admin-*.php' ) as $handler_file ) {
+ $handler_slug = substr( basename( $handler_file, '.php' ), 18 );
+ $class_parts = array_map( 'ucfirst', explode( '-', $handler_slug ) );
+ $handler_class = 'Wprus_Admin_' . implode( '_', $class_parts );
+
+ require_once $handler_file;
+
+ if ( class_exists( $handler_class ) ) {
+ $this->handlers[ $handler_slug ] = new $handler_class( $this, $settings, $init_handler_hooks );
+ }
+ }
+
+ /**
+ * Lets another plugin create its loaded administrative handlers.
+ *
+ * @param Wprus_Api_Admin $api Administrative endpoint transport.
+ * @param Wprus_Settings $settings Plugin settings.
+ * @param bool $init_handler_hooks Whether to register local administrator requests.
+ */
+ do_action( 'wprus_init_admin_handlers', $this, $settings, $init_handler_hooks );
+ }
+
+ /** Find the requested administrative action and return its result. */
+ public function handle_notification() {
+ $_data = $this->get_data_post();
+
+ if (
+ ! is_array( $_data ) ||
+ ! $this->validate( $_data ) ||
+ ! is_string( $_data['username'] ) ||
+ ! is_string( $_data['base_url'] ) ||
+ ! isset( $_data['action'], $_data['data'] ) ||
+ ! is_string( $_data['action'] ) ||
+ ! preg_match( '/^[a-z][a-z0-9_]*$/D', $_data['action'] ) ||
+ ! is_array( $_data['data'] ) ||
+ ! $this->settings->get_site( $_data['base_url'] ) ||
+ ( isset( $_data['data']['base_url'] ) && $_data['data']['base_url'] !== $_data['base_url'] )
+ ) {
+ return new WP_Error( 'wprus_invalid_admin_request', __( 'Invalid administrative request.', 'wprus' ), array( 'status' => 400 ) );
+ }
+
+ $handlers = array();
+
+ foreach ( $this->handlers as $handler_object ) {
+
+ if ( method_exists( $handler_object, 'register_handler' ) ) {
+ $handlers = $handler_object->register_handler( $handlers );
+ }
+ }
+
+ $handlers = apply_filters( 'wprus_admin_handlers', $handlers, $this );
+ $handler = is_array( $handlers ) ? ( $handlers[ $_data['action'] ] ?? null ) : null;
+
+ if ( $handler instanceof Closure ) {
+ return $handler( $_data['data'] );
+ }
+
+ if ( is_string( $handler ) && function_exists( $handler ) ) {
+ return $handler( $_data['data'] );
+ }
+
+ if (
+ ! is_array( $handler ) ||
+ 2 !== count( $handler ) ||
+ ! is_object( $handler[0] ) ||
+ ! is_string( $handler[1] ) ||
+ ! method_exists( $handler[0], $handler[1] )
+ ) {
+ return new WP_Error( 'wprus_unknown_admin_action', __( 'Unknown administrative action.', 'wprus' ), array( 'status' => 400 ) );
+ }
+
+ return $handler[0]->{$handler[1]}( $_data['data'] );
+ }
+
+ /**
+ * Send the final administrative JSON response and end the request.
+ *
+ * @param mixed $result Returned action result.
+ * @param int|null $status Status chosen before the action ran.
+ * @return void This method ends the request.
+ */
+ public function send_response( $result, $status = null ) {
+
+ if ( is_wp_error( $result ) ) {
+
+ if ( null === $status ) {
+ $error_data = $result->get_error_data();
+ $status = is_array( $error_data ) && isset( $error_data['status'] ) ? absint( $error_data['status'] ) : 400;
+ }
+
+ if ( $status < 400 || $status > 599 ) {
+ $status = 400;
+ }
+ }
+
+ if ( null === $result ) {
+ $this->set_response_error( 'wprus_admin_no_result', 500 );
+
+ $status = 500;
+ }
+
+ parent::send_response( $result, $status );
+ }
+
+ /**
+ * Authorize a local administrative AJAX request.
+ *
+ * @return void This method ends an unauthorized request.
+ */
+ public function authorize_local_ajax_request() {
+
+ if ( ! current_user_can( 'manage_options' ) ) {
+ wp_send_json_error( __( 'Error: unauthorized access - please reload the page and try again.', 'wprus' ), 403 );
+ }
+
+ $nonce = filter_input( INPUT_POST, 'nonce', FILTER_UNSAFE_RAW );
+
+ if ( ! wp_verify_nonce( $nonce, 'wprus_test_nonce' ) ) {
+ wp_send_json_error( __( 'Error: unauthorized access - please reload the page and try again.', 'wprus' ) );
+ }
+ }
+}
--- a/wp-remote-users-sync/inc/api/class-wprus-api-abstract.php
+++ b/wp-remote-users-sync/inc/api/class-wprus-api-abstract.php
@@ -69,6 +69,24 @@
*/
protected $data;
/**
+ * Fields decoded from a server-to-server JSON request.
+ *
+ * @var array
+ */
+ protected $request_body = array();
+ /**
+ * HTTP status to use when an action returns false.
+ *
+ * @var int
+ */
+ protected $response_status = 422;
+ /**
+ * Error returned when an action fails.
+ *
+ * @var array
+ */
+ protected $response_error = array();
+ /**
* The user ID used to save and fire async actions.
*
* @var int
@@ -105,7 +123,6 @@
*/
protected $is_authorized_remote;
-
/**
* Constructor
*
@@ -129,12 +146,6 @@
add_action( 'init', array( $this, 'init_remote_hooks' ), PHP_INT_MIN + 100, 0 );
} else {
add_action( 'init', array( $this, 'init_local_hooks' ), PHP_INT_MIN + 100, 0 );
- add_action(
- 'wp_ajax_wprus_' . $endpoint . '_notify_ping_remote',
- array( $this, 'notify_ping_remote' ),
- 10,
- 0
- );
if ( $this->has_async_actions() ) {
@@ -266,10 +277,11 @@
* @return void No value is returned.
*/
public function handle_token_request() {
- $data = $this->get_data_post();
- $token_info = false;
+ $data = $this->get_data_post();
+ $token_info = false;
+ $valid_request = is_array( $data ) && isset( $data['method'] );
- if ( $data && isset( $data['method'] ) ) {
+ if ( $valid_request ) {
$token_info = Wprus_Nonce::create_nonce( true );
}
@@ -293,7 +305,7 @@
Wprus_Logger::log( __( 'Failed to create token - invalid payload', 'wprus' ), 'alert', 'db_log' );
- exit();
+ wp_send_json_error( array( 'code' => $valid_request ? 'token_creation_failed' : 'invalid_token_request' ), $valid_request ? 500 : 400 );
}
/**
@@ -302,14 +314,7 @@
* @return void No value is returned.
*/
public function init_remote_hooks() {
- $data = $this->get_data();
-
- if ( isset( $data['ping'] ) ) {
- add_action( 'wprus_api_' . $this->endpoint, array( $this, 'handle_ping_notification' ), 10, 0 );
- } else {
- add_action( 'wprus_api_' . $this->endpoint, array( $this, 'handle_request' ), 10, 0 );
- }
-
+ add_action( 'wprus_api_' . $this->endpoint, array( $this, 'handle_request' ), 10, 0 );
add_action( 'wprus_api_token', array( $this, 'handle_token_request' ), 10, 0 );
}
@@ -348,12 +353,47 @@
* @return void No value is returned.
*/
public function handle_request() {
- $data = $this->get_data();
+ $this->response_status = 422;
+ $this->response_error = array();
+ $data = $this->get_data();
+ $is_remote_post = $this->doing_remote_action && 'post' === $this->method;
+
+ if (
+ ! in_array( $this->endpoint, array( 'identity', 'admin' ), true ) &&
+ ( ! isset( $this->data[ $this->method ] ) || ! is_array( $this->data[ $this->method ] ) || ! $this->data[ $this->method ] )
+ ) {
+
+ if ( $is_remote_post ) {
+ $this->set_response_error( 'invalid_' . $this->endpoint . '_request', 400 );
+ $this->send_response( false, 400 );
+ } else {
+ status_header( 400 );
+ }
+ } elseif (
+ ! in_array( $this->endpoint, array( 'identity', 'admin' ), true ) &&
+ ! Wprus_Api_Identity::verify_incoming_identity( $data, $this->endpoint )
+ ) {
+ Wprus_Logger::log(
+ sprintf( 'Incoming %s action rejected: user identity mismatch.', $this->endpoint ),
+ 'alert',
+ 'db_log'
+ );
- if ( method_exists( $this, 'handle_notification' ) ) {
+ if ( $is_remote_post ) {
+ $this->set_response_error( 'identity_mismatch', 409 );
+ $this->send_response( false, 409 );
+ } else {
+ status_header( 409 );
+ }
+ } elseif ( method_exists( $this, 'handle_notification' ) ) {
do_action( 'wprus_before_handle_action_notification', $this->endpoint, $data );
+ Wprus_Api_Identity::set_handling_incoming( true );
- $result = $this->handle_notification();
+ try {
+ $result = $this->handle_notification();
+ } finally {
+ Wprus_Api_Identity::set_handling_incoming( false );
+ }
do_action( 'wprus_after_handle_action_notification', $this->endpoint, $data, $result );
@@ -364,9 +404,15 @@
exit();
}
- }
- add_filter( 'wprus_api_needs_redirect', array( $this, 'needs_redirect' ), 10, 0 );
+ add_filter( 'wprus_api_needs_redirect', array( $this, 'needs_redirect' ), 10, 0 );
+
+ if ( $is_remote_post ) {
+ $this->send_response( $result );
+ } elseif ( $this->doing_remote_action ) {
+ status_header( $this->get_response_status( $result ) );
+ }
+ }
}
/**
@@ -376,9 +422,9 @@
*/
public function authorize_notification() {
$token_filter = FILTER_UNSAFE_RAW;
- $token = filter_input( INPUT_GET, 'token', $token_filter );
- $token = ( ! $token ) ? filter_input( INPUT_POST, 'token', $token_filter ) : $token;
+ $token = 'post' === $this->method ? ( $this->request_body['token'] ?? null ) : filter_input( INPUT_GET, 'token', $token_filter );
$is_authorized_remote = false;
+ $error_code = 'method_not_allowed';
$origin = false;
$remote_data = $this->get_data();
$remote_addr = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
@@ -391,8 +437,9 @@
Wprus_Nonce::init( true, false, self::$encryption_settings['token_expiry'] );
}
- if ( ! Wprus_Nonce::validate_nonce( $token ) ) {
- $message = __( 'Unauthorized access (invalid token)', 'wprus' );
+ if ( ! is_string( $token ) || ! Wprus_Nonce::validate_nonce( $token ) ) {
+ $error_code = 'invalid_token';
+ $message = __( 'Unauthorized access (invalid token)', 'wprus' );
} else {
if ( 'get' === $this->method ) {
@@ -400,9 +447,12 @@
} elseif ( 'post' === $this->method ) {
if ( self::$ip_whitelist ) {
+
foreach ( self::$ip_whitelist as $range ) {
+
if ( $this->cidr_match( $remote_addr, $range ) ) {
$is_authorized_remote = true;
+
break;
}
}
@@ -422,10 +472,12 @@
if ( $is_authorized_remote ) {
$message = __( 'Access granted', 'wprus' );
} elseif ( 'post' === $this->method && self::$ip_whitelist ) {
+ $error_code = 'ip_not_allowed';
// translators: %s is the remote IP address.
$message = sprintf( __( 'Unauthorized access (invalid remote IP address %s)', 'wprus' ), $remote_addr );
} else {
- $message = __( 'Unauthorized access (invalid method)', 'wprus' );
+ $error_code = 'method_not_allowed';
+ $message = __( 'Unauthorized access (invalid method)', 'wprus' );
}
}
@@ -442,17 +494,20 @@
if ( ! $is_authorized_remote ) {
do_action( 'wprus_unauthorized_access', $this->endpoint, $remote_data, $token, $this );
- if ( isset( $remote_data['ping'] ) ) {
- $message = __( 'The remote website encountered the following error: ', 'wprus' ) . $message;
-
- wp_send_json_error( $message );
+ if ( 'post' === $this->method ) {
+ wp_send_json_error(
+ array(
+ 'code' => $error_code,
+ 'message' => __( 'The remote website encountered the following error: ', 'wprus' ) . $message,
+ ),
+ 403
+ );
} elseif ( $this->needs_redirect() ) {
- $url = isset( $remote_data['callback_url'] ) ? $remote_data['callback_url'] : home_url();
-
- wp_redirect( $url, 303 ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
+ wp_redirect( isset( $remote_data['callback_url'] ) ? $remote_data['callback_url'] : home_url(), 303 ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
exit();
} else {
+ status_header( 403 );
exit();
}
@@ -470,15 +525,12 @@
$init_notification_hooks = apply_filters( 'wprus_init_notification_hooks', true );
if ( ! $init_notification_hooks ) {
-
return;
}
if ( method_exists( $this, 'init_notification_hooks' ) ) {
do_action( 'wprus_before_init_notification_hooks', $this->endpoint, $this );
-
$this->init_notification_hooks();
-
do_action( 'wprus_after_init_notification_hooks', $this->endpoint, $this );
}
}
@@ -583,12 +635,25 @@
* @return void No value is returned.
*/
public function init_data() {
- $data_get = filter_input( INPUT_GET, 'wprusdata', FILTER_UNSAFE_RAW );
- $data_post = filter_input( INPUT_POST, 'wprusdata', FILTER_UNSAFE_RAW );
- $this->method = ( $data_post ) ? 'post' : 'get';
- $this->data = array(
- 'get' => ( $data_get ) ? $this->decrypt_data( $data_get ) : null,
- 'post' => ( $data_post ) ? $this->decrypt_data( $data_post ) : null,
+ $data_get = filter_input( INPUT_GET, 'wprusdata', FILTER_UNSAFE_RAW );
+ $request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_key( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : '';
+ $content_type = isset( $_SERVER['CONTENT_TYPE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['CONTENT_TYPE'] ) ) : '';
+ $this->request_body = array();
+ $this->method = 'post' === strtolower( $request_method ) ? 'post' : 'get';
+ $is_json = 'post' === $this->method && false !== stripos( $content_type, 'application/json' );
+
+ if ( $is_json ) {
+ $decoded = json_decode( file_get_contents( 'php://input' ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Read the incoming HTTP request.
+
+ if ( is_array( $decoded ) ) {
+ $this->request_body = $decoded;
+ }
+ }
+
+ $data_post = $this->request_body['wprusdata'] ?? null;
+ $this->data = array(
+ 'get' => is_string( $data_get ) && $data_get ? $this->decrypt_data( $data_get ) : null,
+ 'post' => is_string( $data_post ) && $data_post ? $this->decrypt_data( $data_post ) : null,
);
}
@@ -599,12 +664,7 @@
* @return array The list of endpoints
*/
public function add_action_endpoints( $endpoints ) {
- $endpoints = array_merge(
- $endpoints,
- $this->get_endpoints()
- );
-
- return $endpoints;
+ return array_merge( $endpoints, $this->get_endpoints() );
}
/**
@@ -617,209 +677,8 @@
*/
public function get_active_site_for_action( $endpoint, $site_url = false, $direction = 'incoming' ) {
$site_url = ( $site_url ) ? $site_url : get_option( 'home' );
- $site = $this->settings->get_site( $site_url, $endpoint, $direction );
-
- return $site;
- }
-
- /**
- * Handle requests for test pings and reply with JSON data
- *
- * @return void No value is returned.
- */
- public function handle_ping_notification() {
- $data = $this->get_data_post();
-
- if ( empty( $data ) ) {
- Wprus_Logger::log( __( 'A ping was received but the initiator did not use matching encryption and signature action keys', 'wprus' ), 'info', 'db_log' );
- wp_send_json_error( __( 'Mismatch Encryption settings - please make sure the action keys are correctly configured on both sites.', 'wprus' ) );
- }
-
- if (
- empty( $data['base_url'] ) ||
- empty( $data['direction'] ) ||
- (
- 'incoming' !== $data['direction'] &&
- 'outgoing' !== $data['direction']
- )
- ) {
- Wprus_Logger::log( __( 'A ping was received but the initiator did not send the proper data.', 'wprus' ), 'info', 'db_log' );
- wp_send_json_error( __( 'Malformed data - the test request was received but the data could not be extracted.', 'wprus' ) );
- }
-
- $site = $this->get_active_site_for_action( $this->endpoint, $data['base_url'], $data['direction'] );
- $action_label = $this->endpoint;
- $direction_label = ( 'incoming' === $data['direction'] ) ? __( 'incoming', 'wprus' ) : __( 'outgoing', 'wprus' );
- $remote_addr = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
- $settings_class = self::$settings_class;
- $class_vars = get_class_vars( $settings_class );
-
- if ( isset( $class_vars['actions'][ $action_label ] ) ) {
- $action_label = $class_vars['actions'][ $action_label ];
- }
-
- if ( $site ) {
- do_action( 'wprus_ping_success', $this->endpoint, $data, $remote_addr );
-
- // translators: %1$s is the sync action name, %2$s is the remote site URL, %3$s is the remote IP, %4$s is the direction.
- $message = __( 'Ping received for activated action "%1$s" from %2$s with remote IP %3$s (%4$s)', 'wprus' );
-
- Wprus_Logger::log(
- sprintf(
- $message,
- $action_label,
- $data['base_url'],
- $remote_addr,
- $direction_label
- ),
- 'success',
- 'db_log'
- );
-
- // translators: %1$s is the sync action name, %2$s is the current site URL, %3$s is the remote IP, %4$s is the direction.
- $message = __( 'Ping success for action "%1$s" from %2$s with remote IP %3$s (%4$s)', 'wprus' );
-
- wp_send_json_success(
- sprintf(
- $message,
- $action_label,
- get_option( 'home' ),
- $remote_addr,
- $direction_label
- )
- );
- }
-
- do_action( 'wprus_ping_failure', $this->endpoint, $data, $remote_addr );
-
- // translators: %1$s is the sync action name, %2$s is the remote site URL, %3$s is the remote IP, %4$s is the direction.
- $message = __( 'Ping received for deactivated action "%1$s" from %2$s with remote IP %3$s (%4$s)', 'wprus' );
-
- Wprus_Logger::log(
- sprintf(
- $message,
- $action_label,
- $data['base_url'],
- $remote_addr,
- $direction_label
- ),
- 'warning',
- 'db_log'
- );
- // translators: %1$s is the sync action name, %2$s is the current site URL, %3$s is the remote IP, %4$s is the direction.
- $message = __( '"%1$s" action is not activated on %2$s with remote IP %3$s (%4$s).', 'wprus' );
- $message = sprintf(
- $message,
- $action_label,
- get_option( 'home' ),
- $remote_addr,
- $direction_label
- );
-
- wp_send_json_error( $message );
- }
-
- /**
- * Send a test ping request to a remote website and send the response to the user interface
- *
- * @return void No value is returned.
- */
- public function notify_ping_remote() {
- if ( ! current_user_can( 'manage_options' ) ) {
- wp_send_json_error( __( 'Error: unauthorized access - please reload the page and try again.', 'wprus' ), 403 );
- }
-
- $nonce = filter_input( INPUT_POST, 'nonce', FILTER_UNSAFE_RAW );
-
- if ( ! wp_verify_nonce( $nonce, 'wprus_ping_nonce' ) ) {
- wp_send_json_error( __( 'Error: unauthorized access - please reload the page and try again.', 'wprus' ) );
- }
-
- $url = filter_input( INPUT_POST, 'site_url', FILTER_VALIDATE_URL );
- $direction = filter_input( INPUT_POST, 'direction', FILTER_UNSAFE_RAW );
- $data = filter_input( INPUT_POST, 'data', FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY );
- $success = false;
- $payload = false;
- $default_data = array(
- 'ping' => 1,
- 'direction' => ( 'incoming' === $direction ) ? 'outgoing' : 'incoming',
- );
-
- if ( $data ) {
- $data = array_merge( $default_data, $data );
- } else {
- $data = $default_data;
- }
-
- $response = $this->fire_action(
- $url,
- $data,
- true,
- 5
- );
-
- do_action( 'wprus_ping_fired', $this->endpoint, $data, $response );
-
- if ( 200 === absint( $response['response_code'] ) ) {
- $data = json_decode( $response['body'], true );
-
- if ( JSON_ERROR_NONE !== json_last_error() ) {
- $payload = __( 'Error contacting the remote site: ', 'wprus' );
- $payload .= __( 'Payload error - ' ) . json_last_error_msg();
- } else {
-
- if ( $data['success'] ) {
- $success = true;
- }
-
- $payload = $data['data'];
- }
- }
-
- if ( ! $success && ! $payload ) {
- $payload = __( 'Error contacting the remote site: ', 'wprus' );
-
- if (
- ! empty( $response['response_code'] ) &&
- 200 !== $response['response_code'] &&
- ! empty( $response['response_message'] )
- ) {
- $payload .= $response['response_code'] . ' - ' . $response['response_message'];
- } else {
- // translators: %s is the error code.
- $payload .= ( ! empty( $response['response_code'] ) ) ? sprintf( __( ' - code: %s - ', 'wprus' ), $response['response_code'] ) : '';
- $payload .= __( 'an undefined error occured. Please make sure the address is correct and try again.', 'wprus' );
- $payload .= "n";
- $payload .= __( 'On the remote site, please make sure the plugin is activated and that the permalinks are up to date by visiting the permalinks settings page.', 'wprus' );
- }
-
- if ( 404 === absint( $response['response_code'] ) ) {
- $payload .= "n";
- $payload .= __( 'On the remote site, please make sure the permalinks are not using the "Plain" option.', 'wprus' );
- }
- }
-
- $log_type = ( $success ) ? 'success' : 'alert';
-
- Wprus_Logger::log( $payload, $log_type, 'db_log' );
-
- if ( ! $success ) {
- Wprus_Logger::log(
- array(
- 'message' => 'Response data received from the remote site: ',
- $response,
- ),
- 'info',
- 'db_log'
- );
- }
-
- if ( $success ) {
- wp_send_json_success( $payload );
- }
-
- wp_send_json_error( $payload );
+ return $this->settings->get_site( $site_url, $endpoint, $direction );
}
/**
@@ -847,6 +706,7 @@
* @return void No value is returned.
*/
public function add_async_action( $url, $data ) {
+ $data = Wprus_Api_Identity::attach_source_identity( $data, $this->endpoint );
$data['base_url'] = get_option( 'home' );
$data['url'] = $url;
@@ -878,7 +738,6 @@
$location_headers = preg_grep( '/^Location:/i', headers_list() );
if ( ! empty( $location_headers ) ) {
-
return;
}
@@ -961,7 +820,8 @@
$response = wp_safe_remote_post(
trailingslashit( $url ) . 'wprus/' . trailingslashit( $endpoint ),
array(
- 'body' => $body,
+ 'headers' => array( 'Content-Type' => 'application/json' ),
+ 'body' => wp_json_encode( $body ),
'blocking' => $blocking,
'compress' => true,
'timeout' => $timeout,
@@ -1001,7 +861,6 @@
$tokens_info = ( null !== $tokens_info && ! $tokens_info ) ? array() : $tokens_info;
if ( null === $tokens_info ) {
-
return false;
}
@@ -1058,9 +917,8 @@
$response = wp_remote_post(
trailingslashit( $payload['base_url'] ) . 'wprus/token/',
array(
- 'body' => array(
- 'wprusdata' => $this->encrypt_data( $payload ),
- ),
+ 'headers' => array( 'Content-Type' => 'application/json' ),
+ 'body' => wp_json_encode( array( 'wprusdata' => $this->encrypt_data( $payload ) ) ),
'compress' => true,
'timeout' => $timeout,
)
@@ -1070,6 +928,7 @@
if ( $body && 200 === wp_remote_retrieve_response_code( $response ) ) {
$token_info = json_decode( $body, true );
+
if ( ! is_array( $token_info ) || empty( $token_info['nonce'] ) || ! is_string( $token_info['nonce'] ) || ! isset( $token_info['expiry'] ) || ! is_numeric( $token_info['expiry'] ) || $token_info['expiry'] <= time() ) {
$token_info = false;
}
@@ -1135,6 +994,84 @@
}
/**
+ * Choose an HTTP status from an action result.
+ *
+ * @param mixed $result Action result.
+ * @param int|null $status Status chosen before the action ran.
+ * @return int HTTP status.
+ */
+ protected function get_response_status( $result, $status = null ) {
+
+ if ( null === $status ) {
+
+ if ( is_wp_error( $result ) ) {
+ $error_data = $result->get_error_data();
+ $status = is_array( $error_data ) && isset( $error_data['status'] ) ? absint( $error_data['status'] ) : 422;
+ $status = $status >= 400 && $status <= 599 ? $status : 422;
+ } else {
+ $status = null === $result ? 500 : ( false === $result ? $this->response_status : 200 );
+ }
+ }
+
+ return $status;
+ }
+
+ /**
+ * Set the error returned when an action fails.
+ *
+ * @param string $code Error code.
+ * @param int $status HTTP status.
+ * @param array $details Optional result details.
+ * @return void
+ */
+ protected function set_response_error( $code, $status, $details = array() ) {
+ $this->response_status = $status;
+ $this->response_error = array( 'code' => $code );
+
+ if ( $details ) {
+ $this->response_error['details'] = $details;
+ }
+ }
+
+ /**
+ * Send a JSON response and end the request.
+ *
+ * @param mixed $result Action result.
+ * @param int|null $status Status chosen before the action ran.
+ * @return void This method ends the request.
+ */
+ protected function send_response( $result, $status = null ) {
+ $status = $this->get_response_status( $result, $status );
+
+ if ( $status >= 200 && $status < 300 ) {
+ wp_send_json_success( $result, $status );
+ }
+
+ if ( is_wp_error( $result ) ) {
+ $error_data = $result->get_error_data();
+ $details = is_array( $error_data ) ? ( $error_data['details'] ?? array_diff_key( $error_data, array( 'status' => true ) ) ) : array();
+ $error = array(
+ 'code' => $result->get_error_code(),
+ 'message' => $result->get_error_message(),
+ );
+
+ if ( $details ) {
+ $error['details'] = $details;
+ }
+
+ wp_send_json_error( $error, $status );
+ }
+
+ $error = $this->response_error;
+
+ if ( ! $error ) {
+ $error = array( 'code' => 'action_failed' );
+ }
+
+ wp_send_json_error( $error, $status );
+ }
+
+ /**
* Set cookie helper
*
* @param string $name The name of the cookie.
@@ -1176,9 +1113,7 @@
* @return mixed The data
*/
protected function get_data_get() {
- $data_get = $this->data['get'];
-
- return $data_get;
+ return $this->data['get'];
}
/**
@@ -1187,9 +1122,7 @@
* @return mixed The data
*/
protected function get_data_post() {
- $data_post = $this->data['post'];
-
- return $data_post;
+ return $this->data['post'];
}
/**
@@ -1247,9 +1180,7 @@
* @return array The instance's endpoint entries
*/
protected function get_endpoints() {
- return array(
- $this->endpoint => $this->endpoint,
- );
+ return array( $this->endpoint => $this->endpoint );
}
/**
@@ -1415,9 +1346,7 @@
)
);
- $output = ob_get_clean();
-
- return $output;
+ return ob_get_clean();
}
/**
@@ -1429,15 +1358,19 @@
*/
protected function cidr_match( $ip, $range ) {
$parts = explode( '/', $range );
+
if ( 2 !== count( $parts ) || ! ctype_digit( $parts[1] ) || (int) $parts[1] > 32 ) {
return false;
}
+
$ip = ip2long( $ip );
$subnet = ip2long( $parts[0] );
$bits = (int) $parts[1];
+
if ( false === $ip || false === $subnet ) {
return false;
}
+
if ( 0 === $bits ) {
return true;
}
--- a/wp-remote-users-sync/inc/api/class-wprus-api-create.php
+++ b/wp-remote-users-sync/inc/api/class-wprus-api-create.php
@@ -35,6 +35,7 @@
$result = false;
if ( ! $this->validate( $data ) ) {
+ $this->set_response_error( 'invalid_create_request', 400 );
Wprus_Logger::log(
__( 'Create action failed - received invalid data.', 'wprus' ),
'alert',
@@ -63,6 +64,10 @@
}
if ( is_wp_error( $maybe_user_id ) ) {
+ $error_code = $maybe_user_id->get_error_code();
+ $is_conflict = in_array( $error_code, array( 'existing_user_login', 'existing_user_email' ), true );
+
+ $this->set_response_error( $is_conflict ? $error_code : 'user_creation_failed', $is_conflict ? 409 : 422 );
Wprus_Logger::log(
sprintf(
// translators: %1$s is the error; %2$s is the username; %3$s is the caller.
@@ -95,9 +100,15 @@
if ( ! is_wp_error( $maybe_user_id ) && $incoming_roles ) {
$user = get_user_by( 'ID', $maybe_user_id );
- $this->role_handler->handle_notification_roles( $site, $user, $incoming_roles );
+ if ( ! $this->role_handler->handle_notification_roles( $site, $user, $incoming_roles, $error ) ) {
+ $result = false;
+ $error['details']['account_saved'] = true;
+
+ $this->set_response_error( $error['code'], $error['status'], $error['details'] );
+ }
}
} else {
+ $this->set_response_error( 'create_not_allowed', 403 );
Wprus_Logger::log(
sprintf(
// translators: %s is the URL of the caller.
@@ -119,6 +130,10 @@
* @return void No value is returned.
*/
public function notify_remote( $user_id ) {
+ if ( Wprus_Api_Identity::is_creation_blocked( $user_id ) ) {
+ return;
+ }
+
$sites = $this->settings->get_sites( $this->endpoint, 'outgoing' );
$user = get_user_by( 'ID', $user_id );
--- a/wp-remote-users-sync/inc/api/class-wprus-api-delete.php
+++ b/wp-remote-users-sync/inc/api/class-wprus-api-delete.php
@@ -28,23 +28,26 @@
/**
* Receive a user deletion allowed by this site's settings.
*
- * @return void No value is returned.
+ * @return bool Whether the user was deleted.
*/
public function handle_notification() {
$data = $this->get_data_post();
if ( ! $this->validate( $data ) ) {
+ $this->set_response_error( 'invalid_delete_request', 400 );
Wprus_Logger::log(
__( 'Delete action failed - received invalid data.', 'wprus' ),
'alert',
'db_log'
);
- return;
+ return false;
}
- $data = $this->sanitize( $data );
- $site = $this->get_active_site_for_action( $this->endpoint, $data['base_url'] );
+ $data = $this->sanitize( $data );
+ $site = $this->get_active_site_for_action( $this->endpoint, $data['base_url'] );
+ $user = null;
+ $user_reassign = null;
if ( $site ) {
$reassign = null;
@@ -55,11 +58,14 @@
$reassign = $user_reassign->ID;
}
- if ( $user ) {
- wp_delete_user( $user->ID, $reassign );
+ if ( $user && ! wp_delete_user( $user->ID, $reassign ) ) {
+ $this->set_response_error( 'user_deletion_failed', 422 );
+
+ return false;
}
if ( ! $user ) {
+ $this->set_response_error( 'user_not_found', 404 );
Wprus_Logger::log(
sprintf(
// translators: %1$s is the username ; %2$s is the caller.
@@ -71,6 +77,14 @@
'db_log'
);
} elseif ( ! $user_reassign && $data['reassign_username'] ) {
+ $this->set_response_error(
+ 'reassignment_user_not_found',
+ 422,
+ array(
+ 'account_deleted' => true,
+ 'content_reassigned' => false,
+ )
+ );
Wprus_Logger::log(
sprintf(
// translators: %1$s is the username, %2$s is the caller, %3$s is the reassign username.
@@ -107,6 +121,7 @@
);
}
} else {
+ $this->set_response_error( 'delete_not_allowed', 403 );
Wprus_Logger::log(
sprintf(
// translators: %s is the url of the caller.
@@ -117,6 +132,8 @@
'db_log'
);
}
+
+ return $site && $user && ( $user_reassign || ! $data['reassign_username'] );
}
/**
--- a/wp-remote-users-sync/inc/api/class-wprus-api-identity.php
+++ b/wp-remote-users-sync/inc/api/class-wprus-api-identity.php
@@ -0,0 +1,511 @@
+<?php
+/**
+ * Check user identities across connected sites before creating or changing accounts.
+ *
+ * @package Wprus
+ */
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+/** Handle remote identity checks and local registration validation. */
+class Wprus_Api_Identity extends Wprus_Api_Abstract {
+ /**
+ * Approved username and email pairs for this request.
+ *
+ * @var array
+ */
+ private static $approved_creations = array();
+
+ /**
+ * User IDs whose outgoing Create action must be skipped.
+ *
+ * @var array
+ */
+ private static $blocked_creations = array();
+
+ /**
+ * Original email for each user updated in this request.
+ *
+ * @var array
+ */
+ private static $previous_emails = array();
+
+ /**
+ * Exception handler installed before this class.
+ *
+ * @var callable|null
+ */
+ private static $previous_exception_handler;
+
+ /**
+ * Whether an authenticated incoming action is being handled.
+ *
+ * @var bool
+ */
+ private static $handling_incoming = false;
+
+ /**
+ * Set up identity checks that apply to both local and remote requests.
+ *
+ * @param string $endpoint The endpoint name.
+ * @param Wprus_Settings $settings The connected-site settings.
+ * @param bool $init_hooks Whether to register WordPress hooks.
+ */
+ public function __construct( $endpoint, $settings, $init_hooks = false ) {
+ parent::__construct( $endpoint, $settings, $init_hooks );
+
+ if ( $init_hooks ) {
+ add_filter( 'wprus_action_data', array( $this, 'attach_identity_email' ), PHP_INT_MAX, 3 );
+ self::$previous_exception_handler = set_exception_handler( array( self::class, 'handle_uncaught_exception' ) );
+ }
+ }
+
+ /** Register validation for local WordPress registrations. */
+ public function init_notification_hooks() {
+ add_filter( 'registration_errors', array( $this, 'validate_registration' ), 10, 3 );
+ add_action( 'user_profile_update_errors', array( $this, 'validate_admin_registration' ), 10, 3 );
+ add_filter( 'rest_pre_insert_user', array( $this, 'validate_rest_registration' ), 10, 2 );
+ add_filter( 'wp_pre_insert_user_data', array( $this, 'require_validated_creation' ), PHP_INT_MAX, 4 );
+ add_action( 'user_register', array( $this, 'check_created_user' ), PHP_INT_MIN + 100, 1 );
+ add_action( 'profile_update', array( $this, 'remember_previous_email' ), PHP_INT_MIN + 100, 2 );
+ }
+
+ /** Answer an authenticated request with only username and email existence. */
+ public function handle_notification() {
+ $data = $this->get_data_post();
+
+ if (
+ ! is_array( $data ) ||
+ ! isset( $data['username'], $data['user_email'], $data['base_url'] ) ||
+ ! is_string( $data['username'] ) ||
+ '' === $data['username'] ||
+ ! is_string( $data['user_email'] ) ||
+ ! is_email( $data['user_email'] ) ||
+ ! is_string( $data['base_url'] ) ||
+ ! $this->settings->get_site( $data['base_url'] )
+ ) {
+ wp_send_json_error( array( 'code' => 'invalid_identity_request' ), 400 );
+ }
+
+ wp_send_json_success(
+ array(
+ 'username_exists' => (bool) username_exists( $data['username'] ),
+ 'email_exists' => (bool) email_exists( $data['user_email'] ),
+ )
+ );
+ }
+
+ /**
+ * Check one connected site, rejecting unreliable replies.
+ *
+ * @param array $site Connected-site settings.
+ * @param string $username Username to check.
+ * @param string $email Email address to check.
+ * @return array|WP_Error Existence results or an error.
+ */
+ public function check_remote_site( $site, $username, $email ) {
+
+ if ( ! is_array( $site ) || empty( $site['url'] ) ) {
+ return new WP_Error( 'wprus_identity_unavailable' );
+ }
+
+ $token_info = $this->get_remote_token(
+ array(
+ 'action' => 'identity',
+ 'method' => 'post',
+ 'base_url' => $site['url'],
+ )
+ );
+
+ if ( ! $token_info || empty( $token_info['nonce'] ) ) {
+ return new WP_Error( 'wprus_identity_unavailable' );
+ }
+
+ $response = wp_safe_remote_post(
+ trailingslashit( $site['url'] ) . 'wprus/identity/',
+ array(
+ 'timeout' => 5,
+ 'headers' => array( 'Content-Type' => 'application/json' ),
+ 'body' => wp_json_encode(
+ array(
+ 'wprusdata' => $this->encrypt_data(
+ array(
+ 'username' => $username,
+ 'user_email' => $email,
+ 'base_url' => home_url(),
+ )
+ ),
+ 'token' => $token_info['nonce'],
+ )
+ ),
+ )
+ );
+
+ if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
+ return new WP_Error( 'wprus_identity_unavailable' );
+ }
+
+ $body = json_decode( wp_remote_retrieve_body( $response ), true );
+
+ if (
+ ! is_array( $body ) ||
+ ! isset( $body['success'], $body['data'] ) ||
+ true !== $body['success'] ||
+ ! is_array( $body['data'] ) ||
+ ! isset( $body['data']['username_exists'], $body['data']['email_exists'] ) ||
+ ! is_bool( $body['data']['username_exists'] ) ||
+ ! is_bool( $body['data']['email_exists'] )
+ ) {
+ return new WP_Error( 'wprus_identity_unavailable' );
+ }
+
+ return $body['data'];
+ }
+
+ /**
+ * Check every connected site, regardless of its action settings.
+ *
+ * @param string $username Username to check.
+ * @param string $email Email address to check.
+ * @return true|WP_Error True when clear everywhere, or an error.
+ */
+ public function check_remote_identity( $username, $email ) {
+
+ foreach ( $this->settings->get_sites() as $site ) {
+ $result = $this->check_remote_site( $site, $username, $email );
+
+ if ( is_wp_error( $result ) ) {
+ return $result;
+ }
+
+ if ( $result['username_exists'] ) {
+ return new WP_Error( 'wprus_username_exists' );
+ }
+
+ if ( $result['email_exists'] ) {
+ return new WP_Error( 'wprus_email_exists' );
+ }
+ }
+
+ return true;
+ }
+
+ /** Whether the current user can manage other users. */
+ public static function can_manage_users() {
+
+ foreach ( array( 'manage_network_users', 'edit_users', 'add_users', 'create_users' ) as $capability ) {
+
+ if ( current_user_can( $capability ) ) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Validate a registration through WordPress's normal error handling.
+ *
+ * @param WP_Error $errors Existing registration errors.
+ * @param string $username Username being registered.
+ * @param string $email Email address being registered.
+ * @return WP_Error Registration errors.
+ */
+ public function validate_registration( $errors, $username, $email ) {
+
+ if ( $errors->has_errors() || self::can_manage_users() ) {
+ return $errors;
+ }
+
+ $result = $this->check_remote_identity( $username, $email );
+
+ if ( is_wp_error( $result ) ) {
+ $errors->add( $result->get_error_code(), $this->get_public_error_message( $result ) );
+ } else {
+ $this->approve_creation( $username, $email );
+ }
+
+ return $errors;
+ }
+
+ /**
+ * Show a clear error without exposing connected-site details.
+ *
+ * @param WP_Error $error Error returned by a connected-site check.
+ * @return string Message suitable for a registration form.
+ */
+ public function get_public_error_message( $error ) {
+
+ switch ( $error->get_error_code() ) {
+ case 'wprus_username_exists':
+ return __( 'This username is already in use. Please choose another.', 'wprus' );
+ case 'wprus_email_exists':
+ return __( 'This email address is already in use.', 'wprus' );
+ default:
+ return __( 'We could not complete your registration right now. Please try again later.', 'wprus' );
+ }
+ }
+
+ /**
+ * Validate a user created from the WordPress administration screen.
+ *
+ * @param WP_Error $errors Existing registration errors.
+ * @param bool $update Whether this is an existing account.
+ * @param WP_User $user Proposed user data.
+ */
+ public function validate_admin_registration( $errors, $update, $user ) {
+
+ if ( ! $update ) {
+ $this->validate_registration( $errors, $user->user_login, $user->user_email );
+ }
+ }
+
+ /**
+ * Validate a user created through the WordPress REST API.
+ *
+ * @param WP_User|WP_Error $prepared_user Proposed user or earlier error.
+ * @param WP_REST_Request $request The REST request.
+ * @return WP_User|WP_Error Proposed user or registration error.
+ */
+ public function validate_rest_registration( $prepared_user, $request ) {
+
+ if ( ! is_wp_error( $prepared_user ) && ! $request->get_param( 'id' ) ) {
+ $errors = $this->validate_registration( new WP_Error(), $prepared_user->user_login, $prepared_user->user_email );
+
+ if ( $errors->has_errors() ) {
+ return $errors;
+ }
+ }
+
+ return $prepared_user;
+ }
+
+ /**
+ * Approve a pair for exactly one later insertion in this request.
+ *
+ * @param string $username Approved username.
+ * @param string $email Approved email address.
+ */
+ public function approve_creation( $username, $email ) {
+ $key = $this->creation_key( $username, $email );
+ self::$approved_creations[ $key ] = ( self::$approved_creations[ $key ] ?? 0 ) + 1;
+ }
+
+ /**
+ * Require validation before any local unprivileged user is inserted.
+ *
+ * @param array $data WordPress user fields after sanitizing.
+ * @param bool $update Whether this is an existing account.
+ * @param int $user_id Existing user ID, when updating.
+ * @param array $userdata Original user fields supplied to WordPress.
+ * @return array User fields when creation is allowed.
+ * @throws Wprus_Identity_Creation_Exception When a registration method has no validation.
+ */
+ public function require_validated_creation( $data, $update, $user_id, $userdata ) {
+
+ if ( $update || self::$handling_incoming || self::can_manage_users() ) {
+ return $data;
+ }
+
+ $username = isset( $data['user_login'] ) ? $data['user_login'] : '';
+ $email = isset( $data['user_email'] ) ? $data['user_email'] : '';
+ $key = $this->creation_key( $username, $email );
+
+ if ( ! empty( self::$approved_creations[ $key ] ) ) {
+ --self::$approved_creations[ $key ];
+
+ return $data;
+ }
+
+ if ( has_action( 'wprus_validate_user_creation' ) ) {
+ $result = $this->check_remote_identity( $username, $email );
+
+ do_action( 'wprus_validate_user_creation', $username, $email, $data, $result );
+
+ return $data;
+ }
+
+ $message = sprintf( 'WPRUS rejected an unvalidated user creation for "%s".', $username );
+
+ $this->log_creation_failure( $message );
+ throw new Wprus_Identity_Creation_Exception( $message ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
+ }
+
+ /**
+ * Check again after insertion and skip Create if the result is uncertain.
+ *
+ * @param int $user_id Newly created user's ID.
+ */
+ public function check_created_user( $user_id ) {
+
+ if ( self::$handling_incoming || self::can_manage_users() ) {
+ return;
+ }
+
+ $user = get_userdata( $user_id );
+
+ if ( ! $user ) {
+ return;
+ }
+
+ $result = $this->check_remote_identity( $user->user_login, $user->user_email );
+
+ if ( is_wp_error( $result ) ) {
+ self::$blocked_creations[ $user_id ] = true;
+
+ Wprus_Logger::log(
+ sprintf( 'Outgoing Create action for user %d was skipped: %s.', $user_id, $result->get_error_code() ),
+ 'alert',
+ 'db_log'
+ );
+ }
+ }
+
+ /**
+ * Whether the current request blocked this user's outgoing Create action.
+ *
+ * @param int $user_id User ID to check.
+ * @return bool Whether Create should be skipped.
+ */
+ public static function is_creation_blocked( $user_id ) {
+ return ! empty( self::$blocked_creations[ $user_id ] );
+ }
+
+ /**
+ * Keep the email from before the first profile update in this request.
+ *
+ * @param int $user_id Updated user's ID.
+ * @param WP_User $old_user_data User data before the update.
+ */
+ public function remember_previous_email( $user_id, $old_user_data ) {
+
+ if ( $old_user_data instanceof WP_User && ! isset( self::$previous_emails[ $user_id ] ) ) {
+ self::$previous_emails[ $user_id ] = $old_user_data->user_email;
+ }
+ }
+
+ /**
+ * Add the sender's identifying email to outgoing action data.
+ *
+ * @param array $data Outgoing action data.
+ * @param string $endpoint Action name.
+ * @param string $url Connected-site URL.
+ * @return array Action data with the source email.
+ */
+ public function attach_identity_email( $data, $endpoint, $url ) {
+ return self::attach_source_identity( $data, $endpoint );
+ }
+
+ /**
+ * Preserve the sender's identity when an action is queued.
+ *
+ * @param array $data Outgoing action data.
+ * @param string $endpoint Action name.
+ * @return array Action data with the source email.
+ */
+ public static function attach_source_identity( $data, $endpoint ) {
+
+ if ( ! is_array( $data ) || ! isset( $data['username'] ) || 'identity' === $endpoint || isset( $data['identity_email'] ) ) {
+ return $data;
+ }
+
+ $user = get_user_by( 'login', $data['username'] );
+
+ if ( ! $user ) {
+ return $data;
+ }
+
+ $data['identity_email'] = 'update' === $endpoint && isset( self::$previous_emails[ $user->ID ] )
+ ? self::$previous_emails[ $user->ID ]
+ : $user->user_email;
+
+ return $data;
+ }
+
+ /**
+ * Reject operations against an existing account with another identity.
+ *
+ * @param array $data Incoming action data.
+ * @param string $endpoint Action name.
+ * @return bool Whether the account identity matches or does not exist locally.
+ */
+ public static function verify_incoming_identity( $data, $endpoint ) {
+
+ if ( ! is_array( $data ) || ! isset( $data['username'] ) || ! is_string( $data['username'] ) || '' === $data['username'] ) {
+ return false;
+ }
+
+ $user = get_user_by( 'login', $data['username'] );
+
+ if ( ! $user ) {
+ return true;
+ }
+
+ return isset( $data['identity_email'] ) &&
+ is_string( $data['identity_email'] ) &&
+ '' !== $data['identity_email'] &&
+ $user->user_login === $data['username'] &&
+ 0 === strcasecmp( $user->user_email, $data['identity_email'] );
+ }
+
+ /**
+ * Mark the authenticated incoming action while its handler runs.
+ *
+ * @param bool $handling Whether an incoming action is being handled.
+ */
+ public static function set_handling_incoming( $handling ) {
+ self::$handling_incoming = (bool) $handling;
+ }
+
+ /**
+ * Display a normal WordPress error page for uncaught creation failures.
+ *
+ * @param Throwable $exception Uncaught exception.
+ * @throws Throwable When no earlier exception handler exists.
+ */
+ public static function handle_uncaught_exception( Throwable $exception ) {
+
+ if ( $exception instanceof Wprus_Identity_Creation_Exception ) {
+ wp_die(
+ esc_html__( 'We could not create your account right now. Please try again later or contact the site administrator.', 'wprus' ),
+ esc_html__( 'Account not created', 'wprus' ),
+ array( 'response' => 409 )
+ );
+
+ return;
+ }
+
+ $previous_handler = self::$previous_exception_handler;
+
+ if ( null !== $previous_handler ) {
+ $previous_handler( $exception );
+
+ return;
+ }
+
+ throw $exception;
+ }
+
+ /**
+ * Use the values after WordPress has sanitized them.
+ *
+ * @param string $username Username supplied to WordPress.
+ * @param string $email Email address supplie