Completed
Push — update/story-block-loading-med... ( e6e62b...d81748 )
by
unknown
28:46 queued 18:45
created

Error_Handler   F

Complexity

Total Complexity 64

Size/Duplication

Total Lines 541
Duplicated Lines 4.44 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 0
Metric Value
dl 24
loc 541
rs 3.28
c 0
b 0
f 0
wmc 64
lcom 2
cbo 2

20 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 2
C handle_verified_errors() 0 20 12
A get_instance() 0 6 2
A report_error() 0 8 5
A should_report_error() 0 32 5
A store_error() 0 27 5
A wp_error_to_array() 0 28 5
A send_error_to_wpcom() 0 20 2
A encrypt_data_to_wpcom() 0 16 2
A get_user_id_from_token() 0 12 4
A get_stored_errors() 12 12 2
A get_verified_errors() 12 12 2
A garbage_collector() 0 17 4
A delete_all_errors() 0 4 1
A delete_stored_errors() 0 3 1
A delete_verified_errors() 0 3 1
A get_error_by_nonce() 0 11 4
A verify_error() 0 15 2
A register_verify_error_endpoint() 0 17 1
A verify_xml_rpc_error() 0 12 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Error_Handler often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Error_Handler, and based on these observations, apply Extract Interface, too.

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