_`: `id` (12 hex chars) finds the record, and only a * sha256 of the whole token is stored, compared with hash_equals. The raw token exists once, * on the screen of the admin who created it. Each token is bound to one WordPress user and every * request runs as that user, so WordPress's own capabilities decide what ADI may touch. */ final class Auth { const OPTION = 'adibridge_tokens'; /** * Last-used times live apart from the token list: ordinary requests write only this, so a * request racing an admin's revoke can never write a stale token list (and the token) back. */ const LAST_USED_OPTION = 'adibridge_last_used'; /** Minimum gap between `last_used` writes, so a busy session is not a DB write per request. */ const LAST_USED_RESOLUTION = 60; /** * WordPress runs a route's permission callback more than once per request (dispatch, and * rest_send_allow_header). Authenticate once and reuse the outcome. * * @var array */ private static $memo = array(); public static function boot() { add_filter( 'adibridge_authenticate', array( self::class, 'authenticate' ), 10, 2 ); // Resolve the token's user as soon as WordPress has decided which REST route it will // dispatch, and before other plugins' rest_authentication_errors checks (Wordfence-style // "no anonymous REST") run. Keyed on the DISPATCHED route only — never the raw URL or // query string, which a caller can point at one route while dispatching another. add_filter( 'rest_authentication_errors', array( self::class, 'early_authenticate' ), 1 ); // A token dies with its user: on some databases a deleted user's id can be given to a later // user, who must not inherit the connection. add_action( 'deleted_user', array( self::class, 'revoke_for_user' ) ); add_action( 'remove_user_from_blog', array( self::class, 'revoke_for_user' ) ); } /** Revoke every token bound to $user_id. Returns how many. */ public static function revoke_for_user( $user_id ) { $count = 0; foreach ( self::fresh() as $id => $record ) { if ( (int) $record['user_id'] === (int) $user_id && self::revoke( $id ) ) { ++$count; } } return $count; } /** Is WordPress dispatching the MCP route in this request? */ private static function dispatching_mcp() { if ( ! defined( 'REST_REQUEST' ) || ! REST_REQUEST || empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) { return false; } return 0 === strcasecmp( untrailingslashit( (string) $GLOBALS['wp']->query_vars['rest_route'] ), '/' . Rest::NAMESPACE_V1 . '/mcp' ); } /** * @param \WP_Error|true|null $result * @return \WP_Error|true|null Unchanged: refusals stay with the route's permission callback. */ public static function early_authenticate( $result ) { if ( null !== $result || ! self::dispatching_mcp() || self::origin_error_for( self::server_header( 'HTTP_ORIGIN' ) ) || self::transport_error() ) { return $result; } $header = self::authorization_header( null ); if ( self::is_ours( $header ) && true === self::verify_memoised( $header ) ) { wp_set_current_user( self::$memo[ 'user:' . hash( 'sha256', $header ) ] ); } return $result; } /** Label of the token that authenticated this request (null for other authenticators). */ private static $token_label = null; public static function current_token_label() { return self::$token_label; } /** Test seam: forget per-request state. */ public static function reset_memo() { self::$memo = array(); self::$token_label = null; } /** * @param true|\WP_Error|null $allowed Earlier result from another authenticator. * @return true|\WP_Error|null */ public static function authenticate( $allowed, \WP_REST_Request $request ) { if ( null !== $allowed ) { return $allowed; } $origin = self::origin_error_for( $request->get_header( 'origin' ) ); if ( $origin ) { return $origin; } $transport = self::transport_error(); if ( $transport ) { return $transport; } $header = self::authorization_header( $request ); if ( ! self::is_ours( $header ) ) { // No header, Basic auth, someone else's bearer scheme: not ours to judge. Another // authenticator may accept it; otherwise Rest::permission answers 401. return null; } $result = self::verify_memoised( $header ); if ( true === $result ) { wp_set_current_user( self::$memo[ 'user:' . hash( 'sha256', $header ) ] ); } return $result; } /** `Bearer adib_…`, scheme case-insensitive (RFC 7235). */ private static function is_ours( $header ) { return (bool) preg_match( '/^bearer\s+adib_/i', $header ); } private static function verify_memoised( $header ) { $key = hash( 'sha256', $header ); if ( ! isset( self::$memo[ $key ] ) ) { self::$memo[ $key ] = self::verify_header( $header ); } return self::$memo[ $key ]; } private static function server_header( $name ) { return isset( $_SERVER[ $name ] ) ? wp_unslash( $_SERVER[ $name ] ) : null; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- compared, never output } /** * Browsers send Origin; ADI's native client does not. A browser request from any other * origin than this site is refused (the MCP spec's DNS-rebinding defence). */ private static function origin_error_for( $origin ) { if ( null === $origin || '' === $origin ) { return null; } $site = wp_parse_url( home_url() ); $from = wp_parse_url( $origin ); $same = is_array( $from ) && isset( $from['host'], $site['host'], $from['scheme'], $site['scheme'] ) && strtolower( $from['scheme'] ) === strtolower( $site['scheme'] ) && strtolower( $from['host'] ) === strtolower( $site['host'] ) && ( isset( $from['port'] ) ? (int) $from['port'] : null ) === ( isset( $site['port'] ) ? (int) $site['port'] : null ); /** * Filters whether a browser Origin may call the MCP endpoint. Default: this site only. */ if ( apply_filters( 'adibridge_allowed_origin', $same, $origin ) ) { return null; } return new \WP_Error( 'adi_bridge_origin', 'Requests from this origin are not allowed.', array( 'status' => 403 ) ); } /** * Did this request reach the site over https? is_ssl(), or the header a TLS-terminating proxy * or CDN in front of the site adds. (A client that sent plain http does not add these headers * itself: the rule protects the token of an honest client, not against a dishonest one.) */ public static function request_is_https() { if ( is_ssl() ) { return true; } $proto = self::server_header( 'HTTP_X_FORWARDED_PROTO' ); if ( is_string( $proto ) && 'https' === strtolower( trim( explode( ',', $proto )[0] ) ) ) { return true; } $ssl = self::server_header( 'HTTP_X_FORWARDED_SSL' ); if ( is_string( $ssl ) && 'on' === strtolower( trim( $ssl ) ) ) { return true; } $visitor = self::server_header( 'HTTP_CF_VISITOR' ); return is_string( $visitor ) && false !== strpos( str_replace( ' ', '', $visitor ), '"scheme":"https"' ); } /** A site on this computer (localhost, 127.0.0.1, ::1): its traffic never leaves the machine. */ public static function site_is_local() { $host = strtolower( trim( (string) wp_parse_url( home_url(), PHP_URL_HOST ), '[]' ) ); return in_array( $host, array( 'localhost', '127.0.0.1', '::1' ), true ); } /** May this site hold connections at all? Its address is https, or it is on this computer. */ public static function site_is_secure() { return self::site_is_local() || 'https' === strtolower( (string) wp_parse_url( home_url(), PHP_URL_SCHEME ) ); } /** * A token sent over plain http can be read on the way, so the endpoint answers nothing over * it, with or without a valid token. No setting or filter turns this off; a site on this * computer is the only exception. */ private static function transport_error() { if ( self::request_is_https() || self::site_is_local() ) { return null; } return new \WP_Error( 'adi_bridge_insecure', 'This request was not sent over https, so the token travelled unencrypted and the site refused it. The site must use https: connect ADI with the https:// address shown in Settings → ADI Bridge. If a token was sent this way, revoke it there and create a new connection.', array( 'status' => 403 ) ); } /** * The credential header, wherever this host put it. Apache under CGI/FastCGI often strips * Authorization unless .htaccess passes it on as REDIRECT_HTTP_AUTHORIZATION, and some hosts * drop it whatever .htaccess says, so ADI sends the same value in X-ADI-Authorization too. * That copy is used only when Authorization doesn't carry one of our tokens: it goes through * the same origin check and verify_header, so it adds a route, never a weaker one. */ private static function authorization_header( $request ) { $value = $request instanceof \WP_REST_Request ? $request->get_header( 'authorization' ) : null; if ( ! $value && isset( $_SERVER['HTTP_AUTHORIZATION'] ) ) { $value = wp_unslash( $_SERVER['HTTP_AUTHORIZATION'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- compared as an opaque secret } if ( ! $value && isset( $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ) ) { $value = wp_unslash( $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $value = is_string( $value ) ? trim( $value ) : ''; if ( self::is_ours( $value ) ) { return $value; } $copy = $request instanceof \WP_REST_Request ? $request->get_header( 'x-adi-authorization' ) : null; if ( ! $copy && isset( $_SERVER['HTTP_X_ADI_AUTHORIZATION'] ) ) { $copy = wp_unslash( $_SERVER['HTTP_X_ADI_AUTHORIZATION'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- compared as an opaque secret } $copy = is_string( $copy ) ? trim( $copy ) : ''; return self::is_ours( $copy ) ? $copy : $value; } private static function unauthorized( $message ) { return new \WP_Error( 'adi_bridge_unauthorized', $message, array( 'status' => 401 ) ); } private static function verify_header( $header ) { if ( ! preg_match( '/^bearer\s+(adib_([0-9a-f]{12})_[A-Za-z0-9_-]{43})\z/i', $header, $m ) ) { return self::unauthorized( 'Missing or invalid ADI Bridge token.' ); } $token = $m[1]; $id = $m[2]; $tokens = self::all(); if ( ! isset( $tokens[ $id ] ) || ! hash_equals( $tokens[ $id ]['hash'], hash( 'sha256', $token ) ) ) { return self::unauthorized( 'Missing or invalid ADI Bridge token.' ); } $record = $tokens[ $id ]; $user = get_userdata( (int) $record['user_id'] ); if ( ! $user ) { self::revoke( $id ); // gone without WordPress's delete hooks: the id must not pass to a later user return self::unauthorized( 'The WordPress user this token belongs to no longer exists. Create a new token.' ); } if ( isset( $record['user_login'] ) && $record['user_login'] !== $user->user_login ) { self::revoke( $id ); // the database gave a deleted user's id to somebody else return self::unauthorized( 'The WordPress user this token belongs to no longer exists. Create a new token.' ); } if ( ! user_can( $user, 'edit_posts' ) ) { return self::unauthorized( 'The WordPress user this token belongs to can no longer edit content. Create a new token for an Editor.' ); } self::$memo[ 'user:' . hash( 'sha256', $header ) ] = $user->ID; self::$token_label = (string) $record['label']; self::touch( $id ); return true; } private static function touch( $id ) { $last = self::last_used_map(); if ( ! isset( $last[ $id ] ) || time() - (int) $last[ $id ] >= self::LAST_USED_RESOLUTION ) { $last[ $id ] = time(); update_option( self::LAST_USED_OPTION, $last, false ); } } private static function last_used_map() { $last = get_option( self::LAST_USED_OPTION, array() ); return is_array( $last ) ? $last : array(); } /** Unix time a token was last used, 0 for never. */ public static function last_used( $id ) { $last = self::last_used_map(); return isset( $last[ $id ] ) ? (int) $last[ $id ] : 0; } /** * The token list as stored right now, bypassing the object cache — create/revoke re-read just * before writing so two admins working at once can't write back each other's stale copy. */ private static function fresh() { wp_cache_delete( self::OPTION, 'options' ); wp_cache_delete( 'alloptions', 'options' ); wp_cache_delete( 'notoptions', 'options' ); return self::all(); } /** @return array */ public static function all() { $tokens = get_option( self::OPTION, array() ); return is_array( $tokens ) ? $tokens : array(); } /** * Create a token for $user_id. Returns the raw token — the only time it exists anywhere. */ public static function create( $label, $user_id, $created_by ) { $id = bin2hex( random_bytes( 6 ) ); $secret = rtrim( strtr( base64_encode( random_bytes( 32 ) ), '+/', '-_' ), '=' ); $token = "adib_{$id}_{$secret}"; $bound = get_userdata( (int) $user_id ); $tokens = self::fresh(); $tokens[ $id ] = array( 'id' => $id, 'label' => $label, 'user_id' => (int) $user_id, 'user_login' => $bound ? $bound->user_login : '', 'hash' => hash( 'sha256', $token ), 'created' => time(), 'created_by' => (int) $created_by, ); update_option( self::OPTION, $tokens, false ); return $token; } public static function revoke( $id ) { $tokens = self::fresh(); if ( ! isset( $tokens[ $id ] ) ) { return false; } unset( $tokens[ $id ] ); update_option( self::OPTION, $tokens, false ); $last = self::last_used_map(); unset( $last[ $id ] ); update_option( self::LAST_USED_OPTION, $last, false ); self::reset_memo(); return true; } /** * The capability gate every tool calls before it reads or writes: refuses with a message the * person can act on, in the same words WordPress would use. * * @param string $cap A capability or meta capability (edit_post, read_post, …). * @param mixed ...$args Object id etc., as for current_user_can(). */ public static function require_cap( $cap, ...$args ) { if ( ! current_user_can( $cap, ...$args ) ) { $user = wp_get_current_user(); $who = $user && $user->exists() ? $user->user_login : 'this connection'; $ids = array_map( static function ( $arg ) { return is_object( $arg ) && isset( $arg->ID ) ? (string) $arg->ID : ( is_scalar( $arg ) ? (string) $arg : '?' ); }, $args ); throw new Tool_Error( esc_html( sprintf( 'The WordPress user %s is not allowed to %s%s.', $who, str_replace( '_', ' ', $cap ), $ids ? ' #' . implode( ', #', $ids ) : '' ) ) ); } } }