Completed
Push — try/jetpack-stories-block-mobi... ( 2fea66 )
by
unknown
126:35 queued 116:47
created

packages/connection/src/class-error-handler.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
	/**
80
	 * The error code for event tracking purposes.
81
	 * If there are many, only the first error code will be tracked.
82
	 *
83
	 * @var string
84
	 */
85
	private $error_code;
86
87
	/**
88
	 * List of known errors. Only error codes in this list will be handled
89
	 *
90
	 * @since 8.7.0
91
	 *
92
	 * @var array
93
	 */
94
	public $known_errors = array(
95
		'malformed_token',
96
		'malformed_user_id',
97
		'unknown_user',
98
		'no_user_tokens',
99
		'empty_master_user_option',
100
		'no_token_for_user',
101
		'token_malformed',
102
		'user_id_mismatch',
103
		'no_possible_tokens',
104
		'no_valid_user_token',
105
		'no_valid_blog_token',
106
		'unknown_token',
107
		'could_not_sign',
108
		'invalid_scheme',
109
		'invalid_secret',
110
		'invalid_token',
111
		'token_mismatch',
112
		'invalid_body',
113
		'invalid_signature',
114
		'invalid_body_hash',
115
		'invalid_nonce',
116
		'signature_mismatch',
117
	);
118
119
	/**
120
	 * Holds the instance of this singleton class
121
	 *
122
	 * @since 8.7.0
123
	 *
124
	 * @var Error_Handler $instance
125
	 */
126
	public static $instance = null;
127
128
	/**
129
	 * Initialize instance, hookds and load verified errors handlers
130
	 *
131
	 * @since 8.7.0
132
	 */
133
	private function __construct() {
134
		defined( 'JETPACK__ERRORS_PUBLIC_KEY' ) || define( 'JETPACK__ERRORS_PUBLIC_KEY', 'KdZY80axKX+nWzfrOcizf0jqiFHnrWCl9X8yuaClKgM=' );
135
136
		add_action( 'rest_api_init', array( $this, 'register_verify_error_endpoint' ) );
137
138
		$this->handle_verified_errors();
139
140
		// If the site gets reconnected, clear errors.
141
		add_action( 'jetpack_site_registered', array( $this, 'delete_all_errors' ) );
142
		add_action( 'jetpack_get_site_data_success', array( $this, 'delete_all_errors' ) );
143
		add_filter( 'jetpack_connection_disconnect_site_wpcom', array( $this, 'delete_all_errors_and_return_unfiltered_value' ) );
144
		add_filter( 'jetpack_connection_delete_all_tokens', array( $this, 'delete_all_errors_and_return_unfiltered_value' ) );
145
		add_action( 'jetpack_unlinked_user', array( $this, 'delete_all_errors' ) );
146
	}
147
148
	/**
149
	 * Gets the list of verified errors and act upon them
150
	 *
151
	 * @since 8.7.0
152
	 *
153
	 * @return void
154
	 */
155
	public function handle_verified_errors() {
156
		$verified_errors = $this->get_verified_errors();
157
		foreach ( array_keys( $verified_errors ) as $error_code ) {
158
			switch ( $error_code ) {
159
				case 'malformed_token':
160
				case 'token_malformed':
161
				case 'no_possible_tokens':
162
				case 'no_valid_user_token':
163
				case 'no_valid_blog_token':
164
				case 'unknown_token':
165
				case 'could_not_sign':
166
				case 'invalid_token':
167
				case 'token_mismatch':
168
				case 'invalid_signature':
169
				case 'signature_mismatch':
170
				case 'no_user_tokens':
171
				case 'no_token_for_user':
172
					add_action( 'admin_notices', array( $this, 'generic_admin_notice_error' ) );
173
					add_action( 'react_connection_errors_initial_state', array( $this, 'jetpack_react_dashboard_error' ) );
174
					$this->error_code = $error_code;
0 ignored issues
show
Documentation Bug introduced by
It seems like $error_code can also be of type integer. However, the property $error_code is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
175
176
					// Since we are only generically handling errors, we don't need to trigger error messages for each one of them.
177
					break 2;
178
			}
179
		}
180
	}
