Edit File by line
/home/zeestwma/richards.../wp-conte.../plugins/woocomme.../src/StoreApi
File: Authentication.php
<?php
[0] Fix | Delete
declare( strict_types=1 );
[1] Fix | Delete
namespace Automattic\WooCommerce\StoreApi;
[2] Fix | Delete
[3] Fix | Delete
use Automattic\WooCommerce\StoreApi\Utilities\RateLimits;
[4] Fix | Delete
use Automattic\WooCommerce\StoreApi\Utilities\CartTokenUtils;
[5] Fix | Delete
use Automattic\WooCommerce\Utilities\FeaturesUtil;
[6] Fix | Delete
[7] Fix | Delete
/**
[8] Fix | Delete
* Authentication class.
[9] Fix | Delete
*/
[10] Fix | Delete
class Authentication {
[11] Fix | Delete
/**
[12] Fix | Delete
* Hook into WP lifecycle events. This is hooked by the StoreAPI class on `rest_api_init`.
[13] Fix | Delete
*/
[14] Fix | Delete
public function init() {
[15] Fix | Delete
if ( ! $this->is_request_to_store_api() ) {
[16] Fix | Delete
return;
[17] Fix | Delete
}
[18] Fix | Delete
add_filter( 'rest_authentication_errors', array( $this, 'check_authentication' ) );
[19] Fix | Delete
add_filter( 'rest_authentication_errors', array( $this, 'opt_in_checkout_endpoint' ), 9, 1 );
[20] Fix | Delete
add_action( 'set_logged_in_cookie', array( $this, 'set_logged_in_cookie' ) );
[21] Fix | Delete
add_filter( 'rest_pre_serve_request', array( $this, 'send_cors_headers' ), 10, 4 );
[22] Fix | Delete
add_filter( 'rest_allowed_cors_headers', array( $this, 'allowed_cors_headers' ) );
[23] Fix | Delete
add_filter( 'rest_exposed_cors_headers', array( $this, 'exposed_cors_headers' ) );
[24] Fix | Delete
[25] Fix | Delete
// Remove the default CORS headers--we will add our own.
[26] Fix | Delete
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
[27] Fix | Delete
}
[28] Fix | Delete
[29] Fix | Delete
/**
[30] Fix | Delete
* Add allowed cors headers for store API headers.
[31] Fix | Delete
*
[32] Fix | Delete
* @param array $allowed_headers Allowed headers.
[33] Fix | Delete
* @return array
[34] Fix | Delete
*/
[35] Fix | Delete
public function allowed_cors_headers( $allowed_headers ) {
[36] Fix | Delete
$allowed_headers[] = 'Cart-Token';
[37] Fix | Delete
$allowed_headers[] = 'Nonce';
[38] Fix | Delete
return $allowed_headers;
[39] Fix | Delete
}
[40] Fix | Delete
[41] Fix | Delete
/**
[42] Fix | Delete
* Expose Store API headers in CORS responses.
[43] Fix | Delete
* We're explicitly exposing the Cart-Token, not the nonce. Only one of them is needed.
[44] Fix | Delete
*
[45] Fix | Delete
* @param array $exposed_headers Exposed headers.
[46] Fix | Delete
* @return array
[47] Fix | Delete
*/
[48] Fix | Delete
public function exposed_cors_headers( $exposed_headers ) {
[49] Fix | Delete
$exposed_headers[] = 'Cart-Token';
[50] Fix | Delete
return $exposed_headers;
[51] Fix | Delete
}
[52] Fix | Delete
[53] Fix | Delete
/**
[54] Fix | Delete
* Add CORS headers to a response object.
[55] Fix | Delete
*
[56] Fix | Delete
* These checks prevent access to the Store API from non-allowed origins. By default, the WordPress REST API allows
[57] Fix | Delete
* access from any origin. Because some Store API routes return PII, we need to add our own CORS headers.
[58] Fix | Delete
*
[59] Fix | Delete
* Allowed origins can be changed using the WordPress `allowed_http_origins` or `allowed_http_origin` filters if
[60] Fix | Delete
* access needs to be granted to other domains.
[61] Fix | Delete
*
[62] Fix | Delete
* Users of valid Cart Tokens are also allowed access from any origin.
[63] Fix | Delete
*
[64] Fix | Delete
* @param bool $served Whether the request has already been served.
[65] Fix | Delete
* @param \WP_REST_Response $result The response object.
[66] Fix | Delete
* @param \WP_REST_Request $request The request object.
[67] Fix | Delete
* @param \WP_REST_Server $server The REST server instance.
[68] Fix | Delete
* @return bool
[69] Fix | Delete
*/
[70] Fix | Delete
public function send_cors_headers( $served, $result, $request, $server ) {
[71] Fix | Delete
$origin = get_http_origin();
[72] Fix | Delete
[73] Fix | Delete
if ( 'null' !== $origin ) {
[74] Fix | Delete
$origin = esc_url_raw( $origin );
[75] Fix | Delete
}
[76] Fix | Delete
[77] Fix | Delete
// Send standard CORS headers.
[78] Fix | Delete
$server->send_header( 'Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE' );
[79] Fix | Delete
$server->send_header( 'Access-Control-Allow-Credentials', 'true' );
[80] Fix | Delete
$server->send_header( 'Vary', 'Origin', false );
[81] Fix | Delete
[82] Fix | Delete
// Allow preflight requests, certain http origins, and any origin if a cart token is present. Preflight requests
[83] Fix | Delete
// are allowed because we'll be unable to validate cart token headers at that point.
[84] Fix | Delete
if ( $this->is_preflight() || CartTokenUtils::validate_cart_token( $this->get_cart_token( $request ) ) || is_allowed_http_origin( $origin ) ) {
[85] Fix | Delete
$server->send_header( 'Access-Control-Allow-Origin', $origin );
[86] Fix | Delete
}
[87] Fix | Delete
[88] Fix | Delete
// Exit early during preflight requests. This is so someone cannot access API data by sending an OPTIONS request
[89] Fix | Delete
// with preflight headers and a _GET property to override the method.
[90] Fix | Delete
if ( $this->is_preflight() ) {
[91] Fix | Delete
exit;
[92] Fix | Delete
}
[93] Fix | Delete
[94] Fix | Delete
return $served;
[95] Fix | Delete
}
[96] Fix | Delete
[97] Fix | Delete
/**
[98] Fix | Delete
* Is the request a preflight request? Checks the request method
[99] Fix | Delete
*
[100] Fix | Delete
* @return boolean
[101] Fix | Delete
*/
[102] Fix | Delete
protected function is_preflight() {
[103] Fix | Delete
return isset( $_SERVER['REQUEST_METHOD'], $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'], $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'], $_SERVER['HTTP_ORIGIN'] ) && 'OPTIONS' === $_SERVER['REQUEST_METHOD'];
[104] Fix | Delete
}
[105] Fix | Delete
[106] Fix | Delete
/**
[107] Fix | Delete
* Gets the cart token from the request header.
[108] Fix | Delete
*
[109] Fix | Delete
* @param \WP_REST_Request $request The REST request instance.
[110] Fix | Delete
* @return string
[111] Fix | Delete
*/
[112] Fix | Delete
protected function get_cart_token( \WP_REST_Request $request ) {
[113] Fix | Delete
return wc_clean( wp_unslash( $request->get_header( 'Cart-Token' ) ?? '' ) );
[114] Fix | Delete
}
[115] Fix | Delete
[116] Fix | Delete
/**
[117] Fix | Delete
* The Store API does not require authentication.
[118] Fix | Delete
*
[119] Fix | Delete
* @param \WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not.
[120] Fix | Delete
* @return \WP_Error|null|bool
[121] Fix | Delete
*/
[122] Fix | Delete
public function check_authentication( $result ) {
[123] Fix | Delete
// Enable Rate Limiting for logged-in users without 'edit posts' capability.
[124] Fix | Delete
if ( ! current_user_can( 'edit_posts' ) ) {
[125] Fix | Delete
$result = $this->apply_rate_limiting( $result );
[126] Fix | Delete
}
[127] Fix | Delete
[128] Fix | Delete
// Pass through errors from other authentication methods used before this one.
[129] Fix | Delete
return ! empty( $result ) ? $result : true;
[130] Fix | Delete
}
[131] Fix | Delete
[132] Fix | Delete
/**
[133] Fix | Delete
* When the login cookies are set, they are not available until the next page reload. For the Store API, specifically
[134] Fix | Delete
* for returning updated nonces, we need this to be available immediately.
[135] Fix | Delete
*
[136] Fix | Delete
* @param string $logged_in_cookie The value for the logged in cookie.
[137] Fix | Delete
*/
[138] Fix | Delete
public function set_logged_in_cookie( $logged_in_cookie ) {
[139] Fix | Delete
if ( ! defined( 'LOGGED_IN_COOKIE' ) ) {
[140] Fix | Delete
return;
[141] Fix | Delete
}
[142] Fix | Delete
$_COOKIE[ LOGGED_IN_COOKIE ] = $logged_in_cookie;
[143] Fix | Delete
}
[144] Fix | Delete
[145] Fix | Delete
/**
[146] Fix | Delete
* Opt in to rate limiting for the checkout endpoint.
[147] Fix | Delete
*
[148] Fix | Delete
* @param \WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not.
[149] Fix | Delete
* @return \WP_Error|null|bool
[150] Fix | Delete
*/
[151] Fix | Delete
public function opt_in_checkout_endpoint( $result ) {
[152] Fix | Delete
if (
[153] Fix | Delete
FeaturesUtil::feature_is_enabled( 'rate_limit_checkout' )
[154] Fix | Delete
&& $this->is_request_to_store_api()
[155] Fix | Delete
&& preg_match( '#/wc/store(?:/v\d+)?/checkout#', $GLOBALS['wp']->query_vars['rest_route'] )
[156] Fix | Delete
&& isset( $_SERVER['REQUEST_METHOD'] )
[157] Fix | Delete
&& 'POST' === $_SERVER['REQUEST_METHOD']
[158] Fix | Delete
) {
[159] Fix | Delete
add_filter(
[160] Fix | Delete
'woocommerce_store_api_rate_limit_options',
[161] Fix | Delete
function ( $options ) {
[162] Fix | Delete
$options['enabled'] = true;
[163] Fix | Delete
$options['limit'] = 3;
[164] Fix | Delete
$options['seconds'] = 60;
[165] Fix | Delete
return $options;
[166] Fix | Delete
},
[167] Fix | Delete
1,
[168] Fix | Delete
1
[169] Fix | Delete
);
[170] Fix | Delete
}
[171] Fix | Delete
return $result;
[172] Fix | Delete
}
[173] Fix | Delete
/**
[174] Fix | Delete
* Applies Rate Limiting to the request, and passes through any errors from other authentication methods used before this one.
[175] Fix | Delete
*
[176] Fix | Delete
* @param \WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not.
[177] Fix | Delete
* @return \WP_Error|null|bool
[178] Fix | Delete
*/
[179] Fix | Delete
protected function apply_rate_limiting( $result ) {
[180] Fix | Delete
$rate_limiting_options = RateLimits::get_options();
[181] Fix | Delete
[182] Fix | Delete
if ( $rate_limiting_options->enabled ) {
[183] Fix | Delete
$action_id = 'store_api_request_' . self::get_rate_limiting_id( $rate_limiting_options->proxy_support );
[184] Fix | Delete
[185] Fix | Delete
$retry = RateLimits::is_exceeded_retry_after( $action_id );
[186] Fix | Delete
$server = rest_get_server();
[187] Fix | Delete
$server->send_header( 'RateLimit-Limit', $rate_limiting_options->limit );
[188] Fix | Delete
[189] Fix | Delete
if ( false !== $retry ) {
[190] Fix | Delete
$server->send_header( 'RateLimit-Remaining', 0 );
[191] Fix | Delete
$server->send_header( 'RateLimit-Retry-After', $retry );
[192] Fix | Delete
$server->send_header( 'RateLimit-Reset', time() + $retry );
[193] Fix | Delete
[194] Fix | Delete
/**
[195] Fix | Delete
* Fires when the rate limit is exceeded.
[196] Fix | Delete
*
[197] Fix | Delete
* @param string $ip_address The IP address of the request.
[198] Fix | Delete
* @param string $action_id The grouping identifier to the request.
[199] Fix | Delete
*
[200] Fix | Delete
* @since 8.9.0
[201] Fix | Delete
* @since 9.8.0 Added $action_id parameter.
[202] Fix | Delete
*/
[203] Fix | Delete
do_action(
[204] Fix | Delete
'woocommerce_store_api_rate_limit_exceeded',
[205] Fix | Delete
self::get_ip_address( $rate_limiting_options->proxy_support ),
[206] Fix | Delete
$action_id
[207] Fix | Delete
);
[208] Fix | Delete
[209] Fix | Delete
return new \WP_Error(
[210] Fix | Delete
'rate_limit_exceeded',
[211] Fix | Delete
sprintf(
[212] Fix | Delete
'Too many requests. Please wait %d seconds before trying again.',
[213] Fix | Delete
$retry
[214] Fix | Delete
),
[215] Fix | Delete
array( 'status' => 400 )
[216] Fix | Delete
);
[217] Fix | Delete
}
[218] Fix | Delete
[219] Fix | Delete
$rate_limit = RateLimits::update_rate_limit( $action_id );
[220] Fix | Delete
$server->send_header( 'RateLimit-Remaining', $rate_limit->remaining );
[221] Fix | Delete
$server->send_header( 'RateLimit-Reset', $rate_limit->reset );
[222] Fix | Delete
}
[223] Fix | Delete
[224] Fix | Delete
return $result;
[225] Fix | Delete
}
[226] Fix | Delete
[227] Fix | Delete
/**
[228] Fix | Delete
* Generates the request grouping identifier for the rate limiting.
[229] Fix | Delete
*
[230] Fix | Delete
* @param bool $proxy_support Rate Limiting proxy support.
[231] Fix | Delete
*
[232] Fix | Delete
* @return string
[233] Fix | Delete
*/
[234] Fix | Delete
protected static function get_rate_limiting_id( bool $proxy_support ): string {
[235] Fix | Delete
[236] Fix | Delete
if ( is_user_logged_in() ) {
[237] Fix | Delete
$id = (string) get_current_user_id();
[238] Fix | Delete
} else {
[239] Fix | Delete
$id = md5( self::get_ip_address( $proxy_support ) );
[240] Fix | Delete
}
[241] Fix | Delete
[242] Fix | Delete
/**
[243] Fix | Delete
* Filters the rate limiting identifier.
[244] Fix | Delete
*
[245] Fix | Delete
* @param string $id The rate limiting identifier.
[246] Fix | Delete
*
[247] Fix | Delete
* @since 9.8.0
[248] Fix | Delete
*/
[249] Fix | Delete
$id = apply_filters( 'woocommerce_store_api_rate_limit_id', $id );
[250] Fix | Delete
[251] Fix | Delete
return sanitize_key( $id );
[252] Fix | Delete
}
[253] Fix | Delete
[254] Fix | Delete
/**
[255] Fix | Delete
* Check if is request to the Store API.
[256] Fix | Delete
*
[257] Fix | Delete
* @return bool
[258] Fix | Delete
*/
[259] Fix | Delete
protected function is_request_to_store_api() {
[260] Fix | Delete
if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
[261] Fix | Delete
return false;
[262] Fix | Delete
}
[263] Fix | Delete
return 0 === strpos( $GLOBALS['wp']->query_vars['rest_route'], '/wc/store/' );
[264] Fix | Delete
}
[265] Fix | Delete
[266] Fix | Delete
/**
[267] Fix | Delete
* Get current user IP Address.
[268] Fix | Delete
*
[269] Fix | Delete
* X_REAL_IP and CLIENT_IP are custom implementations designed to facilitate obtaining a user's ip through proxies, load balancers etc.
[270] Fix | Delete
*
[271] Fix | Delete
* _FORWARDED_FOR (XFF) request header is a de-facto standard header for identifying the originating IP address of a client connecting to a web server through a proxy server.
[272] Fix | Delete
* Note for X_FORWARDED_FOR, Proxy servers can send through this header like this: X-Forwarded-For: client1, proxy1, proxy2.
[273] Fix | Delete
* Make sure we always only send through the first IP in the list which should always be the client IP.
[274] Fix | Delete
* Documentation at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
[275] Fix | Delete
*
[276] Fix | Delete
* Forwarded request header contains information that may be added by reverse proxy servers (load balancers, CDNs, and so on).
[277] Fix | Delete
* Documentation at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded
[278] Fix | Delete
* Full RFC at https://datatracker.ietf.org/doc/html/rfc7239
[279] Fix | Delete
*
[280] Fix | Delete
* @param boolean $proxy_support Enables/disables proxy support.
[281] Fix | Delete
*
[282] Fix | Delete
* @return string
[283] Fix | Delete
*/
[284] Fix | Delete
protected static function get_ip_address( bool $proxy_support = false ) {
[285] Fix | Delete
[286] Fix | Delete
if ( ! $proxy_support ) {
[287] Fix | Delete
return self::validate_ip( sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ?? 'unresolved_ip' ) ) );
[288] Fix | Delete
}
[289] Fix | Delete
[290] Fix | Delete
if ( array_key_exists( 'HTTP_X_REAL_IP', $_SERVER ) ) {
[291] Fix | Delete
return self::validate_ip( sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_REAL_IP'] ) ) );
[292] Fix | Delete
}
[293] Fix | Delete
[294] Fix | Delete
if ( array_key_exists( 'HTTP_CLIENT_IP', $_SERVER ) ) {
[295] Fix | Delete
return self::validate_ip( sanitize_text_field( wp_unslash( $_SERVER['HTTP_CLIENT_IP'] ) ) );
[296] Fix | Delete
}
[297] Fix | Delete
[298] Fix | Delete
if ( array_key_exists( 'HTTP_X_FORWARDED_FOR', $_SERVER ) ) {
[299] Fix | Delete
$ips = explode( ',', sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) );
[300] Fix | Delete
if ( is_array( $ips ) && ! empty( $ips ) ) {
[301] Fix | Delete
return self::validate_ip( trim( $ips[0] ) );
[302] Fix | Delete
}
[303] Fix | Delete
}
[304] Fix | Delete
[305] Fix | Delete
if ( array_key_exists( 'HTTP_FORWARDED', $_SERVER ) ) {
[306] Fix | Delete
// Using regex instead of explode() for a smaller code footprint.
[307] Fix | Delete
// Expected format: Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43,for="[2001:db8:cafe::17]:4711"...
[308] Fix | Delete
preg_match(
[309] Fix | Delete
'/(?<=for\=)[^;,]*/i', // We catch everything on the first "for" entry, and validate later.
[310] Fix | Delete
sanitize_text_field( wp_unslash( $_SERVER['HTTP_FORWARDED'] ) ),
[311] Fix | Delete
$matches
[312] Fix | Delete
);
[313] Fix | Delete
[314] Fix | Delete
if ( strpos( $matches[0] ?? '', '"[' ) !== false ) { // Detect for ipv6, eg "[ipv6]:port".
[315] Fix | Delete
preg_match(
[316] Fix | Delete
'/(?<=\[).*(?=\])/i', // We catch only the ipv6 and overwrite $matches.
[317] Fix | Delete
$matches[0],
[318] Fix | Delete
$matches
[319] Fix | Delete
);
[320] Fix | Delete
}
[321] Fix | Delete
[322] Fix | Delete
if ( ! empty( $matches ) ) {
[323] Fix | Delete
return self::validate_ip( trim( $matches[0] ) );
[324] Fix | Delete
}
[325] Fix | Delete
}
[326] Fix | Delete
[327] Fix | Delete
return '0.0.0.0';
[328] Fix | Delete
}
[329] Fix | Delete
[330] Fix | Delete
/**
[331] Fix | Delete
* Uses filter_var() to validate and return ipv4 and ipv6 addresses
[332] Fix | Delete
* Will return 0.0.0.0 if the ip is not valid. This is done to group and still rate limit invalid ips.
[333] Fix | Delete
*
[334] Fix | Delete
* @param string $ip ipv4 or ipv6 ip string.
[335] Fix | Delete
*
[336] Fix | Delete
* @return string
[337] Fix | Delete
*/
[338] Fix | Delete
protected static function validate_ip( $ip ) {
[339] Fix | Delete
$ip = filter_var(
[340] Fix | Delete
$ip,
[341] Fix | Delete
FILTER_VALIDATE_IP,
[342] Fix | Delete
array( FILTER_FLAG_NO_RES_RANGE, FILTER_FLAG_IPV6 )
[343] Fix | Delete
);
[344] Fix | Delete
[345] Fix | Delete
return $ip ?: '0.0.0.0';
[346] Fix | Delete
}
[347] Fix | Delete
}
[348] Fix | Delete
[349] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function