From cc791f56bfa1114d8e5c721f68eb4ad581140883 Mon Sep 17 00:00:00 2001 From: Jake Barnby Date: Wed, 12 Aug 2026 18:51:48 +1200 Subject: [PATCH] Merge pull request #123 from utopia-php/fix/http-empty-json-object fix(http): keep an empty JSON object out of the array shape it cannot survive --- Dockerfile.fpm | 2 +- src/Http/Adapter/FPM/Request.php | 2 +- src/Http/Adapter/Swoole/Request.php | 2 +- src/Http/Request.php | 39 ++++++++++++ tests/BaseTest.php | 24 ++++++++ tests/SwooleRequestTest.php | 93 +++++++++++++++++++++++++++++ tests/e2e/Client.php | 8 ++- tests/e2e/init.php | 8 +++ 8 files changed, 174 insertions(+), 4 deletions(-) create mode 100644 tests/SwooleRequestTest.php diff --git a/Dockerfile.fpm b/Dockerfile.fpm index 111582236a..bb3e30c77a 100644 --- a/Dockerfile.fpm +++ b/Dockerfile.fpm @@ -1,4 +1,4 @@ -FROM php:8.3-fpm-alpine AS final +FROM php:8.5-fpm-alpine AS final LABEL maintainer="team@appwrite.io" ENV DEBIAN_FRONTEND=noninteractive \ diff --git a/src/Http/Adapter/FPM/Request.php b/src/Http/Adapter/FPM/Request.php index 2f3db6bbc4..733c786fdb 100644 --- a/src/Http/Adapter/FPM/Request.php +++ b/src/Http/Adapter/FPM/Request.php @@ -247,7 +247,7 @@ class Request extends UtopiaRequest $this->rawPayload = file_get_contents('php://input') ?: ''; $this->payload = match ($contentType) { - 'application/json' => json_decode($this->rawPayload, true), + 'application/json' => $this->decodePayload($this->rawPayload), default => $_POST, }; diff --git a/src/Http/Adapter/Swoole/Request.php b/src/Http/Adapter/Swoole/Request.php index 3c4e19eaf0..6c215095e3 100644 --- a/src/Http/Adapter/Swoole/Request.php +++ b/src/Http/Adapter/Swoole/Request.php @@ -267,7 +267,7 @@ class Request extends UtopiaRequest $contentType = substr($contentType, 0, $length); $this->payload = match ($contentType) { - 'application/json' => json_decode(\strval($this->swoole->rawContent()), true), + 'application/json' => $this->decodePayload(\strval($this->swoole->rawContent())), default => $this->swoole->post, }; diff --git a/src/Http/Request.php b/src/Http/Request.php index d286213b18..bc3da980ce 100755 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -578,6 +578,45 @@ abstract class Request */ abstract protected function generateInput(): array; + /** + * Decode a JSON request body into params. + * + * Params are associative arrays, but PHP has no empty associative array, so + * `json_decode($body, true)` returns the same `[]` for `{}` and for `[]` and + * re-encoding an empty object emits `[]`. Bodies that can contain an empty + * object are decoded into objects instead, and only the empty ones are kept + * as `stdClass`; everything else becomes the associative array the params + * contract expects. + * + * @return array + */ + protected function decodePayload(string $raw): array + { + // An empty JSON object is always `{`, JSON whitespace, `}`, and `\s` covers + // every JSON whitespace character, so no match means no empty object at any + // depth. A `{}` inside a string literal matches and costs only the walk. + $decoded = preg_match('/\{\s*\}/', $raw) === 0 + ? json_decode($raw, true) + : $this->toAssociative(json_decode($raw)); + + return \is_array($decoded) ? $decoded : []; + } + + private function toAssociative(mixed $value): mixed + { + if ($value instanceof \stdClass) { + $properties = (array) $value; + + return $properties === [] ? $value : array_map($this->toAssociative(...), $properties); + } + + if (\is_array($value)) { + return array_map($this->toAssociative(...), $value); + } + + return $value; + } + /** * Content Range Parser * diff --git a/tests/BaseTest.php b/tests/BaseTest.php index 6b028f9aab..69ebd98264 100644 --- a/tests/BaseTest.php +++ b/tests/BaseTest.php @@ -54,4 +54,28 @@ trait BaseTest $this->assertSame('Aliased!', $response['body']); } } + + /** + * An object param has to come back as the object that was sent. Decoding the + * body into associative arrays turned every empty object into an empty array, + * so a stored `{}` was served back as `[]` for the life of the record. + */ + public function testObjectParamRoundTrips(): void + { + $bodies = [ + '{"data":{}}', + '{"data":{"inner":{}}}', + '{"data":{"a":{},"b":1}}', + '{"data":{"l1":{"l2":{}}}}', + '{"data":{"arr":[{},{"x":1}]}}', + '{"data":{"a":1}}', + ]; + + foreach ($bodies as $body) { + $response = $this->client->call(Client::METHOD_POST, '/object', ['Content-Type: application/json'], [], $body); + + $this->assertSame(200, $response['headers']['status-code'], $body); + $this->assertSame($body, $response['body'], 'the echoed object must match the body that was sent'); + } + } } diff --git a/tests/SwooleRequestTest.php b/tests/SwooleRequestTest.php new file mode 100644 index 0000000000..5664e981fc --- /dev/null +++ b/tests/SwooleRequestTest.php @@ -0,0 +1,93 @@ + + */ + public static function bodies(): \Iterator + { + yield 'bare empty object' => ['{"data":{}}', '{"data":{}}']; + yield 'nested empty object' => ['{"data":{"inner":{}}}', '{"data":{"inner":{}}}']; + yield 'empty object beside a value' => ['{"data":{"a":{},"b":1}}', '{"data":{"a":{},"b":1}}']; + yield 'empty object two levels down' => ['{"data":{"l1":{"l2":{}}}}', '{"data":{"l1":{"l2":{}}}}']; + yield 'empty object inside a list' => ['{"data":{"arr":[{},{"x":1}]}}', '{"data":{"arr":[{},{"x":1}]}}']; + yield 'populated object' => ['{"data":{"a":1}}', '{"data":{"a":1}}']; + yield 'empty object as the only param' => ['{"data":{},"other":{}}', '{"data":{},"other":{}}']; + yield 'braces inside a string literal' => ['{"data":{"note":"braces {} in text"}}', '{"data":{"note":"braces {} in text"}}']; + yield 'whitespace inside the empty object' => ['{"data":{"a":{ }}}', '{"data":{"a":{}}}']; + yield 'newline inside the empty object' => ["{\"data\":{\"a\":{\n}}}", '{"data":{"a":{}}}']; + yield 'empty list stays a list' => ['{"data":{"a":[]}}', '{"data":{"a":[]}}']; + } + + /** + * A param holding an empty JSON object has to re-encode as the object that was + * sent. `json_decode($body, true)` returns `[]` for both `{}` and `[]`, so an + * empty object silently became an empty array in every stored payload. + */ + #[DataProvider('bodies')] + public function testJSONBodyRoundTrips(string $body, string $expected): void + { + $request = new Request($this->swooleRequest($body)); + + $this->assertSame( + $expected, + json_encode($request->getParams()), + 'the decoded params must re-encode as the body that was sent', + ); + } + + public function testPopulatedObjectsStayAssociativeArrays(): void + { + $request = new Request($this->swooleRequest('{"data":{"a":{},"b":{"c":1}}}')); + + $data = $request->getPayload('data'); + + $this->assertIsArray($data); + $this->assertInstanceOf(\stdClass::class, $data['a']); + $this->assertIsArray($data['b'], 'a populated object must stay an associative array'); + $this->assertSame(['c' => 1], $data['b']); + } + + public function testBodyWithoutParamsDecodesToNoParams(): void + { + foreach (['{}', '{ }', '[]', '', 'not json', '"a string"', '5'] as $body) { + $request = new Request($this->swooleRequest($body)); + + $this->assertSame([], $request->getParams(), 'body ' . $body . ' carries no params'); + } + } + + public function testFormBodyIsUnaffected(): void + { + $swoole = $this->swooleRequest('data=value', 'application/x-www-form-urlencoded'); + + $this->assertSame(['data' => 'value'], (new Request($swoole))->getParams()); + } + + private function swooleRequest(string $body, string $contentType = 'application/json'): SwooleRequest + { + $request = SwooleRequest::create(['parse_cookie' => false, 'parse_files' => false]); + $request->parse( + "POST /v1/documents HTTP/1.1\r\n" + . "Host: localhost\r\n" + . 'Content-Type: ' . $contentType . "\r\n" + . 'Content-Length: ' . \strlen($body) . "\r\n" + . "\r\n" + . $body, + ); + + return $request; + } +} diff --git a/tests/e2e/Client.php b/tests/e2e/Client.php index 69516d5c77..fe66b7f08b 100644 --- a/tests/e2e/Client.php +++ b/tests/e2e/Client.php @@ -50,7 +50,7 @@ class Client * * @throws Exception */ - public function call(string $method, string $path = '', array $headers = [], array $params = []): array + public function call(string $method, string $path = '', array $headers = [], array $params = [], string $body = ''): array { if ($method === '') { throw new Exception('HTTP method is required'); @@ -66,6 +66,12 @@ class Client curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + if ($body !== '') { + // Sent verbatim, so a test can pin the exact bytes on the wire. + curl_setopt($ch, CURLOPT_POSTFIELDS, $body); + } + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); diff --git a/tests/e2e/init.php b/tests/e2e/init.php index d2ce8ccf2a..4fe0fcad80 100644 --- a/tests/e2e/init.php +++ b/tests/e2e/init.php @@ -7,6 +7,7 @@ require_once __DIR__ . '/../../vendor/autoload.php'; use Utopia\Http\Http; use Utopia\Http\Request; use Utopia\Http\Response; +use Utopia\Validator\JSON\ObjectValidator; use Utopia\Validator\Text; ini_set('memory_limit', '1024M'); @@ -81,3 +82,10 @@ Http::get('/aliased') ->action(function (Response $response) { $response->send('Aliased!'); }); + +Http::post('/object') + ->param('data', [], new ObjectValidator()) + ->inject('response') + ->action(function (mixed $data, Response $response) { + $response->json(['data' => $data]); + });