PHP 8.3 json_validate() for Drupal webhooks
A webhook endpoint on a Drupal site is public by definition, so sooner or later someone sends it garbage: a truncated body, a payload nested a few thousand levels deep, or a 20 MB blob of "JSON" that is really a log file. My old reflex was json_decode() straight into an array and then checking the result. That builds the entire structure in memory just to find out I should have refused the request.
PHP 8.3 added json_validate(string $json, int $depth = 512, int $flags = 0): bool, which checks syntax and depth without building anything. Here is how I wrap it.
A small guard class
The guard returns NULL when the body is acceptable, or a short reason string when it is not. The cheap checks (empty, too large) go first, because json_validate() still has to scan the whole string.
<?php
declare(strict_types=1);
namespace Drupal\my_webhooks;
/**
* Rejects bad JSON bodies before anything is decoded.
*/
final class JsonGuard {
public function __construct(
private readonly int $maxBytes = 65536,
private readonly int $maxDepth = 8,
) {}
/**
* Returns NULL if the body is acceptable, otherwise a reason.
*/
public function check(string $raw): ?string {
if ($raw === '') {
return 'Empty body';
}
if (strlen($raw) > $this->maxBytes) {
return 'Body too large';
}
if (!json_validate($raw, $this->maxDepth)) {
return json_last_error_msg();
}
return NULL;
}
}
I ran this logic on PHP 8.3.6 in the CLI. {"a": gave "Syntax error", twenty nested brackets with a depth limit of 8 gave "Maximum stack depth exceeded", and a lone "\xff" string gave "Malformed UTF-8 characters, possibly incorrectly encoded". I did not run the Drupal wiring below, so treat that part as a sketch I traced by hand.
Wiring it into a controller
The controller asks the guard first. Only a body that passed gets decoded, and by then I can use JSON_THROW_ON_ERROR with the same depth and know it will not blow up on structure.
<?php
declare(strict_types=1);
namespace Drupal\my_webhooks\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\my_webhooks\JsonGuard;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
final class WebhookController extends ControllerBase {
public function receive(Request $request): JsonResponse {
$raw = $request->getContent();
$reason = (new JsonGuard())->check($raw);
if ($reason !== NULL) {
return new JsonResponse(['error' => $reason], Response::HTTP_BAD_REQUEST);
}
$payload = json_decode($raw, TRUE, 8, JSON_THROW_ON_ERROR);
// ... hand $payload to a queue, as usual.
return new JsonResponse(['ok' => TRUE], Response::HTTP_ACCEPTED);
}
}
In real code I inject the guard as a service instead of calling new, and I verify the signature before any of this, since an unauthenticated caller should not even cost me a JSON scan.
The gotchas
- No
JSON_THROW_ON_ERROR. The manual says the only accepted flag isJSON_INVALID_UTF8_IGNORE. Anything else throws aValueError; on my machine passingJSON_THROW_ON_ERRORdid exactly that. Read the reason withjson_last_error_msg()instead. - Depth means the same as in
json_decode().[[1]]passes at depth 2 and fails at depth 1. - It does not replace decoding. A valid body still gets parsed a second time. The win is on the reject path, so it pays off when you expect junk and costs a little extra when everything is clean.
I would use this on any public endpoint that takes JSON, and skip it on internal ones where the sender is trusted and the bodies are small. It is a cheap first filter, not a validator: it tells you the body is JSON, not that it has the shape you expect. That job still belongs to a schema or a Symfony Validator constraint after decoding.