Completed
Push — add/jetpack-debugger-token-hea... ( d9f7f2...10157b )
by
unknown
27:28 queued 19:31
created

Client::get_signed_token()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 44

Duplication

Lines 5
Ratio 11.36 %

Importance

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