Completed
Push — add/private-site-mode ( 81d3a8...c37ff2 )
by
unknown
25:46 queued 11:45
created

Client::remote_request()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 2
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * The Connection Client class file.
4
 *
5
 * @package automattic/jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
use Automattic\Jetpack\Constants;
11
12
/**
13
 * The Client class that is used to connect to WordPress.com Jetpack API.
14
 */
15
class Client {
16
	const WPCOM_JSON_API_VERSION = '1.1';
17
18
	/**
19
	 * Makes an authorized remote request using Jetpack_Signature
20
	 *
21
	 * @param array        $args the arguments for the remote request.
22
	 * @param array|String $body the request body.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $body not be array|string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
23
	 * @return array|WP_Error WP HTTP response on success
24
	 */
25
	public static function remote_request( $args, $body = null ) {
26
		$result = self::build_signed_request( $args, $body );
27
		if ( ! $result || is_wp_error( $result ) ) {
28
			return $result;
29
		}
30
		return self::_wp_remote_request( $result['url'], $result['request'] );
31
	}
32
33
	/**
34
	 * Adds authorization signature to a remote request using Jetpack_Signature
35
	 *
36
	 * @param array        $args the arguments for the remote request.
37
	 * @param array|String $body the request body.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $body not be array|string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
38
	 * @return WP_Error|array {
39
	 *     An array containing URL and request items.
40
	 *
41
	 *     @type String $url     The request URL.
42
	 *     @type array  $request Request arguments.
43
	 * }
44
	 */
45
	public static function build_signed_request( $args, $body = null ) {
46
		add_filter(
47
			'jetpack_constant_default_value',
48
			__NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
49
			10,
50
			2
51
		);
52
53
		$defaults = array(
54
			'url'           => '',
55
			'user_id'       => 0,
56
			'blog_id'       => 0,
57
			'auth_location' => Constants::get_constant( 'JETPACK_CLIENT__AUTH_LOCATION' ),
58
			'method'        => 'POST',
59
			'timeout'       => 10,
60
			'redirection'   => 0,
61
			'headers'       => array(),
62
			'stream'        => false,
63
			'filename'      => null,
64
			'sslverify'     => true,
65
		);
66
67
		$args = wp_parse_args( $args, $defaults );
0 ignored issues
show
Documentation introduced by
$defaults is of type array<string,*,{"url":"s..."sslverify":"boolean"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
68
69
		$args['blog_id'] = (int) $args['blog_id'];
70
71
		if ( 'header' !== $args['auth_location'] ) {
72
			$args['auth_location'] = 'query_string';
73
		}
74
75
		$token = ( new Tokens() )->get_access_token( $args['user_id'] );
76
		if ( ! $token ) {
77
			return new \WP_Error( 'missing_token' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'missing_token'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
78
		}
79
80
		$method = strtoupper( $args['method'] );
81
82
		$timeout = (int) $args['timeout'];
83
84
		$redirection = $args['redirection'];
85
		$stream      = $args['stream'];
86
		$filename    = $args['filename'];
87
		$sslverify   = $args['sslverify'];
88
89
		$request = compact( 'method', 'body', 'timeout', 'redirection', 'stream', 'filename', 'sslverify' );
90
91
		@list( $token_key, $secret ) = explode( '.', $token->secret ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
92
		if ( empty( $token ) || empty( $secret ) ) {
93
			return new \WP_Error( 'malformed_token' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_token'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
94
		}
95
96
		$token_key = sprintf(
97
			'%s:%d:%d',
98
			$token_key,
99
			Constants::get_constant( 'JETPACK__API_VERSION' ),
100
			$token->external_user_id
101
		);
102
103
		$time_diff         = (int) \Jetpack_Options::get_option( 'time_diff' );
104
		$jetpack_signature = new \Jetpack_Signature( $token->secret, $time_diff );
105
106
		$timestamp = time() + $time_diff;
107
108 View Code Duplication
		if ( function_exists( 'wp_generate_password' ) ) {
109
			$nonce = wp_generate_password( 10, false );
110
		} else {
111
			$nonce = substr( sha1( wp_rand( 0, 1000000 ) ), 0, 10 );
112
		}
113
114
		// Kind of annoying.  Maybe refactor Jetpack_Signature to handle body-hashing.
115
		if ( is_null( $body ) ) {
116
			$body_hash = '';
117
118
		} else {
119
			// Allow arrays to be used in passing data.
120
			$body_to_hash = $body;
121
122
			if ( is_array( $body ) ) {
123
				// We cast this to a new variable, because the array form of $body needs to be
124
				// maintained so it can be passed into the request later on in the code.
125
				if ( count( $body ) > 0 ) {
126
					$body_to_hash = wp_json_encode( self::_stringify_data( $body ) );
127
				} else {
128
					$body_to_hash = '';
129
				}
130
			}
131
132
			if ( ! is_string( $body_to_hash ) ) {
133
				return new \WP_Error( 'invalid_body', 'Body is malformed.' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_body'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
134
			}
135
136
			$body_hash = base64_encode( sha1( $body_to_hash, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
137
		}
138
139
		$auth = array(
140
			'token'     => $token_key,
141
			'timestamp' => $timestamp,
142
			'nonce'     => $nonce,
143
			'body-hash' => $body_hash,
144
		);
145
146
		if ( false !== strpos( $args['url'], 'xmlrpc.php' ) ) {
147
			$url_args = array(
148
				'for'           => 'jetpack',
149
				'wpcom_blog_id' => \Jetpack_Options::get_option( 'id' ),
150
			);
151
		} else {
152
			$url_args = array();
153
		}
154
155
		if ( 'header' !== $args['auth_location'] ) {
156
			$url_args += $auth;
157
		}
158
159
		$url = add_query_arg( urlencode_deep( $url_args ), $args['url'] );
160
161
		$signature = $jetpack_signature->sign_request( $token_key, $timestamp, $nonce, $body_hash, $method, $url, $body, false );
162
163
		if ( ! $signature || is_wp_error( $signature ) ) {
164
			return $signature;
165
		}
166
167
		// Send an Authorization header so various caches/proxies do the right thing.
168
		$auth['signature'] = $signature;
169
		$auth['version']   = Constants::get_constant( 'JETPACK__VERSION' );
170
		$header_pieces     = array();
171
		foreach ( $auth as $key => $value ) {
172
			$header_pieces[] = sprintf( '%s="%s"', $key, $value );
173
		}
174
		$request['headers'] = array_merge(
175
			$args['headers'],
176
			array(
177
				'Authorization' => 'X_JETPACK ' . join( ' ', $header_pieces ),
178
			)
179
		);
180
181
		if ( 'header' !== $args['auth_location'] ) {
182
			$url = add_query_arg( 'signature', rawurlencode( $signature ), $url );
183
		}
184
185
		return compact( 'url', 'request' );
186
	}
187
188
	/**
189
	 * Wrapper for wp_remote_request().  Turns off SSL verification for certain SSL errors.
190
	 * This is lame, but many, many, many hosts have misconfigured SSL.
191
	 *
192
	 * When Jetpack is registered, the jetpack_fallback_no_verify_ssl_certs option is set to the current time if:
193
	 * 1. a certificate error is found AND
194
	 * 2. not verifying the certificate works around the problem.
195
	 *
196
	 * The option is checked on each request.
197
	 *
198
	 * @internal
199
	 *
200
	 * @param String  $url the request URL.
201
	 * @param array   $args request arguments.
202
	 * @param Boolean $set_fallback whether to allow flagging this request to use a fallback certficate override.
203
	 * @return array|WP_Error WP HTTP response on success
204
	 */
205
	public static function _wp_remote_request( $url, $args, $set_fallback = false ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
206
		$fallback = \Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
207
		if ( false === $fallback ) {
208
			\Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', 0 );
209
		}
210
211
		/**
212
		 * SSL verification (`sslverify`) for the JetpackClient remote request
213
		 * defaults to off, use this filter to force it on.
214
		 *
215
		 * Return `true` to ENABLE SSL verification, return `false`
216
		 * to DISABLE SSL verification.
217
		 *
218
		 * @since 3.6.0
219
		 *
220
		 * @param bool Whether to force `sslverify` or not.
221
		 */
222
		if ( apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
223
			return wp_remote_request( $url, $args );
224
		}
225
226
		if ( (int) $fallback ) {
227
			// We're flagged to fallback.
228
			$args['sslverify'] = false;
229
		}
230
231
		$response = wp_remote_request( $url, $args );
232
233
		if (
234
			! $set_fallback                                     // We're not allowed to set the flag on this request, so whatever happens happens.
235
			||
236
			isset( $args['sslverify'] ) && ! $args['sslverify'] // No verification - no point in doing it again.
237
			||
238
			! is_wp_error( $response )                          // Let it ride.
239
		) {
240
			self::set_time_diff( $response, $set_fallback );
241
			return $response;
242
		}
243
244
		// At this point, we're not flagged to fallback and we are allowed to set the flag on this request.
245
246
		$message = $response->get_error_message();
247
248
		// Is it an SSL Certificate verification error?
249
		if (
250
			false === strpos( $message, '14090086' ) // OpenSSL SSL3 certificate error.
251
			&&
252
			false === strpos( $message, '1407E086' ) // OpenSSL SSL2 certificate error.
253
			&&
254
			false === strpos( $message, 'error setting certificate verify locations' ) // cURL CA bundle not found.
255
			&&
256
			false === strpos( $message, 'Peer certificate cannot be authenticated with' ) // cURL CURLE_SSL_CACERT: CA bundle found, but not helpful
257
			// Different versions of curl have different error messages
258
			// this string should catch them all.
259
			&&
260
			false === strpos( $message, 'Problem with the SSL CA cert' ) // cURL CURLE_SSL_CACERT_BADFILE: probably access rights.
261
		) {
262
			// No, it is not.
263
			return $response;
264
		}
265
266
		// Redo the request without SSL certificate verification.
267
		$args['sslverify'] = false;
268
		$response          = wp_remote_request( $url, $args );
269
270
		if ( ! is_wp_error( $response ) ) {
271
			// The request went through this time, flag for future fallbacks.
272
			\Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', time() );
273
			self::set_time_diff( $response, $set_fallback );
274
		}
275
276
		return $response;
277
	}
278
279
	/**
280
	 * Sets the time difference for correct signature computation.
281
	 *
282
	 * @param HTTP_Response $response the response object.
283
	 * @param Boolean       $force_set whether to force setting the time difference.
284
	 */
285
	public static function set_time_diff( &$response, $force_set = false ) {
286
		$code = wp_remote_retrieve_response_code( $response );
287
288
		// Only trust the Date header on some responses.
289
		if ( 200 != $code && 304 != $code && 400 != $code && 401 != $code ) { // phpcs:ignore  WordPress.PHP.StrictComparisons.LooseComparison
290
			return;
291
		}
292
293
		$date = wp_remote_retrieve_header( $response, 'date' );
294
		if ( ! $date ) {
295
			return;
296
		}
297
298
		$time = (int) strtotime( $date );
299
		if ( 0 >= $time ) {
300
			return;
301
		}
302
303
		$time_diff = $time - time();
304
305
		if ( $force_set ) { // During register.
306
			\Jetpack_Options::update_option( 'time_diff', $time_diff );
307
		} else { // Otherwise.
308
			$old_diff = \Jetpack_Options::get_option( 'time_diff' );
309
			if ( false === $old_diff || abs( $time_diff - (int) $old_diff ) > 10 ) {
310
				\Jetpack_Options::update_option( 'time_diff', $time_diff );
311
			}
312
		}
313
	}
314
315
	/**
316
	 * Validate and build arguments for a WordPress.com REST API request.
317
	 *
318
	 * @param  string $path             REST API path.
319
	 * @param  string $version          REST API version. Default is `2`.
320
	 * @param  array  $args             Arguments to {@see WP_Http}. Default is `array()`.
321
	 * @param  string $base_api_path    REST API root. Default is `wpcom`.
322
	 *
323
	 * @return array|WP_Error $response Response data, else {@see WP_Error} on failure.
324
	 */
325
	public static function validate_args_for_wpcom_json_api_request(
326
		$path,
327
		$version = '2',
328
		$args = array(),
329
		$base_api_path = 'wpcom'
330
	) {
331
		$base_api_path = trim( $base_api_path, '/' );
332
		$version       = ltrim( $version, 'v' );
333
		$path          = ltrim( $path, '/' );
334
335
		$filtered_args = array_intersect_key(
336
			$args,
337
			array(
338
				'headers'     => 'array',
339
				'method'      => 'string',
340
				'timeout'     => 'int',
341
				'redirection' => 'int',
342
				'stream'      => 'boolean',
343
				'filename'    => 'string',
344
				'sslverify'   => 'boolean',
345
			)
346
		);
347
348
		// Use GET by default whereas `remote_request` uses POST.
349
		$request_method = isset( $filtered_args['method'] ) ? strtoupper( $filtered_args['method'] ) : 'GET';
350
351
		$url = sprintf(
352
			'%s/%s/v%s/%s',
353
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
354
			$base_api_path,
355
			$version,
356
			$path
357
		);
358
359
		$validated_args = array_merge(
360
			$filtered_args,
361
			array(
362
				'url'    => $url,
363
				'method' => $request_method,
364
			)
365
		);
366
367
		return $validated_args;
368
	}
369
370
	/**
371
	 * Queries the WordPress.com REST API with a user token.
372
	 *
373
	 * @param  string $path             REST API path.
374
	 * @param  string $version          REST API version. Default is `2`.
375
	 * @param  array  $args             Arguments to {@see WP_Http}. Default is `array()`.
376
	 * @param  string $body             Body passed to {@see WP_Http}. Default is `null`.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $body not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
377
	 * @param  string $base_api_path    REST API root. Default is `wpcom`.
378
	 *
379
	 * @return array|WP_Error $response Response data, else {@see WP_Error} on failure.
380
	 */
381
	public static function wpcom_json_api_request_as_user(
382
		$path,
383
		$version = '2',
384
		$args = array(),
385
		$body = null,
386
		$base_api_path = 'wpcom'
387
	) {
388
		$args            = self::validate_args_for_wpcom_json_api_request( $path, $version, $args, $base_api_path );
389
		$args['user_id'] = get_current_user_id();
390
391
		if ( isset( $body ) && ! isset( $args['headers'] ) && in_array( $args['method'], array( 'POST', 'PUT', 'PATCH' ), true ) ) {
392
			$args['headers'] = array( 'Content-Type' => 'application/json' );
393
		}
394
395
		if ( isset( $body ) && ! is_string( $body ) ) {
396
			$body = wp_json_encode( $body );
397
		}
398
399
		return self::remote_request( $args, $body );
0 ignored issues
show
Security Bug introduced by
It seems like $body defined by wp_json_encode($body) on line 396 can also be of type false; however, Automattic\Jetpack\Conne...lient::remote_request() does only seem to accept array|string|null, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
400
	}
401
402
	/**
403
	 * Query the WordPress.com REST API using the blog token
404
	 *
405
	 * @param String $path The API endpoint relative path.
406
	 * @param String $version The API version.
407
	 * @param array  $args Request arguments.
408
	 * @param String $body Request body.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $body not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
409
	 * @param String $base_api_path (optional) the API base path override, defaults to 'rest'.
410
	 * @return array|WP_Error $response Data.
411
	 */
412
	public static function wpcom_json_api_request_as_blog(
413
		$path,
414
		$version = self::WPCOM_JSON_API_VERSION,
415
		$args = array(),
416
		$body = null,
417
		$base_api_path = 'rest'
418
	) {
419
		$validated_args            = self::validate_args_for_wpcom_json_api_request( $path, $version, $args, $base_api_path );
420
		$validated_args['blog_id'] = (int) \Jetpack_Options::get_option( 'id' );
421
422
		// For Simple sites get the response directly without any HTTP requests.
423
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
424
			add_filter( 'is_jetpack_authorized_for_site', '__return_true' );
425
			require_lib( 'wpcom-api-direct' );
426
			return \WPCOM_API_Direct::do_request( $validated_args, $body );
427
		}
428
429
		return self::remote_request( $validated_args, $body );
430
	}
431
432
	/**
433
	 * Takes an array or similar structure and recursively turns all values into strings. This is used to
434
	 * make sure that body hashes are made ith the string version, which is what will be seen after a
435
	 * server pulls up the data in the $_POST array.
436
	 *
437
	 * @param array|Mixed $data the data that needs to be stringified.
438
	 *
439
	 * @return array|string
440
	 */
441
	public static function _stringify_data( $data ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
442
443
		// Booleans are special, lets just makes them and explicit 1/0 instead of the 0 being an empty string.
444
		if ( is_bool( $data ) ) {
445
			return $data ? '1' : '0';
446
		}
447
448
		// Cast objects into arrays.
449
		if ( is_object( $data ) ) {
450
			$data = (array) $data;
451
		}
452
453
		// Non arrays at this point should be just converted to strings.
454
		if ( ! is_array( $data ) ) {
455
			return (string) $data;
456
		}
457
458
		foreach ( $data as &$value ) {
459
			$value = self::_stringify_data( $value );
460
		}
461
462
		return $data;
463
	}
464
465
	/**
466
	 * Gets protocol string.
467
	 *
468
	 * @return string Always 'https'.
469
	 *
470
	 * @deprecated 9.1.0 WP.com API no longer supports requests using `http://`.
471
	 */
472
	public static function protocol() {
473
		_deprecated_function( __METHOD__, 'jetpack-9.1.0' );
474
475
		return 'https';
476
	}
477
}
478