mirror of
https://github.com/appwrite/appwrite.git
synced 2026-11-18 20:36:03 +00:00
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
This commit is contained in:
1 parent
9d8d374926
commit
cc791f56bf
8 files changed
+174
-4
No files matched your search
+1
-1
@@ -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 \
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
|
||||
@@ -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<string, mixed>
|
||||
*/
|
||||
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
|
||||
*
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Utopia\Http\Tests;
|
||||
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Swoole\Http\Request as SwooleRequest;
|
||||
use Utopia\Http\Adapter\Swoole\Request;
|
||||
|
||||
#[RequiresPhpExtension('swoole')]
|
||||
final class SwooleRequestTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* @return \Iterator<string, array{string, string}>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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]);
|
||||
});
|
||||
Reference in new issue
Block a user