Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
79.84% covered (warning)
79.84%
194 / 243
30.00% covered (danger)
30.00%
3 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
Client
79.84% covered (warning)
79.84%
194 / 243
30.00% covered (danger)
30.00%
3 / 10
123.36
0.00% covered (danger)
0.00%
0 / 1
 remote_request
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
10
 build_signed_request
91.35% covered (success)
91.35%
95 / 104
0.00% covered (danger)
0.00%
0 / 1
17.19
 is_safe_url_path
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 add_query_args
85.71% covered (warning)
85.71%
12 / 14
0.00% covered (danger)
0.00%
0 / 1
5.07
 _wp_remote_request
42.31% covered (danger)
42.31%
11 / 26
0.00% covered (danger)
0.00%
0 / 1
51.64
 set_time_diff
40.00% covered (danger)
40.00%
6 / 15
0.00% covered (danger)
0.00%
0 / 1
31.60
 validate_args_for_wpcom_json_api_request
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
2
 wpcom_json_api_request_as_user
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
6.84
 wpcom_json_api_request_as_blog
57.14% covered (warning)
57.14%
4 / 7
0.00% covered (danger)
0.00%
0 / 1
3.71
 _stringify_data
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
42
1<?php
2/**
3 * The Connection Client class file.
4 *
5 * @package automattic/jetpack-connection
6 */
7
8namespace Automattic\Jetpack\Connection;
9
10use Automattic\Jetpack\Constants;
11use WP_Error;
12
13// `wp_remote_request` returns an array with a particular format.
14'@phan-type _WP_Remote_Response_Array = array{headers:\WpOrg\Requests\Utility\CaseInsensitiveDictionary,body:string,response:array{code:int,message:string},cookies:\WP_HTTP_Cookie[],filename:?string,http_response:WP_HTTP_Requests_Response}';
15
16/**
17 * The Client class that is used to connect to WordPress.com Jetpack API.
18 */
19class Client {
20    const WPCOM_JSON_API_VERSION = '1.1';
21
22    /**
23     * Makes an authorized remote request using Jetpack_Signature
24     *
25     * @param array             $args the arguments for the remote request.
26     * @param array|string|null $body the request body.
27     * @return array|WP_Error WP HTTP response on success
28     * @phan-return _WP_Remote_Response_Array|WP_Error
29     */
30    public static function remote_request( $args, $body = null ) {
31        if ( isset( $args['url'] ) ) {
32            /**
33             * Filters the remote request url.
34             *
35             * @since 1.30.12
36             *
37             * @param string The remote request url.
38             */
39            $args['url'] = apply_filters( 'jetpack_remote_request_url', $args['url'] );
40        }
41
42        // Feed failures into the outgoing-request error flow of Error_Handler: any known
43        // connection error is stored and surfaced to the user. See the Error_Handler
44        // class docblock for the full picture of both error-handling flows.
45        // Outgoing XML-RPC calls (Jetpack_IXR_Client) are funneled through this method too;
46        // tell the transports apart by the endpoint the request targets.
47        // The literals match Error_Handler::ERROR_TYPE_XMLRPC / ERROR_TYPE_REST. The constants
48        // themselves must not be referenced from this class: during a plugin update, a stale
49        // Error_Handler that predates them can already be loaded, and resolving them against
50        // it would fatal the request.
51        $request_path = (string) wp_parse_url( empty( $args['url'] ) ? '' : $args['url'], PHP_URL_PATH );
52        $error_type   = '/xmlrpc.php' === substr( $request_path, -strlen( '/xmlrpc.php' ) ) ? 'xmlrpc' : 'rest';
53
54        $result = self::build_signed_request( $args, $body );
55        if ( is_wp_error( $result ) ) {
56            // The request was never made, so it has no response to check. Report the signing
57            // failure; attribution comes from the error itself â€” see
58            // `Error_Handler::check_signed_request_for_errors()`.
59            // Reporting is best-effort and must never fatal a request running mid-plugin-update:
60            // skip it when the already-loaded Error_Handler is a stale version predating this method.
61            if ( method_exists( Error_Handler::class, 'check_signed_request_for_errors' ) ) {
62                Error_Handler::get_instance()->check_signed_request_for_errors(
63                    $result,
64                    empty( $args['url'] ) ? '' : $args['url'],
65                    empty( $args['method'] ) ? 'POST' : $args['method'],
66                    $error_type
67                );
68            }
69
70            return $result;
71        }
72
73        $response = self::_wp_remote_request( $result['url'], $result['request'] );
74
75        Error_Handler::get_instance()->check_api_response_for_errors(
76            $response,
77            $result['auth'],
78            empty( $args['url'] ) ? '' : $args['url'],
79            empty( $args['method'] ) ? 'POST' : $args['method'],
80            $error_type
81        );
82
83        /**
84         * Fired when the remote request response has been received.
85         *
86         * @since 1.30.8
87         *
88         * @param array|WP_Error The HTTP response.
89         */
90        do_action( 'jetpack_received_remote_request_response', $response );
91
92        return $response;
93    }
94
95    /**
96     * Adds authorization signature to a remote request using Jetpack_Signature
97     *
98     * @param array             $args the arguments for the remote request.
99     * @param array|string|null $body the request body.
100     * @return WP_Error|array{url:string,request:array,auth:array} {
101     *     An array containing URL and request items.
102     *
103     *     @type string $url     The request URL.
104     *     @type array  $request Request arguments.
105     *     @type array  $auth    Authorization data.
106     * }
107     */
108    public static function build_signed_request( $args, $body = null ) {
109        add_filter(
110            'jetpack_constant_default_value',
111            __NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
112            10,
113            2
114        );
115
116        $defaults = array(
117            'url'           => '',
118            'user_id'       => 0,
119            'blog_id'       => 0,
120            'auth_location' => Constants::get_constant( 'JETPACK_CLIENT__AUTH_LOCATION' ),
121            'method'        => 'POST',
122            'format'        => 'json',
123            'timeout'       => 10,
124            'redirection'   => 0,
125            'headers'       => array(),
126            'stream'        => false,
127            'filename'      => null,
128            'sslverify'     => true,
129        );
130
131        $args = wp_parse_args( $args, $defaults );
132
133        $args['blog_id'] = (int) $args['blog_id'];
134
135        if ( ! self::is_safe_url_path( $args['url'] ) ) {
136            return new WP_Error( 'invalid_request_path', 'The request path contains a dot segment, a fragment or whitespace.' );
137        }
138
139        if ( 'header' !== $args['auth_location'] ) {
140            $args['auth_location'] = 'query_string';
141        }
142
143        // Return the specific reason the token could not be loaded instead of a bare `false`.
144        // Note the returned `WP_Error` is truthy, so this must not be tested with `! $token`.
145        $token = ( new Tokens() )->get_access_token(
146            $args['user_id'],
147            false, // token_key
148            false  // suppress_errors
149        );
150        if ( is_wp_error( $token ) ) {
151            return $token;
152        }
153        if ( ! $token ) {
154            // `get_access_token()` explains itself for every case but one: it returns a bare
155            // `false` when the tokens are locked. That lock is one-shot and self-healing.
156            return new WP_Error( 'tokens_locked' );
157        }
158
159        $method = strtoupper( $args['method'] );
160
161        $timeout = (int) $args['timeout'];
162
163        $redirection = $args['redirection'];
164        $stream      = $args['stream'];
165        $filename    = $args['filename'];
166        $sslverify   = $args['sslverify'];
167
168        $request = compact( 'method', 'body', 'timeout', 'redirection', 'stream', 'filename', 'sslverify' );
169
170        @list( $token_key, $secret ) = explode( '.', $token->secret ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
171        if ( ! $secret ) {
172            return new WP_Error( 'malformed_token' );
173        }
174
175        $token_key = sprintf(
176            '%s:%d:%d',
177            $token_key,
178            Constants::get_constant( 'JETPACK__API_VERSION' ),
179            $token->external_user_id
180        );
181
182        $time_diff         = (int) \Jetpack_Options::get_option( 'time_diff' );
183        $jetpack_signature = new \Jetpack_Signature( $token->secret, $time_diff );
184
185        $timestamp = time() + $time_diff;
186
187        if ( function_exists( 'wp_generate_password' ) ) {
188            $nonce = wp_generate_password( 10, false );
189        } else {
190            $nonce = substr( sha1( (string) wp_rand( 0, 1000000 ) ), 0, 10 );
191        }
192
193        // Kind of annoying.  Maybe refactor Jetpack_Signature to handle body-hashing.
194        if ( $body === null ) {
195            $body_hash = '';
196
197        } else {
198            // Allow arrays to be used in passing data.
199            $body_to_hash = $body;
200
201            if ( $args['format'] === 'jsonl' ) {
202                parse_str( $body, $body_to_hash );
203            }
204            if ( is_array( $body_to_hash ) ) {
205                // We cast this to a new variable, because the array form of $body needs to be
206                // maintained so it can be passed into the request later on in the code.
207                if ( array() !== $body_to_hash ) {
208                    $body_to_hash = wp_json_encode(
209                        self::_stringify_data( $body_to_hash ),
210                        0 // phpcs:ignore Jetpack.Functions.JsonEncodeFlags.ZeroFound -- No `json_encode()` flags because this needs to match whatever is calculating the hash on the other end.
211                    );
212                } else {
213                    $body_to_hash = '';
214                }
215            }
216
217            if ( ! is_string( $body_to_hash ) ) {
218                return new WP_Error( 'invalid_body', 'Body is malformed.' );
219            }
220            $body_hash = base64_encode( sha1( $body_to_hash, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
221        }
222
223        $auth = array(
224            'token'     => $token_key,
225            'timestamp' => $timestamp,
226            'nonce'     => $nonce,
227            'body-hash' => $body_hash,
228        );
229
230        if ( false !== strpos( $args['url'], 'xmlrpc.php' ) ) {
231            $url_args = array(
232                'for'           => 'jetpack',
233                'wpcom_blog_id' => \Jetpack_Options::get_option( 'id' ),
234            );
235        } else {
236            $url_args = array();
237        }
238
239        if ( 'header' !== $args['auth_location'] ) {
240            $url_args += $auth;
241        }
242
243        $url = self::add_query_args( $url_args, $args['url'] );
244
245        $signature = $jetpack_signature->sign_request( $token_key, $timestamp, $nonce, $body_hash, $method, $url, $body, false );
246
247        if ( is_wp_error( $signature ) ) {
248            return $signature;
249        }
250
251        // Send an Authorization header so various caches/proxies do the right thing.
252        $auth['signature'] = $signature;
253        $auth['version']   = Constants::get_constant( 'JETPACK__VERSION' );
254        $header_pieces     = array();
255        foreach ( $auth as $key => $value ) {
256            $header_pieces[] = sprintf( '%s="%s"', $key, $value );
257        }
258        $request['headers'] = array_merge(
259            $args['headers'],
260            array(
261                'Authorization' => 'X_JETPACK ' . implode( ' ', $header_pieces ),
262            )
263        );
264
265        if ( 'header' !== $args['auth_location'] ) {
266            $url = self::add_query_args( array( 'signature' => $signature ), $url );
267        }
268
269        return compact( 'url', 'request', 'auth' );
270    }
271
272    /**
273     * Checks that the part of a URL before its query names one resource, so the transport cannot resolve it to another.
274     *
275     * The HTTP transport removes `.` and `..` segments before it sends the request, and the receiving server can decode `%2e` and `%2f` into them.
276     *
277     * @param string $url The URL.
278     * @return bool False when the path holds a dot segment, literal or encoded, a fragment, or whitespace.
279     */
280    private static function is_safe_url_path( $url ) {
281        $position = strpos( $url, '?' );
282        $path     = false === $position ? $url : substr( $url, 0, $position );
283
284        if ( preg_match( '#[\#\s\x00-\x1f\x7f]#', $path ) ) {
285            return false;
286        }
287
288        return ! preg_match( '#(^|/)\.\.?(/|$)#', rawurldecode( $path ) );
289    }
290
291    /**
292     * Adds arguments to the query string of a URL, keeping each existing key and value with the meaning the caller gave it.
293     *
294     * @param array  $args Unencoded scalar arguments to add. They replace existing arguments with the same name.
295     * @param string $url  The URL.
296     * @return string The URL with the arguments added and every key and value encoded.
297     */
298    private static function add_query_args( $args, $url ) {
299        $fragment = '';
300        $position = strpos( $url, '#' );
301        if ( false !== $position ) {
302            $fragment = substr( $url, $position );
303            $url      = substr( $url, 0, $position );
304        }
305
306        $params   = array();
307        $position = strpos( $url, '?' );
308        if ( false !== $position ) {
309            parse_str( substr( $url, $position + 1 ), $params );
310            $url = substr( $url, 0, $position );
311        }
312
313        foreach ( $args as $key => $value ) {
314            $params[ $key ] = (string) $value;
315        }
316
317        $query = http_build_query( $params, '', '&' );
318
319        return $url . ( '' === $query ? '' : '?' . $query ) . $fragment;
320    }
321
322    /**
323     * Wrapper for wp_remote_request().  Turns off SSL verification for certain SSL errors.
324     * This is lame, but many, many, many hosts have misconfigured SSL.
325     *
326     * When Jetpack is registered, the jetpack_fallback_no_verify_ssl_certs option is set to the current time if:
327     * 1. a certificate error is found AND
328     * 2. not verifying the certificate works around the problem.
329     *
330     * The option is checked on each request.
331     *
332     * @internal
333     *
334     * @param string  $url the request URL.
335     * @param array   $args request arguments.
336     * @param boolean $set_fallback whether to allow flagging this request to use a fallback certficate override.
337     * @return array|WP_Error WP HTTP response on success
338     * @phan-return _WP_Remote_Response_Array|WP_Error
339     */
340    public static function _wp_remote_request( $url, $args, $set_fallback = false ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
341        $fallback = \Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
342        if ( false === $fallback ) {
343            \Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', 0 );
344        }
345
346        /**
347         * SSL verification (`sslverify`) for the JetpackClient remote request
348         * defaults to off, use this filter to force it on.
349         *
350         * Return `true` to ENABLE SSL verification, return `false`
351         * to DISABLE SSL verification.
352         *
353         * @since 1.7.0
354         * @since-jetpack 3.6.0
355         *
356         * @param bool Whether to force `sslverify` or not.
357         */
358        if ( apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
359            return wp_remote_request( $url, $args );
360        }
361
362        if ( (int) $fallback ) {
363            // We're flagged to fallback.
364            $args['sslverify'] = false;
365        }
366
367        $response = wp_remote_request( $url, $args );
368
369        if (
370            ! $set_fallback                                     // We're not allowed to set the flag on this request, so whatever happens happens.
371            ||
372            isset( $args['sslverify'] ) && ! $args['sslverify'] // No verification - no point in doing it again.
373            ||
374            ! is_wp_error( $response )                          // Let it ride.
375        ) {
376            self::set_time_diff( $response, $set_fallback );
377            return $response;
378        }
379
380        // At this point, we're not flagged to fallback and we are allowed to set the flag on this request.
381
382        $message = $response->get_error_message();
383
384        // Is it an SSL Certificate verification error?
385        if (
386            false === strpos( $message, '14090086' ) // OpenSSL SSL3 certificate error.
387            &&
388            false === strpos( $message, '1407E086' ) // OpenSSL SSL2 certificate error.
389            &&
390            false === strpos( $message, 'error setting certificate verify locations' ) // cURL CA bundle not found.
391            &&
392            false === strpos( $message, 'Peer certificate cannot be authenticated with' ) // cURL CURLE_SSL_CACERT: CA bundle found, but not helpful
393            // Different versions of curl have different error messages
394            // this string should catch them all.
395            &&
396            false === strpos( $message, 'Problem with the SSL CA cert' ) // cURL CURLE_SSL_CACERT_BADFILE: probably access rights.
397        ) {
398            // No, it is not.
399            return $response;
400        }
401
402        // Redo the request without SSL certificate verification.
403        $args['sslverify'] = false;
404        $response          = wp_remote_request( $url, $args );
405
406        if ( ! is_wp_error( $response ) ) {
407            // The request went through this time, flag for future fallbacks.
408            \Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', time() );
409            self::set_time_diff( $response, $set_fallback );
410        }
411
412        return $response;
413    }
414
415    /**
416     * Sets the time difference for correct signature computation.
417     *
418     * @param array|WP_Error $response Response array from `wp_remote_request`, or WP_Error on error.
419     * @param bool           $force_set whether to force setting the time difference.
420     * @phan-param _WP_Remote_Response_Array|WP_Error $response
421     */
422    public static function set_time_diff( &$response, $force_set = false ) {
423        $code = wp_remote_retrieve_response_code( $response );
424
425        // Only trust the Date header on some responses.
426        if ( 200 != $code && 304 != $code && 400 != $code && 401 != $code ) { // phpcs:ignore  Universal.Operators.StrictComparisons.LooseNotEqual
427            return;
428        }
429
430        $date = wp_remote_retrieve_header( $response, 'date' );
431        if ( ! $date ) {
432            return;
433        }
434
435        $time = (int) strtotime( $date );
436        if ( 0 >= $time ) {
437            return;
438        }
439
440        $time_diff = $time - time();
441
442        if ( $force_set ) { // During register.
443            \Jetpack_Options::update_option( 'time_diff', $time_diff );
444        } else { // Otherwise.
445            $old_diff = \Jetpack_Options::get_option( 'time_diff' );
446            if ( false === $old_diff || abs( $time_diff - (int) $old_diff ) > 10 ) {
447                \Jetpack_Options::update_option( 'time_diff', $time_diff );
448            }
449        }
450    }
451
452    /**
453     * Validate and build arguments for a WordPress.com REST API request.
454     *
455     * @param  string $path             REST API path.
456     * @param  string $version          REST API version. Default is `2`.
457     * @param  array  $args             Arguments to {@see WP_Http}. Default is `array()`.
458     * @param  string $base_api_path    REST API root. Default is `wpcom`.
459     *
460     * @return array Validated arguments.
461     */
462    public static function validate_args_for_wpcom_json_api_request(
463        $path,
464        $version = '2',
465        $args = array(),
466        $base_api_path = 'wpcom'
467    ) {
468        $base_api_path = trim( $base_api_path, '/' );
469        $version       = ltrim( $version, 'v' );
470        $path          = ltrim( $path, '/' );
471
472        $filtered_args = array_intersect_key(
473            $args,
474            array(
475                'headers'     => 'array',
476                'method'      => 'string',
477                'format'      => 'string',
478                'timeout'     => 'int',
479                'redirection' => 'int',
480                'stream'      => 'boolean',
481                'filename'    => 'string',
482                'sslverify'   => 'boolean',
483            )
484        );
485
486        // Use GET by default whereas `remote_request` uses POST.
487        $request_method = isset( $filtered_args['method'] ) ? strtoupper( $filtered_args['method'] ) : 'GET';
488
489        $url = sprintf(
490            '%s/%s/v%s/%s',
491            Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
492            $base_api_path,
493            $version,
494            $path
495        );
496
497        $validated_args = array_merge(
498            $filtered_args,
499            array(
500                'url'    => $url,
501                'method' => $request_method,
502            )
503        );
504
505        return $validated_args;
506    }
507
508    /**
509     * Queries the WordPress.com REST API with a user token.
510     *
511     * @param string            $path             REST API path.
512     * @param string            $version          REST API version. Default is `2`.
513     * @param array             $args             Arguments to {@see WP_Http}. Default is `array()`.
514     * @param null|string|array $body             Body passed to {@see WP_Http}. Default is `null`.
515     * @param string            $base_api_path    REST API root. Default is `wpcom`.
516     *
517     * @return array|WP_Error $response Response data, else {@see WP_Error} on failure.
518     * @phan-return _WP_Remote_Response_Array|WP_Error
519     */
520    public static function wpcom_json_api_request_as_user(
521        $path,
522        $version = '2',
523        $args = array(),
524        $body = null,
525        $base_api_path = 'wpcom'
526    ) {
527        $args            = self::validate_args_for_wpcom_json_api_request( $path, $version, $args, $base_api_path );
528        $args['user_id'] = get_current_user_id();
529
530        if ( isset( $body ) && ! isset( $args['headers'] ) && in_array( $args['method'], array( 'POST', 'PUT', 'PATCH' ), true ) ) {
531            $args['headers'] = array( 'Content-Type' => 'application/json' );
532        }
533
534        if ( isset( $body ) && ! is_string( $body ) ) {
535            $body = wp_json_encode( $body, JSON_UNESCAPED_SLASHES );
536        }
537
538        return self::remote_request( $args, $body );
539    }
540
541    /**
542     * Query the WordPress.com REST API using the blog token
543     *
544     * @param string            $path The API endpoint relative path.
545     * @param string            $version The API version.
546     * @param array             $args Request arguments.
547     * @param array|string|null $body Request body.
548     * @param string            $base_api_path (optional) the API base path override, defaults to 'rest'.
549     * @return array|WP_Error $response Data.
550     * @phan-return _WP_Remote_Response_Array|WP_Error
551     */
552    public static function wpcom_json_api_request_as_blog(
553        $path,
554        $version = self::WPCOM_JSON_API_VERSION,
555        $args = array(),
556        $body = null,
557        $base_api_path = 'rest'
558    ) {
559        $validated_args            = self::validate_args_for_wpcom_json_api_request( $path, $version, $args, $base_api_path );
560        $validated_args['blog_id'] = (int) \Jetpack_Options::get_option( 'id' );
561
562        // For Simple sites get the response directly without any HTTP requests.
563        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
564            add_filter( 'is_jetpack_authorized_for_site', '__return_true' );
565            require_lib( 'wpcom-api-direct' );
566            return \WPCOM_API_Direct::do_request( $validated_args, $body );
567        }
568
569        return self::remote_request( $validated_args, $body );
570    }
571
572    /**
573     * Takes an array or similar structure and recursively turns all values into strings. This is used to
574     * make sure that body hashes are made ith the string version, which is what will be seen after a
575     * server pulls up the data in the $_POST array.
576     *
577     * @param mixed $data the data that needs to be stringified.
578     *
579     * @return array|string
580     */
581    public static function _stringify_data( $data ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
582
583        // Booleans are special, lets just makes them and explicit 1/0 instead of the 0 being an empty string.
584        if ( is_bool( $data ) ) {
585            return $data ? '1' : '0';
586        }
587
588        // Cast objects into arrays.
589        if ( is_object( $data ) ) {
590            $data = (array) $data;
591        }
592
593        // Non arrays at this point should be just converted to strings.
594        if ( ! is_array( $data ) ) {
595            return (string) $data;
596        }
597
598        foreach ( $data as &$value ) {
599            $value = self::_stringify_data( $value );
600        }
601
602        return $data;
603    }
604}