Completed
Push — fix/128-auto-updates-visible-o... ( 878943...7e3a71 )
by
unknown
27:54 queued 19:45
created

Error_Handler::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
1
<?php
2
/**
3
 * The Jetpack Connection error class file.
4
 *
5
 * @package automattic/jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
/**
11
 * The Jetpack Connection Errors that handles errors
12
 *
13
 * This class handles the following workflow:
14
 *
15
 * 1. A XML-RCP request with an invalid signature triggers a error
16
 * 2. Applies a gate to only process each error code once an hour to avoid overflow
17
 * 3. It stores the error on the database, but we don't know yet if this is a valid error, because
18
 *    we can't confirm it came from WP.com.
19
 * 4. It encrypts the error details and send it to thw wp.com server
20
 * 5. wp.com checks it and, if valid, sends a new request back to this site using the verify_xml_rpc_error REST endpoint
21
 * 6. This endpoint add this error to the Verified errors in the database
22
 * 7. Triggers a workflow depending on the error (display user an error message, do some self healing, etc.)
23
 *
24
 * Errors are stored in the database as options in the following format:
25
 *
26
 * [
27
 *   $error_code => [
28
 *     $user_id => [
29
 *       $error_details
30
 *     ]
31
 *   ]
32
 * ]
33
 *
34
 * For each error code we store a maximum of 5 errors for 5 different user ids.
35
 *
36
 * An user ID can be
37
 * * 0 for blog tokens
38
 * * positive integer for user tokens
39
 * * 'invalid' for malformed tokens
40
 *
41
 * @since 8.7.0
42
 */
