jdecool/scaleway-runtimepublic Fork
⑂ 2352980
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: trust only the headers Scaleway overwrites, and take the host from an optionUnverified

The probe showed that clients can forge X-Forwarded-Host, X-Forwarded-Port
and Forwarded, prepend to X-Forwarded-For, and that no Host header reaches
the function. The Request now gets its client from X-Real-Ip, its scheme
from X-Forwarded-Proto and its host from the new "host" runtime option
(SCALEWAY_HOST, localhost by default), without trusting any proxy.
Jérémy DECOOL committed 2026-11-14T11:53:02+01:00 Browse files
2352980 parent: 8215677
added docs/adr/0007-trust-only-headers-the-platform-overwrites.md +18 -0
new file mode 100644
@@ -0,0 +1,18 @@
1+# The Request trusts only the headers the platform overwrites
2+
3+The probe showed that Scaleway overwrites `X-Real-Ip` and `X-Forwarded-Proto` on every HTTP call, but passes `X-Forwarded-Host`, `X-Forwarded-Port` and `Forwarded` through from the client, prepends the client's `X-Forwarded-For` to its own, and drops the `Host` header.
4+Trusting a proxy for the usual `X-Forwarded-*` set, as the runtime did, let any client choose `getClientIp()` and the host of absolute URLs.
5+We therefore trust no proxy: the Request gets `REMOTE_ADDR` from `X-Real-Ip` (`127.0.0.1` when absent, as for CRON Invocations), `HTTPS` and the default port from `X-Forwarded-Proto`, and its host from the `host` runtime option (`SCALEWAY_HOST`, `localhost` by default), whatever Host the Event carries.
6+The forgeable headers still reach the Application as plain headers, and trusted proxies an application configures itself keep applying, as Symfony does.
7+
8+## Considered Options
9+
10+- Trusting `127.0.0.1` for `X-Forwarded-Proto` only: rejected, `REMOTE_ADDR` must hold the client for `getClientIp()` to need no trusted header at all, and the proxy would then never match it.
11+- Taking the client from `X-Envoy-External-Address`: equivalent, `X-Real-Ip` is the conventional name.
12+- Taking the host from the function's own domain: impossible, nothing in the Event or the environment carries it.
13+
14+## Consequences
15+
16+- Absolute URLs (router, redirects to absolute URLs, signed URLs) are only correct once `host` is set; Terraform cannot pass a function its own `domain_name` (the reference would be a cycle), so set it from a custom domain or after a first deploy.
17+- `X-Real-Ip` and `X-Forwarded-Proto` are undocumented platform behaviour, measured once; a change of the platform would need a new probe.
18+- An application configuring `framework.trusted_proxies` against `REMOTE_ADDR` or private ranges trusts forgeable headers again.
new file mode 100644
@@ -0,0 +1,18 @@
1+# The Request trusts only the headers the platform overwrites
2+
3+The probe showed that Scaleway overwrites `X-Real-Ip` and `X-Forwarded-Proto` on every HTTP call, but passes `X-Forwarded-Host`, `X-Forwarded-Port` and `Forwarded` through from the client, prepends the client's `X-Forwarded-For` to its own, and drops the `Host` header.
4+Trusting a proxy for the usual `X-Forwarded-*` set, as the runtime did, let any client choose `getClientIp()` and the host of absolute URLs.
5+We therefore trust no proxy: the Request gets `REMOTE_ADDR` from `X-Real-Ip` (`127.0.0.1` when absent, as for CRON Invocations), `HTTPS` and the default port from `X-Forwarded-Proto`, and its host from the `host` runtime option (`SCALEWAY_HOST`, `localhost` by default), whatever Host the Event carries.
6+The forgeable headers still reach the Application as plain headers, and trusted proxies an application configures itself keep applying, as Symfony does.
7+
8+## Considered Options
9+
10+- Trusting `127.0.0.1` for `X-Forwarded-Proto` only: rejected, `REMOTE_ADDR` must hold the client for `getClientIp()` to need no trusted header at all, and the proxy would then never match it.
11+- Taking the client from `X-Envoy-External-Address`: equivalent, `X-Real-Ip` is the conventional name.
12+- Taking the host from the function's own domain: impossible, nothing in the Event or the environment carries it.
13+
14+## Consequences
15+
16+- Absolute URLs (router, redirects to absolute URLs, signed URLs) are only correct once `host` is set; Terraform cannot pass a function its own `domain_name` (the reference would be a cycle), so set it from a custom domain or after a first deploy.
17+- `X-Real-Ip` and `X-Forwarded-Proto` are undocumented platform behaviour, measured once; a change of the platform would need a new probe.
18+- An application configuring `framework.trusted_proxies` against `REMOTE_ADDR` or private ranges trusts forgeable headers again.
modified src/HttpConverter.php +15 -15
@@ -17,22 +17,20 @@ use Symfony\Component\HttpFoundation\Response;
1717 final class HttpConverter
1818 {
1919 /**
20- * The address the Request sees as its peer: Scaleway always fronts the function,
21- * so the peer is the platform proxy and the client comes from X-Forwarded-For.
20+ * The client address of Events without X-Real-Ip, which only CRON Invocations lack: they come from the platform itself.
2221 */
2322 public const string PROXY_ADDRESS = '127.0.0.1';
2423
25- public const int TRUSTED_HEADERS = Request::HEADER_X_FORWARDED_FOR
26- | Request::HEADER_X_FORWARDED_HOST
27- | Request::HEADER_X_FORWARDED_PORT
28- | Request::HEADER_X_FORWARDED_PROTO;
29-
3024 /**
25+ * The client, scheme and host come only from what the platform sets itself, as clients can forge the other
26+ * forwarding headers: no proxy is trusted (see docs/adr/0007-trust-only-headers-the-platform-overwrites.md).
27+ *
3128 * @param array<mixed> $event
29+ * @param string $host the public host of the function, as no Host header reaches it
3230 */
33- public static function toRequest(array $event): Request
31+ public static function toRequest(array $event, string $host = 'localhost'): Request
3432 {
35- $method = strtoupper(self::string($event['method'] ?? $event['httpMethod'] ?? null) ?? 'GET');
33+ $method = strtoupper(self::string($event['httpMethod'] ?? $event['method'] ?? null) ?? 'GET');
3634 $path = '/'.ltrim(self::string($event['path'] ?? null) ?? '', '/');
3735 // An explicit separator, as arg_separator.output may be "&amp;".
3836 $queryString = http_build_query(self::stringMap($event['queryStringParameters'] ?? null), '', '&');
@@ -51,7 +49,6 @@ final class HttpConverter
5149 'REQUEST_URI' => '' === $queryString ? $path : $path.'?'.$queryString,
5250 'QUERY_STRING' => $queryString,
5351 'SERVER_PROTOCOL' => 'HTTP/1.1',
54- 'REMOTE_ADDR' => self::PROXY_ADDRESS,
5552 'REQUEST_TIME' => time(),
5653 'REQUEST_TIME_FLOAT' => microtime(true),
5754 ];
@@ -69,11 +66,14 @@ final class HttpConverter
6966 $contentType = strtolower($value);
7067 }
7168 }
72- // Events need not carry a Host (CRON ones may not), and without one the Request's URI would be "http://:/";
73- // Request::create() falls back to the same default.
74- if ('' === ($server['HTTP_HOST'] ?? '')) {
75- $server['HTTP_HOST'] = 'localhost';
76- }
69+ // The platform overwrites X-Real-Ip and X-Forwarded-Proto on every HTTP call, whatever the client sends.
70+ $server['REMOTE_ADDR'] = filter_var($server['HTTP_X_REAL_IP'] ?? '', \FILTER_VALIDATE_IP) ?: self::PROXY_ADDRESS;
71+ $proto = $server['HTTP_X_FORWARDED_PROTO'] ?? null;
72+ $secure = \is_string($proto) && 'https' === strtolower($proto);
73+ $server['HTTPS'] = $secure ? 'on' : 'off';
74+ $server['SERVER_PORT'] = $secure ? 443 : 80;
75+ // The platform drops the client's Host, and an Event carrying one cannot come from it.
76+ $server['HTTP_HOST'] = '' === $host ? 'localhost' : $host;
7777
7878 // PHP only parses form bodies into $_POST for POST; Symfony's createFromGlobals() covers the other body methods.
7979 $post = $files = [];
@@ -17,22 +17,20 @@ use Symfony\Component\HttpFoundation\Response;
17 final class HttpConverter17 final class HttpConverter
18 {18 {
19 /**19 /**
20- * The address the Request sees as its peer: Scaleway always fronts the function,20+ * The client address of Events without X-Real-Ip, which only CRON Invocations lack: they come from the platform itself.
21- * so the peer is the platform proxy and the client comes from X-Forwarded-For.
22 */21 */
23 public const string PROXY_ADDRESS = '127.0.0.1';22 public const string PROXY_ADDRESS = '127.0.0.1';
24 23
25- public const int TRUSTED_HEADERS = Request::HEADER_X_FORWARDED_FOR
26- | Request::HEADER_X_FORWARDED_HOST
27- | Request::HEADER_X_FORWARDED_PORT
28- | Request::HEADER_X_FORWARDED_PROTO;
29-
30 /**24 /**
25+ * The client, scheme and host come only from what the platform sets itself, as clients can forge the other
26+ * forwarding headers: no proxy is trusted (see docs/adr/0007-trust-only-headers-the-platform-overwrites.md).
27+ *
31 * @param array<mixed> $event28 * @param array<mixed> $event
29+ * @param string $host the public host of the function, as no Host header reaches it
32 */30 */
33- public static function toRequest(array $event): Request31+ public static function toRequest(array $event, string $host = 'localhost'): Request
34 {32 {
35- $method = strtoupper(self::string($event['method'] ?? $event['httpMethod'] ?? null) ?? 'GET');33+ $method = strtoupper(self::string($event['httpMethod'] ?? $event['method'] ?? null) ?? 'GET');
36 $path = '/'.ltrim(self::string($event['path'] ?? null) ?? '', '/');34 $path = '/'.ltrim(self::string($event['path'] ?? null) ?? '', '/');
37 // An explicit separator, as arg_separator.output may be "&amp;".35 // An explicit separator, as arg_separator.output may be "&amp;".
38 $queryString = http_build_query(self::stringMap($event['queryStringParameters'] ?? null), '', '&');36 $queryString = http_build_query(self::stringMap($event['queryStringParameters'] ?? null), '', '&');
@@ -51,7 +49,6 @@ final class HttpConverter
51 'REQUEST_URI' => '' === $queryString ? $path : $path.'?'.$queryString,49 'REQUEST_URI' => '' === $queryString ? $path : $path.'?'.$queryString,
52 'QUERY_STRING' => $queryString,50 'QUERY_STRING' => $queryString,
53 'SERVER_PROTOCOL' => 'HTTP/1.1',51 'SERVER_PROTOCOL' => 'HTTP/1.1',
54- 'REMOTE_ADDR' => self::PROXY_ADDRESS,
55 'REQUEST_TIME' => time(),52 'REQUEST_TIME' => time(),
56 'REQUEST_TIME_FLOAT' => microtime(true),53 'REQUEST_TIME_FLOAT' => microtime(true),
57 ];54 ];
@@ -69,11 +66,14 @@ final class HttpConverter
69 $contentType = strtolower($value);66 $contentType = strtolower($value);
70 }67 }
71 }68 }
72- // Events need not carry a Host (CRON ones may not), and without one the Request's URI would be "http://:/";69+ // The platform overwrites X-Real-Ip and X-Forwarded-Proto on every HTTP call, whatever the client sends.
73- // Request::create() falls back to the same default.70+ $server['REMOTE_ADDR'] = filter_var($server['HTTP_X_REAL_IP'] ?? '', \FILTER_VALIDATE_IP) ?: self::PROXY_ADDRESS;
74- if ('' === ($server['HTTP_HOST'] ?? '')) {71+ $proto = $server['HTTP_X_FORWARDED_PROTO'] ?? null;
75- $server['HTTP_HOST'] = 'localhost';72+ $secure = \is_string($proto) && 'https' === strtolower($proto);
76- }73+ $server['HTTPS'] = $secure ? 'on' : 'off';
74+ $server['SERVER_PORT'] = $secure ? 443 : 80;
75+ // The platform drops the client's Host, and an Event carrying one cannot come from it.
76+ $server['HTTP_HOST'] = '' === $host ? 'localhost' : $host;
77 77
78 // PHP only parses form bodies into $_POST for POST; Symfony's createFromGlobals() covers the other body methods.78 // PHP only parses form bodies into $_POST for POST; Symfony's createFromGlobals() covers the other body methods.
79 $post = $files = [];79 $post = $files = [];
modified src/Runner/HttpKernelRunner.php +3 -7
@@ -6,7 +6,6 @@ namespace JDecool\ScalewayRuntime\Runner;
66
77 use JDecool\ScalewayRuntime\HttpConverter;
88 use Symfony\Component\HttpFoundation\File\UploadedFile;
9-use Symfony\Component\HttpFoundation\Request;
109 use Symfony\Component\HttpKernel\HttpKernelInterface;
1110 use Symfony\Component\HttpKernel\KernelInterface;
1211 use Symfony\Component\HttpKernel\TerminableInterface;
@@ -15,25 +14,22 @@ final readonly class HttpKernelRunner implements InvocationRunner
1514 {
1615 /**
1716 * @param resource $errorLog
17+ * @param string $host the public host of the function
1818 */
1919 public function __construct(
2020 private HttpKernelInterface $kernel,
2121 private mixed $errorLog,
22+ private string $host = 'localhost',
2223 ) {
2324 // Booting here makes a broken container a boot failure, so the Handler retries with a fresh Application.
2425 if ($kernel instanceof KernelInterface) {
2526 $kernel->boot();
2627 }
27-
28- // The Kernel applies the app's own trusted_proxies while booting; only fill the gap when it set none.
29- if ([] === Request::getTrustedProxies()) {
30- Request::setTrustedProxies([HttpConverter::PROXY_ADDRESS], HttpConverter::TRUSTED_HEADERS);
31- }
3228 }
3329
3430 public function invoke(array $event, mixed $context): array
3531 {
36- $request = HttpConverter::toRequest($event);
32+ $request = HttpConverter::toRequest($event, $this->host);
3733 // Captured before the Application can alter the bag, so every temp file gets deleted.
3834 $uploads = $request->files->all();
3935 try {
@@ -6,7 +6,6 @@ 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\File\UploadedFile;
9-use Symfony\Component\HttpFoundation\Request;
10 use Symfony\Component\HttpKernel\HttpKernelInterface;9 use Symfony\Component\HttpKernel\HttpKernelInterface;
11 use Symfony\Component\HttpKernel\KernelInterface;10 use Symfony\Component\HttpKernel\KernelInterface;
12 use Symfony\Component\HttpKernel\TerminableInterface;11 use Symfony\Component\HttpKernel\TerminableInterface;
@@ -15,25 +14,22 @@ final readonly class HttpKernelRunner implements InvocationRunner
15 {14 {
16 /**15 /**
17 * @param resource $errorLog16 * @param resource $errorLog
17+ * @param string $host the public host of the function
18 */18 */
19 public function __construct(19 public function __construct(
20 private HttpKernelInterface $kernel,20 private HttpKernelInterface $kernel,
21 private mixed $errorLog,21 private mixed $errorLog,
22+ private string $host = 'localhost',
22 ) {23 ) {
23 // Booting here makes a broken container a boot failure, so the Handler retries with a fresh Application.24 // Booting here makes a broken container a boot failure, so the Handler retries with a fresh Application.
24 if ($kernel instanceof KernelInterface) {25 if ($kernel instanceof KernelInterface) {
25 $kernel->boot();26 $kernel->boot();
26 }27 }
27-
28- // The Kernel applies the app's own trusted_proxies while booting; only fill the gap when it set none.
29- if ([] === Request::getTrustedProxies()) {
30- Request::setTrustedProxies([HttpConverter::PROXY_ADDRESS], HttpConverter::TRUSTED_HEADERS);
31- }
32 }28 }
33 29
34 public function invoke(array $event, mixed $context): array30 public function invoke(array $event, mixed $context): array
35 {31 {
36- $request = HttpConverter::toRequest($event);32+ $request = HttpConverter::toRequest($event, $this->host);
37 // Captured before the Application can alter the bag, so every temp file gets deleted.33 // Captured before the Application can alter the bag, so every temp file gets deleted.
38 $uploads = $request->files->all();34 $uploads = $request->files->all();
39 try {35 try {
modified src/ScalewayRuntime.php +17 -3
@@ -24,7 +24,9 @@ use Symfony\Component\Runtime\SymfonyRuntime;
2424 * Runs Symfony Applications on Scaleway Serverless Functions.
2525 *
2626 * On top of the options managed by SymfonyRuntime, it accepts:
27- * - "front_controller": the Front Controller path, relative to "project_dir"; defaults to "public/index.php".
27+ * - "front_controller": the Front Controller path, relative to "project_dir"; defaults to "public/index.php";
28+ * - "host": the public host of the function, as no Host header reaches it; defaults to the SCALEWAY_HOST
29+ * environment variable, then to "localhost".
2830 *
2931 * Unlike SymfonyRuntime, it defaults the env to prod when the process environment sets none, whatever .env files say.
3032 *
@@ -44,11 +46,13 @@ use Symfony\Component\Runtime\SymfonyRuntime;
4446 */
4547 class ScalewayRuntime extends SymfonyRuntime
4648 {
49+ public const string HOST_VAR = 'SCALEWAY_HOST';
50+
4751 /** The Request of the Invocation the Front Controller closure is being called for. */
4852 private ?Request $request = null;
4953
5054 /**
51- * @param array<mixed> $options see SymfonyRuntime, plus "front_controller"
55+ * @param array<mixed> $options see SymfonyRuntime, plus "front_controller" and "host"
5256 */
5357 public function __construct(array $options = [])
5458 {
@@ -63,6 +67,9 @@ class ScalewayRuntime extends SymfonyRuntime
6367 // FrameworkBundle would otherwise render error pages with its CLI renderer, which dumps the exception even in prod.
6468 $_SERVER['APP_RUNTIME_MODE'] ??= 'web=1&worker=1';
6569
70+ // Read after Dotenv ran, so .env files may set it like any other variable.
71+ $this->options['host'] ??= ($_SERVER[self::HOST_VAR] ?? null) ?: ($_ENV[self::HOST_VAR] ?? null) ?: getenv(self::HOST_VAR) ?: 'localhost';
72+
6673 $projectDir = $this->options['project_dir'] ?? null;
6774 if (\is_string($projectDir) && !is_writable(is_dir($projectDir.'/var') ? $projectDir.'/var' : $projectDir)) {
6875 // Kernels using MicroKernelTrait read these from $_SERVER only; values set by the app win.
@@ -168,7 +175,14 @@ class ScalewayRuntime extends SymfonyRuntime
168175 }
169176
170177 return new FrameworkApplication($kernel);
171- }, new HttpKernelRunner($kernel, $errorLog), $errorLog);
178+ }, new HttpKernelRunner($kernel, $errorLog, $this->host()), $errorLog);
179+ }
180+
181+ private function host(): string
182+ {
183+ $host = $this->options['host'] ?? null;
184+
185+ return \is_string($host) ? $host : throw new \LogicException('The "host" runtime option must be a string.');
172186 }
173187
174188 protected function getArgument(\ReflectionParameter $parameter, ?string $type): mixed
@@ -24,7 +24,9 @@ use Symfony\Component\Runtime\SymfonyRuntime;
24 * Runs Symfony Applications on Scaleway Serverless Functions.24 * Runs Symfony Applications on Scaleway Serverless Functions.
25 *25 *
26 * On top of the options managed by SymfonyRuntime, it accepts:26 * On top of the options managed by SymfonyRuntime, it accepts:
27- * - "front_controller": the Front Controller path, relative to "project_dir"; defaults to "public/index.php".27+ * - "front_controller": the Front Controller path, relative to "project_dir"; defaults to "public/index.php";
28+ * - "host": the public host of the function, as no Host header reaches it; defaults to the SCALEWAY_HOST
29+ * environment variable, then to "localhost".
28 *30 *
29 * Unlike SymfonyRuntime, it defaults the env to prod when the process environment sets none, whatever .env files say.31 * Unlike SymfonyRuntime, it defaults the env to prod when the process environment sets none, whatever .env files say.
30 *32 *
@@ -44,11 +46,13 @@ use Symfony\Component\Runtime\SymfonyRuntime;
44 */46 */
45 class ScalewayRuntime extends SymfonyRuntime47 class ScalewayRuntime extends SymfonyRuntime
46 {48 {
49+ public const string HOST_VAR = 'SCALEWAY_HOST';
50+
47 /** The Request of the Invocation the Front Controller closure is being called for. */51 /** The Request of the Invocation the Front Controller closure is being called for. */
48 private ?Request $request = null;52 private ?Request $request = null;
49 53
50 /**54 /**
51- * @param array<mixed> $options see SymfonyRuntime, plus "front_controller"55+ * @param array<mixed> $options see SymfonyRuntime, plus "front_controller" and "host"
52 */56 */
53 public function __construct(array $options = [])57 public function __construct(array $options = [])
54 {58 {
@@ -63,6 +67,9 @@ class ScalewayRuntime extends SymfonyRuntime
63 // FrameworkBundle would otherwise render error pages with its CLI renderer, which dumps the exception even in prod.67 // FrameworkBundle would otherwise render error pages with its CLI renderer, which dumps the exception even in prod.
64 $_SERVER['APP_RUNTIME_MODE'] ??= 'web=1&worker=1';68 $_SERVER['APP_RUNTIME_MODE'] ??= 'web=1&worker=1';
65 69
70+ // Read after Dotenv ran, so .env files may set it like any other variable.
71+ $this->options['host'] ??= ($_SERVER[self::HOST_VAR] ?? null) ?: ($_ENV[self::HOST_VAR] ?? null) ?: getenv(self::HOST_VAR) ?: 'localhost';
72+
66 $projectDir = $this->options['project_dir'] ?? null;73 $projectDir = $this->options['project_dir'] ?? null;
67 if (\is_string($projectDir) && !is_writable(is_dir($projectDir.'/var') ? $projectDir.'/var' : $projectDir)) {74 if (\is_string($projectDir) && !is_writable(is_dir($projectDir.'/var') ? $projectDir.'/var' : $projectDir)) {
68 // Kernels using MicroKernelTrait read these from $_SERVER only; values set by the app win.75 // Kernels using MicroKernelTrait read these from $_SERVER only; values set by the app win.
@@ -168,7 +175,14 @@ class ScalewayRuntime extends SymfonyRuntime
168 }175 }
169 176
170 return new FrameworkApplication($kernel);177 return new FrameworkApplication($kernel);
171- }, new HttpKernelRunner($kernel, $errorLog), $errorLog);178+ }, new HttpKernelRunner($kernel, $errorLog, $this->host()), $errorLog);
179+ }
180+
181+ private function host(): string
182+ {
183+ $host = $this->options['host'] ?? null;
184+
185+ return \is_string($host) ? $host : throw new \LogicException('The "host" runtime option must be a string.');
172 }186 }
173 187
174 protected function getArgument(\ReflectionParameter $parameter, ?string $type): mixed188 protected function getArgument(\ReflectionParameter $parameter, ?string $type): mixed
modified tests/EmulatorTest.php +0 -1
@@ -50,6 +50,5 @@ final class EmulatorTest extends TestCase
5050
5151 self::assertSame('/search', $request->getPathInfo());
5252 self::assertSame(['q' => 'café', 'page' => ['size' => '10']], $request->query->all());
53- self::assertSame('example.test', $request->getHost());
5453 }
5554 }
@@ -50,6 +50,5 @@ final class EmulatorTest extends TestCase
50 50
51 self::assertSame('/search', $request->getPathInfo());51 self::assertSame('/search', $request->getPathInfo());
52 self::assertSame(['q' => 'café', 'page' => ['size' => '10']], $request->query->all());52 self::assertSame(['q' => 'café', 'page' => ['size' => '10']], $request->query->all());
53- self::assertSame('example.test', $request->getHost());
54 }53 }
55 }54 }
modified tests/HandlerTest.php +18 -1
@@ -118,13 +118,30 @@ final class HandlerTest extends TestCase
118118 {
119119 $handler = $this->handler(['front_controller' => 'front-controllers/request-response.php']);
120120
121- $first = $handler->invoke(['queryStringParameters' => ['name' => 'Ada'], 'headers' => ['X-Forwarded-For' => '203.0.113.7']], []);
121+ $first = $handler->invoke(['queryStringParameters' => ['name' => 'Ada'], 'headers' => ['X-Real-Ip' => '203.0.113.7']], []);
122122 $second = $handler->invoke(['queryStringParameters' => ['name' => 'Grace']], []);
123123
124124 self::assertSame('Hello Ada from 203.0.113.7', $first['body']);
125125 self::assertSame('Hello Grace from 127.0.0.1', $second['body']);
126126 }
127127
128+ public function testHostOptionIsTheHostOfEveryRequest(): void
129+ {
130+ $handler = $this->handler(['front_controller' => 'front-controllers/recording.php', 'host' => 'app.example.com']);
131+ $handler->invoke(['path' => '/', 'headers' => ['X-Forwarded-Proto' => 'https', 'Host' => 'spoofed.example']], []);
132+
133+ self::assertSame('https://app.example.com/', RecordingKernel::$last?->lastRequest?->getUri());
134+ }
135+
136+ public function testHostDefaultsToTheScalewayHostVariable(): void
137+ {
138+ $_SERVER['SCALEWAY_HOST'] = 'fn.example.com';
139+ $handler = $this->handler(['front_controller' => 'front-controllers/recording.php']);
140+ $handler->invoke(['path' => '/'], []);
141+
142+ self::assertSame('fn.example.com', RecordingKernel::$last?->lastRequest?->getHost());
143+ }
144+
128145 public function testResponseFrontControllerReturningSomethingElseFailsTheInvocation(): void
129146 {
130147 $handler = $this->handler(['front_controller' => 'front-controllers/request-response.php', 'debug' => false]);
@@ -118,13 +118,30 @@ final class HandlerTest extends TestCase
118 {118 {
119 $handler = $this->handler(['front_controller' => 'front-controllers/request-response.php']);119 $handler = $this->handler(['front_controller' => 'front-controllers/request-response.php']);
120 120
121- $first = $handler->invoke(['queryStringParameters' => ['name' => 'Ada'], 'headers' => ['X-Forwarded-For' => '203.0.113.7']], []);121+ $first = $handler->invoke(['queryStringParameters' => ['name' => 'Ada'], 'headers' => ['X-Real-Ip' => '203.0.113.7']], []);
122 $second = $handler->invoke(['queryStringParameters' => ['name' => 'Grace']], []);122 $second = $handler->invoke(['queryStringParameters' => ['name' => 'Grace']], []);
123 123
124 self::assertSame('Hello Ada from 203.0.113.7', $first['body']);124 self::assertSame('Hello Ada from 203.0.113.7', $first['body']);
125 self::assertSame('Hello Grace from 127.0.0.1', $second['body']);125 self::assertSame('Hello Grace from 127.0.0.1', $second['body']);
126 }126 }
127 127
128+ public function testHostOptionIsTheHostOfEveryRequest(): void
129+ {
130+ $handler = $this->handler(['front_controller' => 'front-controllers/recording.php', 'host' => 'app.example.com']);
131+ $handler->invoke(['path' => '/', 'headers' => ['X-Forwarded-Proto' => 'https', 'Host' => 'spoofed.example']], []);
132+
133+ self::assertSame('https://app.example.com/', RecordingKernel::$last?->lastRequest?->getUri());
134+ }
135+
136+ public function testHostDefaultsToTheScalewayHostVariable(): void
137+ {
138+ $_SERVER['SCALEWAY_HOST'] = 'fn.example.com';
139+ $handler = $this->handler(['front_controller' => 'front-controllers/recording.php']);
140+ $handler->invoke(['path' => '/'], []);
141+
142+ self::assertSame('fn.example.com', RecordingKernel::$last?->lastRequest?->getHost());
143+ }
144+
128 public function testResponseFrontControllerReturningSomethingElseFailsTheInvocation(): void145 public function testResponseFrontControllerReturningSomethingElseFailsTheInvocation(): void
129 {146 {
130 $handler = $this->handler(['front_controller' => 'front-controllers/request-response.php', 'debug' => false]);147 $handler = $this->handler(['front_controller' => 'front-controllers/request-response.php', 'debug' => false]);
modified tests/HttpConverterTest.php +105 -23
@@ -15,6 +15,51 @@ use Symfony\Component\HttpFoundation\StreamedResponse;
1515
1616 final class HttpConverterTest extends TestCase
1717 {
18+ /** An HTTP Event as measured on Scaleway (docs/probe-results.md), GET without a body. */
19+ private const array PLATFORM_EVENT = [
20+ 'resource' => '/some/path',
21+ 'path' => '/some/path',
22+ 'httpMethod' => 'GET',
23+ 'headers' => [
24+ 'Accept' => '*/*',
25+ 'Forwarded' => 'for="[2001:db8::1]";proto=https, for=100.96.1.187',
26+ 'K-Proxy-Request' => 'activator',
27+ 'User-Agent' => 'curl/8.7.1',
28+ 'X-Custom' => 'hello',
29+ 'X-Envoy-External-Address' => '2001:db8::1',
30+ 'X-Forwarded-For' => '2001:db8::1, 100.96.1.187, 100.96.38.33',
31+ 'X-Forwarded-Proto' => 'https',
32+ 'X-Real-Ip' => '2001:db8::1',
33+ 'X-Request-Id' => '6f1c1e0a-3b4e-4f7a-9a52-0d1f3e6c2b11',
34+ ],
35+ 'multiValueHeaders' => null,
36+ 'queryStringParameters' => ['single' => '1', 'repeated' => 'b', 'list[]' => 'y'],
37+ 'multiValueQueryStringParameters' => null,
38+ 'pathParameters' => null,
39+ 'stageVariables' => [],
40+ 'requestContext' => ['httpMethod' => 'GET'],
41+ 'body' => '',
42+ 'isBase64Encoded' => true,
43+ ];
44+
45+ /** A CRON Event as measured on Scaleway (docs/probe-results.md). */
46+ private const array CRON_EVENT = [
47+ 'path' => '/',
48+ 'httpMethod' => 'POST',
49+ 'headers' => [
50+ 'Content-Length' => '40',
51+ 'Content-Type' => 'application/json',
52+ 'Forwarded' => 'for=100.96.2.180;proto=http',
53+ 'K-Proxy-Request' => 'activator',
54+ 'User-Agent' => 'Go-http-client/1.1',
55+ 'X-Forwarded-For' => '100.96.2.180, 100.96.36.219',
56+ 'X-Forwarded-Proto' => 'http',
57+ 'X-Request-Id' => '0b8e4a52-7c1d-4e0f-8a3b-5d6c7e8f9a01',
58+ ],
59+ 'queryStringParameters' => [],
60+ 'body' => '{"probe":"cron","nested":{"list":[1,2]}}',
61+ ];
62+
1863 protected function tearDown(): void
1964 {
2065 Request::setTrustedProxies([], 0);
@@ -26,10 +71,10 @@ final class HttpConverterTest extends TestCase
2671 'path' => '/blog/post',
2772 'method' => 'put',
2873 'queryStringParameters' => ['page' => '2', 'q' => 'a b&c'],
29- 'headers' => ['Content-Type' => 'application/json', 'Content-Length' => '13', 'X-Custom-Header' => 'yes', 'Host' => 'example.com'],
74+ 'headers' => ['Content-Type' => 'application/json', 'Content-Length' => '13', 'X-Custom-Header' => 'yes'],
3075 'body' => '{"ok": true}',
3176 'isBase64Encoded' => false,
32- ]);
77+ ], 'example.com');
3378
3479 self::assertSame('PUT', $request->getMethod());
3580 self::assertSame('/blog/post', $request->getPathInfo());
@@ -238,42 +283,79 @@ final class HttpConverterTest extends TestCase
238283 self::assertSame('text/html, application/json', $request->headers->get('Accept'));
239284 }
240285
241- public function testForwardedHeadersApplyOnceTheProxyIsTrusted(): void
286+ public function testClientAndSchemeComeFromTheHeadersThePlatformOverwrites(): void
242287 {
243- Request::setTrustedProxies([HttpConverter::PROXY_ADDRESS], HttpConverter::TRUSTED_HEADERS);
244-
245- $request = HttpConverter::toRequest([
246- 'path' => '/',
247- 'headers' => [
248- 'Host' => 'internal.local',
249- 'X-Forwarded-For' => '203.0.113.7',
250- 'X-Forwarded-Host' => 'app.example.com',
251- 'X-Forwarded-Proto' => 'https',
252- 'X-Forwarded-Port' => '443',
253- ],
254- ]);
288+ $request = HttpConverter::toRequest(self::PLATFORM_EVENT);
255289
290+ self::assertSame('2001:db8::1', $request->getClientIp());
256291 self::assertTrue($request->isSecure());
292+ self::assertSame(443, $request->getPort());
293+ self::assertSame('https://localhost/some/path?list%5B0%5D=y&repeated=b&single=1', $request->getUri());
294+ }
295+
296+ public function testClientForgeableForwardingHeadersAreIgnored(): void
297+ {
298+ $request = HttpConverter::toRequest(['headers' => [
299+ 'X-Real-Ip' => '2001:db8::1',
300+ 'X-Forwarded-For' => '203.0.113.66,2001:db8::1, 100.96.2.180',
301+ 'X-Forwarded-Host' => 'spoofed.example',
302+ 'X-Forwarded-Port' => '1234',
303+ 'Forwarded' => 'for=203.0.113.66;host=spoofed.example',
304+ 'Host' => 'spoofed.example',
305+ 'X-Forwarded-Proto' => 'http',
306+ ]], 'app.example.com');
307+
308+ self::assertSame('2001:db8::1', $request->getClientIp());
309+ self::assertSame('http://app.example.com/', $request->getUri());
310+ self::assertSame(80, $request->getPort());
311+ self::assertSame([], Request::getTrustedProxies());
312+ }
313+
314+ public function testTrustedProxiesConfiguredByTheAppStillApply(): void
315+ {
316+ Request::setTrustedProxies(['2001:db8::1'], Request::HEADER_X_FORWARDED_HOST);
317+
318+ $request = HttpConverter::toRequest(['headers' => ['X-Real-Ip' => '2001:db8::1', 'X-Forwarded-Host' => 'app.example.com']]);
319+
257320 self::assertSame('app.example.com', $request->getHost());
258- self::assertSame('https://app.example.com/', $request->getUri());
259- self::assertSame('203.0.113.7', $request->getClientIp());
260321 }
261322
262- public function testForwardedHeadersAreIgnoredWhileTheProxyIsUntrusted(): void
323+ public function testCronEventComesFromThePlatformOverHttp(): void
263324 {
264- $request = HttpConverter::toRequest(['headers' => ['Host' => 'internal.local', 'X-Forwarded-Proto' => 'https']]);
325+ $request = HttpConverter::toRequest(self::CRON_EVENT);
265326
327+ self::assertSame('POST', $request->getMethod());
328+ self::assertSame(HttpConverter::PROXY_ADDRESS, $request->getClientIp());
266329 self::assertFalse($request->isSecure());
267- self::assertSame('internal.local', $request->getHost());
330+ self::assertSame('http://localhost/', $request->getUri());
331+ self::assertSame(['probe' => 'cron', 'nested' => ['list' => [1, 2]]], $request->toArray());
332+ }
333+
334+ public function testMalformedRealIpFallsBackToTheProxyAddress(): void
335+ {
336+ self::assertSame(HttpConverter::PROXY_ADDRESS, HttpConverter::toRequest(['headers' => ['X-Real-Ip' => 'not an ip']])->getClientIp());
268337 }
269338
270- public function testEventWithoutHostGetsTheDefaultHostOfRequestCreate(): void
339+ public function testEmptyHostOptionGetsTheDefaultHostOfRequestCreate(): void
271340 {
272- $request = HttpConverter::toRequest(['path' => '/jobs', 'method' => 'POST']);
341+ $request = HttpConverter::toRequest(['path' => '/jobs', 'httpMethod' => 'POST'], '');
273342
274343 self::assertSame('http://localhost/jobs', $request->getUri());
275344 self::assertSame(80, $request->getPort());
276- self::assertSame('http://localhost/jobs', HttpConverter::toRequest(['path' => '/jobs', 'headers' => ['Host' => '']])->getUri());
345+ }
346+
347+ public function testRealEventShapes(): void
348+ {
349+ // Text bodies come without isBase64Encoded, and an Event without query string has an empty list.
350+ $text = HttpConverter::toRequest(['httpMethod' => 'POST', 'headers' => ['Content-Type' => 'application/json'], 'queryStringParameters' => [], 'body' => '{"a":"é"}']
351+ + array_diff_key(self::PLATFORM_EVENT, ['isBase64Encoded' => true]));
352+ self::assertSame('{"a":"é"}', $text->getContent());
353+ self::assertSame([], $text->query->all());
354+
355+ $emptyGet = HttpConverter::toRequest(self::PLATFORM_EVENT);
356+ self::assertSame('', $emptyGet->getContent());
357+ self::assertSame(['single' => '1', 'repeated' => 'b', 'list' => ['y']], $emptyGet->query->all());
358+ self::assertSame('hello', $emptyGet->headers->get('X-Custom'));
277359 }
278360
279361 public function testFunctionResponseFromTextResponse(): void
@@ -15,6 +15,51 @@ use Symfony\Component\HttpFoundation\StreamedResponse;
15 15
16 final class HttpConverterTest extends TestCase16 final class HttpConverterTest extends TestCase
17 {17 {
18+ /** An HTTP Event as measured on Scaleway (docs/probe-results.md), GET without a body. */
19+ private const array PLATFORM_EVENT = [
20+ 'resource' => '/some/path',
21+ 'path' => '/some/path',
22+ 'httpMethod' => 'GET',
23+ 'headers' => [
24+ 'Accept' => '*/*',
25+ 'Forwarded' => 'for="[2001:db8::1]";proto=https, for=100.96.1.187',
26+ 'K-Proxy-Request' => 'activator',
27+ 'User-Agent' => 'curl/8.7.1',
28+ 'X-Custom' => 'hello',
29+ 'X-Envoy-External-Address' => '2001:db8::1',
30+ 'X-Forwarded-For' => '2001:db8::1, 100.96.1.187, 100.96.38.33',
31+ 'X-Forwarded-Proto' => 'https',
32+ 'X-Real-Ip' => '2001:db8::1',
33+ 'X-Request-Id' => '6f1c1e0a-3b4e-4f7a-9a52-0d1f3e6c2b11',
34+ ],
35+ 'multiValueHeaders' => null,
36+ 'queryStringParameters' => ['single' => '1', 'repeated' => 'b', 'list[]' => 'y'],
37+ 'multiValueQueryStringParameters' => null,
38+ 'pathParameters' => null,
39+ 'stageVariables' => [],
40+ 'requestContext' => ['httpMethod' => 'GET'],
41+ 'body' => '',
42+ 'isBase64Encoded' => true,
43+ ];
44+
45+ /** A CRON Event as measured on Scaleway (docs/probe-results.md). */
46+ private const array CRON_EVENT = [
47+ 'path' => '/',
48+ 'httpMethod' => 'POST',
49+ 'headers' => [
50+ 'Content-Length' => '40',
51+ 'Content-Type' => 'application/json',
52+ 'Forwarded' => 'for=100.96.2.180;proto=http',
53+ 'K-Proxy-Request' => 'activator',
54+ 'User-Agent' => 'Go-http-client/1.1',
55+ 'X-Forwarded-For' => '100.96.2.180, 100.96.36.219',
56+ 'X-Forwarded-Proto' => 'http',
57+ 'X-Request-Id' => '0b8e4a52-7c1d-4e0f-8a3b-5d6c7e8f9a01',
58+ ],
59+ 'queryStringParameters' => [],
60+ 'body' => '{"probe":"cron","nested":{"list":[1,2]}}',
61+ ];
62+
18 protected function tearDown(): void63 protected function tearDown(): void
19 {64 {
20 Request::setTrustedProxies([], 0);65 Request::setTrustedProxies([], 0);
@@ -26,10 +71,10 @@ final class HttpConverterTest extends TestCase
26 'path' => '/blog/post',71 'path' => '/blog/post',
27 'method' => 'put',72 'method' => 'put',
28 'queryStringParameters' => ['page' => '2', 'q' => 'a b&c'],73 'queryStringParameters' => ['page' => '2', 'q' => 'a b&c'],
29- 'headers' => ['Content-Type' => 'application/json', 'Content-Length' => '13', 'X-Custom-Header' => 'yes', 'Host' => 'example.com'],74+ 'headers' => ['Content-Type' => 'application/json', 'Content-Length' => '13', 'X-Custom-Header' => 'yes'],
30 'body' => '{"ok": true}',75 'body' => '{"ok": true}',
31 'isBase64Encoded' => false,76 'isBase64Encoded' => false,
32- ]);77+ ], 'example.com');
33 78
34 self::assertSame('PUT', $request->getMethod());79 self::assertSame('PUT', $request->getMethod());
35 self::assertSame('/blog/post', $request->getPathInfo());80 self::assertSame('/blog/post', $request->getPathInfo());
@@ -238,42 +283,79 @@ final class HttpConverterTest extends TestCase
238 self::assertSame('text/html, application/json', $request->headers->get('Accept'));283 self::assertSame('text/html, application/json', $request->headers->get('Accept'));
239 }284 }
240 285
241- public function testForwardedHeadersApplyOnceTheProxyIsTrusted(): void286+ public function testClientAndSchemeComeFromTheHeadersThePlatformOverwrites(): void
242 {287 {
243- Request::setTrustedProxies([HttpConverter::PROXY_ADDRESS], HttpConverter::TRUSTED_HEADERS);288+ $request = HttpConverter::toRequest(self::PLATFORM_EVENT);
244-
245- $request = HttpConverter::toRequest([
246- 'path' => '/',
247- 'headers' => [
248- 'Host' => 'internal.local',
249- 'X-Forwarded-For' => '203.0.113.7',
250- 'X-Forwarded-Host' => 'app.example.com',
251- 'X-Forwarded-Proto' => 'https',
252- 'X-Forwarded-Port' => '443',
253- ],
254- ]);
255 289
290+ self::assertSame('2001:db8::1', $request->getClientIp());
256 self::assertTrue($request->isSecure());291 self::assertTrue($request->isSecure());
292+ self::assertSame(443, $request->getPort());
293+ self::assertSame('https://localhost/some/path?list%5B0%5D=y&repeated=b&single=1', $request->getUri());
294+ }
295+
296+ public function testClientForgeableForwardingHeadersAreIgnored(): void
297+ {
298+ $request = HttpConverter::toRequest(['headers' => [
299+ 'X-Real-Ip' => '2001:db8::1',
300+ 'X-Forwarded-For' => '203.0.113.66,2001:db8::1, 100.96.2.180',
301+ 'X-Forwarded-Host' => 'spoofed.example',
302+ 'X-Forwarded-Port' => '1234',
303+ 'Forwarded' => 'for=203.0.113.66;host=spoofed.example',
304+ 'Host' => 'spoofed.example',
305+ 'X-Forwarded-Proto' => 'http',
306+ ]], 'app.example.com');
307+
308+ self::assertSame('2001:db8::1', $request->getClientIp());
309+ self::assertSame('http://app.example.com/', $request->getUri());
310+ self::assertSame(80, $request->getPort());
311+ self::assertSame([], Request::getTrustedProxies());
312+ }
313+
314+ public function testTrustedProxiesConfiguredByTheAppStillApply(): void
315+ {
316+ Request::setTrustedProxies(['2001:db8::1'], Request::HEADER_X_FORWARDED_HOST);
317+
318+ $request = HttpConverter::toRequest(['headers' => ['X-Real-Ip' => '2001:db8::1', 'X-Forwarded-Host' => 'app.example.com']]);
319+
257 self::assertSame('app.example.com', $request->getHost());320 self::assertSame('app.example.com', $request->getHost());
258- self::assertSame('https://app.example.com/', $request->getUri());
259- self::assertSame('203.0.113.7', $request->getClientIp());
260 }321 }
261 322
262- public function testForwardedHeadersAreIgnoredWhileTheProxyIsUntrusted(): void323+ public function testCronEventComesFromThePlatformOverHttp(): void
263 {324 {
264- $request = HttpConverter::toRequest(['headers' => ['Host' => 'internal.local', 'X-Forwarded-Proto' => 'https']]);325+ $request = HttpConverter::toRequest(self::CRON_EVENT);
265 326
327+ self::assertSame('POST', $request->getMethod());
328+ self::assertSame(HttpConverter::PROXY_ADDRESS, $request->getClientIp());
266 self::assertFalse($request->isSecure());329 self::assertFalse($request->isSecure());
267- self::assertSame('internal.local', $request->getHost());330+ self::assertSame('http://localhost/', $request->getUri());
331+ self::assertSame(['probe' => 'cron', 'nested' => ['list' => [1, 2]]], $request->toArray());
332+ }
333+
334+ public function testMalformedRealIpFallsBackToTheProxyAddress(): void
335+ {
336+ self::assertSame(HttpConverter::PROXY_ADDRESS, HttpConverter::toRequest(['headers' => ['X-Real-Ip' => 'not an ip']])->getClientIp());
268 }337 }
269 338
270- public function testEventWithoutHostGetsTheDefaultHostOfRequestCreate(): void339+ public function testEmptyHostOptionGetsTheDefaultHostOfRequestCreate(): void
271 {340 {
272- $request = HttpConverter::toRequest(['path' => '/jobs', 'method' => 'POST']);341+ $request = HttpConverter::toRequest(['path' => '/jobs', 'httpMethod' => 'POST'], '');
273 342
274 self::assertSame('http://localhost/jobs', $request->getUri());343 self::assertSame('http://localhost/jobs', $request->getUri());
275 self::assertSame(80, $request->getPort());344 self::assertSame(80, $request->getPort());
276- self::assertSame('http://localhost/jobs', HttpConverter::toRequest(['path' => '/jobs', 'headers' => ['Host' => '']])->getUri());345+ }
346+
347+ public function testRealEventShapes(): void
348+ {
349+ // Text bodies come without isBase64Encoded, and an Event without query string has an empty list.
350+ $text = HttpConverter::toRequest(['httpMethod' => 'POST', 'headers' => ['Content-Type' => 'application/json'], 'queryStringParameters' => [], 'body' => '{"a":"é"}']
351+ + array_diff_key(self::PLATFORM_EVENT, ['isBase64Encoded' => true]));
352+ self::assertSame('{"a":"é"}', $text->getContent());
353+ self::assertSame([], $text->query->all());
354+
355+ $emptyGet = HttpConverter::toRequest(self::PLATFORM_EVENT);
356+ self::assertSame('', $emptyGet->getContent());
357+ self::assertSame(['single' => '1', 'repeated' => 'b', 'list' => ['y']], $emptyGet->query->all());
358+ self::assertSame('hello', $emptyGet->headers->get('X-Custom'));
277 }359 }
278 360
279 public function testFunctionResponseFromTextResponse(): void361 public function testFunctionResponseFromTextResponse(): void
modified tests/IntegrationTest.php +8 -9
@@ -45,11 +45,11 @@ final class IntegrationTest extends TestCase
4545 'path' => '/state',
4646 'method' => 'GET',
4747 'queryStringParameters' => ['page' => '2'],
48- 'headers' => ['Host' => 'internal.local', 'X-Forwarded-Proto' => 'https', 'X-Forwarded-For' => '203.0.113.7'],
48+ 'headers' => ['X-Forwarded-Proto' => 'https', 'X-Real-Ip' => '203.0.113.7'],
4949 'body' => '',
5050 'isBase64Encoded' => false,
5151 ],
52- ['path' => '/state', 'method' => 'GET', 'headers' => ['Host' => 'internal.local']],
52+ ['path' => '/state', 'method' => 'GET', 'headers' => []],
5353 ]);
5454
5555 self::assertSame(200, $first['statusCode']);
@@ -134,7 +134,7 @@ final class IntegrationTest extends TestCase
134134 public function testRawCallableIsBuiltOnceAndGetsEveryEventUntouchedCronIncluded(): void
135135 {
136136 $cron = ['method' => 'POST', 'path' => '/', 'body' => '{"command":"app:count","secret":"cron-secret"}'];
137- $http = ['path' => '/state', 'method' => 'GET', 'headers' => ['Host' => 'internal.local'], 'isBase64Encoded' => false];
137+ $http = ['path' => '/state', 'method' => 'GET', 'headers' => ['X-Real-Ip' => '203.0.113.7'], 'isBase64Encoded' => false];
138138
139139 [$first, $second] = $this->invoke([$http, $cron], ['front_controller' => 'public/raw.php']);
140140
@@ -153,18 +153,17 @@ final class IntegrationTest extends TestCase
153153 'path' => '/upload',
154154 'method' => 'POST',
155155 'headers' => [
156- 'Host' => 'internal.local',
157156 'Content-Type' => 'multipart/form-data; boundary=b',
158- 'X-Forwarded-For' => '203.0.113.7',
159- 'X-Forwarded-Host' => 'api.example.com',
157+ 'X-Real-Ip' => '203.0.113.7',
158+ 'X-Forwarded-Host' => 'spoofed.example',
160159 'X-Forwarded-Proto' => 'https',
161160 ],
162161 'body' => base64_encode("--b\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nReport\r\n"
163162 ."--b\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"report.csv\"\r\n\r\na,b\r\n--b--\r\n"),
164163 'isBase64Encoded' => true,
165164 ],
166- ['path' => '/', 'headers' => ['Host' => 'internal.local']],
167- ], ['front_controller' => 'public/request-handler.php']);
165+ ['path' => '/'],
166+ ], ['front_controller' => 'public/request-handler.php', 'host' => 'api.example.com']);
168167
169168 self::assertSame(201, $first['statusCode']);
170169 self::assertIsArray($first['headers']);
@@ -178,7 +177,7 @@ final class IntegrationTest extends TestCase
178177 self::assertSame(['title' => 'Report'], $first['parsedBody']);
179178 self::assertSame(['doc' => ['name' => 'report.csv', 'content' => 'a,b']], $first['files']);
180179 self::assertSame([], glob($this->dir.'/tmp/php*'), 'Uploaded files must be deleted after the Invocation.');
181- self::assertSame(['uri' => 'http://internal.local/', 'remoteAddr' => '127.0.0.1', 'handled' => 2, 'resets' => 1], array_intersect_key($second, ['uri' => 0, 'remoteAddr' => 0, 'handled' => 0, 'resets' => 0]));
180+ self::assertSame(['uri' => 'http://api.example.com/', 'remoteAddr' => '127.0.0.1', 'handled' => 2, 'resets' => 1], array_intersect_key($second, ['uri' => 0, 'remoteAddr' => 0, 'handled' => 0, 'resets' => 0]));
182181 self::assertSame($first['pid'], $second['pid']);
183182 }
184183
@@ -45,11 +45,11 @@ final class IntegrationTest extends TestCase
45 'path' => '/state',45 'path' => '/state',
46 'method' => 'GET',46 'method' => 'GET',
47 'queryStringParameters' => ['page' => '2'],47 'queryStringParameters' => ['page' => '2'],
48- 'headers' => ['Host' => 'internal.local', 'X-Forwarded-Proto' => 'https', 'X-Forwarded-For' => '203.0.113.7'],48+ 'headers' => ['X-Forwarded-Proto' => 'https', 'X-Real-Ip' => '203.0.113.7'],
49 'body' => '',49 'body' => '',
50 'isBase64Encoded' => false,50 'isBase64Encoded' => false,
51 ],51 ],
52- ['path' => '/state', 'method' => 'GET', 'headers' => ['Host' => 'internal.local']],52+ ['path' => '/state', 'method' => 'GET', 'headers' => []],
53 ]);53 ]);
54 54
55 self::assertSame(200, $first['statusCode']);55 self::assertSame(200, $first['statusCode']);
@@ -134,7 +134,7 @@ final class IntegrationTest extends TestCase
134 public function testRawCallableIsBuiltOnceAndGetsEveryEventUntouchedCronIncluded(): void134 public function testRawCallableIsBuiltOnceAndGetsEveryEventUntouchedCronIncluded(): void
135 {135 {
136 $cron = ['method' => 'POST', 'path' => '/', 'body' => '{"command":"app:count","secret":"cron-secret"}'];136 $cron = ['method' => 'POST', 'path' => '/', 'body' => '{"command":"app:count","secret":"cron-secret"}'];
137- $http = ['path' => '/state', 'method' => 'GET', 'headers' => ['Host' => 'internal.local'], 'isBase64Encoded' => false];137+ $http = ['path' => '/state', 'method' => 'GET', 'headers' => ['X-Real-Ip' => '203.0.113.7'], 'isBase64Encoded' => false];
138 138
139 [$first, $second] = $this->invoke([$http, $cron], ['front_controller' => 'public/raw.php']);139 [$first, $second] = $this->invoke([$http, $cron], ['front_controller' => 'public/raw.php']);
140 140
@@ -153,18 +153,17 @@ final class IntegrationTest extends TestCase
153 'path' => '/upload',153 'path' => '/upload',
154 'method' => 'POST',154 'method' => 'POST',
155 'headers' => [155 'headers' => [
156- 'Host' => 'internal.local',
157 'Content-Type' => 'multipart/form-data; boundary=b',156 'Content-Type' => 'multipart/form-data; boundary=b',
158- 'X-Forwarded-For' => '203.0.113.7',157+ 'X-Real-Ip' => '203.0.113.7',
159- 'X-Forwarded-Host' => 'api.example.com',158+ 'X-Forwarded-Host' => 'spoofed.example',
160 'X-Forwarded-Proto' => 'https',159 'X-Forwarded-Proto' => 'https',
161 ],160 ],
162 'body' => base64_encode("--b\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nReport\r\n"161 'body' => base64_encode("--b\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nReport\r\n"
163 ."--b\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"report.csv\"\r\n\r\na,b\r\n--b--\r\n"),162 ."--b\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"report.csv\"\r\n\r\na,b\r\n--b--\r\n"),
164 'isBase64Encoded' => true,163 'isBase64Encoded' => true,
165 ],164 ],
166- ['path' => '/', 'headers' => ['Host' => 'internal.local']],165+ ['path' => '/'],
167- ], ['front_controller' => 'public/request-handler.php']);166+ ], ['front_controller' => 'public/request-handler.php', 'host' => 'api.example.com']);
168 167
169 self::assertSame(201, $first['statusCode']);168 self::assertSame(201, $first['statusCode']);
170 self::assertIsArray($first['headers']);169 self::assertIsArray($first['headers']);
@@ -178,7 +177,7 @@ final class IntegrationTest extends TestCase
178 self::assertSame(['title' => 'Report'], $first['parsedBody']);177 self::assertSame(['title' => 'Report'], $first['parsedBody']);
179 self::assertSame(['doc' => ['name' => 'report.csv', 'content' => 'a,b']], $first['files']);178 self::assertSame(['doc' => ['name' => 'report.csv', 'content' => 'a,b']], $first['files']);
180 self::assertSame([], glob($this->dir.'/tmp/php*'), 'Uploaded files must be deleted after the Invocation.');179 self::assertSame([], glob($this->dir.'/tmp/php*'), 'Uploaded files must be deleted after the Invocation.');
181- self::assertSame(['uri' => 'http://internal.local/', 'remoteAddr' => '127.0.0.1', 'handled' => 2, 'resets' => 1], array_intersect_key($second, ['uri' => 0, 'remoteAddr' => 0, 'handled' => 0, 'resets' => 0]));180+ self::assertSame(['uri' => 'http://api.example.com/', 'remoteAddr' => '127.0.0.1', 'handled' => 2, 'resets' => 1], array_intersect_key($second, ['uri' => 0, 'remoteAddr' => 0, 'handled' => 0, 'resets' => 0]));
182 self::assertSame($first['pid'], $second['pid']);181 self::assertSame($first['pid'], $second['pid']);
183 }182 }
184 183
modified tests/Runner/HttpKernelRunnerTest.php +11 -4
@@ -4,7 +4,6 @@ declare(strict_types=1);
44
55 namespace JDecool\ScalewayRuntime\Tests\Runner;
66
7-use JDecool\ScalewayRuntime\HttpConverter;
87 use JDecool\ScalewayRuntime\Runner\HttpKernelRunner;
98 use JDecool\ScalewayRuntime\Tests\Fixtures\RecordingKernel;
109 use PHPUnit\Framework\TestCase;
@@ -28,12 +27,20 @@ final class HttpKernelRunnerTest extends TestCase
2827 Request::setTrustedProxies([], 0);
2928 }
3029
31- public function testPlatformProxyIsTrustedByDefault(): void
30+ public function testNoProxyIsTrusted(): void
3231 {
3332 new HttpKernelRunner(new RecordingKernel(), $this->errorLog);
3433
35- self::assertSame([HttpConverter::PROXY_ADDRESS], Request::getTrustedProxies());
36- self::assertSame(HttpConverter::TRUSTED_HEADERS, Request::getTrustedHeaderSet());
34+ self::assertSame([], Request::getTrustedProxies());
35+ }
36+
37+ public function testRequestsGetTheHostOfTheFunction(): void
38+ {
39+ $kernel = new RecordingKernel();
40+
41+ new HttpKernelRunner($kernel, $this->errorLog, 'app.example.com')->invoke(['path' => '/'], []);
42+
43+ self::assertSame('app.example.com', $kernel->lastRequest?->getHost());
3744 }
3845
3946 public function testTrustedProxiesConfiguredByTheAppAreKept(): void
@@ -4,7 +4,6 @@ declare(strict_types=1);
4 4
5 namespace JDecool\ScalewayRuntime\Tests\Runner;5 namespace JDecool\ScalewayRuntime\Tests\Runner;
6 6
7-use JDecool\ScalewayRuntime\HttpConverter;
8 use JDecool\ScalewayRuntime\Runner\HttpKernelRunner;7 use JDecool\ScalewayRuntime\Runner\HttpKernelRunner;
9 use JDecool\ScalewayRuntime\Tests\Fixtures\RecordingKernel;8 use JDecool\ScalewayRuntime\Tests\Fixtures\RecordingKernel;
10 use PHPUnit\Framework\TestCase;9 use PHPUnit\Framework\TestCase;
@@ -28,12 +27,20 @@ final class HttpKernelRunnerTest extends TestCase
28 Request::setTrustedProxies([], 0);27 Request::setTrustedProxies([], 0);
29 }28 }
30 29
31- public function testPlatformProxyIsTrustedByDefault(): void30+ public function testNoProxyIsTrusted(): void
32 {31 {
33 new HttpKernelRunner(new RecordingKernel(), $this->errorLog);32 new HttpKernelRunner(new RecordingKernel(), $this->errorLog);
34 33
35- self::assertSame([HttpConverter::PROXY_ADDRESS], Request::getTrustedProxies());34+ self::assertSame([], Request::getTrustedProxies());
36- self::assertSame(HttpConverter::TRUSTED_HEADERS, Request::getTrustedHeaderSet());35+ }
36+
37+ public function testRequestsGetTheHostOfTheFunction(): void
38+ {
39+ $kernel = new RecordingKernel();
40+
41+ new HttpKernelRunner($kernel, $this->errorLog, 'app.example.com')->invoke(['path' => '/'], []);
42+
43+ self::assertSame('app.example.com', $kernel->lastRequest?->getHost());
37 }44 }
38 45
39 public function testTrustedProxiesConfiguredByTheAppAreKept(): void46 public function testTrustedProxiesConfiguredByTheAppAreKept(): void
modified tests/Runner/RequestHandlerKernelTest.php +11 -15
@@ -21,7 +21,7 @@ final class RequestHandlerKernelTest extends TestCase
2121 $errorLog = fopen('php://memory', 'w+');
2222 self::assertNotFalse($errorLog);
2323 $this->handler = new EchoRequestHandler();
24- $this->runner = new HttpKernelRunner(new RequestHandlerKernel($this->handler), $errorLog);
24+ $this->runner = new HttpKernelRunner(new RequestHandlerKernel($this->handler), $errorLog, 'api.example.com');
2525 }
2626
2727 protected function tearDown(): void
@@ -35,35 +35,31 @@ final class RequestHandlerKernelTest extends TestCase
3535 'path' => '/items',
3636 'queryStringParameters' => ['page' => '2'],
3737 'headers' => [
38- 'Host' => 'internal.local',
39- 'X-Forwarded-For' => '203.0.113.7',
40- 'X-Forwarded-Host' => 'api.example.com',
38+ 'X-Real-Ip' => '2001:db8::1',
39+ 'X-Forwarded-For' => '203.0.113.66,2001:db8::1',
40+ 'X-Forwarded-Host' => 'spoofed.example',
4141 'X-Forwarded-Proto' => 'https',
4242 ],
4343 ]);
4444
4545 self::assertSame('https://api.example.com/items?page=2', $echo['uri']);
46- self::assertSame('203.0.113.7', $echo['remoteAddr']);
46+ self::assertSame('2001:db8::1', $echo['remoteAddr']);
4747 self::assertSame(['page' => '2'], $echo['query']);
4848 }
4949
50- public function testRequestWithoutForwardedHeadersComesFromThePlatformProxy(): void
50+ public function testCronEventComesFromThePlatformProxy(): void
5151 {
52- $echo = $this->echo(['path' => '/', 'headers' => ['Host' => 'internal.local']]);
52+ $echo = $this->echo(['path' => '/', 'httpMethod' => 'POST', 'headers' => ['X-Forwarded-Proto' => 'http']]);
5353
54- self::assertSame('http://internal.local/', $echo['uri']);
54+ self::assertSame('http://api.example.com/', $echo['uri']);
5555 self::assertSame('127.0.0.1', $echo['remoteAddr']);
5656 }
5757
58- public function testEventWithoutHostGetsAParsableUri(): void
59- {
60- self::assertSame('http://localhost/', $this->echo(['path' => '/'])['uri']);
61- self::assertSame('https://localhost/', $this->echo(['path' => '/', 'headers' => ['X-Forwarded-Proto' => 'https']])['uri']);
62- }
63-
6458 public function testMalformedHostIsABadRequestThatSkipsTheHandler(): void
6559 {
66- $functionResponse = $this->runner->invoke(['path' => '/', 'headers' => ['Host' => 'internal.local', 'X-Forwarded-Host' => 'bad host!']], []);
60+ // Only reachable when the application trusts X-Forwarded-Host itself.
61+ Request::setTrustedProxies(['127.0.0.1'], Request::HEADER_X_FORWARDED_HOST);
62+ $functionResponse = $this->runner->invoke(['path' => '/', 'headers' => ['X-Forwarded-Host' => 'bad host!']], []);
6763
6864 self::assertSame(400, $functionResponse['statusCode']);
6965 self::assertSame(0, $this->handler->handled);
@@ -21,7 +21,7 @@ final class RequestHandlerKernelTest extends TestCase
21 $errorLog = fopen('php://memory', 'w+');21 $errorLog = fopen('php://memory', 'w+');
22 self::assertNotFalse($errorLog);22 self::assertNotFalse($errorLog);
23 $this->handler = new EchoRequestHandler();23 $this->handler = new EchoRequestHandler();
24- $this->runner = new HttpKernelRunner(new RequestHandlerKernel($this->handler), $errorLog);24+ $this->runner = new HttpKernelRunner(new RequestHandlerKernel($this->handler), $errorLog, 'api.example.com');
25 }25 }
26 26
27 protected function tearDown(): void27 protected function tearDown(): void
@@ -35,35 +35,31 @@ final class RequestHandlerKernelTest extends TestCase
35 'path' => '/items',35 'path' => '/items',
36 'queryStringParameters' => ['page' => '2'],36 'queryStringParameters' => ['page' => '2'],
37 'headers' => [37 'headers' => [
38- 'Host' => 'internal.local',38+ 'X-Real-Ip' => '2001:db8::1',
39- 'X-Forwarded-For' => '203.0.113.7',39+ 'X-Forwarded-For' => '203.0.113.66,2001:db8::1',
40- 'X-Forwarded-Host' => 'api.example.com',40+ 'X-Forwarded-Host' => 'spoofed.example',
41 'X-Forwarded-Proto' => 'https',41 'X-Forwarded-Proto' => 'https',
42 ],42 ],
43 ]);43 ]);
44 44
45 self::assertSame('https://api.example.com/items?page=2', $echo['uri']);45 self::assertSame('https://api.example.com/items?page=2', $echo['uri']);
46- self::assertSame('203.0.113.7', $echo['remoteAddr']);46+ self::assertSame('2001:db8::1', $echo['remoteAddr']);
47 self::assertSame(['page' => '2'], $echo['query']);47 self::assertSame(['page' => '2'], $echo['query']);
48 }48 }
49 49
50- public function testRequestWithoutForwardedHeadersComesFromThePlatformProxy(): void50+ public function testCronEventComesFromThePlatformProxy(): void
51 {51 {
52- $echo = $this->echo(['path' => '/', 'headers' => ['Host' => 'internal.local']]);52+ $echo = $this->echo(['path' => '/', 'httpMethod' => 'POST', 'headers' => ['X-Forwarded-Proto' => 'http']]);
53 53
54- self::assertSame('http://internal.local/', $echo['uri']);54+ self::assertSame('http://api.example.com/', $echo['uri']);
55 self::assertSame('127.0.0.1', $echo['remoteAddr']);55 self::assertSame('127.0.0.1', $echo['remoteAddr']);
56 }56 }
57 57
58- public function testEventWithoutHostGetsAParsableUri(): void
59- {
60- self::assertSame('http://localhost/', $this->echo(['path' => '/'])['uri']);
61- self::assertSame('https://localhost/', $this->echo(['path' => '/', 'headers' => ['X-Forwarded-Proto' => 'https']])['uri']);
62- }
63-
64 public function testMalformedHostIsABadRequestThatSkipsTheHandler(): void58 public function testMalformedHostIsABadRequestThatSkipsTheHandler(): void
65 {59 {
66- $functionResponse = $this->runner->invoke(['path' => '/', 'headers' => ['Host' => 'internal.local', 'X-Forwarded-Host' => 'bad host!']], []);60+ // Only reachable when the application trusts X-Forwarded-Host itself.
61+ Request::setTrustedProxies(['127.0.0.1'], Request::HEADER_X_FORWARDED_HOST);
62+ $functionResponse = $this->runner->invoke(['path' => '/', 'headers' => ['X-Forwarded-Host' => 'bad host!']], []);
67 63
68 self::assertSame(400, $functionResponse['statusCode']);64 self::assertSame(400, $functionResponse['statusCode']);
69 self::assertSame(0, $this->handler->handled);65 self::assertSame(0, $this->handler->handled);