Commit edc2a1c01cb for woocommerce

commit edc2a1c01cb125e81b09667a09145f2a88971e95
Author: Luigi Teschio <gigitux@gmail.com>
Date:   Mon Nov 23 15:18:59 2026 +0100

    Strengthen nonce checks for Store API batch requests (#71256)

    Forward-port of Automattic/woocommerce#542.

    Co-authored-by: Mike Jolley <mike.jolley@me.com>

diff --git a/plugins/woocommerce/includes/class-woocommerce.php b/plugins/woocommerce/includes/class-woocommerce.php
index 8acaa15abb2..ef9aa6eade7 100644
--- a/plugins/woocommerce/includes/class-woocommerce.php
+++ b/plugins/woocommerce/includes/class-woocommerce.php
@@ -719,12 +719,14 @@ final class WooCommerce {

 		// Pretty permalinks: the namespace is part of the path, e.g. /wp-json/wc/store/v1/cart. Match the
 		// path only (a leading slash anchors the prefix) so a REST-like query argument such as
-		// /some-page/?arg=/wp-json/wc/store/ is not mistaken for a Store API request.
+		// /some-page/?arg=/wp-json/wc/store/ is not mistaken for a Store API request. Decode the path because WordPress
+		// also matches rewrite rules against the decoded path, so /wp%2Djson/wc/store/v1/cart reaches the Store API.
 		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
 		$path = wp_parse_url( '/' . ltrim( (string) wp_unslash( $_SERVER['REQUEST_URI'] ), '/' ), PHP_URL_PATH );
 		if ( is_string( $path ) ) {
+			$path = rawurldecode( $path );
 			foreach ( $namespaces as $namespace ) {
-				if ( false !== strpos( $path, '/' . trailingslashit( rest_get_url_prefix() ) . $namespace ) ) {
+				if ( false !== stripos( $path, '/' . trailingslashit( rest_get_url_prefix() ) . $namespace ) ) {
 					return true;
 				}
 			}
@@ -736,7 +738,7 @@ final class WooCommerce {
 			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the route only, no state change.
 			$rest_route = '/' . ltrim( rawurldecode( sanitize_text_field( wp_unslash( $_GET['rest_route'] ) ) ), '/' );
 			foreach ( $namespaces as $namespace ) {
-				if ( 0 === strpos( $rest_route, '/' . $namespace ) ) {
+				if ( 0 === stripos( $rest_route, '/' . $namespace ) ) {
 					return true;
 				}
 			}
diff --git a/plugins/woocommerce/src/StoreApi/Authentication.php b/plugins/woocommerce/src/StoreApi/Authentication.php
index e90e6f629c5..0105b6dbb9a 100644
--- a/plugins/woocommerce/src/StoreApi/Authentication.php
+++ b/plugins/woocommerce/src/StoreApi/Authentication.php
@@ -14,6 +14,9 @@ class Authentication {
 	 * Hook into WP lifecycle events. This is hooked by the StoreAPI class on `rest_api_init`.
 	 */
 	public function init() {
+		// Core's /batch/v1 also reaches Store API routes, so this runs for every REST request.
+		add_filter( 'rest_request_before_callbacks', array( $this, 'sanitize_batch_request' ), 10, 3 );
+
 		// UCP routes get rate limiting only: the other filters below assume a browser client with a nonce.
 		if ( 0 === stripos( $GLOBALS['wp']->query_vars['rest_route'] ?? '', '/wc/ucp/' ) ) {
 			add_filter( 'rest_authentication_errors', array( $this, 'rate_limit_ucp_request' ) );
@@ -35,6 +38,59 @@ class Authentication {
 		remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
 	}

+	/**
+	 * Stop batch requests from passing untrusted nonces to Store API routes.
+	 *
+	 * Core's /batch/v1 can't run Store API requests. The Store API batch keeps sub-request nonces, which come from
+	 * request data, only when it was sent as JSON or with its own Nonce header. A link or cross-site form can't do either.
+	 *
+	 * @since 11.4.0
+	 * @param mixed            $result  Response to replace the requested version with.
+	 * @param array            $handler Route handler used for the request.
+	 * @param \WP_REST_Request $request Request used to generate the response.
+	 * @phpstan-param mixed            $handler
+	 * @phpstan-param mixed            $request
+	 * @return mixed
+	 */
+	public function sanitize_batch_request( $result, $handler, $request ) {
+		$callback = is_array( $handler ) ? ( $handler['callback'] ?? null ) : null;
+		$requests = $request instanceof \WP_REST_Request ? $request->get_param( 'requests' ) : null;
+
+		if ( ! is_array( $callback ) || ! is_array( $requests ) ) {
+			return $result;
+		}
+
+		if ( $callback[0] instanceof \WP_REST_Server && 'serve_batch_request_v1' === ( $callback[1] ?? '' ) ) {
+			foreach ( $requests as $sub_request ) {
+				$path = isset( $sub_request['path'] ) && is_string( $sub_request['path'] ) ? wp_parse_url( $sub_request['path'], PHP_URL_PATH ) : null;
+
+				if ( is_string( $path ) && 0 === stripos( $path, '/wc/store/' ) ) {
+					return new \WP_Error( 'woocommerce_rest_invalid_path', __( 'Store API requests must use the Store API batch endpoint.', 'woocommerce' ), array( 'status' => 400 ) );
+				}
+			}
+
+			return $result;
+		}
+
+		$content_type = $request->get_content_type();
+
+		if ( ! $callback[0] instanceof Routes\V1\Batch || $request->get_header( 'Nonce' ) || 'application/json' === trim( $content_type['value'] ?? '' ) ) {
+			return $result;
+		}
+
+		foreach ( $requests as $index => $sub_request ) {
+			foreach ( array_keys( (array) ( $sub_request['headers'] ?? array() ) ) as $name ) {
+				if ( 'nonce' === \WP_REST_Request::canonicalize_header_name( (string) $name ) ) {
+					unset( $requests[ $index ]['headers'][ $name ] );
+				}
+			}
+		}
+
+		$request->set_param( 'requests', $requests );
+
+		return $result;
+	}
+
 	/**
 	 * Add allowed cors headers for store API headers.
 	 *
@@ -139,7 +195,7 @@ class Authentication {

 		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Store API context check.
 		$rest_route = rawurldecode( esc_url_raw( wp_unslash( $_GET['rest_route'] ) ) );
-		return 0 === strpos( $rest_route, '/wc/store/' );
+		return 0 === stripos( $rest_route, '/wc/store/' );
 	}

 	/**
@@ -211,7 +267,7 @@ class Authentication {
 		$route = $GLOBALS['wp']->query_vars['rest_route'] ?? '';

 		// Of the UCP checkout routes only complete places an order, so only it is matched.
-		$is_checkout = ( $this->is_request_to_store_api() && preg_match( '#/wc/store(?:/v\d+)?/checkout#', $route ) )
+		$is_checkout = ( $this->is_request_to_store_api() && preg_match( '#/wc/store(?:/v\d+)?/checkout#i', $route ) )
 			|| preg_match( '#^/wc/ucp/v\d+/checkout-sessions/[^/]+/complete/?$#i', $route );

 		if (
@@ -323,7 +379,7 @@ class Authentication {
 		if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
 			return false;
 		}
-		return 0 === strpos( $GLOBALS['wp']->query_vars['rest_route'], '/wc/store/' );
+		return 0 === stripos( $GLOBALS['wp']->query_vars['rest_route'], '/wc/store/' );
 	}

 	/**
diff --git a/plugins/woocommerce/tests/php/includes/class-woocommerce-test.php b/plugins/woocommerce/tests/php/includes/class-woocommerce-test.php
index a965bd0c989..3348c05e347 100644
--- a/plugins/woocommerce/tests/php/includes/class-woocommerce-test.php
+++ b/plugins/woocommerce/tests/php/includes/class-woocommerce-test.php
@@ -229,6 +229,52 @@ class WooCommerce_Test extends \WC_Unit_Test_Case {
 		$this->assertTrue( WC()->is_store_api_request(), 'A ?rest_route=/wc/store/ request should be detected as Store API.' );
 	}

+	/**
+	 * @testdox Should detect a Store API request whose route uses different letter case, as the REST server matches routes case-insensitively.
+	 * @testWith ["/wp-json/wc/Store/v1/cart", ""]
+	 *           ["/WP-JSON/WC/STORE/v1/cart", ""]
+	 *           ["/index.php?rest_route=/wc/Store/v1/cart", "/wc/Store/v1/cart"]
+	 *
+	 * @param string $request_uri Request URI.
+	 * @param string $rest_route  The rest_route query argument, or empty for none.
+	 */
+	public function test_is_store_api_request_ignores_letter_case( string $request_uri, string $rest_route ): void {
+		$_SERVER['REQUEST_URI'] = $request_uri;
+		if ( '' !== $rest_route ) {
+			$_GET['rest_route'] = $rest_route;
+		}
+
+		$this->assertTrue( WC()->is_store_api_request() );
+	}
+
+	/**
+	 * @testdox Should detect a Store API request with a percent-encoded path, as WordPress also matches rewrite rules against the decoded path.
+	 * @testWith ["/wp%2Djson/wc/store/v1/cart"]
+	 *           ["/%77p-json/wc/store/v1/cart"]
+	 *           ["/wp-json%2Fwc%2Fstore%2Fv1%2Fcart"]
+	 *           ["/wp%2Djson/wc/st%6Fre/v1/cart"]
+	 *
+	 * @param string $request_uri Request URI.
+	 */
+	public function test_is_store_api_request_decodes_the_path( string $request_uri ): void {
+		$_SERVER['REQUEST_URI'] = $request_uri;
+
+		$this->assertTrue( WC()->is_store_api_request() );
+	}
+
+	/**
+	 * @testdox Should not detect a Store API request from a double-encoded path or an encoded query argument, as WordPress doesn't route these to the Store API.
+	 * @testWith ["/wp%252Djson/wc/store/v1/cart"]
+	 *           ["/some-page/?arg=/wp%2Djson/wc/store/"]
+	 *
+	 * @param string $request_uri Request URI.
+	 */
+	public function test_is_store_api_request_decodes_the_path_only_once( string $request_uri ): void {
+		$_SERVER['REQUEST_URI'] = $request_uri;
+
+		$this->assertFalse( WC()->is_store_api_request() );
+	}
+
 	/**
 	 * @testdox Should not detect a non-Store API plain-permalink request as Store API.
 	 */
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/AuthenticationRouteMatchingTest.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/AuthenticationRouteMatchingTest.php
new file mode 100644
index 00000000000..f8a1268125b
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/AuthenticationRouteMatchingTest.php
@@ -0,0 +1,97 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Blocks\StoreApi;
+
+use Automattic\WooCommerce\Internal\Features\FeaturesController;
+use Automattic\WooCommerce\StoreApi\Authentication;
+use Automattic\WooCommerce\StoreApi\SessionHandler;
+use Automattic\WooCommerce\StoreApi\Utilities\CartTokenUtils;
+use WC_Unit_Test_Case;
+
+/**
+ * Tests that Store API authentication recognises routes the way the REST server matches them.
+ */
+class AuthenticationRouteMatchingTest extends WC_Unit_Test_Case {
+
+	/**
+	 * The System Under Test.
+	 *
+	 * @var Authentication
+	 */
+	private $sut;
+
+	/**
+	 * The $_SERVER values from before the test.
+	 *
+	 * @var array<string, mixed>
+	 */
+	private $original_server;
+
+	/**
+	 * Set up test fixtures.
+	 */
+	public function setUp(): void {
+		parent::setUp();
+		$this->sut             = new Authentication();
+		$this->original_server = $_SERVER;
+	}
+
+	/**
+	 * Tear down test fixtures.
+	 */
+	public function tearDown(): void {
+		try {
+			unset( $GLOBALS['wp']->query_vars['rest_route'] );
+			$_SERVER = $this->original_server;
+		} finally {
+			parent::tearDown();
+		}
+	}
+
+	/**
+	 * @testdox Should apply Store API CORS handling to Store API routes in any letter case.
+	 * @testWith ["/wc/store/v1/cart", true]
+	 *           ["/wc/Store/v1/cart", true]
+	 *           ["/WC/STORE/v1/cart", true]
+	 *           ["/wc-admin/options", false]
+	 *
+	 * @param string $route    Requested REST route.
+	 * @param bool   $expected Whether Store API CORS handling should be hooked.
+	 */
+	public function test_init_hooks_cors_handling_for_store_api_routes( string $route, bool $expected ): void {
+		$GLOBALS['wp']->query_vars['rest_route'] = $route;
+
+		$this->sut->init();
+
+		$this->assertSame( $expected, is_int( has_filter( 'rest_pre_serve_request', array( $this->sut, 'send_cors_headers' ) ) ) );
+	}
+
+	/**
+	 * @testdox Should rate limit checkout requests in any letter case when checkout rate limiting is enabled.
+	 * @testWith ["/wc/store/v1/checkout"]
+	 *           ["/wc/Store/v1/checkout"]
+	 *           ["/wc/store/v1/Checkout"]
+	 *
+	 * @param string $route Requested REST route.
+	 */
+	public function test_opt_in_checkout_endpoint_ignores_letter_case( string $route ): void {
+		wc_get_container()->get( FeaturesController::class )->change_feature_enable( 'rate_limit_checkout', true );
+		$GLOBALS['wp']->query_vars['rest_route'] = $route;
+		$_SERVER['REQUEST_METHOD']               = 'POST';
+
+		$this->sut->opt_in_checkout_endpoint( null );
+
+		$this->assertNotFalse( has_filter( 'woocommerce_store_api_rate_limit_options' ) );
+	}
+
+	/**
+	 * @testdox Should use the Cart-Token session when the request path is percent-encoded.
+	 */
+	public function test_session_handler_uses_cart_token_for_encoded_path(): void {
+		$_SERVER['REQUEST_URI']     = '/wp%2Djson/wc/store/v1/cart';
+		$_SERVER['HTTP_CART_TOKEN'] = CartTokenUtils::get_cart_token( 'test-customer' );
+
+		$this->assertSame( SessionHandler::class, $this->sut->maybe_use_store_api_session_handler( \WC_Session_Handler::class ) );
+	}
+}
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Batch.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Batch.php
index 2b198763042..8e6eb418c28 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Batch.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Batch.php
@@ -164,6 +164,7 @@ class Batch extends ControllerTestCase {
 		add_filter( 'woocommerce_get_cart_item_from_session', $session_failure_callback );

 		$request = new \WP_REST_Request( 'POST', '/wc/store/v1/batch' );
+		$request->set_header( 'Content-Type', 'application/json' );
 		$request->set_body_params(
 			array(
 				'requests' => array(
@@ -411,4 +412,119 @@ class Batch extends ControllerTestCase {
 		$this->assertEquals( 400, $response->get_status(), 'Batch should be rejected when any sub-request path is invalid' );
 		$this->assertEquals( 'woocommerce_rest_invalid_path', $response->get_data()['code'] );
 	}
+
+	/**
+	 * @testdox Should only trust a sub-request nonce when the batch was sent as JSON or with its own Nonce header.
+	 * @testWith ["/wc/store/v1/batch", "", false, "Nonce", 401]
+	 *           ["/WC/Store/v1/Batch", "", false, "nonce", 401]
+	 *           ["/wc/store/batch", "", false, "Nonce", 401]
+	 *           ["/wc/store/v1/batch\n", "", false, "Nonce", 401]
+	 *           ["/wc/store/v1/batch", "application/x-www-form-urlencoded", false, "NONCE", 401]
+	 *           ["/wc/store/v1/batch", "text/plain; x=\"a, application/json;\"", false, "Nonce", 401]
+	 *           ["/wc/store/v1/batch", "application/json; charset=utf-8", false, "Nonce", 201]
+	 *           ["/wc/store/v1/batch", "", true, "Nonce", 201]
+	 *
+	 * @param string $route           Batch route.
+	 * @param string $content_type    Content type of the batch request, or empty for none.
+	 * @param bool   $batch_nonce     Whether the batch request has its own Nonce header.
+	 * @param string $header_name     Name of the sub-request's nonce header.
+	 * @param int    $expected_status Expected sub-request status.
+	 */
+	public function test_batch_sub_request_nonce( string $route, string $content_type, bool $batch_nonce, string $header_name, int $expected_status ): void {
+		$request = new \WP_REST_Request( 'POST', $route );
+		if ( '' !== $content_type ) {
+			$request->set_header( 'Content-Type', $content_type );
+		}
+		if ( $batch_nonce ) {
+			$request->set_header( 'Nonce', wp_create_nonce( 'wc_store_api' ) );
+		}
+		$request->set_body_params(
+			array(
+				'requests' => array(
+					array(
+						'method'  => 'POST',
+						'path'    => '/wc/store/v1/cart/add-item',
+						'body'    => array(
+							'id'       => $this->products[0]->get_id(),
+							'quantity' => 1,
+						),
+						'headers' => array( $header_name => wp_create_nonce( 'wc_store_api' ) ),
+					),
+				),
+			)
+		);
+
+		$sub_response = rest_get_server()->dispatch( $request )->get_data()['responses'][0];
+
+		$this->assertSame( $expected_status, $sub_response['status'] );
+	}
+
+	/**
+	 * @testdox Should refuse Store API requests sent through core's batch endpoint.
+	 * @testWith ["/batch/v1", "", "/wc/store/v1/cart/add-item"]
+	 *           ["/batch/v1", "application/json", "/wc/store/v1/cart/add-item"]
+	 *           ["/BATCH/v1", "application/json", "/WC/Store/v1/cart/add-item"]
+	 *           ["/batch/v1\n", "application/json", "/wc/store/cart/add-item?x=1"]
+	 *
+	 * @param string $route        Batch route.
+	 * @param string $content_type Content type of the batch request, or empty for none.
+	 * @param string $path         Sub-request path.
+	 */
+	public function test_core_batch_refuses_store_api_requests( string $route, string $content_type, string $path ): void {
+		$request = new \WP_REST_Request( 'POST', $route );
+		if ( '' !== $content_type ) {
+			$request->set_header( 'Content-Type', $content_type );
+		}
+		$request->set_header( 'Nonce', wp_create_nonce( 'wc_store_api' ) );
+		$request->set_body_params(
+			array(
+				'requests' => array(
+					array(
+						'method'  => 'POST',
+						'path'    => $path,
+						'body'    => array(
+							'id'       => $this->products[0]->get_id(),
+							'quantity' => 1,
+						),
+						'headers' => array( 'Nonce' => wp_create_nonce( 'wc_store_api' ) ),
+					),
+				),
+			)
+		);
+
+		$response = rest_get_server()->dispatch( $request );
+
+		$this->assertSame( 400, $response->get_status() );
+		$this->assertSame( 'woocommerce_rest_invalid_path', $response->get_data()['code'] );
+		$this->assertTrue( WC()->cart->is_empty(), 'No sub-request should run.' );
+	}
+
+	/**
+	 * @testdox Should leave core's batch endpoint working for routes outside the Store API.
+	 * @testWith ["wc-test/v1"]
+	 *           ["wc/storefront/v1"]
+	 *
+	 * @param string $route_namespace REST namespace of the route.
+	 */
+	public function test_core_batch_allows_other_routes( string $route_namespace ): void {
+		register_rest_route(
+			$route_namespace,
+			'/echo',
+			array(
+				'methods'             => 'POST',
+				'callback'            => static function () {
+					return array( 'ok' => true );
+				},
+				'permission_callback' => '__return_true',
+				'allow_batch'         => array( 'v1' => true ),
+			)
+		);
+		$request = new \WP_REST_Request( 'POST', '/batch/v1' );
+		$request->set_body_params( array( 'requests' => array( array( 'path' => "/{$route_namespace}/echo" ) ) ) );
+
+		$response = rest_get_server()->dispatch( $request );
+
+		$this->assertSame( 207, $response->get_status() );
+		$this->assertSame( 200, $response->get_data()['responses'][0]['status'] );
+	}
 }