43
class Error_Handler {
44
45
	/**
46
	 * The name of the option that stores the errors
47
	 *
48
	 * @since 8.7.0
49
	 *
50
	 * @var string
51
	 */
52
	const STORED_ERRORS_OPTION = 'jetpack_connection_xmlrpc_errors';
53
54
	/**
55
	 * The name of the option that stores the errors
56
	 *
57
	 * @since 8.7.0
58
	 *
59
	 * @var string
60
	 */
61
	const STORED_VERIFIED_ERRORS_OPTION = 'jetpack_connection_xmlrpc_verified_errors';
62
63
	/**
64
	 * The prefix of the transient that controls the gate for each error code
65
	 *
66
	 * @since 8.7.0
67
	 *
68
	 * @var string
69
	 */
70
	const ERROR_REPORTING_GATE = 'jetpack_connection_error_reporting_gate_';
71
72
	/**
73
	 * Time in seconds a test should live in the database before being discarded
74
	 *
75
	 * @since 8.7.0
76
	 */
77
	const ERROR_LIFE_TIME = DAY_IN_SECONDS;
78
	/**
79
	 * List of known errors. Only error codes in this list will be handled
80
	 *
81
	 * @since 8.7.0
82
	 *
83
	 * @var array
84
	 */
85
	public $known_errors = array(
86
		'malformed_token',
87
		'malformed_user_id',
88
		'unknown_user',
89
		'no_user_tokens',
90
		'empty_master_user_option',
91
		'no_token_for_user',
92
		'token_malformed',
93
		'user_id_mismatch',
94
		'no_possible_tokens',
95
		'no_valid_token',
96
		'unknown_token',
97
		'could_not_sign',
98
		'invalid_scheme',
99
		'invalid_secret',
100
		'invalid_token',
101
		'token_mismatch',
102
		'invalid_body',
103
		'invalid_signature',
104
		'invalid_body_hash',
105
		'invalid_nonce',
106
		'signature_mismatch',
107
	);
108
109
	/**
110
	 * Holds the instance of this singleton class
111
	 *
112
	 * @since 8.7.0
113
	 *
114
	 * @var Error_Handler $instance
115
	 */
116
	public static $instance = null;
117
118
	/**
119
	 * Initialize instance, hookds and load verified errors handlers
120
	 *
121
	 * @since 8.7.0
122
	 */
123
	private function __construct() {
124
		defined( 'JETPACK__ERRORS_PUBLIC_KEY' ) || define( 'JETPACK__ERRORS_PUBLIC_KEY', 'KdZY80axKX+nWzfrOcizf0jqiFHnrWCl9X8yuaClKgM=' );
125
126
		add_action( 'rest_api_init', array( $this, 'register_verify_error_endpoint' ) );
127
128
		$this->handle_verified_errors();
129
130
		// If the site gets reconnected, clear errors.
131
		add_action( 'jetpack_site_registered', array( $this, 'delete_all_errors' ) );
132
		add_action( 'jetpack_get_site_data_success', array( $this, 'delete_all_errors' ) );
133
	}
134
135
	/**
136
	 * Gets the list of verified errors and act upon them
137
	 *
138
	 * @since 8.7.0
139
	 *
140
	 * @return void
141
	 */
142
	public function handle_verified_errors() {
143
		$verified_errors = $this->get_verified_errors();
144
		foreach ( array_keys( $verified_errors ) as $error_code ) {
145
146
			$error_found = false;
147
148
			switch ( $error_code ) {
149
				case 'malformed_token':
150
				case 'token_malformed':
151
				case 'no_possible_tokens':
152
				case 'no_valid_token':
153
				case 'unknown_token':
154
				case 'could_not_sign':
155
				case 'invalid_token':
156
				case 'token_mismatch':
157
				case 'invalid_signature':
158
				case 'signature_mismatch':
159
				case 'no_user_tokens':
160
				case 'no_token_for_user':
161
					add_action( 'admin_notices', array( $this, 'generic_admin_notice_error' ) );
162
					add_action( 'react_connection_errors_initial_state', array( $this, 'jetpack_react_dashboard_error' ) );
163
					$error_found = true;
164
			}
165
			if ( $error_found ) {
166
				// Since we are only generically handling errors, we don't need to trigger error messages for each one of them.
167
				break;
168
			}
169
		}
170
	}
171
172
	/**
173
	 * Gets the instance of this singleton class
174
	 *
175
	 * @since 8.7.0
176
	 *
177
	 * @return Error_Handler $instance
178
	 */
179
	public static function get_instance() {
180
		if ( is_null( self::$instance ) ) {
181
			self::$instance = new self();
182
		}
183
		return self::$instance;
184
	}
185
186
	/**
187
	 * Keep track of a connection error that was encountered
188
	 *
189
	 * @since 8.7.0
190
	 *
191
	 * @param \WP_Error $error the error object.
192
	 * @param boolean   $force Force the report, even if should_report_error is false.
193
	 * @return void
194
	 */
195
	public function report_error( \WP_Error $error, $force = false ) {
196
		if ( in_array( $error->get_error_code(), $this->known_errors, true ) && $this->should_report_error( $error ) || $force ) {
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
197
			$stored_error = $this->store_error( $error );
198
			if ( $stored_error ) {
199
				$this->send_error_to_wpcom( $stored_error );
200
			}
201
		}
202
	}
203
204
	/**
205
	 * Checks the status of the gate
206
	 *
207
	 * This protects the site (and WPCOM) against over loads.
208
	 *
209
	 * @since 8.7.0
210
	 *
211
	 * @param \WP_Error $error the error object.
212
	 * @return boolean $should_report True if gate is open and the error should be reported.
213
	 */
214
	public function should_report_error( \WP_Error $error ) {
215
216
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
217
			return true;
218
		}
219
220
		/**
221
		 * Whether to bypass the gate for XML-RPC error handling
222
		 *
223
		 * By default, we only process XML-RPC errors once an hour for each error code.
224
		 * This is done to avoid overflows. If you need to disable this gate, you can set this variable to true.
225
		 *
226
		 * This filter is useful for unit testing
227
		 *
228
		 * @since 8.7.0
229
		 *
230
		 * @param boolean $bypass_gate whether to bypass the gate. Default is false, do not bypass.
231
		 */
232
		$bypass_gate = apply_filters( 'jetpack_connection_bypass_error_reporting_gate', false );
233
		if ( true === $bypass_gate ) {
234
			return true;
235
		}
236
237
		$transient = self::ERROR_REPORTING_GATE . $error->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
238
239
		if ( get_transient( $transient ) ) {
240
			return false;
241
		}
242
243
		set_transient( $transient, true, HOUR_IN_SECONDS );
244
		return true;
245
	}
246
247
	/**
248
	 * Stores the error in the database so we know there is an issue and can inform the user
249
	 *
250
	 * @since 8.7.0
251
	 *
252
	 * @param \WP_Error $error the error object.
253
	 * @return boolean|array False if stored errors were not updated and the error array if it was successfully stored.
254
	 */
