Completed
Push — renovate/url-polyfill-1.x ( 01368d...f2aaf6 )
by
unknown
114:05 queued 106:27
created

Error_Handler::delete_stored_errors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
rs 10
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
	}
133
134
	/**
135
	 * Gets the list of verified errors and act upon them
136
	 *
137
	 * @since 8.7.0
138
	 *
139
	 * @return void
140
	 */
141
	public function handle_verified_errors() {
142
		$verified_errors = $this->get_verified_errors();
143
		foreach ( $verified_errors as $error_code => $user_errors ) {
144
145
			switch ( $error_code ) {
146
				case 'malformed_token':
147
				case 'token_malformed':
148
				case 'no_possible_tokens':
149
				case 'no_valid_token':
150
				case 'unknown_token':
151
				case 'could_not_sign':
152
				case 'invalid_token':
153
				case 'token_mismatch':
154
				case 'invalid_signature':
155
				case 'signature_mismatch':
156
					new Error_Handlers\Invalid_Blog_Token( $user_errors );
157
					break;
158
			}
159
		}
160
	}
161
162
	/**
163
	 * Gets the instance of this singleton class
164
	 *
165
	 * @since 8.7.0
166
	 *
167
	 * @return Error_Handler $instance
168
	 */
169
	public static function get_instance() {
170
		if ( is_null( self::$instance ) ) {
171
			self::$instance = new self();
172
		}
173
		return self::$instance;
174
	}
175
176
	/**
177
	 * Keep track of a connection error that was encountered
178
	 *
179
	 * @since 8.7.0
180
	 *
181
	 * @param \WP_Error $error the error object.
182
	 * @param boolean   $force Force the report, even if should_report_error is false.
183
	 * @return void
184
	 */
185
	public function report_error( \WP_Error $error, $force = false ) {
186
		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...
187
			$stored_error = $this->store_error( $error );
188
			if ( $stored_error ) {
189
				$this->send_error_to_wpcom( $stored_error );
190
			}
191
		}
192
	}
193
194
	/**
195
	 * Checks the status of the gate
196
	 *
197
	 * This protects the site (and WPCOM) against over loads.
198
	 *
199
	 * @since 8.7.0
200
	 *
201
	 * @param \WP_Error $error the error object.
202
	 * @return boolean $should_report True if gate is open and the error should be reported.
203
	 */
204
	public function should_report_error( \WP_Error $error ) {
205
206
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
207
			return true;
208
		}
209
210
		/**
211
		 * Whether to bypass the gate for XML-RPC error handling
212
		 *
213
		 * By default, we only process XML-RPC errors once an hour for each error code.
214
		 * This is done to avoid overflows. If you need to disable this gate, you can set this variable to true.
215
		 *
216
		 * This filter is useful for unit testing
217
		 *
218
		 * @since 8.7.0
219
		 *
220
		 * @param boolean $bypass_gate whether to bypass the gate. Default is false, do not bypass.
221
		 */
222
		$bypass_gate = apply_filters( 'jetpack_connection_bypass_error_reporting_gate', false );
223
		if ( true === $bypass_gate ) {
224
			return true;
225
		}
226
227
		$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...
228
229
		if ( get_transient( $transient ) ) {
230
			return false;
231
		}
232
233
		set_transient( $transient, true, HOUR_IN_SECONDS );
234
		return true;
235
	}
236
237
	/**
238
	 * Stores the error in the database so we know there is an issue and can inform the user
239
	 *
240
	 * @since 8.7.0
241
	 *
242
	 * @param \WP_Error $error the error object.
243
	 * @return boolean|array False if stored errors were not updated and the error array if it was successfully stored.
244
	 */
245
	public function store_error( \WP_Error $error ) {
246
247
		$stored_errors = $this->get_stored_errors();
248
		$error_array   = $this->wp_error_to_array( $error );
249
		$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...
250
		$user_id       = $error_array['user_id'];
251
252
		if ( ! isset( $stored_errors[ $error_code ] ) || ! is_array( $stored_errors[ $error_code ] ) ) {
253
			$stored_errors[ $error_code ] = array();
254
		}
255
256
		$stored_errors[ $error_code ][ $user_id ] = $error_array;
257
258
		// Let's store a maximum of 5 different user ids for each error code.
259
		if ( count( $stored_errors[ $error_code ] ) > 5 ) {
260
			// array_shift will destroy keys here because they are numeric, so manually remove first item.
261
			$keys = array_keys( $stored_errors[ $error_code ] );
262
			unset( $stored_errors[ $error_code ][ $keys[0] ] );
263
		}
264
265
		if ( update_option( self::STORED_ERRORS_OPTION, $stored_errors ) ) {
266
			return $error_array;
267
		}
268
269
		return false;
270
271
	}