181
182
	/**
183
	 * Gets the instance of this singleton class
184
	 *
185
	 * @since 8.7.0
186
	 *
187
	 * @return Error_Handler $instance
188
	 */
189
	public static function get_instance() {
190
		if ( is_null( self::$instance ) ) {
191
			self::$instance = new self();
192
		}
193
		return self::$instance;
194
	}
195
196
	/**
197
	 * Keep track of a connection error that was encountered
198
	 *
199
	 * @since 8.7.0
200
	 *
201
	 * @param \WP_Error $error the error object.
202
	 * @param boolean   $force Force the report, even if should_report_error is false.
203
	 * @return void
204
	 */
205
	public function report_error( \WP_Error $error, $force = false ) {
206
		if ( in_array( $error->get_error_code(), $this->known_errors, true ) && $this->should_report_error( $error ) || $force ) {
207
			$stored_error = $this->store_error( $error );
208
			if ( $stored_error ) {
209
				$this->send_error_to_wpcom( $stored_error );
210
			}
211
		}
212
	}
213
214
	/**
215
	 * Checks the status of the gate
216
	 *
217
	 * This protects the site (and WPCOM) against over loads.
218
	 *
219
	 * @since 8.7.0
220
	 *
221
	 * @param \WP_Error $error the error object.
222
	 * @return boolean $should_report True if gate is open and the error should be reported.
223
	 */
224
	public function should_report_error( \WP_Error $error ) {
225
226
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
227
			return true;
228
		}
229
230
		/**
231
		 * Whether to bypass the gate for XML-RPC error handling
232
		 *
233
		 * By default, we only process XML-RPC errors once an hour for each error code.
234
		 * This is done to avoid overflows. If you need to disable this gate, you can set this variable to true.
235
		 *
236
		 * This filter is useful for unit testing
237
		 *
238
		 * @since 8.7.0
239
		 *
240
		 * @param boolean $bypass_gate whether to bypass the gate. Default is false, do not bypass.
241
		 */
242
		$bypass_gate = apply_filters( 'jetpack_connection_bypass_error_reporting_gate', false );
243
		if ( true === $bypass_gate ) {
244
			return true;
245
		}
246
247
		$transient = self::ERROR_REPORTING_GATE . $error->get_error_code();
248
249
		if ( get_transient( $transient ) ) {
250
			return false;
251
		}
252
253
		set_transient( $transient, true, HOUR_IN_SECONDS );
254
		return true;
255
	}
256
257
	/**
258
	 * Stores the error in the database so we know there is an issue and can inform the user
259
	 *
260
	 * @since 8.7.0
261
	 *
262
	 * @param \WP_Error $error the error object.
263
	 * @return boolean|array False if stored errors were not updated and the error array if it was successfully stored.
264
	 */
265
	public function store_error( \WP_Error $error ) {
266
267
		$stored_errors = $this->get_stored_errors();
268
		$error_array   = $this->wp_error_to_array( $error );
269
		$error_code    = $error->get_error_code();
270
		$user_id       = $error_array['user_id'];
271
272
		if ( ! isset( $stored_errors[ $error_code ] ) || ! is_array( $stored_errors[ $error_code ] ) ) {
273
			$stored_errors[ $error_code ] = array();
274
		}
275
276
		$stored_errors[ $error_code ][ $user_id ] = $error_array;
277
278
		// Let's store a maximum of 5 different user ids for each error code.
279
		if ( count( $stored_errors[ $error_code ] ) > 5 ) {
280
			// array_shift will destroy keys here because they are numeric, so manually remove first item.
281
			$keys = array_keys( $stored_errors[ $error_code ] );
282
			unset( $stored_errors[ $error_code ][ $keys[0] ] );
283
		}
284
285
		if ( update_option( self::STORED_ERRORS_OPTION, $stored_errors ) ) {
286
			return $error_array;
287
		}
288
289
		return false;
290
291
	}
292
293
	/**
294
	 * Converts a WP_Error object in the array representation we store in the database
295
	 *
296
	 * @since 8.7.0
297
	 *
298
	 * @param \WP_Error $error the error object.
299
	 * @return boolean|array False if error is invalid or the error array
300
	 */
