feat: parse multipart/form-data bodies into fields and uploaded filesUnverified
POST multipart bodies now fill the Request like PHP fills $_POST and $_FILES, using riverline/multipart-parser and parse_str() for PHP's field nesting. Files are written to temp files as test-mode UploadedFile, so move() works, and are deleted after each Invocation as PHP does at the end of a request.
755512e parent: de59a71 modified
composer.json +1 -0 | @@ -11,6 +11,7 @@ | ||
| 11 | 11 | ], |
| 12 | 12 | "require": { |
| 13 | 13 | "php": ">=8.4", |
| 14 | + "riverline/multipart-parser": "^2.3", | |
| 14 | 15 | "symfony/http-foundation": "^7.4 || ^8.0", |
| 15 | 16 | "symfony/http-kernel": "^7.4 || ^8.0", |
| 16 | 17 | "symfony/runtime": "^7.4 || ^8.0" |
| @@ -11,6 +11,7 @@ | |||
| 11 | ], | 11 | ], |
| 12 | "require": { | 12 | "require": { |
| 13 | "php": ">=8.4", | 13 | "php": ">=8.4", |
| 14 | + "riverline/multipart-parser": "^2.3", | ||
| 14 | "symfony/http-foundation": "^7.4 || ^8.0", | 15 | "symfony/http-foundation": "^7.4 || ^8.0", |
| 15 | "symfony/http-kernel": "^7.4 || ^8.0", | 16 | "symfony/http-kernel": "^7.4 || ^8.0", |
| 16 | "symfony/runtime": "^7.4 || ^8.0" | 17 | "symfony/runtime": "^7.4 || ^8.0" |
modified
src/HttpConverter.php +63 -2 | @@ -4,6 +4,8 @@ declare(strict_types=1); | ||
| 4 | 4 | |
| 5 | 5 | namespace JDecool\ScalewayRuntime; |
| 6 | 6 | |
| 7 | +use Riverline\MultiPartParser\StreamedPart; | |
| 8 | +use Symfony\Component\HttpFoundation\File\UploadedFile; | |
| 7 | 9 | use Symfony\Component\HttpFoundation\Request; |
| 8 | 10 | use Symfony\Component\HttpFoundation\Response; |
| 9 | 11 | |
| @@ -55,6 +57,7 @@ final class HttpConverter | ||
| 55 | 57 | ]; |
| 56 | 58 | $cookies = []; |
| 57 | 59 | $contentType = ''; |
| 60 | + $contentTypeHeader = ''; | |
| 58 | 61 | foreach (self::stringMap($event['headers'] ?? null) as $name => $value) { |
| 59 | 62 | $key = strtoupper(str_replace('-', '_', $name)); |
| 60 | 63 | // PHP exposes these two without the HTTP_ prefix, and HeaderBag expects them that way. |
| @@ -62,19 +65,77 @@ final class HttpConverter | ||
| 62 | 65 | if ('COOKIE' === $key) { |
| 63 | 66 | $cookies = self::parseCookies($value); |
| 64 | 67 | } elseif ('CONTENT_TYPE' === $key) { |
| 68 | + $contentTypeHeader = $value; | |
| 65 | 69 | $contentType = strtolower($value); |
| 66 | 70 | } |
| 67 | 71 | } |
| 68 | 72 | |
| 69 | 73 | // PHP only parses form bodies into $_POST for POST; Symfony's createFromGlobals() covers the other body methods. |
| 70 | - $post = []; | |
| 74 | + $post = $files = []; | |
| 71 | 75 | if (\in_array($method, ['POST', 'PUT', 'DELETE', 'PATCH', 'QUERY'], true) |
| 72 | 76 | && str_starts_with($contentType, 'application/x-www-form-urlencoded') |
| 73 | 77 | ) { |
| 74 | 78 | parse_str($body, $post); |
| 79 | + } elseif ('POST' === $method && str_starts_with($contentType, 'multipart/form-data')) { | |
| 80 | + [$post, $files] = self::parseMultipart($contentTypeHeader, $body); | |
| 75 | 81 | } |
| 76 | 82 | |
| 77 | - return new Request($query, $post, [], $cookies, [], $server, $body); | |
| 83 | + return new Request($query, $post, [], $cookies, $files, $server, $body); | |
| 84 | + } | |
| 85 | + | |
| 86 | + /** | |
| 87 | + * Fills fields and files like PHP does for a multipart POST: files land in temp files, | |
| 88 | + * which the caller must delete once the Invocation is over, as PHP does at the end of a request. | |
| 89 | + * | |
| 90 | + * @return array{array<mixed>, array<mixed>} | |
| 91 | + */ | |
| 92 | + private static function parseMultipart(string $contentType, string $body): array | |
| 93 | + { | |
| 94 | + $stream = fopen('php://temp', 'r+'); | |
| 95 | + \assert(false !== $stream); | |
| 96 | + fwrite($stream, 'Content-Type: '.$contentType."\r\n\r\n".$body); | |
| 97 | + try { | |
| 98 | + $parts = new StreamedPart($stream)->getParts(); | |
| 99 | + } catch (\InvalidArgumentException|\LogicException) { | |
| 100 | + // PHP leaves $_POST and $_FILES empty for a malformed body rather than failing the request. | |
| 101 | + return [[], []]; | |
| 102 | + } finally { | |
| 103 | + fclose($stream); | |
| 104 | + } | |
| 105 | + | |
| 106 | + $fields = $fileFields = $uploads = []; | |
| 107 | + foreach ($parts as $part) { | |
| 108 | + $name = $part->getName(); | |
| 109 | + if (!\is_string($name) || '' === $name) { | |
| 110 | + continue; | |
| 111 | + } | |
| 112 | + // Field names go through parse_str() so "a[b][]" nests exactly as PHP nests it. | |
| 113 | + if (!$part->isFile()) { | |
| 114 | + $fields[] = rawurlencode($name).'='.rawurlencode((string) $part->getBody()); | |
| 115 | + continue; | |
| 116 | + } | |
| 117 | + | |
| 118 | + $fileFields[] = rawurlencode($name).'='.\count($uploads); | |
| 119 | + $fileName = (string) $part->getFileName(); | |
| 120 | + if ('' === $fileName) { | |
| 121 | + // A file input left empty: the $_FILES entry PHP builds, which Symfony's FileBag turns into null. | |
| 122 | + $uploads[] = ['name' => '', 'type' => '', 'tmp_name' => '', 'error' => \UPLOAD_ERR_NO_FILE, 'size' => 0]; | |
| 123 | + continue; | |
| 124 | + } | |
| 125 | + $path = tempnam(sys_get_temp_dir(), 'php'); | |
| 126 | + \assert(false !== $path); | |
| 127 | + file_put_contents($path, (string) $part->getBody()); | |
| 128 | + // Test mode, as the file was not uploaded through the SAPI and is_uploaded_file() would reject it. | |
| 129 | + $uploads[] = new UploadedFile($path, $fileName, (string) $part->getMimeType(), \UPLOAD_ERR_OK, true); | |
| 130 | + } | |
| 131 | + | |
| 132 | + parse_str(implode('&', $fields), $post); | |
| 133 | + parse_str(implode('&', $fileFields), $files); | |
| 134 | + array_walk_recursive($files, static function (mixed &$index) use ($uploads): void { | |
| 135 | + $index = \is_string($index) ? $uploads[(int) $index] : null; | |
| 136 | + }); | |
| 137 | + | |
| 138 | + return [$post, $files]; | |
| 78 | 139 | } |
| 79 | 140 | |
| 80 | 141 | /** |
| @@ -4,6 +4,8 @@ declare(strict_types=1); | |||
| 4 | 4 | ||
| 5 | namespace JDecool\ScalewayRuntime; | 5 | namespace JDecool\ScalewayRuntime; |
| 6 | 6 | ||
| 7 | +use Riverline\MultiPartParser\StreamedPart; | ||
| 8 | +use Symfony\Component\HttpFoundation\File\UploadedFile; | ||
| 7 | use Symfony\Component\HttpFoundation\Request; | 9 | use Symfony\Component\HttpFoundation\Request; |
| 8 | use Symfony\Component\HttpFoundation\Response; | 10 | use Symfony\Component\HttpFoundation\Response; |
| 9 | 11 | ||
| @@ -55,6 +57,7 @@ final class HttpConverter | |||
| 55 | ]; | 57 | ]; |
| 56 | $cookies = []; | 58 | $cookies = []; |
| 57 | $contentType = ''; | 59 | $contentType = ''; |
| 60 | + $contentTypeHeader = ''; | ||
| 58 | foreach (self::stringMap($event['headers'] ?? null) as $name => $value) { | 61 | foreach (self::stringMap($event['headers'] ?? null) as $name => $value) { |
| 59 | $key = strtoupper(str_replace('-', '_', $name)); | 62 | $key = strtoupper(str_replace('-', '_', $name)); |
| 60 | // PHP exposes these two without the HTTP_ prefix, and HeaderBag expects them that way. | 63 | // PHP exposes these two without the HTTP_ prefix, and HeaderBag expects them that way. |
| @@ -62,19 +65,77 @@ final class HttpConverter | |||
| 62 | if ('COOKIE' === $key) { | 65 | if ('COOKIE' === $key) { |
| 63 | $cookies = self::parseCookies($value); | 66 | $cookies = self::parseCookies($value); |
| 64 | } elseif ('CONTENT_TYPE' === $key) { | 67 | } elseif ('CONTENT_TYPE' === $key) { |
| 68 | + $contentTypeHeader = $value; | ||
| 65 | $contentType = strtolower($value); | 69 | $contentType = strtolower($value); |
| 66 | } | 70 | } |
| 67 | } | 71 | } |
| 68 | 72 | ||
| 69 | // PHP only parses form bodies into $_POST for POST; Symfony's createFromGlobals() covers the other body methods. | 73 | // PHP only parses form bodies into $_POST for POST; Symfony's createFromGlobals() covers the other body methods. |
| 70 | - $post = []; | 74 | + $post = $files = []; |
| 71 | if (\in_array($method, ['POST', 'PUT', 'DELETE', 'PATCH', 'QUERY'], true) | 75 | if (\in_array($method, ['POST', 'PUT', 'DELETE', 'PATCH', 'QUERY'], true) |
| 72 | && str_starts_with($contentType, 'application/x-www-form-urlencoded') | 76 | && str_starts_with($contentType, 'application/x-www-form-urlencoded') |
| 73 | ) { | 77 | ) { |
| 74 | parse_str($body, $post); | 78 | parse_str($body, $post); |
| 79 | + } elseif ('POST' === $method && str_starts_with($contentType, 'multipart/form-data')) { | ||
| 80 | + [$post, $files] = self::parseMultipart($contentTypeHeader, $body); | ||
| 75 | } | 81 | } |
| 76 | 82 | ||
| 77 | - return new Request($query, $post, [], $cookies, [], $server, $body); | 83 | + return new Request($query, $post, [], $cookies, $files, $server, $body); |
| 84 | + } | ||
| 85 | + | ||
| 86 | + /** | ||
| 87 | + * Fills fields and files like PHP does for a multipart POST: files land in temp files, | ||
| 88 | + * which the caller must delete once the Invocation is over, as PHP does at the end of a request. | ||
| 89 | + * | ||
| 90 | + * @return array{array<mixed>, array<mixed>} | ||
| 91 | + */ | ||
| 92 | + private static function parseMultipart(string $contentType, string $body): array | ||
| 93 | + { | ||
| 94 | + $stream = fopen('php://temp', 'r+'); | ||
| 95 | + \assert(false !== $stream); | ||
| 96 | + fwrite($stream, 'Content-Type: '.$contentType."\r\n\r\n".$body); | ||
| 97 | + try { | ||
| 98 | + $parts = new StreamedPart($stream)->getParts(); | ||
| 99 | + } catch (\InvalidArgumentException|\LogicException) { | ||
| 100 | + // PHP leaves $_POST and $_FILES empty for a malformed body rather than failing the request. | ||
| 101 | + return [[], []]; | ||
| 102 | + } finally { | ||
| 103 | + fclose($stream); | ||
| 104 | + } | ||
| 105 | + | ||
| 106 | + $fields = $fileFields = $uploads = []; | ||
| 107 | + foreach ($parts as $part) { | ||
| 108 | + $name = $part->getName(); | ||
| 109 | + if (!\is_string($name) || '' === $name) { | ||
| 110 | + continue; | ||
| 111 | + } | ||
| 112 | + // Field names go through parse_str() so "a[b][]" nests exactly as PHP nests it. | ||
| 113 | + if (!$part->isFile()) { | ||
| 114 | + $fields[] = rawurlencode($name).'='.rawurlencode((string) $part->getBody()); | ||
| 115 | + continue; | ||
| 116 | + } | ||
| 117 | + | ||
| 118 | + $fileFields[] = rawurlencode($name).'='.\count($uploads); | ||
| 119 | + $fileName = (string) $part->getFileName(); | ||
| 120 | + if ('' === $fileName) { | ||
| 121 | + // A file input left empty: the $_FILES entry PHP builds, which Symfony's FileBag turns into null. | ||
| 122 | + $uploads[] = ['name' => '', 'type' => '', 'tmp_name' => '', 'error' => \UPLOAD_ERR_NO_FILE, 'size' => 0]; | ||
| 123 | + continue; | ||
| 124 | + } | ||
| 125 | + $path = tempnam(sys_get_temp_dir(), 'php'); | ||
| 126 | + \assert(false !== $path); | ||
| 127 | + file_put_contents($path, (string) $part->getBody()); | ||
| 128 | + // Test mode, as the file was not uploaded through the SAPI and is_uploaded_file() would reject it. | ||
| 129 | + $uploads[] = new UploadedFile($path, $fileName, (string) $part->getMimeType(), \UPLOAD_ERR_OK, true); | ||
| 130 | + } | ||
| 131 | + | ||
| 132 | + parse_str(implode('&', $fields), $post); | ||
| 133 | + parse_str(implode('&', $fileFields), $files); | ||
| 134 | + array_walk_recursive($files, static function (mixed &$index) use ($uploads): void { | ||
| 135 | + $index = \is_string($index) ? $uploads[(int) $index] : null; | ||
| 136 | + }); | ||
| 137 | + | ||
| 138 | + return [$post, $files]; | ||
| 78 | } | 139 | } |
| 79 | 140 | ||
| 80 | /** | 141 | /** |
modified
src/Runner/HttpKernelRunner.php +25 -13 | @@ -5,6 +5,7 @@ declare(strict_types=1); | ||
| 5 | 5 | namespace JDecool\ScalewayRuntime\Runner; |
| 6 | 6 | |
| 7 | 7 | use JDecool\ScalewayRuntime\HttpConverter; |
| 8 | +use Symfony\Component\HttpFoundation\File\UploadedFile; | |
| 8 | 9 | use Symfony\Component\HttpFoundation\Request; |
| 9 | 10 | use Symfony\Component\HttpKernel\HttpKernelInterface; |
| 10 | 11 | use Symfony\Component\HttpKernel\KernelInterface; |
| @@ -33,20 +34,31 @@ final readonly class HttpKernelRunner implements InvocationRunner | ||
| 33 | 34 | public function invoke(array $event, mixed $context): array |
| 34 | 35 | { |
| 35 | 36 | $request = HttpConverter::toRequest($event); |
| 36 | - // The Kernel resets its services itself (services_resetter) when the next main request is handled. | |
| 37 | - $response = $this->kernel->handle($request); | |
| 38 | - $functionResponse = HttpConverter::toFunctionResponse($response); | |
| 39 | - | |
| 40 | - if ($this->kernel instanceof TerminableInterface) { | |
| 41 | - try { | |
| 42 | - $this->kernel->terminate($request, $response); | |
| 43 | - } catch (\Throwable $e) { | |
| 44 | - // Behind FPM the client already got the Response when terminate() runs; turning it into | |
| 45 | - // a 500 would invite retries of an operation that succeeded. | |
| 46 | - fwrite($this->errorLog, 'Kernel termination failed: '.$e.\PHP_EOL); | |
| 37 | + // Captured before the Application can alter the bag, so every temp file gets deleted. | |
| 38 | + $uploads = $request->files->all(); | |
| 39 | + try { | |
| 40 | + // The Kernel resets its services itself (services_resetter) when the next main request is handled. | |
| 41 | + $response = $this->kernel->handle($request); | |
| 42 | + $functionResponse = HttpConverter::toFunctionResponse($response); | |
| 43 | + | |
| 44 | + if ($this->kernel instanceof TerminableInterface) { | |
| 45 | + try { | |
| 46 | + $this->kernel->terminate($request, $response); | |
| 47 | + } catch (\Throwable $e) { | |
| 48 | + // Behind FPM the client already got the Response when terminate() runs; turning it into | |
| 49 | + // a 500 would invite retries of an operation that succeeded. | |
| 50 | + fwrite($this->errorLog, 'Kernel termination failed: '.$e.\PHP_EOL); | |
| 51 | + } | |
| 47 | 52 | } |
| 48 | - } | |
| 49 | 53 | |
| 50 | - return $functionResponse; | |
| 54 | + return $functionResponse; | |
| 55 | + } finally { | |
| 56 | + // PHP deletes uploaded files at the end of each request; a Warm Process must do it itself. | |
| 57 | + array_walk_recursive($uploads, static function (mixed $file): void { | |
| 58 | + if ($file instanceof UploadedFile && is_file($file->getPathname())) { | |
| 59 | + unlink($file->getPathname()); | |
| 60 | + } | |
| 61 | + }); | |
| 62 | + } | |
| 51 | 63 | } |
| 52 | 64 | } |
| @@ -5,6 +5,7 @@ declare(strict_types=1); | |||
| 5 | namespace JDecool\ScalewayRuntime\Runner; | 5 | namespace JDecool\ScalewayRuntime\Runner; |
| 6 | 6 | ||
| 7 | use JDecool\ScalewayRuntime\HttpConverter; | 7 | use JDecool\ScalewayRuntime\HttpConverter; |
| 8 | +use Symfony\Component\HttpFoundation\File\UploadedFile; | ||
| 8 | use Symfony\Component\HttpFoundation\Request; | 9 | use Symfony\Component\HttpFoundation\Request; |
| 9 | use Symfony\Component\HttpKernel\HttpKernelInterface; | 10 | use Symfony\Component\HttpKernel\HttpKernelInterface; |
| 10 | use Symfony\Component\HttpKernel\KernelInterface; | 11 | use Symfony\Component\HttpKernel\KernelInterface; |
| @@ -33,20 +34,31 @@ final readonly class HttpKernelRunner implements InvocationRunner | |||
| 33 | public function invoke(array $event, mixed $context): array | 34 | public function invoke(array $event, mixed $context): array |
| 34 | { | 35 | { |
| 35 | $request = HttpConverter::toRequest($event); | 36 | $request = HttpConverter::toRequest($event); |
| 36 | - // The Kernel resets its services itself (services_resetter) when the next main request is handled. | 37 | + // Captured before the Application can alter the bag, so every temp file gets deleted. |
| 37 | - $response = $this->kernel->handle($request); | 38 | + $uploads = $request->files->all(); |
| 38 | - $functionResponse = HttpConverter::toFunctionResponse($response); | 39 | + try { |
| 39 | - | 40 | + // The Kernel resets its services itself (services_resetter) when the next main request is handled. |
| 40 | - if ($this->kernel instanceof TerminableInterface) { | 41 | + $response = $this->kernel->handle($request); |
| 41 | - try { | 42 | + $functionResponse = HttpConverter::toFunctionResponse($response); |
| 42 | - $this->kernel->terminate($request, $response); | 43 | + |
| 43 | - } catch (\Throwable $e) { | 44 | + if ($this->kernel instanceof TerminableInterface) { |
| 44 | - // Behind FPM the client already got the Response when terminate() runs; turning it into | 45 | + try { |
| 45 | - // a 500 would invite retries of an operation that succeeded. | 46 | + $this->kernel->terminate($request, $response); |
| 46 | - fwrite($this->errorLog, 'Kernel termination failed: '.$e.\PHP_EOL); | 47 | + } catch (\Throwable $e) { |
| 48 | + // Behind FPM the client already got the Response when terminate() runs; turning it into | ||
| 49 | + // a 500 would invite retries of an operation that succeeded. | ||
| 50 | + fwrite($this->errorLog, 'Kernel termination failed: '.$e.\PHP_EOL); | ||
| 51 | + } | ||
| 47 | } | 52 | } |
| 48 | - } | ||
| 49 | 53 | ||
| 50 | - return $functionResponse; | 54 | + return $functionResponse; |
| 55 | + } finally { | ||
| 56 | + // PHP deletes uploaded files at the end of each request; a Warm Process must do it itself. | ||
| 57 | + array_walk_recursive($uploads, static function (mixed $file): void { | ||
| 58 | + if ($file instanceof UploadedFile && is_file($file->getPathname())) { | ||
| 59 | + unlink($file->getPathname()); | ||
| 60 | + } | ||
| 61 | + }); | ||
| 62 | + } | ||
| 51 | } | 63 | } |
| 52 | } | 64 | } |
modified
tests/Fixtures/App/Kernel.php +14 -0 | @@ -6,6 +6,7 @@ namespace JDecool\ScalewayRuntime\Tests\Fixtures\App; | ||
| 6 | 6 | |
| 7 | 7 | use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; |
| 8 | 8 | use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; |
| 9 | +use Symfony\Component\HttpFoundation\File\UploadedFile; | |
| 9 | 10 | use Symfony\Component\HttpFoundation\JsonResponse; |
| 10 | 11 | use Symfony\Component\HttpFoundation\Request; |
| 11 | 12 | use Symfony\Component\HttpKernel\Kernel as BaseKernel; |
| @@ -49,6 +50,18 @@ final class Kernel extends BaseKernel | ||
| 49 | 50 | ]); |
| 50 | 51 | } |
| 51 | 52 | |
| 53 | + public function upload(Request $request): JsonResponse | |
| 54 | + { | |
| 55 | + $file = $request->files->get('doc'); | |
| 56 | + \assert($file instanceof UploadedFile); | |
| 57 | + | |
| 58 | + return new JsonResponse([ | |
| 59 | + 'title' => $request->request->get('title'), | |
| 60 | + 'name' => $file->getClientOriginalName(), | |
| 61 | + 'content' => $file->getContent(), | |
| 62 | + ]); | |
| 63 | + } | |
| 64 | + | |
| 52 | 65 | private function configureContainer(ContainerConfigurator $container): void |
| 53 | 66 | { |
| 54 | 67 | $container->extension('framework', ['secret' => 'fixture', 'http_method_override' => false]); |
| @@ -61,5 +74,6 @@ final class Kernel extends BaseKernel | ||
| 61 | 74 | private function configureRoutes(RoutingConfigurator $routes): void |
| 62 | 75 | { |
| 63 | 76 | $routes->add('state', '/state')->controller('kernel::state'); |
| 77 | + $routes->add('upload', '/upload')->controller('kernel::upload'); | |
| 64 | 78 | } |
| 65 | 79 | } |
| @@ -6,6 +6,7 @@ namespace JDecool\ScalewayRuntime\Tests\Fixtures\App; | |||
| 6 | 6 | ||
| 7 | use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; | 7 | use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; |
| 8 | use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; | 8 | use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; |
| 9 | +use Symfony\Component\HttpFoundation\File\UploadedFile; | ||
| 9 | use Symfony\Component\HttpFoundation\JsonResponse; | 10 | use Symfony\Component\HttpFoundation\JsonResponse; |
| 10 | use Symfony\Component\HttpFoundation\Request; | 11 | use Symfony\Component\HttpFoundation\Request; |
| 11 | use Symfony\Component\HttpKernel\Kernel as BaseKernel; | 12 | use Symfony\Component\HttpKernel\Kernel as BaseKernel; |
| @@ -49,6 +50,18 @@ final class Kernel extends BaseKernel | |||
| 49 | ]); | 50 | ]); |
| 50 | } | 51 | } |
| 51 | 52 | ||
| 53 | + public function upload(Request $request): JsonResponse | ||
| 54 | + { | ||
| 55 | + $file = $request->files->get('doc'); | ||
| 56 | + \assert($file instanceof UploadedFile); | ||
| 57 | + | ||
| 58 | + return new JsonResponse([ | ||
| 59 | + 'title' => $request->request->get('title'), | ||
| 60 | + 'name' => $file->getClientOriginalName(), | ||
| 61 | + 'content' => $file->getContent(), | ||
| 62 | + ]); | ||
| 63 | + } | ||
| 64 | + | ||
| 52 | private function configureContainer(ContainerConfigurator $container): void | 65 | private function configureContainer(ContainerConfigurator $container): void |
| 53 | { | 66 | { |
| 54 | $container->extension('framework', ['secret' => 'fixture', 'http_method_override' => false]); | 67 | $container->extension('framework', ['secret' => 'fixture', 'http_method_override' => false]); |
| @@ -61,5 +74,6 @@ final class Kernel extends BaseKernel | |||
| 61 | private function configureRoutes(RoutingConfigurator $routes): void | 74 | private function configureRoutes(RoutingConfigurator $routes): void |
| 62 | { | 75 | { |
| 63 | $routes->add('state', '/state')->controller('kernel::state'); | 76 | $routes->add('state', '/state')->controller('kernel::state'); |
| 77 | + $routes->add('upload', '/upload')->controller('kernel::upload'); | ||
| 64 | } | 78 | } |
| 65 | } | 79 | } |
modified
tests/Fixtures/RecordingKernel.php +2 -0 | @@ -17,6 +17,7 @@ final class RecordingKernel implements HttpKernelInterface, TerminableInterface | ||
| 17 | 17 | |
| 18 | 18 | public int $handled = 0; |
| 19 | 19 | public int $terminated = 0; |
| 20 | + public ?Request $lastRequest = null; | |
| 20 | 21 | |
| 21 | 22 | public static function build(): self |
| 22 | 23 | { |
| @@ -38,6 +39,7 @@ final class RecordingKernel implements HttpKernelInterface, TerminableInterface | ||
| 38 | 39 | |
| 39 | 40 | public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = true): Response |
| 40 | 41 | { |
| 42 | + $this->lastRequest = $request; | |
| 41 | 43 | if ('/throw' === $request->getPathInfo()) { |
| 42 | 44 | throw new \LogicException('Escaped on purpose.'); |
| 43 | 45 | } |
| @@ -17,6 +17,7 @@ final class RecordingKernel implements HttpKernelInterface, TerminableInterface | |||
| 17 | 17 | ||
| 18 | public int $handled = 0; | 18 | public int $handled = 0; |
| 19 | public int $terminated = 0; | 19 | public int $terminated = 0; |
| 20 | + public ?Request $lastRequest = null; | ||
| 20 | 21 | ||
| 21 | public static function build(): self | 22 | public static function build(): self |
| 22 | { | 23 | { |
| @@ -38,6 +39,7 @@ final class RecordingKernel implements HttpKernelInterface, TerminableInterface | |||
| 38 | 39 | ||
| 39 | public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = true): Response | 40 | public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = true): Response |
| 40 | { | 41 | { |
| 42 | + $this->lastRequest = $request; | ||
| 41 | if ('/throw' === $request->getPathInfo()) { | 43 | if ('/throw' === $request->getPathInfo()) { |
| 42 | throw new \LogicException('Escaped on purpose.'); | 44 | throw new \LogicException('Escaped on purpose.'); |
| 43 | } | 45 | } |
modified
tests/HttpConverterTest.php +89 -0 | @@ -8,6 +8,7 @@ use JDecool\ScalewayRuntime\HttpConverter; | ||
| 8 | 8 | use PHPUnit\Framework\TestCase; |
| 9 | 9 | use Symfony\Component\HttpFoundation\BinaryFileResponse; |
| 10 | 10 | use Symfony\Component\HttpFoundation\Cookie; |
| 11 | +use Symfony\Component\HttpFoundation\File\UploadedFile; | |
| 11 | 12 | use Symfony\Component\HttpFoundation\Request; |
| 12 | 13 | use Symfony\Component\HttpFoundation\Response; |
| 13 | 14 | use Symfony\Component\HttpFoundation\StreamedResponse; |
| @@ -121,6 +122,94 @@ final class HttpConverterTest extends TestCase | ||
| 121 | 122 | self::assertSame([], $request->request->all()); |
| 122 | 123 | } |
| 123 | 124 | |
| 125 | + public function testMultipartBodyIsParsedLikePhp(): void | |
| 126 | + { | |
| 127 | + $body = implode("\r\n", [ | |
| 128 | + '--XyZ', | |
| 129 | + 'Content-Disposition: form-data; name="title"', | |
| 130 | + '', | |
| 131 | + 'Hello & welcome', | |
| 132 | + '--XyZ', | |
| 133 | + 'Content-Disposition: form-data; name="tags[]"', | |
| 134 | + '', | |
| 135 | + 'php', | |
| 136 | + '--XyZ', | |
| 137 | + 'Content-Disposition: form-data; name="doc[cv]"; filename="C:\\Users\\me\\résumé.pdf"', | |
| 138 | + 'Content-Type: application/pdf', | |
| 139 | + '', | |
| 140 | + "%PDF\x00\xff", | |
| 141 | + '--XyZ', | |
| 142 | + 'Content-Disposition: form-data; name="photos[]"; filename="a.png"', | |
| 143 | + 'Content-Type: image/png', | |
| 144 | + '', | |
| 145 | + '', | |
| 146 | + '--XyZ', | |
| 147 | + 'Content-Disposition: form-data; name="avatar"; filename=""', | |
| 148 | + 'Content-Type: application/octet-stream', | |
| 149 | + '', | |
| 150 | + '', | |
| 151 | + '--XyZ--', | |
| 152 | + '', | |
| 153 | + ]); | |
| 154 | + | |
| 155 | + $request = HttpConverter::toRequest([ | |
| 156 | + 'method' => 'POST', | |
| 157 | + 'headers' => ['Content-Type' => 'multipart/form-data; boundary=XyZ'], | |
| 158 | + 'body' => base64_encode($body), | |
| 159 | + 'isBase64Encoded' => true, | |
| 160 | + ]); | |
| 161 | + | |
| 162 | + self::assertSame(['title' => 'Hello & welcome', 'tags' => ['php']], $request->request->all()); | |
| 163 | + self::assertNull($request->files->get('avatar')); | |
| 164 | + | |
| 165 | + $docs = $request->files->get('doc'); | |
| 166 | + self::assertIsArray($docs); | |
| 167 | + $doc = $docs['cv']; | |
| 168 | + self::assertInstanceOf(UploadedFile::class, $doc); | |
| 169 | + self::assertTrue($doc->isValid()); | |
| 170 | + self::assertSame('résumé.pdf', $doc->getClientOriginalName()); | |
| 171 | + self::assertSame('application/pdf', $doc->getClientMimeType()); | |
| 172 | + self::assertSame("%PDF\x00\xff", file_get_contents($doc->getPathname())); | |
| 173 | + | |
| 174 | + $photos = $request->files->get('photos'); | |
| 175 | + self::assertIsArray($photos); | |
| 176 | + $photo = $photos[0]; | |
| 177 | + self::assertInstanceOf(UploadedFile::class, $photo); | |
| 178 | + self::assertSame(0, $photo->getSize()); | |
| 179 | + | |
| 180 | + // The file can be moved like a real upload. | |
| 181 | + $target = sys_get_temp_dir().'/scaleway-runtime-'.bin2hex(random_bytes(4)); | |
| 182 | + $moved = $doc->move($target); | |
| 183 | + self::assertSame("%PDF\x00\xff", file_get_contents($moved->getPathname())); | |
| 184 | + unlink($moved->getPathname()); | |
| 185 | + rmdir($target); | |
| 186 | + unlink($photo->getPathname()); | |
| 187 | + } | |
| 188 | + | |
| 189 | + public function testMalformedMultipartBodyIsIgnoredLikePhp(): void | |
| 190 | + { | |
| 191 | + $request = HttpConverter::toRequest([ | |
| 192 | + 'method' => 'POST', | |
| 193 | + 'headers' => ['Content-Type' => 'multipart/form-data; boundary=XyZ'], | |
| 194 | + 'body' => 'not multipart at all', | |
| 195 | + ]); | |
| 196 | + | |
| 197 | + self::assertSame([], $request->request->all()); | |
| 198 | + self::assertSame([], $request->files->all()); | |
| 199 | + self::assertSame('not multipart at all', $request->getContent()); | |
| 200 | + } | |
| 201 | + | |
| 202 | + public function testMultipartBodyIsOnlyParsedForPostLikePhp(): void | |
| 203 | + { | |
| 204 | + $request = HttpConverter::toRequest([ | |
| 205 | + 'method' => 'PUT', | |
| 206 | + 'headers' => ['Content-Type' => 'multipart/form-data; boundary=b'], | |
| 207 | + 'body' => "--b\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\n1\r\n--b--\r\n", | |
| 208 | + ]); | |
| 209 | + | |
| 210 | + self::assertSame([], $request->request->all()); | |
| 211 | + } | |
| 212 | + | |
| 124 | 213 | public function testCookiesAreParsedLikePhp(): void |
| 125 | 214 | { |
| 126 | 215 | $request = HttpConverter::toRequest(['headers' => ['Cookie' => 'session=abc%3D%3D; theme=dark;session=ignored; broken; =nameless']]); |
| @@ -8,6 +8,7 @@ use JDecool\ScalewayRuntime\HttpConverter; | |||
| 8 | use PHPUnit\Framework\TestCase; | 8 | use PHPUnit\Framework\TestCase; |
| 9 | use Symfony\Component\HttpFoundation\BinaryFileResponse; | 9 | use Symfony\Component\HttpFoundation\BinaryFileResponse; |
| 10 | use Symfony\Component\HttpFoundation\Cookie; | 10 | use Symfony\Component\HttpFoundation\Cookie; |
| 11 | +use Symfony\Component\HttpFoundation\File\UploadedFile; | ||
| 11 | use Symfony\Component\HttpFoundation\Request; | 12 | use Symfony\Component\HttpFoundation\Request; |
| 12 | use Symfony\Component\HttpFoundation\Response; | 13 | use Symfony\Component\HttpFoundation\Response; |
| 13 | use Symfony\Component\HttpFoundation\StreamedResponse; | 14 | use Symfony\Component\HttpFoundation\StreamedResponse; |
| @@ -121,6 +122,94 @@ final class HttpConverterTest extends TestCase | |||
| 121 | self::assertSame([], $request->request->all()); | 122 | self::assertSame([], $request->request->all()); |
| 122 | } | 123 | } |
| 123 | 124 | ||
| 125 | + public function testMultipartBodyIsParsedLikePhp(): void | ||
| 126 | + { | ||
| 127 | + $body = implode("\r\n", [ | ||
| 128 | + '--XyZ', | ||
| 129 | + 'Content-Disposition: form-data; name="title"', | ||
| 130 | + '', | ||
| 131 | + 'Hello & welcome', | ||
| 132 | + '--XyZ', | ||
| 133 | + 'Content-Disposition: form-data; name="tags[]"', | ||
| 134 | + '', | ||
| 135 | + 'php', | ||
| 136 | + '--XyZ', | ||
| 137 | + 'Content-Disposition: form-data; name="doc[cv]"; filename="C:\\Users\\me\\résumé.pdf"', | ||
| 138 | + 'Content-Type: application/pdf', | ||
| 139 | + '', | ||
| 140 | + "%PDF\x00\xff", | ||
| 141 | + '--XyZ', | ||
| 142 | + 'Content-Disposition: form-data; name="photos[]"; filename="a.png"', | ||
| 143 | + 'Content-Type: image/png', | ||
| 144 | + '', | ||
| 145 | + '', | ||
| 146 | + '--XyZ', | ||
| 147 | + 'Content-Disposition: form-data; name="avatar"; filename=""', | ||
| 148 | + 'Content-Type: application/octet-stream', | ||
| 149 | + '', | ||
| 150 | + '', | ||
| 151 | + '--XyZ--', | ||
| 152 | + '', | ||
| 153 | + ]); | ||
| 154 | + | ||
| 155 | + $request = HttpConverter::toRequest([ | ||
| 156 | + 'method' => 'POST', | ||
| 157 | + 'headers' => ['Content-Type' => 'multipart/form-data; boundary=XyZ'], | ||
| 158 | + 'body' => base64_encode($body), | ||
| 159 | + 'isBase64Encoded' => true, | ||
| 160 | + ]); | ||
| 161 | + | ||
| 162 | + self::assertSame(['title' => 'Hello & welcome', 'tags' => ['php']], $request->request->all()); | ||
| 163 | + self::assertNull($request->files->get('avatar')); | ||
| 164 | + | ||
| 165 | + $docs = $request->files->get('doc'); | ||
| 166 | + self::assertIsArray($docs); | ||
| 167 | + $doc = $docs['cv']; | ||
| 168 | + self::assertInstanceOf(UploadedFile::class, $doc); | ||
| 169 | + self::assertTrue($doc->isValid()); | ||
| 170 | + self::assertSame('résumé.pdf', $doc->getClientOriginalName()); | ||
| 171 | + self::assertSame('application/pdf', $doc->getClientMimeType()); | ||
| 172 | + self::assertSame("%PDF\x00\xff", file_get_contents($doc->getPathname())); | ||
| 173 | + | ||
| 174 | + $photos = $request->files->get('photos'); | ||
| 175 | + self::assertIsArray($photos); | ||
| 176 | + $photo = $photos[0]; | ||
| 177 | + self::assertInstanceOf(UploadedFile::class, $photo); | ||
| 178 | + self::assertSame(0, $photo->getSize()); | ||
| 179 | + | ||
| 180 | + // The file can be moved like a real upload. | ||
| 181 | + $target = sys_get_temp_dir().'/scaleway-runtime-'.bin2hex(random_bytes(4)); | ||
| 182 | + $moved = $doc->move($target); | ||
| 183 | + self::assertSame("%PDF\x00\xff", file_get_contents($moved->getPathname())); | ||
| 184 | + unlink($moved->getPathname()); | ||
| 185 | + rmdir($target); | ||
| 186 | + unlink($photo->getPathname()); | ||
| 187 | + } | ||
| 188 | + | ||
| 189 | + public function testMalformedMultipartBodyIsIgnoredLikePhp(): void | ||
| 190 | + { | ||
| 191 | + $request = HttpConverter::toRequest([ | ||
| 192 | + 'method' => 'POST', | ||
| 193 | + 'headers' => ['Content-Type' => 'multipart/form-data; boundary=XyZ'], | ||
| 194 | + 'body' => 'not multipart at all', | ||
| 195 | + ]); | ||
| 196 | + | ||
| 197 | + self::assertSame([], $request->request->all()); | ||
| 198 | + self::assertSame([], $request->files->all()); | ||
| 199 | + self::assertSame('not multipart at all', $request->getContent()); | ||
| 200 | + } | ||
| 201 | + | ||
| 202 | + public function testMultipartBodyIsOnlyParsedForPostLikePhp(): void | ||
| 203 | + { | ||
| 204 | + $request = HttpConverter::toRequest([ | ||
| 205 | + 'method' => 'PUT', | ||
| 206 | + 'headers' => ['Content-Type' => 'multipart/form-data; boundary=b'], | ||
| 207 | + 'body' => "--b\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\n1\r\n--b--\r\n", | ||
| 208 | + ]); | ||
| 209 | + | ||
| 210 | + self::assertSame([], $request->request->all()); | ||
| 211 | + } | ||
| 212 | + | ||
| 124 | public function testCookiesAreParsedLikePhp(): void | 213 | public function testCookiesAreParsedLikePhp(): void |
| 125 | { | 214 | { |
| 126 | $request = HttpConverter::toRequest(['headers' => ['Cookie' => 'session=abc%3D%3D; theme=dark;session=ignored; broken; =nameless']]); | 215 | $request = HttpConverter::toRequest(['headers' => ['Cookie' => 'session=abc%3D%3D; theme=dark;session=ignored; broken; =nameless']]); |
modified
tests/IntegrationTest.php +16 -0 | @@ -74,6 +74,22 @@ final class IntegrationTest extends TestCase | ||
| 74 | 74 | self::assertSame(404, $response['statusCode']); |
| 75 | 75 | } |
| 76 | 76 | |
| 77 | + public function testMultipartUploadReachesTheController(): void | |
| 78 | + { | |
| 79 | + [$response] = $this->invoke([[ | |
| 80 | + 'path' => '/upload', | |
| 81 | + 'method' => 'POST', | |
| 82 | + 'headers' => ['Content-Type' => 'multipart/form-data; boundary=b'], | |
| 83 | + 'body' => base64_encode("--b\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nReport\r\n" | |
| 84 | + ."--b\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"report.csv\"\r\nContent-Type: text/csv\r\n\r\na,b\n1,2\r\n--b--\r\n"), | |
| 85 | + 'isBase64Encoded' => true, | |
| 86 | + ]]); | |
| 87 | + | |
| 88 | + self::assertSame(200, $response['statusCode']); | |
| 89 | + self::assertSame(['title' => 'Report', 'name' => 'report.csv', 'content' => "a,b\n1,2"], $this->json($response)); | |
| 90 | + self::assertSame([], glob($this->dir.'/tmp/php*'), 'Uploaded files must be deleted after the Invocation.'); | |
| 91 | + } | |
| 92 | + | |
| 77 | 93 | public function testReadOnlyProjectUsesTheWarmedBuildDirAndATempCacheDir(): void |
| 78 | 94 | { |
| 79 | 95 | $this->invoke([['path' => '/state']]); |
| @@ -74,6 +74,22 @@ final class IntegrationTest extends TestCase | |||
| 74 | self::assertSame(404, $response['statusCode']); | 74 | self::assertSame(404, $response['statusCode']); |
| 75 | } | 75 | } |
| 76 | 76 | ||
| 77 | + public function testMultipartUploadReachesTheController(): void | ||
| 78 | + { | ||
| 79 | + [$response] = $this->invoke([[ | ||
| 80 | + 'path' => '/upload', | ||
| 81 | + 'method' => 'POST', | ||
| 82 | + 'headers' => ['Content-Type' => 'multipart/form-data; boundary=b'], | ||
| 83 | + 'body' => base64_encode("--b\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nReport\r\n" | ||
| 84 | + ."--b\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"report.csv\"\r\nContent-Type: text/csv\r\n\r\na,b\n1,2\r\n--b--\r\n"), | ||
| 85 | + 'isBase64Encoded' => true, | ||
| 86 | + ]]); | ||
| 87 | + | ||
| 88 | + self::assertSame(200, $response['statusCode']); | ||
| 89 | + self::assertSame(['title' => 'Report', 'name' => 'report.csv', 'content' => "a,b\n1,2"], $this->json($response)); | ||
| 90 | + self::assertSame([], glob($this->dir.'/tmp/php*'), 'Uploaded files must be deleted after the Invocation.'); | ||
| 91 | + } | ||
| 92 | + | ||
| 77 | public function testReadOnlyProjectUsesTheWarmedBuildDirAndATempCacheDir(): void | 93 | public function testReadOnlyProjectUsesTheWarmedBuildDirAndATempCacheDir(): void |
| 78 | { | 94 | { |
| 79 | $this->invoke([['path' => '/state']]); | 95 | $this->invoke([['path' => '/state']]); |
modified
tests/Runner/HttpKernelRunnerTest.php +17 -0 | @@ -8,6 +8,7 @@ use JDecool\ScalewayRuntime\HttpConverter; | ||
| 8 | 8 | use JDecool\ScalewayRuntime\Runner\HttpKernelRunner; |
| 9 | 9 | use JDecool\ScalewayRuntime\Tests\Fixtures\RecordingKernel; |
| 10 | 10 | use PHPUnit\Framework\TestCase; |
| 11 | +use Symfony\Component\HttpFoundation\File\UploadedFile; | |
| 11 | 12 | use Symfony\Component\HttpFoundation\Request; |
| 12 | 13 | |
| 13 | 14 | final class HttpKernelRunnerTest extends TestCase |
| @@ -66,4 +67,20 @@ final class HttpKernelRunnerTest extends TestCase | ||
| 66 | 67 | rewind($this->errorLog); |
| 67 | 68 | self::assertStringContainsString('Termination failed on purpose.', (string) stream_get_contents($this->errorLog)); |
| 68 | 69 | } |
| 70 | + | |
| 71 | + public function testUploadedFilesAreDeletedAfterTheInvocation(): void | |
| 72 | + { | |
| 73 | + $kernel = new RecordingKernel(); | |
| 74 | + | |
| 75 | + new HttpKernelRunner($kernel, $this->errorLog)->invoke([ | |
| 76 | + 'path' => '/', | |
| 77 | + 'method' => 'POST', | |
| 78 | + 'headers' => ['Content-Type' => 'multipart/form-data; boundary=b'], | |
| 79 | + 'body' => "--b\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\nhello\r\n--b--\r\n", | |
| 80 | + ], []); | |
| 81 | + | |
| 82 | + $file = $kernel->lastRequest?->files->get('doc'); | |
| 83 | + self::assertInstanceOf(UploadedFile::class, $file); | |
| 84 | + self::assertFileDoesNotExist($file->getPathname()); | |
| 85 | + } | |
| 69 | 86 | } |
| @@ -8,6 +8,7 @@ use JDecool\ScalewayRuntime\HttpConverter; | |||
| 8 | use JDecool\ScalewayRuntime\Runner\HttpKernelRunner; | 8 | use JDecool\ScalewayRuntime\Runner\HttpKernelRunner; |
| 9 | use JDecool\ScalewayRuntime\Tests\Fixtures\RecordingKernel; | 9 | use JDecool\ScalewayRuntime\Tests\Fixtures\RecordingKernel; |
| 10 | use PHPUnit\Framework\TestCase; | 10 | use PHPUnit\Framework\TestCase; |
| 11 | +use Symfony\Component\HttpFoundation\File\UploadedFile; | ||
| 11 | use Symfony\Component\HttpFoundation\Request; | 12 | use Symfony\Component\HttpFoundation\Request; |
| 12 | 13 | ||
| 13 | final class HttpKernelRunnerTest extends TestCase | 14 | final class HttpKernelRunnerTest extends TestCase |
| @@ -66,4 +67,20 @@ final class HttpKernelRunnerTest extends TestCase | |||
| 66 | rewind($this->errorLog); | 67 | rewind($this->errorLog); |
| 67 | self::assertStringContainsString('Termination failed on purpose.', (string) stream_get_contents($this->errorLog)); | 68 | self::assertStringContainsString('Termination failed on purpose.', (string) stream_get_contents($this->errorLog)); |
| 68 | } | 69 | } |
| 70 | + | ||
| 71 | + public function testUploadedFilesAreDeletedAfterTheInvocation(): void | ||
| 72 | + { | ||
| 73 | + $kernel = new RecordingKernel(); | ||
| 74 | + | ||
| 75 | + new HttpKernelRunner($kernel, $this->errorLog)->invoke([ | ||
| 76 | + 'path' => '/', | ||
| 77 | + 'method' => 'POST', | ||
| 78 | + 'headers' => ['Content-Type' => 'multipart/form-data; boundary=b'], | ||
| 79 | + 'body' => "--b\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\nhello\r\n--b--\r\n", | ||
| 80 | + ], []); | ||
| 81 | + | ||
| 82 | + $file = $kernel->lastRequest?->files->get('doc'); | ||
| 83 | + self::assertInstanceOf(UploadedFile::class, $file); | ||
| 84 | + self::assertFileDoesNotExist($file->getPathname()); | ||
| 85 | + } | ||
| 69 | } | 86 | } |