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