Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
74.40% covered (warning)
74.40%
154 / 207
25.00% covered (danger)
25.00%
2 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
Client
74.40% covered (warning)
74.40%
154 / 207
25.00% covered (danger)
25.00%
2 / 8
123.46
0.00% covered (danger)
0.00%
0 / 1
 remote_request
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
5
 build_signed_request
89.58% covered (warning)
89.58%
86 / 96
0.00% covered (danger)
0.00%
0 / 1
15.25
 _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
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
42
 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        $result = self::build_signed_request( $args, $body );
43        if ( is_wp_error( $result ) ) {
44            return $result;
45        }
46
47        $response = self::_wp_remote_request( $result['url'], $result['request'] );
48
49        Error_Handler::get_instance()->check_api_response_for_errors(
50            $response,
51            $result['auth'],
52            empty( $args['url'] ) ? '' : $args['url'],
53            empty( $args['method'] ) ? 'POST' : $args['method'],
54            'rest'
55        );
56
57        /**
58         * Fired when the remote request response has been received.
59         *
60         * @since 1.30.8
61         *
62         * @param array|WP_Error The HTTP response.
63         */
64        do_action( 'jetpack_received_remote_request_response', $response );
65
66        return $response;
67    }
68
69    /**
70     * Adds authorization signature to a remote request using Jetpack_Signature
71     *
72     * @param array             $args the arguments for the remote request.
73     * @param array|string|null $body the request body.
74     * @return WP_Error|array{url:string,request:array,auth:array} {
75     *     An array containing URL and request items.
76     *
77     *     @type string $url     The request URL.
78     *     @type array  $request Request arguments.
79     *     @type array  $auth    Authorization data.
80     * }
81     */
82    public static function build_signed_request( $args, $body = null ) {
83        add_filter(
84            'jetpack_constant_default_value',
85            __NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
86            10,
87            2
88        );
89
90        $defaults = array(
91            'url'           => '',
92            'user_id'       => 0,
93            'blog_id'       => 0,
94            'auth_location' => Constants::get_constant( 'JETPACK_CLIENT__AUTH_LOCATION' ),
95            'method'        => 'POST',
96            'format'        => 'json',
97            'timeout'       => 10,
98            'redirection'   => 0,
99            'headers'       => array(),
100            'stream'        => false,
101            'filename'      => null,
102            'sslverify'     => true,
103        );
104
105        $args = wp_parse_args( $args, $defaults );
106
107        $args['blog_id'] = (int) $args['blog_id'];
108
109        if ( 'header' !== $args['auth_location'] ) {
110            $args['auth_location'] = 'query_string';
111        }
112
113        $token = ( new Tokens() )->get_access_token( $args['user_id'] );
114        if ( ! $token ) {
115            return new WP_Error( 'missing_token' );
116        }
117
118        $method = strtoupper( $args['method'] );
119
120        $timeout = (int) $args['timeout'];
121
122        $redirection = $args['redirection'];
123        $stream      = $args['stream'];
124        $filename    = $args['filename'];
125        $sslverify   = $args['sslverify'];
126
127        $request = compact( 'method', 'body', 'timeout', 'redirection', 'stream', 'filename', 'sslverify' );
128
129        @list( $token_key, $secret ) = explode( '.', $token->secret ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
130        if ( ! $secret ) {
131            return new WP_Error( 'malformed_token' );
132        }
133
134        $token_key = sprintf(
135            '%s:%d:%d',
136            $token_key,
137            Constants::get_constant( 'JETPACK__API_VERSION' ),
138            $token->external_user_id
139        );
140
141        $time_diff         = (int) \Jetpack_Options::get_option( 'time_diff' );
142        $jetpack_signature = new \Jetpack_Signature( $token->secret, $time_diff );
143
144        $timestamp = time() + $time_diff;
145
146        if ( function_exists( 'wp_generate_password' ) ) {
147            $nonce = wp_generate_password( 10, false );
148        } else {
149            $nonce = substr( sha1( (string) wp_rand( 0, 1000000 ) ), 0, 10 );
150        }
151
152        // Kind of annoying.  Maybe refactor Jetpack_Signature to handle body-hashing.
153        if ( $body === null ) {
154            $body_hash = '';
155
156        } else {
157            // Allow arrays to be used in passing data.
158            $body_to_hash = $body;
159
160            if ( $args['format'] === 'jsonl' ) {
161                parse_str( $body, $body_to_hash );
162            }
163            if ( is_array( $body_to_hash ) ) {
164                // We cast this to a new variable, because the array form of $body needs to be
165                // maintained so it can be passed into the request later on in the code.
166                if ( array() !== $body_to_hash ) {
167                    $body_to_hash = wp_json_encode(
168                        self::_stringify_data( $body_to_hash ),
169                        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.
170                    );
171                } else {
172                    $body_to_hash = '';
173                }
174            }
175
176            if ( ! is_string( $body_to_hash ) ) {
177                return new WP_Error( 'invalid_body', 'Body is malformed.' );
178            }
179            $body_hash = base64_encode( sha1( $body_to_hash, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
180        }
181
182        $auth = array(
183            'token'     => $token_key,
184            'timestamp' => $timestamp,
185            'nonce'     => $nonce,
186            'body-hash' => $body_hash,
187        );
188
189        if ( false !== strpos( $args['url'], 'xmlrpc.php' ) ) {
190            $url_args = array(
191                'for'           => 'jetpack',
192                'wpcom_blog_id' => \Jetpack_Options::get_option( 'id' ),
193            );
194        } else {
195            $url_args = array();
196        }
197
198        if ( 'header' !== $args['auth_location'] ) {
199            $url_args += $auth;
200        }
201
202        $url = add_query_arg( urlencode_deep( $url_args ), $args['url'] );
203
204        $signature = $jetpack_signature->sign_request( $token_key, $timestamp, $nonce, $body_hash, $method, $url, $body, false );
205
206        if ( is_wp_error( $signature ) ) {
207            return $signature;
208        }
209
210        // Send an Authorization header so various caches/proxies do the right thing.
211        $auth['signature'] = $signature;
212        $auth['version']   = Constants::get_constant( 'JETPACK__VERSION' );
213        $header_pieces     = array();
214        foreach ( $auth as $key => $value ) {
215            $header_pieces[] = sprintf( '%s="%s"', $key, $value );
216        }
217        $request['headers'] = array_merge(
218            $args['headers'],
219            array(
220                'Authorization' => 'X_JETPACK ' . implode( ' ', $header_pieces ),
221            )
222        );
223
224        if ( 'header' !== $args['auth_location'] ) {
225            $url = add_query_arg( 'signature', rawurlencode( $signature ), $url );
226        }
227
228        return compact( 'url', 'request', 'auth' );
229    }
230
231    /**
232     * Wrapper for wp_remote_request().  Turns off SSL verification for certain SSL errors.
233     * This is lame, but many, many, many hosts have misconfigured SSL.
234     *
235     * When Jetpack is registered, the jetpack_fallback_no_verify_ssl_certs option is set to the current time if:
236     * 1. a certificate error is found AND
237     * 2. not verifying the certificate works around the problem.
238     *
239     * The option is checked on each request.
240     *
241     * @internal
242     *
243     * @param string  $url the request URL.
244     * @param array   $args request arguments.
245     * @param boolean $set_fallback whether to allow flagging this request to use a fallback certficate override.
246     * @return array|WP_Error WP HTTP response on success
247     * @phan-return _WP_Remote_Response_Array|WP_Error
248     */
249    public static function _wp_remote_request( $url, $args, $set_fallback = false ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
250        $fallback = \Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
251        if ( false === $fallback ) {
252            \Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', 0 );
253        }
254
255        /**
256         * SSL verification (`sslverify`) for the JetpackClient remote request
257         * defaults to off, use this filter to force it on.
258         *
259         * Return `true` to ENABLE SSL verification, return `false`
260         * to DISABLE SSL verification.
261         *
262         * @since 1.7.0
263         * @since-jetpack 3.6.0
264         *
265         * @param bool Whether to force `sslverify` or not.
266         */
267        if ( apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
268            return wp_remote_request( $url, $args );
269        }
270
271        if ( (int) $fallback ) {
272            // We're flagged to fallback.
273            $args['sslverify'] = false;
274        }
275
276        $response = wp_remote_request( $url, $args );
277
278        if (
279            ! $set_fallback                                     // We're not allowed to set the flag on this request, so whatever happens happens.
280            ||
281            isset( $args['sslverify'] ) && ! $args['sslverify'] // No verification - no point in doing it again.
282            ||
283            ! is_wp_error( $response )                          // Let it ride.
284        ) {
285            self::set_time_diff( $response, $set_fallback );
286            return $response;
287        }
288
289        // At this point, we're not flagged to fallback and we are allowed to set the flag on this request.
290
291        $message = $response->get_error_message();
292
293        // Is it an SSL Certificate verification error?
294        if (
295            false === strpos( $message, '14090086' ) // OpenSSL SSL3 certificate error.
296            &&
297            false === strpos( $message, '1407E086' ) // OpenSSL SSL2 certificate error.
298            &&
299            false === strpos( $message, 'error setting certificate verify locations' ) // cURL CA bundle not found.
300            &&
301            false === strpos( $message, 'Peer certificate cannot be authenticated with' ) // cURL CURLE_SSL_CACERT: CA bundle found, but not helpful
302            // Different versions of curl have different error messages
303            // this string should catch them all.
304            &&
305            false === strpos( $message, 'Problem with the SSL CA cert' ) // cURL CURLE_SSL_CACERT_BADFILE: probably access rights.
306        ) {
307            // No, it is not.
308            return $response;
309        }
310
311        // Redo the request without SSL certificate verification.
312        $args['sslverify'] = false;
313        $response          = wp_remote_request( $url, $args );
314
315        if ( ! is_wp_error( $response ) ) {
316            // The request went through this time, flag for future fallbacks.
317            \Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', time() );
318            self::set_time_diff( $response, $set_fallback );
319        }
320
321        return $response;
322    }
323
324    /**
325     * Sets the time difference for correct signature computation.
326     *
327     * @param array|WP_Error $response Response array from `wp_remote_request`, or WP_Error on error.
328     * @param bool           $force_set whether to force setting the time difference.
329     * @phan-param _WP_Remote_Response_Array|WP_Error $response
330     */
331    public static function set_time_diff( &$response, $force_set = false ) {
332        $code = wp_remote_retrieve_response_code( $response );
333
334        // Only trust the Date header on some responses.
335        if ( 200 != $code && 304 != $code && 400 != $code && 401 != $code ) { // phpcs:ignore  Universal.Operators.StrictComparisons.LooseNotEqual
336            return;
337        }
338
339        $date = wp_remote_retrieve_header( $response, 'date' );
340        if ( ! $date ) {
341            return;
342        }
343
344        $time = (int) strtotime( $date );
345        if ( 0 >= $time ) {
346            return;
347        }
348
349        $time_diff = $time - time();
350
351        if ( $force_set ) { // During register.
352            \Jetpack_Options::update_option( 'time_diff', $time_diff );
353        } else { // Otherwise.
354            $old_diff = \Jetpack_Options::get_option( 'time_diff' );
355            if ( false === $old_diff || abs( $time_diff - (int) $old_diff ) > 10 ) {
356                \Jetpack_Options::update_option( 'time_diff', $time_diff );
357            }
358        }
359    }
360
361    /**
362     * Validate and build arguments for a WordPress.com REST API request.
363     *
364     * @param  string $path             REST API path.
365     * @param  string $version          REST API version. Default is `2`.
366     * @param  array  $args             Arguments to {@see WP_Http}. Default is `array()`.
367     * @param  string $base_api_path    REST API root. Default is `wpcom`.
368     *
369     * @return array Validated arguments.
370     */
371    public static function validate_args_for_wpcom_json_api_request(
372        $path,
373        $version = '2',
374        $args = array(),
375        $base_api_path = 'wpcom'
376    ) {
377        $base_api_path = trim( $base_api_path, '/' );
378        $version       = ltrim( $version, 'v' );
379        $path          = ltrim( $path, '/' );
380
381        $filtered_args = array_intersect_key(
382            $args,
383            array(
384                'headers'     => 'array',
385                'method'      => 'string',
386                'format'      => 'string',
387                'timeout'     => 'int',
388                'redirection' => 'int',
389                'stream'      => 'boolean',
390                'filename'    => 'string',
391                'sslverify'   => 'boolean',
392            )
393        );
394
395        // Use GET by default whereas `remote_request` uses POST.
396        $request_method = isset( $filtered_args['method'] ) ? strtoupper( $filtered_args['method'] ) : 'GET';
397
398        $url = sprintf(
399            '%s/%s/v%s/%s',
400            Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
401            $base_api_path,
402            $version,
403            $path
404        );
405
406        $validated_args = array_merge(
407            $filtered_args,
408            array(
409                'url'    => $url,
410                'method' => $request_method,
411            )
412        );
413
414        return $validated_args;
415    }
416
417    /**
418     * Queries the WordPress.com REST API with a user token.
419     *
420     * @param string            $path             REST API path.
421     * @param string            $version          REST API version. Default is `2`.
422     * @param array             $args             Arguments to {@see WP_Http}. Default is `array()`.
423     * @param null|string|array $body             Body passed to {@see WP_Http}. Default is `null`.
424     * @param string            $base_api_path    REST API root. Default is `wpcom`.
425     *
426     * @return array|WP_Error $response Response data, else {@see WP_Error} on failure.
427     * @phan-return _WP_Remote_Response_Array|WP_Error
428     */
429    public static function wpcom_json_api_request_as_user(
430        $path,
431        $version = '2',
432        $args = array(),
433        $body = null,
434        $base_api_path = 'wpcom'
435    ) {
436        $args            = self::validate_args_for_wpcom_json_api_request( $path, $version, $args, $base_api_path );
437        $args['user_id'] = get_current_user_id();
438
439        if ( isset( $body ) && ! isset( $args['headers'] ) && in_array( $args['method'], array( 'POST', 'PUT', 'PATCH' ), true ) ) {
440            $args['headers'] = array( 'Content-Type' => 'application/json' );
441        }
442
443        if ( isset( $body ) && ! is_string( $body ) ) {
444            $body = wp_json_encode( $body, JSON_UNESCAPED_SLASHES );
445        }
446
447        return self::remote_request( $args, $body );
448    }
449
450    /**
451     * Query the WordPress.com REST API using the blog token
452     *
453     * @param string            $path The API endpoint relative path.
454     * @param string            $version The API version.
455     * @param array             $args Request arguments.
456     * @param array|string|null $body Request body.
457     * @param string            $base_api_path (optional) the API base path override, defaults to 'rest'.
458     * @return array|WP_Error $response Data.
459     * @phan-return _WP_Remote_Response_Array|WP_Error
460     */
461    public static function wpcom_json_api_request_as_blog(
462        $path,
463        $version = self::WPCOM_JSON_API_VERSION,
464        $args = array(),
465        $body = null,
466        $base_api_path = 'rest'
467    ) {
468        $validated_args            = self::validate_args_for_wpcom_json_api_request( $path, $version, $args, $base_api_path );
469        $validated_args['blog_id'] = (int) \Jetpack_Options::get_option( 'id' );
470
471        // For Simple sites get the response directly without any HTTP requests.
472        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
473            add_filter( 'is_jetpack_authorized_for_site', '__return_true' );
474            require_lib( 'wpcom-api-direct' );
475            return \WPCOM_API_Direct::do_request( $validated_args, $body );
476        }
477
478        return self::remote_request( $validated_args, $body );
479    }
480
481    /**
482     * Takes an array or similar structure and recursively turns all values into strings. This is used to
483     * make sure that body hashes are made ith the string version, which is what will be seen after a
484     * server pulls up the data in the $_POST array.
485     *
486     * @param mixed $data the data that needs to be stringified.
487     *
488     * @return array|string
489     */
490    public static function _stringify_data( $data ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
491
492        // Booleans are special, lets just makes them and explicit 1/0 instead of the 0 being an empty string.
493        if ( is_bool( $data ) ) {
494            return $data ? '1' : '0';
495        }
496
497        // Cast objects into arrays.
498        if ( is_object( $data ) ) {
499            $data = (array) $data;
500        }
501
502        // Non arrays at this point should be just converted to strings.
503        if ( ! is_array( $data ) ) {
504            return (string) $data;
505        }
506
507        foreach ( $data as &$value ) {
508            $value = self::_stringify_data( $value );
509        }
510
511        return $data;
512    }
513}