255
	public function store_error( \WP_Error $error ) {
256
257
		$stored_errors = $this->get_stored_errors();
258
		$error_array   = $this->wp_error_to_array( $error );
259
		$error_code    = $error->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
260
		$user_id       = $error_array['user_id'];
261
262
		if ( ! isset( $stored_errors[ $error_code ] ) || ! is_array( $stored_errors[ $error_code ] ) ) {
263
			$stored_errors[ $error_code ] = array();
264
		}
265
266
		$stored_errors[ $error_code ][ $user_id ] = $error_array;
267
268
		// Let's store a maximum of 5 different user ids for each error code.
269
		if ( count( $stored_errors[ $error_code ] ) > 5 ) {
270
			// array_shift will destroy keys here because they are numeric, so manually remove first item.
271
			$keys = array_keys( $stored_errors[ $error_code ] );
272
			unset( $stored_errors[ $error_code ][ $keys[0] ] );
273
		}
274
275
		if ( update_option( self::STORED_ERRORS_OPTION, $stored_errors ) ) {
276
			return $error_array;
277
		}
278
279
		return false;
280
281
	}
282
283
	/**
284
	 * Converts a WP_Error object in the array representation we store in the database
285
	 *
286
	 * @since 8.7.0
287
	 *
288
	 * @param \WP_Error $error the error object.
289
	 * @return boolean|array False if error is invalid or the error array
290
	 */
291
	public function wp_error_to_array( \WP_Error $error ) {
292
293
		$data = $error->get_error_data();
0 ignored issues
show
Bug introduced by
The method get_error_data() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
294
295
		if ( ! isset( $data['signature_details'] ) || ! is_array( $data['signature_details'] ) ) {
296
			return false;
297
		}
298
299
		$data = $data['signature_details'];
300
301
		if ( ! isset( $data['token'] ) || empty( $data['token'] ) ) {
302
			return false;
303
		}
304
305
		$user_id = $this->get_user_id_from_token( $data['token'] );
306
307
		$error_array = array(
308
			'error_code'    => $error->get_error_code(),
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
309
			'user_id'       => $user_id,
310
			'error_message' => $error->get_error_message(),
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
311
			'error_data'    => $data,
312
			'timestamp'     => time(),
313
			'nonce'         => wp_generate_password( 10, false ),
314
		);
315
316
		return $error_array;
317
318
	}
319
320
	/**
321
	 * Sends the error to WP.com to be verified
322
	 *
323
	 * @since 8.7.0
324
	 *
325
	 * @param array $error_array The array representation of the error as it is stored in the database.
326
	 * @return bool
327
	 */
328
	public function send_error_to_wpcom( $error_array ) {
329
330
		$blog_id = \Jetpack_Options::get_option( 'id' );
331
332
		$encrypted_data = $this->encrypt_data_to_wpcom( $error_array );
333
334
		if ( false === $encrypted_data ) {
335
			return false;
336
		}
337
338
		$args = array(
339
			'body' => array(
340
				'error_data' => $encrypted_data,
341
			),
342
		);
343
344
		// send encrypted data to WP.com Public-API v2.
345
		wp_remote_post( "https://public-api.wordpress.com/wpcom/v2/sites/{$blog_id}/jetpack-report-error/", $args );
346
		return true;
347
	}
348
349
	/**
350
	 * Encrypt data to be sent over to WP.com
351
	 *
352
	 * @since 8.7.0
353
	 *
354
	 * @param array|string $data the data to be encoded.
355
	 * @return boolean|string The encoded string on success, false on failure
356
	 */
357
	public function encrypt_data_to_wpcom( $data ) {
358
359
		try {
360
			// phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
361
			// phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
362
			$encrypted_data = base64_encode( sodium_crypto_box_seal( wp_json_encode( $data ), base64_decode( JETPACK__ERRORS_PUBLIC_KEY ) ) );
363
			// phpcs:enable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
364
			// phpcs:enable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
365
		} catch ( \SodiumException $e ) {
0 ignored issues
show
Bug introduced by
The class SodiumException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
366
			// error encrypting data.
367
			return false;
368
		}
369
370
		return $encrypted_data;
371
372
	}
373
374
	/**
375
	 * Extracts the user ID from a token
376
	 *
377
	 * @since 8.7.0
378
	 *
379
	 * @param string $token the token used to make the xml-rpc request.
380
	 * @return string $the user id or `invalid` if user id not present.
381
	 */
382
	public function get_user_id_from_token( $token ) {
383
		$parsed_token = explode( ':', wp_unslash( $token ) );
384
385
		if ( isset( $parsed_token[2] ) && ctype_digit( $parsed_token[2] ) ) {
386
			$user_id = $parsed_token[2];
387
		} else {
388
			$user_id = 'invalid';
389
		}
390
391
		return $user_id;
392
393
	}
