findByHash( TokenHasher::hash( $raw ) ); if ( null === $token ) { CurrentConnection::markFailure( CurrentConnection::FAILURE_INVALID_TOKEN ); return $user_id; } $failure = self::validateToken( $token, $from_api_key_header ); if ( null !== $failure ) { CurrentConnection::markFailure( $failure ); self::writeAuthFailureAudit( $token, $failure, 0 ); return $user_id; } $connection_store = new ConnectionStore(); $connection = $connection_store->find( (int) $token['connection_id'] ); if ( null === $connection || ConnectionStore::STATUS_ACTIVE !== $connection['status'] ) { CurrentConnection::markFailure( CurrentConnection::FAILURE_CONNECTION_INACTIVE ); self::writeAuthFailureAudit( $token, CurrentConnection::FAILURE_CONNECTION_INACTIVE, 0 ); return $user_id; } if ( ! McpPermissionLevel::isValid( (string) $connection['permission_level'] ) ) { CurrentConnection::markFailure( CurrentConnection::FAILURE_INTERNAL ); self::writeAuthFailureAudit( $token, CurrentConnection::FAILURE_INTERNAL, 0 ); return $user_id; } $owner_id = (int) $connection['user_id']; if ( ! get_userdata( $owner_id ) || ! user_can( $owner_id, 'manage_woocommerce' ) ) { CurrentConnection::markFailure( CurrentConnection::FAILURE_INSUFFICIENT_CAPABILITY ); self::writeAuthFailureAudit( $token, CurrentConnection::FAILURE_INSUFFICIENT_CAPABILITY, $owner_id ); return $user_id; } $set = CurrentConnection::set( array( 'connection_id' => (int) $token['connection_id'], 'user_id' => $owner_id, 'auth_type' => (string) $connection['auth_type'], 'permission_level' => (string) $connection['permission_level'], 'token_id' => (int) $token['id'], 'token_type' => (string) $token['token_type'], 'oauth_client_id' => (int) $connection['oauth_client_id'], 'label' => (string) $connection['label'], ) ); if ( ! $set ) { self::writeAuthFailureAudit( $token, CurrentConnection::FAILURE_INTERNAL, $owner_id ); return $user_id; } $now = gmdate( 'Y-m-d H:i:s' ); $token_store->touchLastUsed( (int) $token['id'], $now ); $connection_store->touchLastUsed( (int) $token['connection_id'], $now ); return $owner_id; } /** * Validate a found token row against every rule a credential must * satisfy before it can authenticate. Does not touch the connection or * the owning user; {@see processCredential()} checks those separately. * * @param array $token Row from {@see TokenStore::findByHash()}. * @param bool $from_api_key_header Whether the credential arrived via X-AIPT-MCP-Key. * @return string|null One of CurrentConnection::FAILURE_* on failure, null when valid so far. */ private static function validateToken( array $token, bool $from_api_key_header ): ?string { $type = (string) ( $token['token_type'] ?? '' ); if ( ! in_array( $type, array( TokenStore::TOKEN_TYPE_API_KEY, TokenStore::TOKEN_TYPE_OAUTH_ACCESS ), true ) ) { return CurrentConnection::FAILURE_INVALID_TOKEN; } if ( $from_api_key_header && TokenStore::TOKEN_TYPE_API_KEY !== $type ) { return CurrentConnection::FAILURE_WRONG_HEADER; } if ( null !== $token['revoked_at'] ) { return CurrentConnection::FAILURE_REVOKED; } $expires_at = $token['expires_at']; if ( TokenStore::TOKEN_TYPE_API_KEY === $type ) { if ( null !== $expires_at ) { return CurrentConnection::FAILURE_INTERNAL; } } else { $expires_ts = null === $expires_at ? false : strtotime( (string) $expires_at ); if ( false === $expires_ts ) { return CurrentConnection::FAILURE_INTERNAL; } if ( $expires_ts <= time() ) { return CurrentConnection::FAILURE_EXPIRED_TOKEN; } } if ( ! McpPermissionLevel::isValid( (string) ( $token['permission_level'] ?? '' ) ) ) { return CurrentConnection::FAILURE_INTERNAL; } return null; } /** * Write an auth_failure audit row, rate-limited per token row so that * replaying ONE known-but-no-longer-valid credential (revoked, expired, * an inactive connection, an owner who lost the required capability) * cannot write unbounded rows: this call site is reached before the * endpoint's own per-connection transport limiter (a failed auth never * sets a connection), so without this, the one existing rate limiter * never applies to a failed-auth replay at all. Never throws; an * audit-logging failure, or a rate-limiter failure, must never affect * the authentication decision already made. * * @param array $token Matched token row. * @param string $reason FAILURE_* reason, stored as status_code. * @param int $user_id Owning user id, when already known (0 otherwise). * @return void */ private static function writeAuthFailureAudit( array $token, string $reason, int $user_id ): void { $token_id = (int) ( $token['id'] ?? 0 ); if ( $token_id > 0 ) { try { $rate = AtomicRateLimiter::checkAndIncrement( McpOAuthConstants::authFailureAuditRateLimitBucketKey( $token_id ), McpOAuthConstants::AUTH_FAILURE_AUDIT_RATE_LIMIT_PER_TOKEN, McpOAuthConstants::AUTH_FAILURE_AUDIT_RATE_LIMIT_WINDOW ); } catch ( \Throwable $e ) { return; } if ( ! $rate['allowed'] ) { return; } } try { ( new AuditLogStore() )->write( array( 'connection_id' => (int) ( $token['connection_id'] ?? 0 ), 'user_id' => $user_id, 'event_type' => AuditLogStore::EVENT_AUTH_FAILURE, 'outcome' => AuditLogStore::OUTCOME_DENIED, 'status_code' => $reason, ) ); } catch ( \Throwable $e ) { } } /** * Whether the current request is inside the REST cycle of the MCP * endpoint specifically: REST_REQUEST must be * defined and true, and the parsed route must be exactly * {@see McpOAuthConstants::MCP_ROUTE}. * * @return bool */ private static function isMcpRequest(): bool { if ( ! defined( 'REST_REQUEST' ) || ! REST_REQUEST ) { return false; } $route = ''; if ( isset( $GLOBALS['wp'] ) && is_object( $GLOBALS['wp'] ) && isset( $GLOBALS['wp']->query_vars ) && is_array( $GLOBALS['wp']->query_vars ) ) { $route = isset( $GLOBALS['wp']->query_vars['rest_route'] ) ? (string) $GLOBALS['wp']->query_vars['rest_route'] : ''; } return McpOAuthConstants::isMcpRoute( $route ); } /** * Read a bearer credential from the Authorization header recovery chain * (servers and proxies that strip it), or fall back to the API-key-only * X-AIPT-MCP-Key header. * * @return array{0:string,1:bool}|null [raw credential, "came from the API-key-only header"], or null when none is present. */ private static function readCredential(): ?array { $bearer = self::readBearerToken(); if ( null !== $bearer ) { return array( $bearer, false ); } $api_key = self::readApiKeyHeader(); if ( null !== $api_key ) { return array( $api_key, true ); } return null; } /** * @return string|null */ private static function readBearerToken(): ?string { $header = self::readAuthorizationHeaderValue(); if ( null === $header || 0 !== stripos( $header, 'Bearer ' ) ) { return null; } return self::normalizeCredentialValue( trim( substr( $header, 7 ) ) ); } /** * @return string|null */ private static function readApiKeyHeader(): ?string { if ( ! isset( $_SERVER['HTTP_X_AIPT_MCP_KEY'] ) ) { return null; } $raw = sanitize_text_field( wp_unslash( (string) $_SERVER['HTTP_X_AIPT_MCP_KEY'] ) ); return self::normalizeCredentialValue( trim( $raw ) ); } /** * Recognize a credential value, or report it is not ours at all. A * connection-doctor probe value is ignored entirely — not even marked * presented, since it is never meant to authenticate anything. * * @param string $raw Trimmed candidate value. * @return string|null */ private static function normalizeCredentialValue( string $raw ): ?string { if ( '' === $raw ) { return null; } if ( 0 === strpos( $raw, McpOAuthConstants::DOCTOR_PROBE_PREFIX ) ) { return null; } if ( 0 !== strpos( $raw, McpOAuthConstants::TOKEN_PREFIX ) ) { return null; } return $raw; } /** * The Authorization header value, read through the full recovery chain: * `HTTP_AUTHORIZATION`, then `REDIRECT_HTTP_AUTHORIZATION`, then * `getallheaders()`/`apache_request_headers()` (case-insensitive name), * for hosts that strip the header into neither $_SERVER key. * * @return string|null */ private static function readAuthorizationHeaderValue(): ?string { if ( ! empty( $_SERVER['HTTP_AUTHORIZATION'] ) ) { return sanitize_text_field( wp_unslash( (string) $_SERVER['HTTP_AUTHORIZATION'] ) ); } if ( ! empty( $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ) ) { return sanitize_text_field( wp_unslash( (string) $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ) ); } foreach ( self::allRequestHeaders() as $name => $value ) { if ( is_string( $name ) && 0 === strcasecmp( $name, 'Authorization' ) ) { $value = trim( sanitize_text_field( (string) $value ) ); return '' === $value ? null : $value; } } return null; } /** * @return array */ private static function allRequestHeaders(): array { if ( function_exists( 'getallheaders' ) ) { $headers = getallheaders(); if ( is_array( $headers ) ) { return $headers; } } if ( function_exists( 'apache_request_headers' ) ) { $headers = apache_request_headers(); if ( is_array( $headers ) ) { return $headers; } } return array(); } }