[13.x] Fix validation stalling for minutes on large arrays

Merged
MA
4mo ago
+19-4

An ordinary request body can stall a request for over a minute. Expanding foo.*.bar rules is quadratic in the number of expanded attributes (array items × wildcard rules), so Validator::make() spends that time building the rule set before a single rule runs. post_max_size and web server body limits never trigger, 8000 items here is only ~1.1 MB.

To reproduce, in php artisan tinker:

$rules = ['items' => ['array']];

foreach (range(1, 17) as $i) {
    $rules["items.*.field{$i}"] = ['nullable', 'string'];
}

foreach ([500, 1000, 2000, 4000, 8000] as $count) {
    $data = ['items' => array_fill(0, $count, ['field1' => 'value'])];

    $start = microtime(true);
    Illuminate\Support\Facades\Validator::make($data, $rules)->passes();
    printf("%5d items: %7.2fs\n", $count, microtime(true) - $start);
}
itemsbeforeafter
5000.29s0.06s
10000.98s0.11s
20003.80s0.24s
400018.59s0.47s
800085.13s0.98s

A max rule on the array does not help: 'items' => ['array', 'max:500'] still expands and evaluates every items.* rule before reporting that the array is too large.

ValidationRuleParser::explodeWildcardRules() accumulates into $results by reassigning the return value of mergeRules():

$results = $this->mergeRules($results, $key, $rule);

mergeRulesForAttribute() receives $results by value and writes to it, so copy-on-write clones the whole accumulated rule set once per expanded attribute: 68,000 copies of an array averaging 34,000 entries for 17 rules over 4000 items. Validator::passes() itself is linear; all of the cost is in the expansion.

The fix moves the merge body into a private method that takes $results by reference, and the wildcard loop calls that instead of round-tripping through the by-value mergeRules().

No public or protected signatures change: mergeRules() is untouched and mergeRulesForAttribute() keeps its exact signature and return value, delegating to the new private method. explodeWildcardRules() no longer routes through it, so an override there no longer affects wildcard expansion. This is unavoidable, since the by-value return is the bug itself.

No new test, since the behaviour is unchanged and a timing assertion would be flaky.