394
395
	/**
396
	 * Gets the reported errors stored in the database
397
	 *
398
	 * @since 8.7.0
399
	 *
400
	 * @return array $errors
401
	 */
402 View Code Duplication
	public function get_stored_errors() {
403
404
		$stored_errors = get_option( self::STORED_ERRORS_OPTION );
405
406
		if ( ! is_array( $stored_errors ) ) {
407
			$stored_errors = array();
408
		}
409
410
		$stored_errors = $this->garbage_collector( $stored_errors );
411
412
		return $stored_errors;
413
	}
414
415
	/**
416
	 * Gets the verified errors stored in the database
417
	 *
418
	 * @since 8.7.0
419
	 *
420
	 * @return array $errors
421
	 */
422 View Code Duplication
	public function get_verified_errors() {
423
424
		$verified_errors = get_option( self::STORED_VERIFIED_ERRORS_OPTION );
425
426
		if ( ! is_array( $verified_errors ) ) {
427
			$verified_errors = array();
428
		}
429
430
		$verified_errors = $this->garbage_collector( $verified_errors );
431
432
		return $verified_errors;
433
	}
434
435
	/**
436
	 * Removes expired errors from the array
437
	 *
438
	 * This method is called by get_stored_errors and get_verified errors and filters their result
439
	 * Whenever a new error is stored to the database or verified, this will be triggered and the
440
	 * expired error will be permantently removed from the database
441
	 *
442
	 * @since 8.7.0
443
	 *
444
	 * @param array $errors array of errors as stored in the database.
445
	 * @return array
446
	 */
447
	private function garbage_collector( $errors ) {
448
		foreach ( $errors as $error_code => $users ) {
449
			foreach ( $users as $user_id => $error ) {
450
				if ( self::ERROR_LIFE_TIME < time() - (int) $error['timestamp'] ) {
451
					unset( $errors[ $error_code ][ $user_id ] );
452
				}
453
			}
454
		}
455
		// Clear empty error codes.
456
		$errors = array_filter(
457
			$errors,
458
			function( $user_errors ) {
459
				return ! empty( $user_errors );
460
			}
461
		);
462
		return $errors;
463
	}
464
465
	/**
466
	 * Delete all stored and verified errors from the database
467
	 *
468
	 * @since 8.7.0
469
	 *
470
	 * @return void
471
	 */
472
	public function delete_all_errors() {
473
		$this->delete_stored_errors();
474
		$this->delete_verified_errors();
475
	}
476
477
	/**
478
	 * Delete the reported errors stored in the database
479
	 *
480
	 * @since 8.7.0
481
	 *
482
	 * @return boolean True, if option is successfully deleted. False on failure.
483
	 */
484
	public function delete_stored_errors() {
485
		return delete_option( self::STORED_ERRORS_OPTION );
486
	}
487
488
	/**
489
	 * Delete the verified errors stored in the database
490
	 *
491
	 * @since 8.7.0
492
	 *
493
	 * @return boolean True, if option is successfully deleted. False on failure.
494
	 */
495
	public function delete_verified_errors() {
496
		return delete_option( self::STORED_VERIFIED_ERRORS_OPTION );
497
	}
498
499
	/**
500
	 * Gets an error based on the nonce
501
	 *
502
	 * Receives a nonce and finds the related error.
503
	 *
504
	 * @since 8.7.0
505
	 *
506
	 * @param string $nonce The nonce created for the error we want to get.
507
	 * @return null|array Returns the error array representation or null if error not found.
508
	 */
509
	public function get_error_by_nonce( $nonce ) {
510
		$errors = $this->get_stored_errors();
511
		foreach ( $errors as $user_group ) {
512
			foreach ( $user_group as $error ) {
513
				if ( $error['nonce'] === $nonce ) {
514
					return $error;
515
				}
516
			}
517
		}
518
		return null;
519
	}
520
521
	/**
522
	 * Adds an error to the verified error list
523
	 *
524
	 * @since 8.7.0
525
	 *
526
	 * @param array $error The error array, as it was saved in the unverified errors list.
527
	 * @return void
528
	 */
