jdecool/scaleway-runtimepublic Fork
⑂ 755512e
Commits
⬇ Clone ▾
git clone https://git.rickub.com/jdecool/scaleway-runtime.git
git clone ssh://git@rickub.com/jdecool/scaleway-runtime.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

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.
Jérémy DECOOL committed 2026-11-13T22:06:42+01:00 Browse files
755512e parent: de59a71
modified composer.json +1 -0
@@ -11,6 +11,7 @@
1111 ],
1212 "require": {
1313 "php": ">=8.4",
14+ "riverline/multipart-parser": "^2.3",
1415 "symfony/http-foundation": "^7.4 || ^8.0",
1516 "symfony/http-kernel": "^7.4 || ^8.0",
1617 "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);
44
55 namespace JDecool\ScalewayRuntime;
66
7+use Riverline\MultiPartParser\StreamedPart;
8+use Symfony\Component\HttpFoundation\File\UploadedFile;
79 use Symfony\Component\HttpFoundation\Request;
810 use Symfony\Component\HttpFoundation\Response;
911
@@ -55,6 +57,7 @@ final class HttpConverter
5557 ];
5658 $cookies = [];
5759 $contentType = '';
60+ $contentTypeHeader = '';
5861 foreach (self::stringMap($event['headers'] ?? null) as $name => $value) {
5962 $key = strtoupper(str_replace('-', '_', $name));
6063 // PHP exposes these two without the HTTP_ prefix, and HeaderBag expects them that way.
@@ -62,19 +65,77 @@ final class HttpConverter
6265 if ('COOKIE' === $key) {
6366 $cookies = self::parseCookies($value);
6467 } elseif ('CONTENT_TYPE' === $key) {
68+ $contentTypeHeader = $value;
6569 $contentType = strtolower($value);
6670 }
6771 }
6872
6973 // PHP only parses form bodies into $_POST for POST; Symfony's createFromGlobals() covers the other body methods.
70- $post = [];
74+ $post = $files = [];
7175 if (\in_array($method, ['POST', 'PUT', 'DELETE', 'PATCH', 'QUERY'], true)
7276 && str_starts_with($contentType, 'application/x-www-form-urlencoded')
7377 ) {
7478 parse_str($body, $post);
79+ } elseif ('POST' === $method && str_starts_with($contentType, 'multipart/form-data')) {
80+ [$post, $files] = self::parseMultipart($contentTypeHeader, $body);
7581 }
7682
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];
78139 }
79140
80141 /**
@@ -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);
55 namespace JDecool\ScalewayRuntime\Runner;
66
77 use JDecool\ScalewayRuntime\HttpConverter;
8+use Symfony\Component\HttpFoundation\File\UploadedFile;
89 use Symfony\Component\HttpFoundation\Request;
910 use Symfony\Component\HttpKernel\HttpKernelInterface;
1011 use Symfony\Component\HttpKernel\KernelInterface;
@@ -33,20 +34,31 @@ final readonly class HttpKernelRunner implements InvocationRunner
3334 public function invoke(array $event, mixed $context): array
3435 {
3536 $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+ }
4752 }
48- }
4953
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+ }
5163 }
5264 }
@@ -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): array34 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 into45+ 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;
66
77 use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
88 use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
9+use Symfony\Component\HttpFoundation\File\UploadedFile;
910 use Symfony\Component\HttpFoundation\JsonResponse;
1011 use Symfony\Component\HttpFoundation\Request;
1112 use Symfony\Component\HttpKernel\Kernel as BaseKernel;
@@ -49,6 +50,18 @@ final class Kernel extends BaseKernel
4950 ]);
5051 }
5152
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+
5265 private function configureContainer(ContainerConfigurator $container): void
5366 {
5467 $container->extension('framework', ['secret' => 'fixture', 'http_method_override' => false]);
@@ -61,5 +74,6 @@ final class Kernel extends BaseKernel
6174 private function configureRoutes(RoutingConfigurator $routes): void
6275 {
6376 $routes->add('state', '/state')->controller('kernel::state');
77+ $routes->add('upload', '/upload')->controller('kernel::upload');
6478 }
6579 }
@@ -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): void65 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): void74 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
1717
1818 public int $handled = 0;
1919 public int $terminated = 0;
20+ public ?Request $lastRequest = null;
2021
2122 public static function build(): self
2223 {
@@ -38,6 +39,7 @@ final class RecordingKernel implements HttpKernelInterface, TerminableInterface
3839
3940 public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = true): Response
4041 {
42+ $this->lastRequest = $request;
4143 if ('/throw' === $request->getPathInfo()) {
4244 throw new \LogicException('Escaped on purpose.');
4345 }
@@ -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(): self22 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): Response40 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;
88 use PHPUnit\Framework\TestCase;
99 use Symfony\Component\HttpFoundation\BinaryFileResponse;
1010 use Symfony\Component\HttpFoundation\Cookie;
11+use Symfony\Component\HttpFoundation\File\UploadedFile;
1112 use Symfony\Component\HttpFoundation\Request;
1213 use Symfony\Component\HttpFoundation\Response;
1314 use Symfony\Component\HttpFoundation\StreamedResponse;
@@ -121,6 +122,94 @@ final class HttpConverterTest extends TestCase
121122 self::assertSame([], $request->request->all());
122123 }
123124
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+
124213 public function testCookiesAreParsedLikePhp(): void
125214 {
126215 $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(): void213 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
7474 self::assertSame(404, $response['statusCode']);
7575 }
7676
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+
7793 public function testReadOnlyProjectUsesTheWarmedBuildDirAndATempCacheDir(): void
7894 {
7995 $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(): void93 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;
88 use JDecool\ScalewayRuntime\Runner\HttpKernelRunner;
99 use JDecool\ScalewayRuntime\Tests\Fixtures\RecordingKernel;
1010 use PHPUnit\Framework\TestCase;
11+use Symfony\Component\HttpFoundation\File\UploadedFile;
1112 use Symfony\Component\HttpFoundation\Request;
1213
1314 final class HttpKernelRunnerTest extends TestCase
@@ -66,4 +67,20 @@ final class HttpKernelRunnerTest extends TestCase
6667 rewind($this->errorLog);
6768 self::assertStringContainsString('Termination failed on purpose.', (string) stream_get_contents($this->errorLog));
6869 }
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+ }
6986 }
@@ -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 TestCase14 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 }