301
	public function wp_error_to_array( \WP_Error $error ) {
302
303
		$data = $error->get_error_data();
304
305
		if ( ! isset( $data['signature_details'] ) || ! is_array( $data['signature_details'] ) ) {
306
			return false;
307
		}
308
309
		$data = $data['signature_details'];
310
311
		if ( ! isset( $data['token'] ) || empty( $data['token'] ) ) {
312
			return false;
313
		}
314
315
		$user_id = $this->get_user_id_from_token( $data['token'] );
316
317
		$error_array = array(
318
			'error_code'    => $error->get_error_code(),
319
			'user_id'       => $user_id,
320
			'error_message' => $error->get_error_message(),
321
			'error_data'    => $data,
322
			'timestamp'     => time(),
323
			'nonce'         => wp_generate_password( 10, false ),
324
		);
325
326
		return $error_array;
327
328
	}
329
330
	/**
331
	 * Sends the error to WP.com to be verified
332
	 *
333
	 * @since 8.7.0
334
	 *
335
	 * @param array $error_array The array representation of the error as it is stored in the database.
336
	 * @return bool
337
	 */
338
	public function send_error_to_wpcom( $error_array ) {
339
340
		$blog_id = \Jetpack_Options::get_option( 'id' );
341
342
		$encrypted_data = $this->encrypt_data_to_wpcom( $error_array );
343
344
		if ( false === $encrypted_data ) {
345
			return false;
346
		}
347
348
		$args = array(
349
			'body' => array(
350
				'error_data' => $encrypted_data,
351
			),
352
		);
353
354
		// send encrypted data to WP.com Public-API v2.
355
		wp_remote_post( "https://public-api.wordpress.com/wpcom/v2/sites/{$blog_id}/jetpack-report-error/", $args );
356
		return true;
357
	}
358
359
	/**
360
	 * Encrypt data to be sent over to WP.com
361
	 *
362
	 * @since 8.7.0
363
	 *
364
	 * @param array|string $data the data to be encoded.
365
	 * @return boolean|string The encoded string on success, false on failure
366
	 */
367
	public function encrypt_data_to_wpcom( $data ) {
368
369
		try {
370
			// phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
371
			// phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
372
			$encrypted_data = base64_encode( sodium_crypto_box_seal( wp_json_encode( $data ), base64_decode( JETPACK__ERRORS_PUBLIC_KEY ) ) );
373
			// phpcs:enable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
374
			// phpcs:enable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
375
		} catch ( \SodiumException $e ) {
376
			// error encrypting data.
377
			return false;
378
		}
379
380
		return $encrypted_data;
381
382
	}
383
384
	/**
385
	 * Extracts the user ID from a token
386
	 *
387
	 * @since 8.7.0
388
	 *
389
	 * @param string $token the token used to make the xml-rpc request.
390
	 * @return string $the user id or `invalid` if user id not present.
391
	 */
392
	public function get_user_id_from_token( $token ) {
393
		$parsed_token = explode( ':', wp_unslash( $token ) );
394
395
		if ( isset( $parsed_token[2] ) && ctype_digit( $parsed_token[2] ) ) {
396
			$user_id = $parsed_token[2];
397
		} else {
398
			$user_id = 'invalid';
399
		}
400
401
		return $user_id;
402
403
	}
404
405
	/**
406
	 * Gets the reported errors stored in the database
407
	 *
408
	 * @since 8.7.0
409
	 *
410
	 * @return array $errors
411
	 */
412 View Code Duplication
	public function get_stored_errors() {
413
414
		$stored_errors = get_option( self::STORED_ERRORS_OPTION );
415
416
		if ( ! is_array( $stored_errors ) ) {
417
			$stored_errors = array();
418
		}
419
420
		$stored_errors = $this->garbage_collector( $stored_errors );
421
422
		return $stored_errors;
423
	}
424
425
	/**
426
	 * Gets the verified errors stored in the database
427
	 *
428
	 * @since 8.7.0
429
	 *
430
	 * @return array $errors
431
	 */
432 View Code Duplication
	public function get_verified_errors() {
433
434
		$verified_errors = get_option( self::STORED_VERIFIED_ERRORS_OPTION );
435
436
		if ( ! is_array( $verified_errors ) ) {
437
			$verified_errors = array();
438
		}
439
440
		$verified_errors = $this->garbage_collector( $verified_errors );
441
442
		return $verified_errors;
443
	}