529
	public function verify_error( $error ) {
530
531
		$verified_errors = $this->get_verified_errors();
532
		$error_code      = $error['error_code'];
533
		$user_id         = $error['user_id'];
534
535
		if ( ! isset( $verified_errors[ $error_code ] ) ) {
536
			$verified_errors[ $error_code ] = array();
537
		}
538
539
		$verified_errors[ $error_code ][ $user_id ] = $error;
540
541
		update_option( self::STORED_VERIFIED_ERRORS_OPTION, $verified_errors );
542
543
	}
544
545
	/**
546
	 * Register REST API end point for error hanlding.
547
	 *
548
	 * @since 8.7.0
549
	 *
550
	 * @return void
551
	 */
552
	public function register_verify_error_endpoint() {
553
		register_rest_route(
554
			'jetpack/v4',
555
			'/verify_xmlrpc_error',
556
			array(
557
				'methods'             => \WP_REST_Server::CREATABLE,
558
				'callback'            => array( $this, 'verify_xml_rpc_error' ),
559
				'permission_callback' => '__return_true',
560
				'args'                => array(
561
					'nonce' => array(
562
						'required' => true,
563
						'type'     => 'string',
564
					),
565
				),
566
			)
567
		);
568
	}
569
570
	/**
571
	 * Handles verification that a xml rpc error is legit and came from WordPres.com
572
	 *
573
	 * @since 8.7.0
574
	 *
575
	 * @param \WP_REST_Request $request The request sent to the WP REST API.
576
	 *
577
	 * @return boolean
578
	 */
579
	public function verify_xml_rpc_error( \WP_REST_Request $request ) {
580
581
		$error = $this->get_error_by_nonce( $request['nonce'] );
582
583
		if ( $error ) {
584
			$this->verify_error( $error );
585
			return new \WP_REST_Response( true, 200 );
586
		}
587
588
		return new \WP_REST_Response( false, 200 );
589
590
	}
591
592
	/**
593
	 * Prints a generic error notice for all connection errors
594
	 *
595
	 * @since 8.9.0
596
	 *
597
	 * @return void
598
	 */
599
	public function generic_admin_notice_error() {
600
		// do not add admin notice to the jetpack dashboard.
601
		global $pagenow;
602
		if ( 'admin.php' === $pagenow || isset( $_GET['page'] ) && 'jetpack' === $_GET['page'] ) { // phpcs:ignore
603
			return;
604
		}
605
606
		if ( ! current_user_can( 'jetpack_connect' ) ) {
607
			return;
608
		}
609
610
		/**
611
		 * Filters the message to be displayed in the admin notices area when there's a xmlrpc error.
612
		 *
613
		 * By default  we don't display any errors.
614
		 *
615
		 * Return an empty value to disable the message.
616
		 *
617
		 * @since 8.9.0
618
		 *
619
		 * @param string $message The error message.
620
		 * @param array  $errors The array of errors. See Automattic\Jetpack\Connection\Error_Handler for details on the array structure.
621
		 */
622
		$message = apply_filters( 'jetpack_connection_error_notice_message', '', $this->get_verified_errors() );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $this->get_verified_errors().

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...
623
624
		/**
625
		 * Fires inside the admin_notices hook just before displaying the error message for a broken connection.
626
		 *
627
		 * If you want to disable the default message from being displayed, return an emtpy value in the jetpack_connection_error_notice_message filter.
628
		 *
629
		 * @since 8.9.0
630
		 *
631
		 * @param array $errors The array of errors. See Automattic\Jetpack\Connection\Error_Handler for details on the array structure.
632
		 */
633
		do_action( 'jetpack_connection_error_notice', $this->get_verified_errors() );
634
635
		if ( empty( $message ) ) {
636
			return;
637
		}
638
639
		?>
640
		<div class="notice notice-error is-dismissible jetpack-message jp-connect" style="display:block !important;">
641
			<p><?php echo esc_html( $message ); ?></p>
642
		</div>
643
		<?php
644
	}
645
646
	/**
647
	 * Adds the error message to the Jetpack React Dashboard
648
	 *
649
	 * @since 8.9.0
650
	 *
651
	 * @param array $errors The array of errors. See Automattic\Jetpack\Connection\Error_Handler for details on the array structure.
652
	 * @return array
653
	 */
654
	public function jetpack_react_dashboard_error( $errors ) {
655
656
		$errors[] = array(
657
			'code'    => 'xmlrpc_error',
658
			'message' => __( 'Your connection with WordPress.com seems to be broken. If you\'re experiencing issues, please try reconnecting.', 'jetpack' ),
659
			'action'  => 'reconnect',
660
		);
661
		return $errors;
662
	}
663
664
}
665