WC_REST_Authentication   C
last analyzed

Complexity

Total Complexity 62

Size/Duplication

Total Lines 414
Duplicated Lines 4.83 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 20
loc 414
rs 5.9493
c 0
b 0
f 0
wmc 62
lcom 1
cbo 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A check_authentication_error() 0 10 2
A is_request_to_rest_api() 0 13 3
A authenticate() 0 12 4
C perform_oauth_authentication() 0 42 7
C check_oauth_signature() 0 47 9
A normalize_parameters() 0 7 1
A get_user_data_by_consumer_key() 0 12 1
C check_permissions() 12 32 12
A update_last_access() 0 11 1
A send_unauthorized_headers() 0 10 3
C perform_basic_authentication() 8 48 11
C check_oauth_timestamp_and_nonce() 0 40 7

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 WC_REST_Authentication 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 WC_REST_Authentication, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * REST API Authentication
4
 *
5
 * @author   WooThemes
6
 * @category API
7
 * @package  WooCommerce/API
8
 * @since    2.6.0
9
 */
10
11
if ( ! defined( 'ABSPATH' ) ) {
12
	exit;
13
}
14
15
class WC_REST_Authentication {
16
17
	/**
18
	 * Initialize authentication actions.
19
	 */
20
	public function __construct() {
21
		add_filter( 'determine_current_user', array( $this, 'authenticate' ), 100 );
22
		add_filter( 'rest_authentication_errors', array( $this, 'check_authentication_error' ) );
23
		add_filter( 'rest_post_dispatch', array( $this, 'send_unauthorized_headers' ), 50 );
24
	}
25
26
	/**
27
	 * Check if is request to our REST API.
28
	 *
29
	 * @return bool
30
	 */
31
	protected function is_request_to_rest_api() {
32
		if ( empty( $_SERVER['REQUEST_URI'] ) ) {
33
			return false;
34
		}
35
36
		// Check if our endpoint.
37
		$woocommerce = false !== strpos( $_SERVER['REQUEST_URI'], 'wp-json/wc/' );
38
39
		// Allow third party plugins use our authentication methods.
40
		$third_party = false !== strpos( $_SERVER['REQUEST_URI'], 'wp-json/wc-' );
41
42
		return apply_filters( 'woocommerce_rest_is_request_to_rest_api', $woocommerce || $third_party );
43
	}
44
45
	/**
46
	 * Authenticate user.
47
	 *
48
	 * @param int|false $user_id User ID if one has been determined, false otherwise.
49
	 * @return int|false
50
	 */
51
	public function authenticate( $user_id ) {
52
		// Do not authenticate twice and check if is a request to our endpoint in the WP REST API.
53
		if ( ! empty( $user_id ) || ! $this->is_request_to_rest_api() ) {
54
			return $user_id;
55
		}
56
57
		if ( is_ssl() ) {
58
			return $this->perform_basic_authentication();
59
		} else {
60
			return $this->perform_oauth_authentication();
61
		}
62
	}
63
64
	/**
65
	 * Check for authentication error.
66
	 *
67
	 * @param WP_Error|null|bool $error
68
	 * @return WP_Error|null|bool
69
	 */
70
	public function check_authentication_error( $error ) {
71
		global $wc_rest_authentication_error;
72
73
		// Passthrough other errors.
74
		if ( ! empty( $error ) ) {
75
			return $error;
76
		}
77
78
		return $wc_rest_authentication_error;
79
	}
80
81
	/**
82
	 * Basic Authentication.
83
	 *
84
	 * SSL-encrypted requests are not subject to sniffing or man-in-the-middle
85
	 * attacks, so the request can be authenticated by simply looking up the user
86
	 * associated with the given consumer key and confirming the consumer secret
87
	 * provided is valid.
88
	 *
89
	 * @return int|bool
90
	 */
91
	private function perform_basic_authentication() {
92
		global $wc_rest_authentication_error;
93
94
		$consumer_key    = '';
95
		$consumer_secret = '';
96
97
		// If the $_GET parameters are present, use those first.
98 View Code Duplication
		if ( ! empty( $_GET['consumer_key'] ) && ! empty( $_GET['consumer_secret'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
99
			$consumer_key    = $_GET['consumer_key'];
100
			$consumer_secret = $_GET['consumer_secret'];
101
		}
102
103
		// If the above is not present, we will do full basic auth.
104 View Code Duplication
		if ( ! $consumer_key && ! empty( $_SERVER['PHP_AUTH_USER'] ) && ! empty( $_SERVER['PHP_AUTH_PW'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
			$consumer_key    = $_SERVER['PHP_AUTH_USER'];
106
			$consumer_secret = $_SERVER['PHP_AUTH_PW'];
107
		}
108
109
		// Stop if don't have any key.
110
		if ( ! $consumer_key || ! $consumer_secret ) {
111
			return false;
112
		}
113
114
		// Get user data.
115
		$user = $this->get_user_data_by_consumer_key( $consumer_key );
116
		if ( empty( $user ) ) {
117
			$wc_rest_authentication_error = new WP_Error( 'woocommerce_rest_authentication_error', __( 'Consumer Key is invalid.', 'woocommerce' ), array( 'status' => 401 ) );
118
119
			return false;
120
		}
121
122
		// Validate user secret.
123
		if ( ! hash_equals( $user->consumer_secret, $consumer_secret ) ) {
124
			$wc_rest_authentication_error = new WP_Error( 'woocommerce_rest_authentication_error', __( 'Consumer Secret is invalid.', 'woocommerce' ), array( 'status' => 401 ) );
125
126
			return false;
127
		}
128
129
		// Check API Key permissions.
130
		if ( ! $this->check_permissions( $user->permissions ) ) {
131
			return false;
132
		}
133
134
		// Update last access.
135
		$this->update_last_access( $user->key_id );
136
137
		return $user->user_id;
138
	}
139
140
	/**
141
	 * Perform OAuth 1.0a "one-legged" (http://oauthbible.com/#oauth-10a-one-legged) authentication for non-SSL requests.
142
	 *
143
	 * This is required so API credentials cannot be sniffed or intercepted when making API requests over plain HTTP.
144
	 *
145
	 * This follows the spec for simple OAuth 1.0a authentication (RFC 5849) as closely as possible, with two exceptions:
146
	 *
147
	 * 1) There is no token associated with request/responses, only consumer keys/secrets are used.
148
	 *
149
	 * 2) The OAuth parameters are included as part of the request query string instead of part of the Authorization header,
150
	 *    This is because there is no cross-OS function within PHP to get the raw Authorization header.
151
	 *
152
	 * @link http://tools.ietf.org/html/rfc5849 for the full spec.
153
	 *
154
	 * @return int|bool
155
	 */
156
	private function perform_oauth_authentication() {
157
		global $wc_rest_authentication_error;
158
159
		$params = array( 'oauth_consumer_key', 'oauth_timestamp', 'oauth_nonce', 'oauth_signature', 'oauth_signature_method' );
160
161
		// Check for required OAuth parameters.
162
		foreach ( $params as $param ) {
163
			if ( empty( $_GET[ $param ] ) ) {
164
				return false;
165
			}
166
		}
167
168
		// Fetch WP user by consumer key
169
		$user = $this->get_user_data_by_consumer_key( $_GET['oauth_consumer_key'] );
170
171
		if ( empty( $user ) ) {
172
			$wc_rest_authentication_error = new WP_Error( 'woocommerce_rest_authentication_error', __( 'Consumer Key is invalid.', 'woocommerce' ), array( 'status' => 401 ) );
173
174
			return false;
175
		}
176
177
		// Perform OAuth validation.
178
		$wc_rest_authentication_error = $this->check_oauth_signature( $user, $_GET );
179
		if ( is_wp_error( $wc_rest_authentication_error ) ) {
180
			return false;
181
		}
182
183
		$wc_rest_authentication_error = $this->check_oauth_timestamp_and_nonce( $user, $_GET['oauth_timestamp'], $_GET['oauth_nonce'] );
184
		if ( is_wp_error( $wc_rest_authentication_error ) ) {
185
			return false;
186
		}
187
188
		// Check API Key permissions.
189
		if ( ! $this->check_permissions( $user->permissions ) ) {
190
			return false;
191
		}
192
193
		// Update last access.
194
		$this->update_last_access( $user->key_id );
195
196
		return $user->user_id;
197
	}
198
199
	/**
200
	 * Verify that the consumer-provided request signature matches our generated signature,
201
	 * this ensures the consumer has a valid key/secret.
202
	 *
203
	 * @param stdClass $user
204
	 * @param array $params The request parameters.
205
	 * @return null|WP_Error
206
	 */
207
	private function check_oauth_signature( $user, $params ) {
208
		$http_method  = strtoupper( $_SERVER['REQUEST_METHOD'] );
209
		$request_path = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
210
		$wp_base      = get_home_url( null, '/', 'relative' );
211
		if ( substr( $request_path, 0, strlen( $wp_base ) ) === $wp_base ) {
212
			$request_path = substr( $request_path, strlen( $wp_base ) );
213
		}
214
		$base_request_uri = rawurlencode( get_home_url( null, $request_path ) );
215
216
		// Get the signature provided by the consumer and remove it from the parameters prior to checking the signature.
217
		$consumer_signature = rawurldecode( $params['oauth_signature'] );
218
		unset( $params['oauth_signature'] );
219
220
		// Sort parameters.
221
		if ( ! uksort( $params, 'strcmp' ) ) {
222
			return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid Signature - failed to sort parameters.', 'woocommerce' ), array( 'status' => 401 ) );
223
		}
224
225
		// Normalize parameter key/values.
226
		$params           = $this->normalize_parameters( $params );
227
		$query_parameters = array();
228
		foreach ( $params as $param_key => $param_value ) {
229
			if ( is_array( $param_value ) ) {
230
				foreach ( $param_value as $param_key_inner => $param_value_inner ) {
231
					$query_parameters[] = $param_key . '%255B' . $param_key_inner . '%255D%3D' . $param_value_inner;
232
				}
233
			} else {
234
				$query_parameters[] = $param_key . '%3D' . $param_value; // Join with equals sign.
235
			}
236
		}
237
		$query_string   = implode( '%26', $query_parameters ); // Join with ampersand.
238
		$string_to_sign = $http_method . '&' . $base_request_uri . '&' . $query_string;
239
240
		if ( $params['oauth_signature_method'] !== 'HMAC-SHA1' && $params['oauth_signature_method'] !== 'HMAC-SHA256' ) {
241
			return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid Signature - signature method is invalid.', 'woocommerce' ), array( 'status' => 401 ) );
242
		}
243
244
		$hash_algorithm = strtolower( str_replace( 'HMAC-', '', $params['oauth_signature_method'] ) );
245
		$secret         = $user->consumer_secret . '&';
246
		$signature      = base64_encode( hash_hmac( $hash_algorithm, $string_to_sign, $secret, true ) );
247
248
		if ( ! hash_equals( $signature, $consumer_signature ) ) {
249
			return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid Signature - provided signature does not match.', 'woocommerce' ), array( 'status' => 401 ) );
250
		}
251
252
		return true;
253
	}
254
255
	/**
256
	 * Normalize each parameter by assuming each parameter may have already been
257
	 * encoded, so attempt to decode, and then re-encode according to RFC 3986.
258
	 *
259
	 * Note both the key and value is normalized so a filter param like:
260
	 *
261
	 * 'filter[period]' => 'week'
262
	 *
263
	 * is encoded to:
264
	 *
265
	 * 'filter%5Bperiod%5D' => 'week'
266
	 *
267
	 * This conforms to the OAuth 1.0a spec which indicates the entire query string
268
	 * should be URL encoded.
269
	 *
270
	 * @see rawurlencode()
271
	 * @param array $parameters Un-normalized pararmeters.
272
	 * @return array Normalized parameters.
273
	 */
274
	private function normalize_parameters( $parameters ) {
275
		$keys       = wc_rest_urlencode_rfc3986( array_keys( $parameters ) );
276
		$values     = wc_rest_urlencode_rfc3986( array_values( $parameters ) );
277
		$parameters = array_combine( $keys, $values );
278
279
		return $parameters;
280
	}
281
282
	/**
283
	 * Verify that the timestamp and nonce provided with the request are valid. This prevents replay attacks where
284
	 * an attacker could attempt to re-send an intercepted request at a later time.
285
	 *
286
	 * - A timestamp is valid if it is within 15 minutes of now.
287
	 * - A nonce is valid if it has not been used within the last 15 minutes.
288
	 *
289
	 * @param stdClass $user
290
	 * @param int $timestamp the unix timestamp for when the request was made
291
	 * @param string $nonce a unique (for the given user) 32 alphanumeric string, consumer-generated
292
	 * @return bool|WP_Error
293
	 */
294
	private function check_oauth_timestamp_and_nonce( $user, $timestamp, $nonce ) {
295
		global $wpdb;
296
297
		$valid_window = 15 * 60; // 15 minute window.
298
299
		if ( ( $timestamp < time() - $valid_window ) || ( $timestamp > time() + $valid_window ) ) {
300
			return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid timestamp.', 'woocommerce' ), array( 'status' => 401 ) );
301
		}
302
303
		$used_nonces = maybe_unserialize( $user->nonces );
304
305
		if ( empty( $used_nonces ) ) {
306
			$used_nonces = array();
307
		}
308
309
		if ( in_array( $nonce, $used_nonces ) ) {
310
			return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid nonce - nonce has already been used.', 'woocommerce' ), array( 'status' => 401 ) );
311
		}
312
313
		$used_nonces[ $timestamp ] = $nonce;
314
315
		// Remove expired nonces.
316
		foreach ( $used_nonces as $nonce_timestamp => $nonce ) {
317
			if ( $nonce_timestamp < ( time() - $valid_window ) ) {
318
				unset( $used_nonces[ $nonce_timestamp ] );
319
			}
320
		}
321
322
		$used_nonces = maybe_serialize( $used_nonces );
323
324
		$wpdb->update(
325
			$wpdb->prefix . 'woocommerce_api_keys',
326
			array( 'nonces' => $used_nonces ),
327
			array( 'key_id' => $user->key_id ),
328
			array( '%s' ),
329
			array( '%d' )
330
		);
331
332
		return true;
333
	}
334
335
	/**
336
	 * Return the user data for the given consumer_key.
337
	 *
338
	 * @param string $consumer_key
339
	 * @return array
340
	 */
341
	private function get_user_data_by_consumer_key( $consumer_key ) {
342
		global $wpdb;
343
344
		$consumer_key = wc_api_hash( sanitize_text_field( $consumer_key ) );
345
		$user         = $wpdb->get_row( $wpdb->prepare( "
346
			SELECT key_id, user_id, permissions, consumer_key, consumer_secret, nonces
347
			FROM {$wpdb->prefix}woocommerce_api_keys
348
			WHERE consumer_key = %s
349
		", $consumer_key ) );
350
351
		return $user;
352
	}
353
354
	/**
355
	 * Check that the API keys provided have the proper key-specific permissions to either read or write API resources.
356
	 *
357
	 * @param string $permissions
358
	 * @return bool
359
	 */
360
	private function check_permissions( $permissions ) {
361
		global $wc_rest_authentication_error;
362
363
		$valid = true;
364
365
		if ( ! isset( $_SERVER['REQUEST_METHOD'] ) ) {
366
			return false;
367
		}
368
369
		switch ( $_SERVER['REQUEST_METHOD'] ) {
370
371
			case 'HEAD' :
372 View Code Duplication
			case 'GET' :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
373
				if ( 'read' !== $permissions && 'read_write' !== $permissions ) {
374
					$wc_rest_authentication_error = new WP_Error( 'woocommerce_rest_authentication_error', __( 'The API key provided does not have read permissions.', 'woocommerce' ), array( 'status' => 401 ) );
375
					$valid = false;
376
				}
377
				break;
378
379
			case 'POST' :
380
			case 'PUT' :
381
			case 'PATCH' :
382 View Code Duplication
			case 'DELETE' :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
383
				if ( 'write' !== $permissions && 'read_write' !== $permissions ) {
384
					$wc_rest_authentication_error = new WP_Error( 'woocommerce_rest_authentication_error', __( 'The API key provided does not have write permissions.', 'woocommerce' ), array( 'status' => 401 ) );
385
					$valid = false;
386
				}
387
				break;
388
		}
389
390
		return $valid;
391
	}
392
393
	/**
394
	 * Updated API Key last access datetime.
395
	 *
396
	 * @param int $key_id
397
	 */
398
	private function update_last_access( $key_id ) {
399
		global $wpdb;
400
401
		$wpdb->update(
402
			$wpdb->prefix . 'woocommerce_api_keys',
403
			array( 'last_access' => current_time( 'mysql' ) ),
404
			array( 'key_id' => $key_id ),
405
			array( '%s' ),
406
			array( '%d' )
407
		);
408
	}
409
410
	/**
411
	 * If the consumer_key and consumer_secret $_GET parameters are NOT provided
412
	 * and the Basic auth headers are either not present or the consumer secret does not match the consumer
413
	 * key provided, then return the correct Basic headers and an error message.
414
	 *
415
	 * @param WP_REST_Response $response Current response being served.
416
	 * @return WP_REST_Response
417
	 */
418
	public function send_unauthorized_headers( $response ) {
419
		global $wc_rest_authentication_error;
420
421
		if ( is_wp_error( $wc_rest_authentication_error ) && is_ssl() ) {
422
			$auth_message = __( 'WooCommerce API - Use a consumer key in the username field and a consumer secret in the password field.', 'woocommerce' );
423
			$response->header( 'WWW-Authenticate', 'Basic realm="' . $auth_message . '"', true );
424
		}
425
426
		return $response;
427
	}
428
}
429
430
new WC_REST_Authentication();
431