444
445
	/**
446
	 * Removes expired errors from the array
447
	 *
448
	 * This method is called by get_stored_errors and get_verified errors and filters their result
449
	 * Whenever a new error is stored to the database or verified, this will be triggered and the
450
	 * expired error will be permantently removed from the database
451
	 *
452
	 * @since 8.7.0
453
	 *
454
	 * @param array $errors array of errors as stored in the database.
455
	 * @return array
456
	 */
457
	private function garbage_collector( $errors ) {
458
		foreach ( $errors as $error_code => $users ) {
459
			foreach ( $users as $user_id => $error ) {
460
				if ( self::ERROR_LIFE_TIME < time() - (int) $error['timestamp'] ) {
461
					unset( $errors[ $error_code ][ $user_id ] );
462
				}
463
			}
464
		}
465
		// Clear empty error codes.
466
		$errors = array_filter(
467
			$errors,
468
			function ( $user_errors ) {
469
				return ! empty( $user_errors );
470
			}
471
		);
472
		return $errors;
473
	}
474
475
	/**
476
	 * Delete all stored and verified errors from the database
477
	 *
478
	 * @since 8.7.0
479
	 *
480
	 * @return void
481
	 */
482
	public function delete_all_errors() {
483
		$this->delete_stored_errors();
484
		$this->delete_verified_errors();
485
	}
486
487
	/**
488
	 * Delete all stored and verified errors from the database and returns unfiltered value
489
	 *
490
	 * This is used to hook into a couple of filters that expect true to not short circuit the disconnection flow
491
	 *
492
	 * @since 8.9.0
493
	 *
494
	 * @param mixed $check The input sent by the filter.
495
	 * @return boolean
496
	 */
497
	public function delete_all_errors_and_return_unfiltered_value( $check ) {
498
		$this->delete_all_errors();
499
		return $check;
500
	}
501
502
	/**
503
	 * Delete the reported errors stored in the database
504
	 *
505
	 * @since 8.7.0
506
	 *
507
	 * @return boolean True, if option is successfully deleted. False on failure.
508
	 */
509
	public function delete_stored_errors() {
510
		return delete_option( self::STORED_ERRORS_OPTION );
511
	}
512
513
	/**
514
	 * Delete the verified errors stored in the database
515
	 *
516
	 * @since 8.7.0
517
	 *
518
	 * @return boolean True, if option is successfully deleted. False on failure.
519
	 */
520
	public function delete_verified_errors() {
521
		return delete_option( self::STORED_VERIFIED_ERRORS_OPTION );
522
	}
523
524
	/**
525
	 * Gets an error based on the nonce
526
	 *
527
	 * Receives a nonce and finds the related error.
528
	 *
529
	 * @since 8.7.0
530
	 *
531
	 * @param string $nonce The nonce created for the error we want to get.
532
	 * @return null|array Returns the error array representation or null if error not found.
533
	 */
534
	public function get_error_by_nonce( $nonce ) {
535
		$errors = $this->get_stored_errors();
536
		foreach ( $errors as $user_group ) {
537
			foreach ( $user_group as $error ) {
538
				if ( $error['nonce'] === $nonce ) {
539
					return $error;
540
				}
541
			}
542
		}
543
		return null;
544
	}
545
546
	/**
547
	 * Adds an error to the verified error list
548
	 *
549
	 * @since 8.7.0
550
	 *
551
	 * @param array $error The error array, as it was saved in the unverified errors list.
552
	 * @return void
553
	 */
554
	public function verify_error( $error ) {
555
556
		$verified_errors = $this->get_verified_errors();
557
		$error_code      = $error['error_code'];
558
		$user_id         = $error['user_id'];
559
560
		if ( ! isset( $verified_errors[ $error_code ] ) ) {
561
			$verified_errors[ $error_code ] = array();
562
		}
563
564
		$verified_errors[ $error_code ][ $user_id ] = $error;
565
566
		update_option( self::STORED_VERIFIED_ERRORS_OPTION, $verified_errors );
567
568
	}
