Make WordPress Core

Opened 2 months ago

Last modified 6 weeks ago

#66136 new defect (bug)

REST API: batch/v1 fires rest_pre_dispatch with a WP_REST_Request whose route is null

Reported by: hinnerk Owned by:
Priority: normal Milestone: Awaiting Review
Component: REST API Version: 5.6
Severity: normal Keywords: has-patch has-unit-tests
Cc: Focuses: rest-api

Description

WP_REST_Server::serve_batch_request_v1() builds each sub-request as

$parsed_url = wp_parse_url( $args['path'] );

if ( false === $parsed_url ) {
        $requests[] = new WP_Error( 'parse_path_failed', ... );
        continue;
}

$single_request = new WP_REST_Request( $args['method'] ?? 'POST', $parsed_url['path'] );

wp_parse_url() only returns false for a URL it cannot parse at all. For a value that parses but has no path component it returns an array without a path key, e.g.

wp_parse_url( 'http://host' ); // [ 'scheme' => 'http', 'host' => 'host' ]
wp_parse_url( '?x=1' );        // [ 'query' => 'x=1' ]

so $parsed_url['path'] is null (with an "Undefined array key" warning) and the sub-request is constructed with $route = null.

The sub-request then fails match_request_to_handler() as expected, but before core rejects it the dispatch loop still runs

$result = apply_filters( 'rest_pre_dispatch', null, $this, $clean_request );

on it. Every rest_pre_dispatch listener now receives a request whose get_route() returns null, although the method is documented as @return string and the constructor's $route as string. Any listener that trusts that contract fatals:

  • WooCommerce 11.1.0: Automattic\WooCommerce\Utilities\RestApiUtil::attach_lazy_loaded_namespace(): Argument #3 ($rest_route) must be of type string, null given
  • WP-ImmoMakler 5.68.0: strpos(): Argument #1 ($haystack) must be of type string, null given

Without such a plugin the request still logs Warning: Undefined array key "path" from serve_batch_request_v1(), and the sub-request is rejected with rest_no_route (404) instead of the parse_path_failed (400) that an unparseable path gets — the two cases are the same thing to the caller and should be reported the same way.

Steps to reproduce

  1. WordPress 7.1, PHP 8.x, WooCommerce active (or any plugin with a typed rest_pre_dispatch callback).
  2. Unauthenticated:
    curl -X POST 'https://example.test/?rest_route=/batch/v1' \
         -H 'Content-Type: application/json' \
         -d '{"requests":[{"path":"?x=1"}]}'
    
  3. Expected: 207 Multi-Status with a parse_path_failed / rest_no_route body for the sub-request.
  4. Actual: 500 with Uncaught TypeError from the first rest_pre_dispatch listener that type-hints the route.

Proposed fix