272
273
	/**
274
	 * Converts a WP_Error object in the array representation we store in the database
275
	 *
276
	 * @since 8.7.0
277
	 *
278
	 * @param \WP_Error $error the error object.
279
	 * @return boolean|array False if error is invalid or the error array
280
	 */
281
	public function wp_error_to_array( \WP_Error $error ) {
282
283
		$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...
284
285
		if ( ! isset( $data['signature_details'] ) || ! is_array( $data['signature_details'] ) ) {
286
			return false;
287
		}
288
289
		$data = $data['signature_details'];
290
291
		if ( ! isset( $data['token'] ) || empty( $data['token'] ) ) {
292
			return false;
293
		}
294
295
		$user_id = $this->get_user_id_from_token( $data['token'] );
296
297
		$error_array = array(
298
			'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...
299
			'user_id'       => $user_id,
300
			'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...
301
			'error_data'    => $data,
302
			'timestamp'     => time(),
303
			'nonce'         => wp_generate_password( 10, false ),
304
		);
305
306
		return $error_array;
307
308
	}
309
310
	/**
311
	 * Sends the error to WP.com to be verified
312
	 *
313
	 * @since 8.7.0
314
	 *
315
	 * @param array $error_array The array representation of the error as it is stored in the database.
316
	 * @return bool
317
	 */
318
	public function send_error_to_wpcom( $error_array ) {
319
320
		$blog_id = \Jetpack_Options::get_option( 'id' );
321
322
		$encrypted_data = $this->encrypt_data_to_wpcom( $error_array );
323
324
		if ( false === $encrypted_data ) {
325
			return false;
326
		}
327
328
		$args = array(
329
			'body' => array(
330
				'error_data' => $encrypted_data,
331
			),
332
		);
333
334
		// send encrypted data to WP.com Public-API v2.
335
		wp_remote_post( "https://public-api.wordpress.com/wpcom/v2/sites/{$blog_id}/jetpack-report-error/", $args );
336
		return true;
337
	}
338
339
	/**
340
	 * Encrypt data to be sent over to WP.com
341
	 *
342
	 * @since 8.7.0
343
	 *
344
	 * @param array|string $data the data to be encoded.
345
	 * @return boolean|string The encoded string on success, false on failure
346
	 */
347
	public function encrypt_data_to_wpcom( $data ) {
348
349
		try {
350
			// phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
351
			// phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
352
			$encrypted_data = base64_encode( sodium_crypto_box_seal( wp_json_encode( $data ), base64_decode( JETPACK__ERRORS_PUBLIC_KEY ) ) );
353
			// phpcs:enable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
354
			// phpcs:enable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
355
		} 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...
356
			// error encrypting data.
357
			return false;
358
		}
359
360
		return $encrypted_data;
361
362
	}
363
364
	/**
365
	 * Extracts the user ID from a token
366
	 *
367
	 * @since 8.7.0
368
	 *
369
	 * @param string $token the token used to make the xml-rpc request.
370
	 * @return string $the user id or `invalid` if user id not present.
371
	 */
372
	public function get_user_id_from_token( $token ) {
373
		$parsed_token = explode( ':', wp_unslash( $token ) );
374
375
		if ( isset( $parsed_token[2] ) && ! empty( $parsed_token[2] ) && ctype_digit( $parsed_token[2] ) ) {
376
			$user_id = $parsed_token[2];
377
		} else {
378
			$user_id = 'invalid';
379
		}
380
381
		return $user_id;
382
383
	}
384
385
	/**
386
	 * Gets the reported errors stored in the database
387
	 *
388
	 * @since 8.7.0
389
	 *
390
	 * @return array $errors
391
	 */
392 View Code Duplication
	public function get_stored_errors() {
393
394
		$stored_errors = get_option( self::STORED_ERRORS_OPTION );
395
396
		if ( ! is_array( $stored_errors ) ) {
397
			$stored_errors = array();
398
		}
399
400
		$stored_errors = $this->garbage_collector( $stored_errors );
401
402
		return $stored_errors;
403
	}
404
405
	/**
406
	 * Gets the verified errors stored in the database
407
	 *
408
	 * @since 8.7.0
409
	 *
410
	 * @return array $errors
411
	 */
412 View Code Duplication
	public function get_verified_errors() {
413
414
		$verified_errors = get_option( self::STORED_VERIFIED_ERRORS_OPTION );
415
416
		if ( ! is_array( $verified_errors ) ) {
417
			$verified_errors = array();
418
		}
419
420
		$verified_errors = $this->garbage_collector( $verified_errors );
421
422
		return $verified_errors;
423
	}