569
570
	/**
571
	 * Register REST API end point for error hanlding.
572
	 *
573
	 * @since 8.7.0
574
	 *
575
	 * @return void
576
	 */
577
	public function register_verify_error_endpoint() {
578
		register_rest_route(
579
			'jetpack/v4',
580
			'/verify_xmlrpc_error',
581
			array(
582
				'methods'             => \WP_REST_Server::CREATABLE,
583
				'callback'            => array( $this, 'verify_xml_rpc_error' ),
584
				'permission_callback' => '__return_true',
585
				'args'                => array(
586
					'nonce' => array(
587
						'required' => true,
588
						'type'     => 'string',
589
					),
590
				),
591
			)
592
		);
593
	}
594
595
	/**
596
	 * Handles verification that a xml rpc error is legit and came from WordPres.com
597
	 *
598
	 * @since 8.7.0
599
	 *
600
	 * @param \WP_REST_Request $request The request sent to the WP REST API.
601
	 *
602
	 * @return boolean
603
	 */
604
	public function verify_xml_rpc_error( \WP_REST_Request $request ) {
605
606
		$error = $this->get_error_by_nonce( $request['nonce'] );
607
608
		if ( $error ) {
609
			$this->verify_error( $error );
610
			return new \WP_REST_Response( true, 200 );
611
		}
612
613
		return new \WP_REST_Response( false, 200 );
614
615
	}
616
617
	/**
618
	 * Prints a generic error notice for all connection errors
619
	 *
620
	 * @since 8.9.0
621
	 *
622
	 * @return void
623
	 */
624
	public function generic_admin_notice_error() {
625
		// do not add admin notice to the jetpack dashboard.
626
		global $pagenow;
627
		if ( 'admin.php' === $pagenow || isset( $_GET['page'] ) && 'jetpack' === $_GET['page'] ) { // phpcs:ignore
628
			return;
629
		}
630
631
		if ( ! current_user_can( 'jetpack_connect' ) ) {
632
			return;
633
		}
634
635
		/**
636
		 * Filters the message to be displayed in the admin notices area when there's a xmlrpc error.
637
		 *
638
		 * By default  we don't display any errors.
639
		 *
640
		 * Return an empty value to disable the message.
641
		 *
642
		 * @since 8.9.0
643
		 *
644
		 * @param string $message The error message.
645
		 * @param array  $errors The array of errors. See Automattic\Jetpack\Connection\Error_Handler for details on the array structure.
646
		 */
647
		$message = apply_filters( 'jetpack_connection_error_notice_message', '', $this->get_verified_errors() );
648
649
		/**
650
		 * Fires inside the admin_notices hook just before displaying the error message for a broken connection.
651
		 *
652
		 * If you want to disable the default message from being displayed, return an emtpy value in the jetpack_connection_error_notice_message filter.
653
		 *
654
		 * @since 8.9.0
655
		 *
656
		 * @param array $errors The array of errors. See Automattic\Jetpack\Connection\Error_Handler for details on the array structure.
657
		 */
658
		do_action( 'jetpack_connection_error_notice', $this->get_verified_errors() );
659
660
		if ( empty( $message ) ) {
661
			return;
662
		}
663
664
		?>
665
		<div class="notice notice-error is-dismissible jetpack-message jp-connect" style="display:block !important;">
666
			<p><?php echo esc_html( $message ); ?></p>
667
		</div>
668
		<?php
669
	}
670
671
	/**
672
	 * Adds the error message to the Jetpack React Dashboard
673
	 *
674
	 * @since 8.9.0
675
	 *
676
	 * @param array $errors The array of errors. See Automattic\Jetpack\Connection\Error_Handler for details on the array structure.
677
	 * @return array
678
	 */
679
	public function jetpack_react_dashboard_error( $errors ) {
680
		$errors[] = array(
681
			'code'    => 'xmlrpc_error',
682
			'message' => __( 'Your connection with WordPress.com seems to be broken. If you\'re experiencing issues, please try reconnecting.', 'jetpack' ),
683
			'action'  => 'reconnect',
684
			'data'    => array( 'api_error_code' => $this->error_code ),
685
		);
686
		return $errors;
687
	}
688
689
}
690