self::SITE_URL_MAX_LENGTH ) { return false; } $label = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?'; if ( 1 !== preg_match( '#\Ahttps://(' . $label . '(?:\.' . $label . ')*)/(?:[A-Za-z0-9._~-]+/)*\z#', $raw, $found ) ) { return false; } $host = $found[1]; if ( strlen( $host ) > 253 ) { return false; } foreach ( explode( '/', substr( $raw, strlen( 'https://' ) + strlen( $host ) + 1 ) ) as $segment ) { if ( '.' === $segment || '..' === $segment ) { return false; } } $labels = explode( '.', $host ); $last = end( $labels ); if ( 1 === preg_match( '/\A(?:[0-9]+|0x[0-9a-f]*)\z/', $last ) ) { if ( 1 !== preg_match( '/\A(?:0|[1-9][0-9]{0,2})(?:\.(?:0|[1-9][0-9]{0,2})){3}\z/', $host ) ) { return false; } foreach ( $labels as $part ) { if ( (int) $part > 255 ) { return false; } } } return true; } /** * The ASCII letters of a URL's host, lower-cased, and nothing else. This is the one rewrite * the site URL gets (spec 4.1): an address WordPress was set up with as `Example.com` is the * same site to a browser, and the grammar is lower-case only. `strtr` rather than * `strtolower`, which before PHP 8.2 follows the server's locale. */ public static function lower_host( $url ) { if ( ! is_string( $url ) || 1 !== preg_match( '#\A(https?://)([^/?\#]*)(.*)\z#s', $url, $parts ) ) { return $url; } return $parts[1] . strtr( $parts[2], 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz' ) . $parts[3]; } /** This site's URL as a connect request writes it: `home_url( '/' )` with its host lower-cased. It may still not fit the grammar. */ public static function canonical_site_url() { return self::lower_host( (string) home_url( '/' ) ); } /** Where WordPress's own admin-post.php is, as the same string: the return URL the app is told to come back to. */ public static function canonical_return_url() { return self::lower_host( (string) admin_url( 'admin-post.php?action=' . self::RETURN_ACTION ) ); } // The pending entry (spec 4.4) /** * The pending entry, read straight from the database, or null when there is none or what is * stored cannot be one. An entry that has been edited by hand or half written is treated as * absent everywhere, rather than half believed. */ public static function read_entry() { return self::sound_entry( EqualSites_Connect_Store::read_record( EqualSites_Connect_Store::PENDING ) ); } /** @return array|null The entry if every field has the shape a Start gives it. */ public static function sound_entry( $entry ) { if ( ! is_array( $entry ) ) { return null; } foreach ( array( 'user_id', 'created_at', 'expires_at' ) as $field ) { if ( ! isset( $entry[ $field ] ) || ! is_int( $entry[ $field ] ) ) { return null; } } foreach ( array( 'nonce', 'verifier', 'code_challenge', 'initiation_hash', 'site_url', 'return_url', 'api_origin', 'state_hash', 'status' ) as $field ) { if ( ! isset( $entry[ $field ] ) || ! is_string( $entry[ $field ] ) ) { return null; } } if ( 1 !== preg_match( '/\A[0-9a-f]{32}\z/', $entry['nonce'] ) || 1 !== preg_match( '/\A[0-9a-f]{64}\z/', $entry['state_hash'] ) || ! self::is_base64url_43( $entry['verifier'] ) || ! self::is_base64url_43( $entry['code_challenge'] ) || ! self::is_base64url_43( $entry['initiation_hash'] ) || '' === $entry['api_origin'] || ! self::site_url_fits( $entry['site_url'] ) || $entry['return_url'] !== $entry['site_url'] . self::RETURN_PATH || ! in_array( $entry['status'], array( 'pending', 'exchanging' ), true ) ) { return null; } return $entry; } /** An entry is live while `now < expires_at`, and at or past it counts as absent (spec 4.4). */ public static function entry_is_live( $entry, $now = null ) { return is_array( $entry ) && ( null === $now ? self::now() : $now ) < $entry['expires_at']; } // The challenge (spec 4.2) /** * What the challenge answers for a presented state: the digest while the entry is `pending`, * before its `expires_at`, and its stored state hash matches the state under `hash_equals`; * a bare 404 for everything else, an entry that is `exchanging` included. No login is * needed and no detail is given, so the answer says nothing about whether a flow exists. * The same function answers both routes, so they cannot disagree. * * @return array array( 'status' => 200|404, 'body' => string ) */ public static function challenge_reply( $state ) { $none = array( 'status' => 404, 'body' => '', ); if ( ! self::is_base64url_43( $state ) ) { return $none; } $entry = self::read_entry(); if ( null === $entry || 'pending' !== $entry['status'] || ! self::entry_is_live( $entry ) ) { return $none; } if ( ! hash_equals( $entry['state_hash'], hash( 'sha256', $state ) ) ) { return $none; } return array( 'status' => 200, 'body' => self::challenge_digest( $state, $entry['code_challenge'], $entry['initiation_hash'], $entry['site_url'], $entry['return_url'] ), ); } /** The headers of both answers: plain text, and nothing a cache or a proxy may keep. */ public static function challenge_headers() { return array( 'Content-Type' => 'text/plain; charset=utf-8', 'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0', ); } /** * `nocache_headers()` and `DONOTCACHEPAGE`, the way the baseline bypass does it: a page-cache * plugin that stored the answer would serve it to the next request after the flow had moved on. */ private static function mark_uncacheable() { nocache_headers(); if ( ! defined( 'DONOTCACHEPAGE' ) ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- DONOTCACHEPAGE is the exact name page-cache plugins look for, so it cannot carry a prefix. define( 'DONOTCACHEPAGE', true ); } } public static function register_rest_routes() { register_rest_route( self::REST_NAMESPACE, self::REST_PATH, array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'rest_challenge' ), // Public on purpose: the app is not a WordPress user. The state is the credential. 'permission_callback' => '__return_true', ) ); } /** * The REST answer. WordPress JSON-encodes whatever a route returns, which would put quotes * round the digest, so the body goes out through `rest_pre_serve_request`: a filter that * returns true tells the server the request has been served. It is added from inside the * route's own callback, so it exists only for a request that reached this route, and it * checks the route again so that a nested REST call cannot let it answer someone else's. * * @param WP_REST_Request $request * @return WP_REST_Response */ public static function rest_challenge( $request ) { $reply = self::challenge_reply( $request->get_param( 'state' ) ); self::mark_uncacheable(); add_filter( 'rest_pre_serve_request', function ( $served, $result, $served_request ) use ( $reply ) { if ( ! $served_request instanceof WP_REST_Request || '/' . self::REST_NAMESPACE . self::REST_PATH !== $served_request->get_route() ) { return $served; } // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- 43 base64url characters the plugin has just computed, or nothing, served as text/plain. echo $reply['body']; return true; }, 10, 3 ); $response = new WP_REST_Response( null, $reply['status'] ); foreach ( self::challenge_headers() as $name => $value ) { $response->header( $name, $value ); } return $response; } /** * The fallback, for sites whose REST API is blocked or whose permalinks are plain: the same * answer at `?ableguard_connect_challenge=`, served on `init` before any * template is chosen. A request that does not carry the parameter is not ours and carries on. */ public static function serve_challenge_fallback() { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- a public read whose state is the credential; the app that asks has no WordPress session, so there is nothing for a nonce to bind to. if ( ! isset( $_GET[ self::FALLBACK_PARAM ] ) || 'GET' !== self::request_method() ) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- see above; sanitised by clean_input(), then only compared against the stored hash, and anything that is not 43 base64url characters is refused first. $state = is_string( $_GET[ self::FALLBACK_PARAM ] ) ? self::clean_input( wp_unslash( $_GET[ self::FALLBACK_PARAM ] ) ) : ''; $reply = self::challenge_reply( $state ); self::mark_uncacheable(); status_header( $reply['status'] ); foreach ( self::challenge_headers() as $name => $value ) { header( $name . ': ' . $value, true ); } // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- as above: the digest, or nothing, as text/plain. echo $reply['body']; self::stop(); } /** * A request value, already unslashed, as `sanitize_text_field()` leaves it, or '' when * sanitising would change it. Each caller matches what comes back against a strict pattern * next, and what no pattern here allows (markup, a line break at either end, a percent-encoded * octet) is just what sanitising strips. Letting it strip first could turn a value the pattern * refuses into one it accepts, and the REST route, which reads the same state from its own * parameter, would then answer differently from the fallback. A value that needs cleaning is * refused instead. * * @param mixed $value * @return string */ private static function clean_input( $value ) { if ( ! is_string( $value ) ) { return ''; } $clean = sanitize_text_field( $value ); return $clean === $value ? $clean : ''; } /** The request's method, upper-cased, or '' when the server did not say. */ private static function request_method() { return isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : ''; } // Notices (spec 2) private static function notice_key() { return self::NOTICE_PREFIX . 'notice_' . get_current_user_id(); } /** * Leaves a notice for this user's next page load of the screen. `$param` is a reason key, an * error text WordPress or the plugin wrote, or empty; `$extra` carries the few values a * success notice names (the account label, the number of fixes). */ public static function set_notice( $code, $param = '', $extra = array() ) { set_transient( self::notice_key(), array_merge( $extra, array( 'code' => $code, 'param' => (string) $param ) ), self::NOTICE_TTL ); } /** The notice waiting for this user, taken: shown once. Anything not from the closed list is dropped. */ public static function take_notice() { $key = self::notice_key(); $stored = get_transient( $key ); if ( false === $stored ) { return null; } delete_transient( $key ); return is_array( $stored ) && isset( $stored['code'] ) && in_array( $stored['code'], self::NOTICE_CODES, true ) ? $stored : null; } /** * Leaves a notice and sends the administrator back to the settings screen. It ends the * request, so no lock may be held when it is called: `exit` runs no `finally`. */ private static function finish( $code, $param = '', $extra = array() ) { self::set_notice( $code, $param, $extra ); wp_safe_redirect( admin_url( 'admin.php?page=ableguard' ) ); self::stop(); } /** * What Start, Disconnect and the manual save check first, in this order: the method, then * the nonce, then the capability. `admin-post.php` dispatches on `$_REQUEST['action']` for * any method, and `check_admin_referer()` accepts a nonce from the query string, so a GET * with a leaked nonce, or a browser's prefetch, would otherwise act. A refused request * changes nothing. */ private static function guard( $action ) { if ( 'POST' !== self::request_method() ) { wp_die( esc_html__( 'Method not allowed.', 'ableguard-accessibility-toolkit' ), '', array( 'response' => 405 ) ); } if ( ! check_admin_referer( $action ) || ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Not allowed.', 'ableguard-accessibility-toolkit' ), '', array( 'response' => 403 ) ); } } // Start (spec 3, S1) /** * Connect, or Reconnect: validate everything, ask the app whether it offers one-click, mint * the secrets, write the site-wide pending entry under the lock, and send this tab to the * app. Anything that stops it leaves a notice with its own reason and changes nothing. * * The probe is a network call of up to ten seconds, so the lock is not held across it: the * lock is taken once to learn the storage is migrated (running the migration if it is not), * and once more to write the entry. */ public static function handle_start() { self::guard( self::START_ACTION ); $migrated = EqualSites_Connect_Store::locked( function () { return true; } ); if ( 'unsupported' === $migrated['status'] ) { self::finish( 'unavailable', 'database' ); return; } if ( 'ok' !== $migrated['status'] ) { self::finish( 'busy_site' ); return; } $api = ableguard_api_url(); if ( '' === $api ) { self::finish( 'unavailable', 'api' ); return; } $site_url = self::canonical_site_url(); if ( ! self::site_url_fits( $site_url ) ) { self::finish( 'unavailable', 'address' ); return; } if ( self::canonical_return_url() !== $site_url . self::RETURN_PATH ) { self::finish( 'unavailable', 'admin' ); return; } $session = (string) wp_get_session_token(); if ( '' === $session ) { self::finish( 'unavailable', 'session' ); return; } $unanswered = self::probe( $api ); if ( null !== $unanswered ) { self::finish( $unanswered[0], $unanswered[1] ); return; } $secrets = self::mint(); if ( null === $secrets ) { self::finish( 'unavailable', 'random' ); return; } $state = self::state_for( wp_salt( 'auth' ), $session, $secrets['nonce'] ); $now = self::now(); $entry = array( 'user_id' => (int) get_current_user_id(), 'nonce' => $secrets['nonce'], 'verifier' => $secrets['verifier'], 'code_challenge' => self::sha256_base64url( $secrets['verifier'] ), 'initiation_hash' => self::sha256_base64url( $secrets['secret'] ), 'site_url' => $site_url, 'return_url' => $site_url . self::RETURN_PATH, 'api_origin' => $api, 'state_hash' => hash( 'sha256', $state ), 'status' => 'pending', 'created_at' => $now, 'expires_at' => $now + self::ENTRY_LIFETIME, ); // Replaces whatever entry exists, whoever started it: one flow per site. $written = EqualSites_Connect_Store::locked( function ( $tx ) use ( $entry ) { return $tx->write( EqualSites_Connect_Store::PENDING, $entry ); } ); if ( 'ok' !== $written['status'] || true !== $written['value'] ) { self::finish( 'busy_site' ); return; } self::send_to_app( $api, array( 'site_url' => $entry['site_url'], 'return_url' => $entry['return_url'], 'state' => $state, 'code_challenge' => $entry['code_challenge'], 'code_challenge_method' => 'S256', 'initiation_hash' => $entry['initiation_hash'], 'plugin_version' => EQUALSITES_VERSION, ), $secrets['secret'] ); } /** * Asks the app whether it offers one-click connect: `GET /api/config`, which answers * `wordpressConnect: true` once the feature is on. Against the old API, or with the switch * off, the flag is missing or false and the owner is sent to the manual form instead. * * @return array|null A notice code and its parameter when the answer is not yes, null when it is. */ private static function probe( $api ) { $response = wp_safe_remote_get( $api . '/api/config', array( 'timeout' => 10, 'redirection' => 0, 'limit_response_size' => 8192, 'headers' => array( 'Accept' => 'application/json' ), ) ); if ( is_wp_error( $response ) ) { return array( 'unreachable', $response->get_error_message() ); } $status = (int) wp_remote_retrieve_response_code( $response ); if ( $status >= 500 ) { return array( 'unreachable', 'HTTP ' . $status ); } if ( 429 === $status ) { return array( 'busy_api', '' ); } $body = 200 === $status ? json_decode( (string) wp_remote_retrieve_body( $response ), true ) : null; if ( ! is_array( $body ) || ! isset( $body['wordpressConnect'] ) || true !== $body['wordpressConnect'] ) { return array( 'unavailable', 'switch' ); } return null; } private static function random( $bytes ) { return null !== self::$random ? call_user_func( self::$random, $bytes ) : random_bytes( $bytes ); } /** * The secrets of one Start: a nonce (16 bytes, hex), a PKCE verifier (32 bytes, base64url, 43 * characters) and the initiation secret (32 bytes, base64url). Null when the server has no * secure source of randomness, in which case nothing weaker is used. * * @return array|null */ public static function mint() { $made = array(); foreach ( array( 'nonce' => 16, 'verifier' => 32, 'secret' => 32 ) as $name => $size ) { try { $bytes = self::random( $size ); } catch ( Exception $e ) { return null; } if ( ! is_string( $bytes ) || strlen( $bytes ) !== $size ) { return null; } $made[ $name ] = 'nonce' === $name ? bin2hex( $bytes ) : self::base64url( $bytes ); } return $made; } /** * Sends this tab to `/connect/wordpress?#ableguard_secret=`. * * `wp_safe_redirect()` drops any host that is not the site's own or allowed, and falls back to * the admin: without help the button would reload wp-admin and do nothing (spec 4.3, R1). So * after the origin has been matched exactly against the allowlist once more, a filter adds * that one host for this one call and is removed again; it is never registered at load. The * query carries only the hash of the initiation secret, and the fragment, which no request * and no Referer ever carries, carries the secret. `wp_sanitize_redirect()` keeps `#`, `=` * and the base64url alphabet, so the fragment survives (W1 proves it on a real site). * * @param string $api An origin already returned by `ableguard_api_url()`. * @param array $fields The seven query fields, in the order the app lists them. * @param string $secret The initiation secret. */ public static function send_to_app( $api, $fields, $secret ) { $host = '' !== $api && ableguard_api_origin( $api ) === $api ? wp_parse_url( $api, PHP_URL_HOST ) : null; if ( ! is_string( $host ) || '' === $host ) { self::finish( 'unavailable', 'api' ); return; } $allow = function ( $hosts ) use ( $host ) { $hosts[] = $host; return $hosts; }; add_filter( 'allowed_redirect_hosts', $allow ); wp_safe_redirect( $api . '/connect/wordpress?' . http_build_query( $fields, '', '&', PHP_QUERY_RFC3986 ) . '#ableguard_secret=' . $secret ); remove_filter( 'allowed_redirect_hosts', $allow ); self::stop(); } // The return (spec 4.4, S8 and S9) private static function send_private_headers() { nocache_headers(); foreach ( self::PRIVATE_HEADERS as $line ) { header( $line, true ); } } /** * A browser that is not logged in reaches the nopriv action. It never reads, stores or logs * the code or the state, and touches no pending state: it sends the visitor to wp-login, and * after the login they land on the plugin's page (spec R3). */ public static function handle_return_logged_out() { self::send_private_headers(); wp_safe_redirect( wp_login_url( admin_url( 'admin.php?page=ableguard' ) ) ); self::stop(); } /** * The owner's browser, back from the app. Neither this nor the logged-out handler has a * `wp_die()` path: a callback that fails any check leaves the entry exactly as it was and * ends on the settings screen with the `expired` notice, so a stranger's callback cannot * cancel a flow and a refresh of a used one cannot do anything. * * There is no WordPress nonce on the return: the state, which only this browser session can * recompute, is the control against a forged request. */ public static function handle_return() { self::send_private_headers(); $callback = self::parse_callback(); $session = (string) wp_get_session_token(); if ( null === $callback || ! current_user_can( 'manage_options' ) || '' === $session ) { self::finish( 'expired' ); return; } $verdict = self::check_callback( self::read_entry(), $callback['state'], $session ); if ( null === $verdict ) { self::finish( 'expired' ); return; } if ( isset( $callback['error'] ) ) { // An error callback carries no proof from AbleGuard, so it leaves the entry alone: an // attacker who has learnt a state must not be able to cancel the owner's flow. self::finish( 'access_denied' === $callback['error'] ? 'cancelled' : 'expired' ); return; } if ( 'exchanging' === $verdict ) { self::finish( 'busy_site' ); return; } self::complete( $callback['code'], $callback['state'], $session ); } /** * The callback's query, parsed from the raw string rather than from `$_GET`, which silently * keeps the last of two duplicate keys. The keys must be exactly `action`, `state` and `code`, * or exactly `action`, `state` and `error`, each once, in a GET request, and `state` and `code` * must be 43 base64url characters. Anything else is not a callback. * * @return array|null array( 'state' => ..., 'code' => ... ) or array( 'state' => ..., 'error' => ... ). */ private static function parse_callback() { if ( 'GET' !== self::request_method() ) { return null; } $query = self::raw_query(); if ( '' === $query ) { return null; } $pairs = array(); foreach ( explode( '&', $query ) as $segment ) { if ( '' === $segment ) { return null; } $cut = strpos( $segment, '=' ); $key = urldecode( false === $cut ? $segment : substr( $segment, 0, $cut ) ); if ( array_key_exists( $key, $pairs ) ) { return null; } $pairs[ $key ] = false === $cut ? '' : urldecode( substr( $segment, $cut + 1 ) ); } $keys = array_map( 'strval', array_keys( $pairs ) ); sort( $keys ); if ( array( 'action', 'code', 'state' ) === $keys ) { $third = 'code'; } elseif ( array( 'action', 'error', 'state' ) === $keys ) { $third = 'error'; } else { return null; } if ( self::RETURN_ACTION !== $pairs['action'] || ! self::is_base64url_43( $pairs['state'] ) ) { return null; } if ( 'code' === $third && ! self::is_base64url_43( $pairs['code'] ) ) { return null; } return array( 'state' => $pairs['state'], $third => $pairs[ $third ], ); } /** The request's query string as the server received it. */ private static function raw_query() { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitised by clean_input(), then parsed and compared against strict patterns below, never output or stored. if ( isset( $_SERVER['QUERY_STRING'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- as above. return self::clean_input( wp_unslash( $_SERVER['QUERY_STRING'] ) ); } // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- as above. $uri = isset( $_SERVER['REQUEST_URI'] ) ? self::clean_input( (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_QUERY ) ) : ''; return $uri; } /** * Step 3 of spec 4.4: does this callback belong to this entry, this administrator and this * browser session, and is the entry still alive? Everything is compared under `hash_equals`, * and the status is the last thing looked at, so a second callback for a flow that is already * being exchanged can be told from a stranger's. * * @return string|null The entry's status (`pending` or `exchanging`) when the callback verifies, null when it does not. */ private static function check_callback( $entry, $state, $session ) { if ( null === $entry || ! self::entry_is_live( $entry ) ) { return null; } if ( (int) get_current_user_id() !== $entry['user_id'] || ! hash_equals( $entry['state_hash'], hash( 'sha256', $state ) ) ) { return null; } if ( ! hash_equals( self::state_for( wp_salt( 'auth' ), $session, $entry['nonce'] ), $state ) ) { return null; } return $entry['status']; } /** * A verified code callback, in the three steps of spec S8 and S9: * * 1. Under the lock, re-read the entry, check it again (the expiry included) and swap it from * that exact `pending` text to `exchanging` with a fenced write. That write is the point * where the flow is decided: an entry that expired between the first check and here is * not marked, and neither is one whose lock has passed to another holder. Release. * 2. Exchange the code, once, with no lock held. The code is burned by the attempt, so it is * never sent twice, whatever the answer. * 3. Take the lock again, waiting for it, because the app has already acted. If the entry is * still this flow's, commit the connection (or restore the entry to `pending` after a * failure); otherwise throw the result away. Release, and only then sync and say so. */ private static function complete( $code, $state, $session ) { $marked = EqualSites_Connect_Store::locked( function ( $tx ) use ( $state, $session ) { $current = self::sound_entry( $tx->read( EqualSites_Connect_Store::PENDING ) ); $verdict = self::check_callback( $current, $state, $session ); if ( 'exchanging' === $verdict ) { return array( 'busy_site' ); } if ( 'pending' !== $verdict ) { return array( 'expired' ); } $exchanging = $current; $exchanging['status'] = 'exchanging'; return $tx->write( EqualSites_Connect_Store::PENDING, $exchanging ) ? array( 'marked', $current, $exchanging ) : array( 'busy_site' ); } ); if ( 'unsupported' === $marked['status'] ) { self::finish( 'unavailable', 'database' ); return; } if ( 'ok' !== $marked['status'] || 'marked' !== $marked['value'][0] ) { self::finish( 'ok' === $marked['status'] ? $marked['value'][0] : 'busy_site' ); return; } $pending = $marked['value'][1]; $exchanging = $marked['value'][2]; $answer = self::exchange( $exchanging, $code, $state ); $settled = EqualSites_Connect_Store::locked( function ( $tx ) use ( $pending, $exchanging, $answer ) { if ( EqualSites_Connect_Store::encode( $exchanging ) !== $tx->read_raw( EqualSites_Connect_Store::PENDING ) ) { return array( 'superseded' ); } if ( ! $answer['ok'] ) { return $tx->write( EqualSites_Connect_Store::PENDING, $pending ) ? array( 'restored' ) : array( 'superseded' ); } $before = $tx->read( EqualSites_Connect_Store::CONNECTION ); $connection = array( 'api_url' => $exchanging['api_origin'], 'site_id' => $answer['site_id'], 'token' => $answer['token'], 'account' => $answer['account'], 'method' => 'one_click', 'saved_at' => self::now(), ); $swapped = EqualSites_Connect_Store::swap_connection( $tx, $connection, $exchanging ); return array( 'ok' === $swapped['status'] ? 'connected' : 'superseded', EqualSites_Connect_Store::connection_active( $before ) ); }, self::LOCK_WAIT_SECONDS ); if ( 'ok' !== $settled['status'] || 'superseded' === $settled['value'][0] ) { self::finish( 'superseded' ); return; } if ( 'restored' === $settled['value'][0] ) { self::finish( $answer['code'], $answer['param'] ); return; } // Committed, and the lock is released. The first sync is what tells the owner how many // fixes now apply, and a sync that fails does not undo the connection. $synced = EqualSites_Api_Client::sync_rules(); if ( is_wp_error( $synced ) ) { self::finish( 'first_sync_failed', $synced->get_error_message(), array( 'account' => $answer['account'] ) ); return; } $notice = $settled['value'][1] ? 'reconnected' : ( $synced > 0 ? 'connected' : 'connected_none' ); self::finish( $notice, '', array( 'account' => $answer['account'], 'fixes' => (int) $synced, ) ); } /** * The exchange (S9): `POST /api/connect/wordpress/token` to the origin the entry was * made for, which is checked against the allowlist again first, so a code never crosses * environments and an address that has since stopped being AbleGuard's is never sent one. * The body has exactly four fields. What comes back is validated before anything is saved: * a UUID, a 48-hex token and the site's own origin, plus a masked account label that is kept * only if it is valid. * * @return array array( 'ok' => true, 'site_id' => ..., 'token' => ..., 'account' => ... ) or * array( 'ok' => false, 'code' => a notice code, 'param' => its parameter ). */ private static function exchange( $entry, $code, $state ) { $api = ableguard_api_origin( $entry['api_origin'] ); if ( '' === $api ) { return array( 'ok' => false, 'code' => 'unavailable', 'param' => 'api', ); } $response = wp_safe_remote_post( $api . '/api/connect/wordpress/token', array( 'timeout' => 20, 'redirection' => 0, 'limit_response_size' => 4096, 'headers' => array( 'Content-Type' => 'application/json', 'Accept' => 'application/json', ), 'body' => wp_json_encode( array( 'code' => $code, 'codeVerifier' => $entry['verifier'], 'state' => $state, 'siteUrl' => $entry['site_url'], ) ), ) ); if ( is_wp_error( $response ) ) { return array( 'ok' => false, 'code' => 'unreachable', 'param' => $response->get_error_message(), ); } $status = (int) wp_remote_retrieve_response_code( $response ); if ( 400 === $status ) { return array( 'ok' => false, 'code' => 'expired', 'param' => '', ); } if ( 429 === $status ) { return array( 'ok' => false, 'code' => 'busy_api', 'param' => '', ); } $reply = 200 === $status ? self::valid_reply( (string) wp_remote_retrieve_body( $response ), $entry['site_url'] ) : null; if ( null === $reply ) { return 200 === $status ? array( 'ok' => false, 'code' => 'expired', 'param' => '', ) : array( 'ok' => false, 'code' => 'unreachable', 'param' => 'HTTP ' . $status, ); } return array_merge( array( 'ok' => true ), $reply ); } /** * The one reply the exchange can succeed with, or null for anything that is not exactly that: * at most 4 KiB, a JSON object, a UUID for the site, a 48-hex token and the origin of the site * URL this flow was started for. The account label is a courtesy shown to the owner, so a label * that is missing or not valid is dropped and the connection is made without it (spec 8: a * refused label leaves the v4 wording). Refusing the reply over it would throw away a token the * app has already rotated, because the code burns when it is presented, and the site would be * left on a dead one. * * @return array|null array( 'site_id' => ..., 'token' => ..., 'account' => '' or a valid label ) */ private static function valid_reply( $body, $site_url ) { $data = strlen( $body ) <= 4096 ? json_decode( $body, true ) : null; if ( ! is_array( $data ) ) { return null; } foreach ( array( 'siteId', 'token', 'origin' ) as $field ) { if ( ! isset( $data[ $field ] ) || ! is_string( $data[ $field ] ) ) { return null; } } if ( 1 !== preg_match( self::UUID_PATTERN, $data['siteId'] ) || 1 !== preg_match( self::TOKEN_PATTERN, $data['token'] ) || self::origin_of( $site_url ) !== $data['origin'] ) { return null; } $account = isset( $data['account'] ) && is_string( $data['account'] ) && self::valid_account_label( $data['account'] ) ? $data['account'] : ''; return array( 'site_id' => $data['siteId'], 'token' => $data['token'], 'account' => $account, ); } /** `https://host` of a site URL: what the app's `new URL(siteUrl).origin` is, with no base path. */ public static function origin_of( $site_url ) { $end = strpos( $site_url, '/', strlen( 'https://' ) ); return false === $end ? $site_url : substr( $site_url, 0, $end ); } /** * The masked address of the account a site is connected to, for example `d***@example.com`, * is kept only if it is at most 254 characters, has exactly one `@` with something on each * side, and holds no whitespace, no control or format character and nothing that could be * markup. It ends up in `wp_options`, where any plugin can read it, and on the settings * screen, always escaped (spec 8, Open for David item 5). */ public static function valid_account_label( $label ) { if ( ! is_string( $label ) || '' === $label || strlen( $label ) > 254 || 1 !== substr_count( $label, '@' ) ) { return false; } if ( 1 !== preg_match( '/\A[^@]+@[^@]+\z/u', $label ) ) { return false; } return 0 === preg_match( '/[\p{Z}\p{C}<>&"\'`]/u', $label ); } // Disconnect (spec 3, S11) /** * Disconnect: under the lock, with fenced writes, the connection record goes first, so * nothing is served from that moment, then the delivery, the pending entry and the * bookkeeping. It makes no network call: the site token stays valid in AbleGuard until the * owner reconnects or deletes the site in the dashboard (R4), because a token that could * retire itself could be retired by whoever holds it. * * On a database that refused the store's statements there is no lock and no record, only * the 0.3.1 options, and those are what it removes. */ public static function handle_disconnect() { self::guard( self::DISCONNECT_ACTION ); $done = EqualSites_Connect_Store::locked( function ( $tx ) { return EqualSites_Connect_Store::disconnect( $tx ); } ); if ( 'unsupported' === $done['status'] ) { EqualSites_Connect_Store::delete_legacy_options( true, true ); self::finish( 'disconnected' ); return; } if ( 'ok' !== $done['status'] ) { self::finish( 'busy_site' ); return; } // A fenced delete that was refused means the lock was lost part way: whatever was deleted // first stays deleted, which is the safe half, and the owner presses Disconnect again. self::finish( true === $done['value'] ? 'disconnected' : 'superseded' ); } // The manual form (spec 8) /** * A posted field, sanitised and trimmed. The nonce has been checked by `guard()` before any * field is read. Unlike a state or a callback, a blank here means something (keep the saved * value, or save production), so a value is cleaned rather than turned into a blank for * needing it: the pattern or the allowlist then judges what is left. */ private static function posted( $key ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- guard() has already checked the nonce; every value is matched against a strict pattern or the allowlist before it is stored. return isset( $_POST[ $key ] ) && is_string( $_POST[ $key ] ) ? trim( sanitize_text_field( wp_unslash( $_POST[ $key ] ) ) ) : ''; } /** * The manual save: the three fields the owner pastes, in a form of their own, so that no * other form can write or blank them (the settings form posts to `options.php` and holds * only the switch). It takes the lock, and in the order of spec 8: * * 1. The posted `generation` must be the connection record's current one. A page drawn * before another administrator connected or saved can no longer write its stale site ID * next to the newer token: it is `superseded`. * 2. A blank API address saves production, and one that is not AbleGuard's is refused * (unless `ABLEGUARD_ALLOW_CUSTOM_API` is set, for development). * 3. A blank site ID or token keeps the saved value; a non-blank site ID must be a UUID * and a non-blank token 48 hex. * 4. A site ID that differs from the current one needs a token of its own. * 5. Then the same connection swap an exchange makes, with fenced writes, which also * deletes the pending entry. * * The token is never printed into the page, so the form cannot post it back: blank means * keep, and that is what lets the owner save the staging address alone. */ public static function handle_manual_save() { self::guard( self::MANUAL_ACTION ); $posted = array( 'generation' => self::posted( 'generation' ), 'api_url' => self::posted( 'ableguard_api_url' ), 'site_id' => self::posted( 'ableguard_site_id' ), 'token' => self::posted( 'ableguard_token' ), ); $done = EqualSites_Connect_Store::locked( function ( $tx ) use ( $posted ) { $current = $tx->read( EqualSites_Connect_Store::CONNECTION ); if ( (string) ( is_array( $current ) && isset( $current['generation'] ) ? $current['generation'] : '' ) !== $posted['generation'] ) { return array( 'superseded' ); } $plan = self::plan_manual_save( $posted, self::saved_connection( $current ) ); if ( isset( $plan['refused'] ) ) { return array( 'refused', $plan['refused'] ); } $swapped = EqualSites_Connect_Store::swap_connection( $tx, $plan['connection'], null ); return array( 'ok' === $swapped['status'] ? self::manual_saved_code( $plan['connection'] ) : 'superseded' ); } ); if ( 'unsupported' === $done['status'] ) { $plan = self::plan_manual_save( $posted, self::saved_connection( EqualSites_Connect_Store::connection_direct() ) ); if ( isset( $plan['refused'] ) ) { self::finish( 'manual_refused', $plan['refused'] ); return; } self::save_unsupported( $plan['connection'] ); self::finish( self::manual_saved_code( $plan['connection'] ) ); return; } if ( 'ok' !== $done['status'] ) { self::finish( 'busy_site' ); return; } if ( 'refused' === $done['value'][0] ) { self::finish( 'manual_refused', $done['value'][1] ); return; } self::finish( $done['value'][0] ); } private static function manual_saved_code( $connection ) { return EqualSites_Connect_Store::connection_active( $connection ) ? 'manual_saved' : 'manual_address_saved'; } /** The connection a manual save starts from, as the values it merges blanks with. */ private static function saved_connection( $connection ) { $connection = is_array( $connection ) ? $connection : array(); $saved = array(); foreach ( array( 'api_url', 'site_id', 'token', 'account', 'method' ) as $field ) { $saved[ $field ] = (string) ( isset( $connection[ $field ] ) ? $connection[ $field ] : '' ); } return $saved; } /** * Steps 2 to 4 of the manual save, which need no database: what would be saved, or why not. * * An address-only record (an address chosen, no site yet) holds nothing else. A record that * is saved unchanged keeps the account label and method it had, because pressing Save with * the form as drawn must not erase what a one-click connect recorded; any change makes the * connection a manual one with no label, since nothing here says whose account it is. * * @return array array( 'connection' => array ) or array( 'refused' => a reason key ). */ private static function plan_manual_save( $posted, $saved ) { $api = ableguard_api_origin( $posted['api_url'] ); if ( '' === $api ) { return array( 'refused' => 'api' ); } if ( '' !== $posted['site_id'] && 1 !== preg_match( self::UUID_PATTERN, $posted['site_id'] ) ) { return array( 'refused' => 'id' ); } if ( '' !== $posted['token'] && 1 !== preg_match( self::TOKEN_PATTERN, $posted['token'] ) ) { return array( 'refused' => 'token' ); } $site_id = '' === $posted['site_id'] ? $saved['site_id'] : $posted['site_id']; $token = '' === $posted['token'] ? $saved['token'] : $posted['token']; if ( $site_id !== $saved['site_id'] && '' === $posted['token'] ) { return array( 'refused' => 'need_token' ); } $connection = array( 'api_url' => $api ); if ( '' !== $site_id ) { $connection['site_id'] = $site_id; } if ( '' !== $token ) { $connection['token'] = $token; } if ( '' !== $site_id && '' !== $token ) { $unchanged = $api === $saved['api_url'] && $site_id === $saved['site_id'] && $token === $saved['token']; $connection['account'] = $unchanged ? $saved['account'] : ''; $connection['method'] = $unchanged && '' !== $saved['method'] ? $saved['method'] : 'manual'; $connection['saved_at'] = self::now(); } return array( 'connection' => $connection ); } /** * What the manual save writes on a database that refused the store's statements: the three * options 0.3.1 kept the connection in, which are the only storage that site has. There is * no lock, no generation and no record there, so nothing here is fenced, and one-click * connect is not offered. */ private static function save_unsupported( $connection ) { update_option( 'ableguard_api_url', $connection['api_url'], false ); update_option( 'ableguard_site_id', isset( $connection['site_id'] ) ? $connection['site_id'] : '', false ); update_option( 'ableguard_token', isset( $connection['token'] ) ? $connection['token'] : '', false ); } // The copy of the notices (spec 2 and 8) /** * What a stored notice says. The text is the plugin's own, chosen by the code and never taken * from a URL: `{reason}` comes from a closed list, `{error}` is WordPress's or the plugin's own * error text, `{account}` the validated label. The caller escapes the whole text when it prints it. * * @param array $stored A notice as `take_notice()` returns it. * @return array array( 'class' => the WordPress notice class, 'text' => the unescaped text ). */ public static function notice_view( $stored ) { $param = isset( $stored['param'] ) ? (string) $stored['param'] : ''; $account = isset( $stored['account'] ) && self::valid_account_label( $stored['account'] ) ? (string) $stored['account'] : ''; $fixes = isset( $stored['fixes'] ) ? (int) $stored['fixes'] : 0; switch ( isset( $stored['code'] ) ? $stored['code'] : '' ) { case 'unavailable': /* translators: %s: why one-click connect is not available here */ return self::notice_text( 'notice-error', sprintf( __( "One-click connect isn't available here: %s. Connect manually under Advanced.", 'ableguard-accessibility-toolkit' ), self::reason_text( $param ) ) ); case 'unreachable': /* translators: %s: the error WordPress reported */ return self::notice_text( 'notice-error', sprintf( __( "Couldn't reach AbleGuard (%s). Press Connect to try again.", 'ableguard-accessibility-toolkit' ), $param ) ); case 'cancelled': return self::notice_text( 'notice-info', __( 'Connection cancelled. Nothing changed.', 'ableguard-accessibility-toolkit' ) ); case 'expired': return self::notice_text( 'notice-error', __( "That approval expired or didn't start here. Press Connect to try again.", 'ableguard-accessibility-toolkit' ) ); case 'busy_api': return self::notice_text( 'notice-warning', __( 'AbleGuard is busy right now. Press Connect again in a minute.', 'ableguard-accessibility-toolkit' ) ); case 'busy_site': return self::notice_text( 'notice-warning', __( 'Another AbleGuard change is in progress on this site. Try again in a moment.', 'ableguard-accessibility-toolkit' ) ); case 'superseded': return self::notice_text( 'notice-warning', __( "Another change to this site's AbleGuard connection happened at the same time, so this one wasn't saved. Reload this page and try again.", 'ableguard-accessibility-toolkit' ) ); case 'connected': return self::notice_text( 'notice-success', '' !== $account /* translators: 1: the masked AbleGuard account address, 2: number of fixes */ ? sprintf( __( 'Connected to AbleGuard as %1$s. %2$d approved fixes are now applied to your pages.', 'ableguard-accessibility-toolkit' ), $account, $fixes ) /* translators: %d: number of fixes */ : sprintf( __( 'Connected to AbleGuard. %d approved fixes are now applied to your pages.', 'ableguard-accessibility-toolkit' ), $fixes ) ); case 'connected_none': return self::notice_text( 'notice-success', '' !== $account /* translators: %s: the masked AbleGuard account address */ ? sprintf( __( 'Connected to AbleGuard as %s. Approve fixes in your dashboard; they arrive at the next sync.', 'ableguard-accessibility-toolkit' ), $account ) : __( 'Connected to AbleGuard. Approve fixes in your dashboard; they arrive at the next sync.', 'ableguard-accessibility-toolkit' ) ); case 'reconnected': return self::notice_text( 'notice-success', '' !== $account /* translators: %s: the masked AbleGuard account address */ ? sprintf( __( 'Reconnected to AbleGuard as %s. The old connection details no longer work.', 'ableguard-accessibility-toolkit' ), $account ) : __( 'Reconnected to AbleGuard. The old connection details no longer work.', 'ableguard-accessibility-toolkit' ) ); case 'first_sync_failed': /* translators: %s: the error WordPress or the plugin reported */ return self::notice_text( 'notice-warning', sprintf( __( 'Connected, but the first sync failed: %s. Press Sync now.', 'ableguard-accessibility-toolkit' ), $param ) ); case 'disconnected': return self::notice_text( 'notice-success', __( 'Disconnected. Fixes and your statement are no longer applied here. The site token stays valid in AbleGuard until you reconnect or delete the site in your dashboard.', 'ableguard-accessibility-toolkit' ) ); case 'manual_saved': return self::notice_text( 'notice-success', __( 'Connection details saved. Press Sync now to fetch your fixes.', 'ableguard-accessibility-toolkit' ) ); case 'manual_address_saved': return self::notice_text( 'notice-success', __( 'API address saved. Press Connect to AbleGuard to connect this site.', 'ableguard-accessibility-toolkit' ) ); case 'manual_refused': /* translators: %s: why the details were not saved */ return self::notice_text( 'notice-error', sprintf( __( "Those connection details weren't saved: %s.", 'ableguard-accessibility-toolkit' ), self::reason_text( $param ) ) ); } return null; } private static function notice_text( $class, $text ) { return array( 'class' => $class, 'text' => $text, ); } /** * The closed list of reasons a notice may give (spec 8), by the key a handler stores. A key * outside the list says nothing specific rather than printing anything that was stored. */ public static function reason_text( $key ) { switch ( $key ) { case 'api': return __( "the API address isn't an AbleGuard address", 'ableguard-accessibility-toolkit' ); case 'address': return __( "this site's address can't be used as written", 'ableguard-accessibility-toolkit' ); case 'admin': return __( "the WordPress admin isn't at this site's address", 'ableguard-accessibility-toolkit' ); case 'session': return __( "you're not signed in with a browser session", 'ableguard-accessibility-toolkit' ); case 'switch': return __( "AbleGuard hasn't switched one-click connect on yet", 'ableguard-accessibility-toolkit' ); case 'database': return __( "this site's database isn't supported", 'ableguard-accessibility-toolkit' ); case 'random': return __( "this server can't make secure random values", 'ableguard-accessibility-toolkit' ); case 'id': return __( "the site ID isn't in the right format", 'ableguard-accessibility-toolkit' ); case 'token': return __( "the site token isn't in the right format", 'ableguard-accessibility-toolkit' ); case 'need_token': return __( 'enter the site token for the new site ID', 'ableguard-accessibility-toolkit' ); } return __( "the request couldn't be made", 'ableguard-accessibility-toolkit' ); } }