Treat a path that parses without a path component the same as one that does not parse at all — it can never match a route anyway (patch attached):

  • src/wp-includes/rest-api/class-wp-rest-server.php

    a b class WP_REST_Server {  
    18091809                foreach ( $batch_request['requests'] as $args ) {
    18101810                        $parsed_url = wp_parse_url( $args['path'] );
    18111811
    1812                         if ( false === $parsed_url ) {
     1812                        if ( false === $parsed_url || ! isset( $parsed_url['path'] ) ) {
    18131813                                $requests[] = new WP_Error( 'parse_path_failed', __( 'Could not parse the path.' ), array( 'status' => 400 ) );
    18141814
    18151815                                continue;

Verified against 7.1: with the patch, {"path":"http://host"}, {"path":"?x=1"} and {"path":"http://:"} all return 207 with a parse_path_failed (400) sub-response; a valid path is unaffected. The $matches/$validation alignment introduced in 6.9.5 / 7.0.2 is preserved because the error is pushed to $requests at the same point the existing false case is.

A second, independent hardening would be for rest_pre_dispatch not to fire for a sub-request that has already failed matching — but that is a behaviour change for listeners, so the patch above is the minimal fix.

For context on why this surfaced now: /batch/v1 is currently being probed at scale with malformed path values, and the variants that parse without a path component produce the 500 above on plugins that trust get_route()'s documented type — we saw it on 20+ unrelated, fully patched 7.1 sites in one night. The batch endpoint itself behaves correctly on those requests; this is purely a robustness issue in how the rejected sub-request is handed to filters.

Tests

The attached patch adds test_batch_v1_path_without_path_component_is_rejected() to Tests_REST_Server with a data provider for http://host, ?x=1 and #top. It asserts a 207 batch response whose sub-response is parse_path_failed (400), and that rest_pre_dispatch did not run for the rejected sub-request.

On unpatched trunk (7.2-alpha-63166) all three data sets error out with Undefined array key "path" at class-wp-rest-server.php:1818; with the patch they pass, and the full Tests_REST_Server suite stays green (132 tests).

Attachments (1)

66136.diff​ (2.6 KB ) - added by hinnerk 2 months ago.
Reject a batch sub-request path without a path component, plus unit test (against trunk r63166)

Download all attachments as: .zip

Change History (4)

@hinnerk
2 months ago

Reject a batch sub-request path without a path component, plus unit test (against trunk r63166)

#1 @kyunghan
7 weeks ago

Reproduction and proposed-condition test report

Tested on WordPress 7.2-alpha-64042, PHP 8.4.26, Windows x64, SQLite 3.53.4 with SQLite Database Integration 1.8.0, Twenty Twenty-Five and no active regular plugins.

I reproduced the issue and tested the exact additional ! isset( $parsed_url['path'] ) condition shown in the ticket description. The attached diff returned HTTP 403 when downloaded, so this is a test of that locally applied source condition, not a claim that I applied the complete attached diff or ran the full PHPUnit suite.

Steps

Register a small batch-enabled POST route /ticket-test/v1/ping whose callback returns array( 'pong' => true ). Add a rest_pre_dispatch filter which passes $request->get_route() to a function with a string $route parameter. Dispatch a WP_REST_Request( 'POST', '/batch/v1' ) with validation set to normal, and sub-requests containing the paths below.

I used actual WP_REST_Server::dispatch() calls after full WordPress bootstrap. Exceptions were caught by the test harness so the remaining cases could run.

Results

For ?x=1, #top and http://host:

  • Before the change, the no-listener cases return a 207 batch with a rest_no_route 404 sub-response, but emit Undefined array key "path" and null-argument deprecation notices. With the typed listener, dispatch throws TypeError when the filter receives a null route.
  • With the proposed condition, both listener configurations return 207 with a parse_path_failed 400 sub-response. There are no warnings or exceptions, and the rejected sub-request is not passed to rest_pre_dispatch.

Additional checks:

Input Result with proposed condition
Empty string 207 with rest_no_route 404; string route, no warning/exception
http://: 207 with parse_path_failed 400; no sub-request filter call
Valid registered path 207 with 200 and pong: true
Valid registered path with query 207 with 200 and pong: true
Nonexistent path 207 with rest_no_route 404; no warning/exception

I also tested mixed batches with the typed listener, to check response-order alignment when a rejected item is before, after, or between valid items:

Sub-request paths Patched sub-response statuses
valid, ?x=1, valid with query 200, 400, 200
#top, valid 400, 200
valid, http://host 200, 400
http://:, valid 400, 200

All 20 patched integration cases completed without warnings or exceptions. The valid responses remained aligned with their input positions. On unpatched nightly, the mixed batches containing ?x=1, #top or http://host throw the same typed-listener error.

AI assistance: OpenAI Codex prepared and executed the scripts and helped draft this report. The logs and response bodies came from the stated local WordPress installation.

This ticket was mentioned in ​PR #13941 on ​WordPress/wordpress-develop by ​@hinnerk.


6 weeks ago
#2

WP_REST_Server::serve_batch_request_v1() only rejects a sub-request path when wp_parse_url() returns false. Values such as http://host, ?x=1 or #top parse to an array without a path key, so the sub-request is built with a null route. That raises an "Undefined array key" warning and hands the request to rest_pre_dispatch before it fails to match a route. Any listener that relies on WP_REST_Request::get_route() returning a string fatals there (WooCommerce 11.1.0 is one example).

This PR treats a path without a path component the same as an unparseable one: the sub-request gets a parse_path_failed (400) response and is never dispatched. Response order in mixed batches is unchanged, because the error is added to $requests at the same point as the existing false case.

The new test test_batch_v1_path_without_path_component_is_rejected() covers the three inputs above. It checks for a 207 batch response with a parse_path_failed sub-response, and that rest_pre_dispatch did not run for the rejected sub-request. All three data sets fail on current trunk and pass with the fix; Tests_REST_Server stays green (132 tests). This is the same change as 66136.diff on the ticket, rebased onto current trunk.

Use of AI Tools

AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus
Used for: Reproducing the bug, drafting the patch, the unit test and this description. I reviewed the change and verified it locally against trunk.

#3 @hinnerk
6 weeks ago

Thanks for testing this so thoroughly, @kyunghan — especially the mixed batches, which confirm that the sub-responses stay in the same order as the requests.

The 403 on the attachment is most likely Trac's browser check blocking a direct download. The patch is now also up as a PR: ​https://github.com/WordPress/wordpress-develop/pull/13941

It's the same change as 66136.diff, applied to current trunk without changes, including test_batch_v1_path_without_path_component_is_rejected(). Locally, all three data sets fail on trunk and pass with the fix, and Tests_REST_Server stays green (132 tests).

Your empty-string result is expected: wp_parse_url( '' ) returns an array with an empty path, so the route is a string and the request is turned down with the normal rest_no_route (404). Only paths with no path component at all reach rest_pre_dispatch with a null route.

Note: See TracTickets for help on using tickets.