424
425
	/**
426
	 * Removes expired errors from the array
427
	 *
428
	 * This method is called by get_stored_errors and get_verified errors and filters their result
429
	 * Whenever a new error is stored to the database or verified, this will be triggered and the
430
	 * expired error will be permantently removed from the database
431
	 *
432
	 * @since 8.7.0
433
	 *
434
	 * @param array $errors array of errors as stored in the database.
435
	 * @return array
436
	 */
437
	private function garbage_collector( $errors ) {
438
		foreach ( $errors as $error_code => $users ) {
439
			foreach ( $users as $user_id => $error ) {
440
				if ( self::ERROR_LIFE_TIME < time() - (int) $error['timestamp'] ) {
441
					unset( $errors[ $error_code ][ $user_id ] );
442
				}
443
			}
444
		}
445
		// Clear empty error codes.
446
		$errors = array_filter(
447
			$errors,
448
			function( $user_errors ) {
449
				return ! empty( $user_errors );
450
			}
451
		);
452
		return $errors;
453
	}
454
455
	/**
456
	 * Delete all stored and verified errors from the database
457
	 *
458
	 * @since 8.7.0
459
	 *
460
	 * @return void
461
	 */
462
	public function delete_all_errors() {
463
		$this->delete_stored_errors();
464
		$this->delete_verified_errors();
465
	}
466
467
	/**
468
	 * Delete the reported errors stored in the database
469
	 *
470
	 * @since 8.7.0
471
	 *
472
	 * @return boolean True, if option is successfully deleted. False on failure.
473
	 */
474
	public function delete_stored_errors() {
475
		return delete_option( self::STORED_ERRORS_OPTION );
476
	}
477
478
	/**
479
	 * Delete the verified errors stored in the database
480
	 *
481
	 * @since 8.7.0
482
	 *
483
	 * @return boolean True, if option is successfully deleted. False on failure.
484
	 */
485
	public function delete_verified_errors() {
486
		return delete_option( self::STORED_VERIFIED_ERRORS_OPTION );
487
	}
488
489
	/**
490
	 * Gets an error based on the nonce
491
	 *
492
	 * Receives a nonce and finds the related error.
493
	 *
494
	 * @since 8.7.0
495
	 *
496
	 * @param string $nonce The nonce created for the error we want to get.
497
	 * @return null|array Returns the error array representation or null if error not found.
498
	 */
499
	public function get_error_by_nonce( $nonce ) {
500
		$errors = $this->get_stored_errors();
501
		foreach ( $errors as $user_group ) {
502
			foreach ( $user_group as $error ) {
503
				if ( $error['nonce'] === $nonce ) {
504
					return $error;
505
				}
506
			}
507
		}
508
		return null;
509
	}
510
511
	/**
512
	 * Adds an error to the verified error list
513
	 *
514
	 * @since 8.7.0
515
	 *
516
	 * @param array $error The error array, as it was saved in the unverified errors list.
517
	 * @return void
518
	 */
519
	public function verify_error( $error ) {
520
521
		$verified_errors = $this->get_verified_errors();
522
		$error_code      = $error['error_code'];
523
		$user_id         = $error['user_id'];
524
525
		if ( ! isset( $verified_errors[ $error_code ] ) ) {
526
			$verified_errors[ $error_code ] = array();
527
		}
528
529
		$verified_errors[ $error_code ][ $user_id ] = $error;
530
531
		update_option( self::STORED_VERIFIED_ERRORS_OPTION, $verified_errors );
532
533
	}
534
535
	/**
536
	 * Register REST API end point for error hanlding.
537
	 *
538
	 * @since 8.7.0
539
	 *
540
	 * @return void
541
	 */
542
	public function register_verify_error_endpoint() {
543
		register_rest_route(
544
			'jetpack/v4',
545
			'/verify_xmlrpc_error',
546
			array(
547
				'methods'  => \WP_REST_Server::CREATABLE,
548
				'callback' => array( $this, 'verify_xml_rpc_error' ),
549
				'args'     => array(
550
					'nonce' => array(
551
						'required' => true,
552
						'type'     => 'string',
553
					),
554
				),
555
			)
556
		);
557
	}
558
559
	/**
560
	 * Handles verification that a xml rpc error is legit and came from WordPres.com
561
	 *
562
	 * @since 8.7.0
563
	 *
564
	 * @param \WP_REST_Request $request The request sent to the WP REST API.
565
	 *
566
	 * @return boolean
567
	 */
568
	public function verify_xml_rpc_error( \WP_REST_Request $request ) {
569
570
		$error = $this->get_error_by_nonce( $request['nonce'] );
571
572
		if ( $error ) {
573
			$this->verify_error( $error );
574
			return new \WP_REST_Response( true, 200 );
575
		}
576
577
		return new \WP_REST_Response( false, 200 );
578
579
	}
580
581
}
582