jdecool/scaleway-runtimepublic Fork
⑂ 158d086
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

fix: keep exception details out of deployed functions' error pagesUnverified

A function deployed without APP_ENV ran the dev env of the shipped .env,
showing stack traces to anyone, and on a read-only code dir every
Invocation answered a 500 carrying the full trace. The runtime now sets
the env option to the process environment's APP_ENV, or prod when unset,
before Dotenv runs; the Emulator sets APP_ENV=dev unless given one.

Error pages also dumped the exception in prod, as FrameworkBundle picks
its CLI error renderer outside a web SAPI: APP_RUNTIME_MODE now defaults
to web=1&worker=1, as in FrankenPHP's worker mode.

symfony/dotenv becomes a dev dependency so the tests boot like a Flex
application, with a .env saying dev.
Jérémy DECOOL committed 2026-11-14T02:32:29+01:00 Browse files
158d086 parent: 0bf08e2
modified README.md +12 -7
@@ -96,16 +96,17 @@ Set these on the function, in production:
9696
9797 | Variable | Kind | Why |
9898 | --- | --- | --- |
99-| `APP_ENV=prod` | Plain | Without it the application runs in `dev`, see below. |
10099 | `APP_SECRET` | Secret | Symfony's `kernel.secret`, used to sign URLs, cookies and CSRF tokens. |
101100 | `SCALEWAY_CRON_SECRET` | Secret | Only to run console commands from CRON triggers, see [Command Invocations](#command-invocations). |
101+| `APP_ENV` | Plain | Only to run another env than `prod`, see below. |
102102
103-> [!WARNING]
104-> The `.env` file is shipped in the zip, and the one Symfony generates says `APP_ENV=dev`.
105-> Without an `APP_ENV` variable on the function, the application therefore runs with `APP_ENV=dev` and debug enabled, and shows stack traces to anyone.
106-> On a read-only code directory it is even worse: the dev container cannot be built next to the prod one warmed in the zip, so every Invocation answers a 500 whose body is the full stack trace, file paths included.
103+The `.env` file is shipped in the zip, and the one Symfony generates says `APP_ENV=dev`, whose error pages show stack traces to anyone.
104+So the runtime runs `prod` when the function's environment sets no `APP_ENV` (or an empty one), whatever the `.env` files say ([ADR 0006](docs/adr/0006-default-to-the-prod-env.md)).
105+Only an `APP_ENV` variable of the function, or the `env` runtime option, picks another env.
106+`APP_DEBUG` follows: off in `prod`, unless set by the function's environment or a `.env` file.
107+The Emulator runs `dev` instead, unless it is started with an `APP_ENV`.
107108
108-Real environment variables win over `.env` files, as usual with Symfony's Dotenv.
109+For every other variable, real environment variables win over `.env` files, as usual with Symfony's Dotenv.
109110 `.env.local`, `.env.local.php` and `.env.*.local` are never shipped.
110111
111112 ### Writable directories
@@ -126,6 +127,9 @@ An exception escaping the Application (a Kernel failing to boot, an unsupported
126127 Its body is `Internal Server Error`, or the full exception when `APP_DEBUG` is true.
127128 A Kernel that failed to boot is built again from scratch on the next Invocation.
128129
130+Errors the Kernel handles itself get Symfony's web error pages, as the runtime sets `APP_RUNTIME_MODE=web=1&worker=1` unless your environment sets it.
131+Outside a web SAPI, FrameworkBundle would pick its CLI error renderer instead, which dumps the exception even in `prod`.
132+
129133 ## Supported Applications
130134
131135 The Front Controller returns a closure, as with any Symfony Runtime.
@@ -345,6 +349,7 @@ vendor/bin/scaleway-serve [127.0.0.1:8000]
345349
346350 The Emulator turns each HTTP request into an Event, calls your `handle()` and turns the Function Response back into the HTTP response.
347351 `handle()` runs in one long-lived PHP process, as in a Warm Process: restart the Emulator after changing code.
352+It sets `APP_ENV=dev` unless started with an `APP_ENV`, as the deployed function defaults to `prod`.
348353 A crashed process is replaced by a fresh one, as Scaleway starts a new instance.
349354
350355 PHP's built-in server receives the requests, and forwards the Events to that process over a Unix socket in a private temporary directory.
@@ -370,7 +375,7 @@ SCALEWAY_CRON_SECRET=local-secret vendor/bin/scaleway-serve
370375 curl -X POST http://127.0.0.1:8000/ --data '{"command": "app:greet", "args": {"name": "Scaleway"}, "secret": "local-secret"}'
371376 ```
372377
373-To run exactly what gets deployed, serve the packaged zip from a read-only copy:
378+To run exactly what gets deployed, serve the packaged zip from a read-only copy, in `prod`:
374379
375380 ```sh
376381 vendor/bin/scaleway-package
@@ -96,16 +96,17 @@ Set these on the function, in production:
96 96
97 | Variable | Kind | Why |97 | Variable | Kind | Why |
98 | --- | --- | --- |98 | --- | --- | --- |
99-| `APP_ENV=prod` | Plain | Without it the application runs in `dev`, see below. |
100 | `APP_SECRET` | Secret | Symfony's `kernel.secret`, used to sign URLs, cookies and CSRF tokens. |99 | `APP_SECRET` | Secret | Symfony's `kernel.secret`, used to sign URLs, cookies and CSRF tokens. |
101 | `SCALEWAY_CRON_SECRET` | Secret | Only to run console commands from CRON triggers, see [Command Invocations](#command-invocations). |100 | `SCALEWAY_CRON_SECRET` | Secret | Only to run console commands from CRON triggers, see [Command Invocations](#command-invocations). |
101+| `APP_ENV` | Plain | Only to run another env than `prod`, see below. |
102 102
103-> [!WARNING]103+The `.env` file is shipped in the zip, and the one Symfony generates says `APP_ENV=dev`, whose error pages show stack traces to anyone.
104-> The `.env` file is shipped in the zip, and the one Symfony generates says `APP_ENV=dev`.104+So the runtime runs `prod` when the function's environment sets no `APP_ENV` (or an empty one), whatever the `.env` files say ([ADR 0006](docs/adr/0006-default-to-the-prod-env.md)).
105-> Without an `APP_ENV` variable on the function, the application therefore runs with `APP_ENV=dev` and debug enabled, and shows stack traces to anyone.105+Only an `APP_ENV` variable of the function, or the `env` runtime option, picks another env.
106-> On a read-only code directory it is even worse: the dev container cannot be built next to the prod one warmed in the zip, so every Invocation answers a 500 whose body is the full stack trace, file paths included.106+`APP_DEBUG` follows: off in `prod`, unless set by the function's environment or a `.env` file.
107+The Emulator runs `dev` instead, unless it is started with an `APP_ENV`.
107 108
108-Real environment variables win over `.env` files, as usual with Symfony's Dotenv.109+For every other variable, real environment variables win over `.env` files, as usual with Symfony's Dotenv.
109 `.env.local`, `.env.local.php` and `.env.*.local` are never shipped.110 `.env.local`, `.env.local.php` and `.env.*.local` are never shipped.
110 111
111 ### Writable directories112 ### Writable directories
@@ -126,6 +127,9 @@ An exception escaping the Application (a Kernel failing to boot, an unsupported
126 Its body is `Internal Server Error`, or the full exception when `APP_DEBUG` is true.127 Its body is `Internal Server Error`, or the full exception when `APP_DEBUG` is true.
127 A Kernel that failed to boot is built again from scratch on the next Invocation.128 A Kernel that failed to boot is built again from scratch on the next Invocation.
128 129
130+Errors the Kernel handles itself get Symfony's web error pages, as the runtime sets `APP_RUNTIME_MODE=web=1&worker=1` unless your environment sets it.
131+Outside a web SAPI, FrameworkBundle would pick its CLI error renderer instead, which dumps the exception even in `prod`.
132+
129 ## Supported Applications133 ## Supported Applications
130 134
131 The Front Controller returns a closure, as with any Symfony Runtime.135 The Front Controller returns a closure, as with any Symfony Runtime.
@@ -345,6 +349,7 @@ vendor/bin/scaleway-serve [127.0.0.1:8000]
345 349
346 The Emulator turns each HTTP request into an Event, calls your `handle()` and turns the Function Response back into the HTTP response.350 The Emulator turns each HTTP request into an Event, calls your `handle()` and turns the Function Response back into the HTTP response.
347 `handle()` runs in one long-lived PHP process, as in a Warm Process: restart the Emulator after changing code.351 `handle()` runs in one long-lived PHP process, as in a Warm Process: restart the Emulator after changing code.
352+It sets `APP_ENV=dev` unless started with an `APP_ENV`, as the deployed function defaults to `prod`.
348 A crashed process is replaced by a fresh one, as Scaleway starts a new instance.353 A crashed process is replaced by a fresh one, as Scaleway starts a new instance.
349 354
350 PHP's built-in server receives the requests, and forwards the Events to that process over a Unix socket in a private temporary directory.355 PHP's built-in server receives the requests, and forwards the Events to that process over a Unix socket in a private temporary directory.
@@ -370,7 +375,7 @@ SCALEWAY_CRON_SECRET=local-secret vendor/bin/scaleway-serve
370 curl -X POST http://127.0.0.1:8000/ --data '{"command": "app:greet", "args": {"name": "Scaleway"}, "secret": "local-secret"}'375 curl -X POST http://127.0.0.1:8000/ --data '{"command": "app:greet", "args": {"name": "Scaleway"}, "secret": "local-secret"}'
371 ```376 ```
372 377
373-To run exactly what gets deployed, serve the packaged zip from a read-only copy:378+To run exactly what gets deployed, serve the packaged zip from a read-only copy, in `prod`:
374 379
375 ```sh380 ```sh
376 vendor/bin/scaleway-package381 vendor/bin/scaleway-package
modified bin/scaleway-serve +5 -0
@@ -48,6 +48,11 @@ function start(array $command, ?array $env = null)
4848 return $process;
4949 }
5050
51+// The Handler runs prod when APP_ENV is unset, to keep debug pages off the platform; locally they are wanted.
52+if (!getenv('APP_ENV')) {
53+ putenv('APP_ENV=dev');
54+}
55+
5156 $startWarmProcess = static function () use ($handlerFile, $socket) {
5257 $warmProcess = start([\PHP_BINARY, __DIR__.'/../resources/emulator/warm-process.php', $handlerFile, $socket]);
5358 // Waits until it listens, so the first requests do not find the socket closed.
@@ -48,6 +48,11 @@ function start(array $command, ?array $env = null)
48 return $process;48 return $process;
49 }49 }
50 50
51+// The Handler runs prod when APP_ENV is unset, to keep debug pages off the platform; locally they are wanted.
52+if (!getenv('APP_ENV')) {
53+ putenv('APP_ENV=dev');
54+}
55+
51 $startWarmProcess = static function () use ($handlerFile, $socket) {56 $startWarmProcess = static function () use ($handlerFile, $socket) {
52 $warmProcess = start([\PHP_BINARY, __DIR__.'/../resources/emulator/warm-process.php', $handlerFile, $socket]);57 $warmProcess = start([\PHP_BINARY, __DIR__.'/../resources/emulator/warm-process.php', $handlerFile, $socket]);
53 // Waits until it listens, so the first requests do not find the socket closed.58 // Waits until it listens, so the first requests do not find the socket closed.
modified composer.json +1 -0
@@ -30,6 +30,7 @@
3030 "phpunit/phpunit": "^13.4",
3131 "psr/http-server-handler": "^1.0",
3232 "symfony/console": "^7.4 || ^8.0",
33+ "symfony/dotenv": "^7.4 || ^8.0",
3334 "symfony/framework-bundle": "^7.4 || ^8.0",
3435 "symfony/psr-http-message-bridge": "^7.4 || ^8.0"
3536 },
@@ -30,6 +30,7 @@
30 "phpunit/phpunit": "^13.4",30 "phpunit/phpunit": "^13.4",
31 "psr/http-server-handler": "^1.0",31 "psr/http-server-handler": "^1.0",
32 "symfony/console": "^7.4 || ^8.0",32 "symfony/console": "^7.4 || ^8.0",
33+ "symfony/dotenv": "^7.4 || ^8.0",
33 "symfony/framework-bundle": "^7.4 || ^8.0",34 "symfony/framework-bundle": "^7.4 || ^8.0",
34 "symfony/psr-http-message-bridge": "^7.4 || ^8.0"35 "symfony/psr-http-message-bridge": "^7.4 || ^8.0"
35 },36 },
added docs/adr/0006-default-to-the-prod-env.md +18 -0
new file mode 100644
@@ -0,0 +1,18 @@
1+# The Handler defaults APP_ENV to prod, whatever the .env files say
2+
3+The zip ships `.env` as committed (ADR 0003), and the one Symfony generates says `APP_ENV=dev`.
4+With Symfony's usual precedence, a function deployed without an `APP_ENV` variable would therefore run dev with debug on, and show stack traces to anyone; on a read-only code directory, every Invocation even answers a 500 whose body is the full trace, as the dev container cannot be built next to the prod one warmed in the zip.
5+We therefore make `ScalewayRuntime`, which only the Handler uses, set the `env` option to the `APP_ENV` of the process environment (`$_SERVER`, `$_ENV`, then `getenv()`), or to `prod` when it is unset or empty, before Dotenv runs.
6+Dotenv never overrides a variable already set, so `.env` files can no longer choose the env, and `APP_DEBUG` follows `prod`, off unless set by the environment or a `.env` file.
7+The Emulator sets `APP_ENV=dev` unless it is started with one, so local development keeps debug pages.
8+
9+## Considered Options
10+
11+- Documenting that `APP_ENV=prod` must be set on the function: kept, but a forgotten variable must not be a leak.
12+- Forcing `APP_DEBUG=0` only: rejected, the application would still run its dev config, and fail on a read-only code directory.
13+- Rewriting `APP_ENV` in the shipped `.env`, or running `composer dump-env prod`: rejected, it alters committed files and needs Symfony Flex.
14+
15+## Consequences
16+
17+- An `APP_ENV` in `.env`, `.env.local` (never shipped anyway) or `.env.<env>` is ignored by the Handler and the Emulator alike: only the process environment, or the `env` runtime option, picks another env.
18+- With `dotenv_overload`, `.env` files still win, as the application explicitly asked.
new file mode 100644
@@ -0,0 +1,18 @@
1+# The Handler defaults APP_ENV to prod, whatever the .env files say
2+
3+The zip ships `.env` as committed (ADR 0003), and the one Symfony generates says `APP_ENV=dev`.
4+With Symfony's usual precedence, a function deployed without an `APP_ENV` variable would therefore run dev with debug on, and show stack traces to anyone; on a read-only code directory, every Invocation even answers a 500 whose body is the full trace, as the dev container cannot be built next to the prod one warmed in the zip.
5+We therefore make `ScalewayRuntime`, which only the Handler uses, set the `env` option to the `APP_ENV` of the process environment (`$_SERVER`, `$_ENV`, then `getenv()`), or to `prod` when it is unset or empty, before Dotenv runs.
6+Dotenv never overrides a variable already set, so `.env` files can no longer choose the env, and `APP_DEBUG` follows `prod`, off unless set by the environment or a `.env` file.
7+The Emulator sets `APP_ENV=dev` unless it is started with one, so local development keeps debug pages.
8+
9+## Considered Options
10+
11+- Documenting that `APP_ENV=prod` must be set on the function: kept, but a forgotten variable must not be a leak.
12+- Forcing `APP_DEBUG=0` only: rejected, the application would still run its dev config, and fail on a read-only code directory.
13+- Rewriting `APP_ENV` in the shipped `.env`, or running `composer dump-env prod`: rejected, it alters committed files and needs Symfony Flex.
14+
15+## Consequences
16+
17+- An `APP_ENV` in `.env`, `.env.local` (never shipped anyway) or `.env.<env>` is ignored by the Handler and the Emulator alike: only the process environment, or the `env` runtime option, picks another env.
18+- With `dotenv_overload`, `.env` files still win, as the application explicitly asked.
modified docs/plan.md +2 -0
@@ -14,6 +14,7 @@ Vocabulary follows [GLOSSARY.md](../GLOSSARY.md); decisions are recorded in [doc
1414 - A Front Controller returning a PSR-15 `RequestHandlerInterface` is built once like a Kernel and served through `symfony/psr-http-message-bridge` (suggested, with `nyholm/psr7`); the PSR-7 request carries the client resolved from the trusted `X-Forwarded-*` headers in its server params (`REMOTE_ADDR`, `HTTPS`, `HTTP_HOST`, `SERVER_PORT`) and URI; a handler implementing `ResetInterface` is reset before every Invocation but the first.
1515 - HTTP mapping: base64 bodies decoded on input; output marked `isBase64Encoded` when the body is not valid UTF-8; multi-value headers sent as arrays; streamed and binary file responses buffered; query string rebuilt from `queryStringParameters`; `X-Forwarded-*` trusted; platform limits documented.
1616 - Errors escaping the Application are logged to stderr and returned as a 500 Function Response (generic body, details when `APP_DEBUG=1`).
17+- The Handler runs `prod` when the process environment sets no `APP_ENV`, whatever the shipped `.env` says, and the Emulator `dev` (ADR 0006); `APP_RUNTIME_MODE` defaults to `web=1&worker=1`, so error pages use the web renderer.
1718 - Cache is warmed at build time; cache and log dirs fall back to `/tmp` when the project dir is not writable; the runtime logs its own errors to stderr, the application's logs are its own configuration.
1819 - `vendor/bin/scaleway-package` builds a zip with `vendor/` (`--no-dev --classmap-authoritative`, from `composer.lock`) and a warmed prod cache, excluding `var/`, `tests/`, `.env.local` (ADR 0003).
1920 - CRON Invocations become `POST /` HTTP requests by default; a JSON body `{"command": "...", "args": {...}, "secret": "..."}` whose secret matches `SCALEWAY_CRON_SECRET` makes it a Command Invocation run through the Console Application of the same Kernel, non-interactive, `args` mapped to an `ArrayInput`; the exit code 0 yields a 200 and any other a 500, both with the command output (ADR 0005).
@@ -45,6 +46,7 @@ Recorded per phase; the settled design above already reflects them.
4546 - **Phase 4**: a Front Controller returning a Response is called for every Invocation rather than once per process, a `Request` argument receiving the Invocation's Request (ADR 0004).
4647 - **Phase 6**: the Command Invocation body carries the CRON Secret, matched against `SCALEWAY_CRON_SECRET`, as nothing known tells a CRON Invocation from an HTTP one (ADR 0005); Front Controllers returning a Console `Application` or a `Command` serve Command Invocations only, and answer a 403 to the others.
4748 - **Phase 7**: the raw callable is a `Closure` returned by the Front Controller closure, not any callable, and must return the documented Function Response shape, undocumented keys being dropped.
49+- **Phase 8**: documenting the environment variables showed that a function deployed without `APP_ENV` ran the shipped `.env`'s `dev`, and that error pages dumped the exception even in `prod`, through FrameworkBundle's CLI error renderer: the Handler now defaults to `prod` (ADR 0006) and to the web runtime mode, and `symfony/dotenv` is a dev dependency so the tests boot like a Flex application.
4850
4951 ## Remaining work
5052
@@ -14,6 +14,7 @@ Vocabulary follows [GLOSSARY.md](../GLOSSARY.md); decisions are recorded in [doc
14 - A Front Controller returning a PSR-15 `RequestHandlerInterface` is built once like a Kernel and served through `symfony/psr-http-message-bridge` (suggested, with `nyholm/psr7`); the PSR-7 request carries the client resolved from the trusted `X-Forwarded-*` headers in its server params (`REMOTE_ADDR`, `HTTPS`, `HTTP_HOST`, `SERVER_PORT`) and URI; a handler implementing `ResetInterface` is reset before every Invocation but the first.14 - A Front Controller returning a PSR-15 `RequestHandlerInterface` is built once like a Kernel and served through `symfony/psr-http-message-bridge` (suggested, with `nyholm/psr7`); the PSR-7 request carries the client resolved from the trusted `X-Forwarded-*` headers in its server params (`REMOTE_ADDR`, `HTTPS`, `HTTP_HOST`, `SERVER_PORT`) and URI; a handler implementing `ResetInterface` is reset before every Invocation but the first.
15 - HTTP mapping: base64 bodies decoded on input; output marked `isBase64Encoded` when the body is not valid UTF-8; multi-value headers sent as arrays; streamed and binary file responses buffered; query string rebuilt from `queryStringParameters`; `X-Forwarded-*` trusted; platform limits documented.15 - HTTP mapping: base64 bodies decoded on input; output marked `isBase64Encoded` when the body is not valid UTF-8; multi-value headers sent as arrays; streamed and binary file responses buffered; query string rebuilt from `queryStringParameters`; `X-Forwarded-*` trusted; platform limits documented.
16 - Errors escaping the Application are logged to stderr and returned as a 500 Function Response (generic body, details when `APP_DEBUG=1`).16 - Errors escaping the Application are logged to stderr and returned as a 500 Function Response (generic body, details when `APP_DEBUG=1`).
17+- The Handler runs `prod` when the process environment sets no `APP_ENV`, whatever the shipped `.env` says, and the Emulator `dev` (ADR 0006); `APP_RUNTIME_MODE` defaults to `web=1&worker=1`, so error pages use the web renderer.
17 - Cache is warmed at build time; cache and log dirs fall back to `/tmp` when the project dir is not writable; the runtime logs its own errors to stderr, the application's logs are its own configuration.18 - Cache is warmed at build time; cache and log dirs fall back to `/tmp` when the project dir is not writable; the runtime logs its own errors to stderr, the application's logs are its own configuration.
18 - `vendor/bin/scaleway-package` builds a zip with `vendor/` (`--no-dev --classmap-authoritative`, from `composer.lock`) and a warmed prod cache, excluding `var/`, `tests/`, `.env.local` (ADR 0003).19 - `vendor/bin/scaleway-package` builds a zip with `vendor/` (`--no-dev --classmap-authoritative`, from `composer.lock`) and a warmed prod cache, excluding `var/`, `tests/`, `.env.local` (ADR 0003).
19 - CRON Invocations become `POST /` HTTP requests by default; a JSON body `{"command": "...", "args": {...}, "secret": "..."}` whose secret matches `SCALEWAY_CRON_SECRET` makes it a Command Invocation run through the Console Application of the same Kernel, non-interactive, `args` mapped to an `ArrayInput`; the exit code 0 yields a 200 and any other a 500, both with the command output (ADR 0005).20 - CRON Invocations become `POST /` HTTP requests by default; a JSON body `{"command": "...", "args": {...}, "secret": "..."}` whose secret matches `SCALEWAY_CRON_SECRET` makes it a Command Invocation run through the Console Application of the same Kernel, non-interactive, `args` mapped to an `ArrayInput`; the exit code 0 yields a 200 and any other a 500, both with the command output (ADR 0005).
@@ -45,6 +46,7 @@ Recorded per phase; the settled design above already reflects them.
45 - **Phase 4**: a Front Controller returning a Response is called for every Invocation rather than once per process, a `Request` argument receiving the Invocation's Request (ADR 0004).46 - **Phase 4**: a Front Controller returning a Response is called for every Invocation rather than once per process, a `Request` argument receiving the Invocation's Request (ADR 0004).
46 - **Phase 6**: the Command Invocation body carries the CRON Secret, matched against `SCALEWAY_CRON_SECRET`, as nothing known tells a CRON Invocation from an HTTP one (ADR 0005); Front Controllers returning a Console `Application` or a `Command` serve Command Invocations only, and answer a 403 to the others.47 - **Phase 6**: the Command Invocation body carries the CRON Secret, matched against `SCALEWAY_CRON_SECRET`, as nothing known tells a CRON Invocation from an HTTP one (ADR 0005); Front Controllers returning a Console `Application` or a `Command` serve Command Invocations only, and answer a 403 to the others.
47 - **Phase 7**: the raw callable is a `Closure` returned by the Front Controller closure, not any callable, and must return the documented Function Response shape, undocumented keys being dropped.48 - **Phase 7**: the raw callable is a `Closure` returned by the Front Controller closure, not any callable, and must return the documented Function Response shape, undocumented keys being dropped.
49+- **Phase 8**: documenting the environment variables showed that a function deployed without `APP_ENV` ran the shipped `.env`'s `dev`, and that error pages dumped the exception even in `prod`, through FrameworkBundle's CLI error renderer: the Handler now defaults to `prod` (ADR 0006) and to the web runtime mode, and `symfony/dotenv` is a dev dependency so the tests boot like a Flex application.
48 50
49 ## Remaining work51 ## Remaining work
50 52
modified src/ScalewayRuntime.php +11 -0
@@ -26,6 +26,8 @@ use Symfony\Component\Runtime\SymfonyRuntime;
2626 * On top of the options managed by SymfonyRuntime, it accepts:
2727 * - "front_controller": the Front Controller path, relative to "project_dir"; defaults to "public/index.php".
2828 *
29+ * Unlike SymfonyRuntime, it defaults the env to prod when the process environment sets none, whatever .env files say.
30+ *
2931 * When the project's var/ directory is not writable (the deployed code may be read-only),
3032 * the cache and log dirs move to the system temp dir through APP_CACHE_DIR and APP_LOG_DIR,
3133 * while APP_BUILD_DIR keeps the container warmed at build time.
@@ -50,8 +52,17 @@ class ScalewayRuntime extends SymfonyRuntime
5052 */
5153 public function __construct(array $options = [])
5254 {
55+ $envKey = \is_string($options['env_var_name'] ?? null) ? $options['env_var_name'] : 'APP_ENV';
56+ // The shipped .env says dev, whose error pages leak stack traces: only the function's own environment,
57+ // or the "env" option, may choose another env than prod (see docs/adr/0006-default-to-the-prod-env.md).
58+ $options['env'] ??= ($_SERVER[$envKey] ?? null) ?: ($_ENV[$envKey] ?? null) ?: getenv($envKey) ?: 'prod';
59+
5360 parent::__construct($options); // @phpstan-ignore argument.type (options come from untyped config)
5461
62+ // Invocations are web requests served by a long-lived process, as in FrankenPHP's worker mode; in a CLI SAPI,
63+ // 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';
65+
5566 $projectDir = $this->options['project_dir'] ?? null;
5667 if (\is_string($projectDir) && !is_writable(is_dir($projectDir.'/var') ? $projectDir.'/var' : $projectDir)) {
5768 // Kernels using MicroKernelTrait read these from $_SERVER only; values set by the app win.
@@ -26,6 +26,8 @@ use Symfony\Component\Runtime\SymfonyRuntime;
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 *28 *
29+ * Unlike SymfonyRuntime, it defaults the env to prod when the process environment sets none, whatever .env files say.
30+ *
29 * When the project's var/ directory is not writable (the deployed code may be read-only),31 * When the project's var/ directory is not writable (the deployed code may be read-only),
30 * the cache and log dirs move to the system temp dir through APP_CACHE_DIR and APP_LOG_DIR,32 * the cache and log dirs move to the system temp dir through APP_CACHE_DIR and APP_LOG_DIR,
31 * while APP_BUILD_DIR keeps the container warmed at build time.33 * while APP_BUILD_DIR keeps the container warmed at build time.
@@ -50,8 +52,17 @@ class ScalewayRuntime extends SymfonyRuntime
50 */52 */
51 public function __construct(array $options = [])53 public function __construct(array $options = [])
52 {54 {
55+ $envKey = \is_string($options['env_var_name'] ?? null) ? $options['env_var_name'] : 'APP_ENV';
56+ // The shipped .env says dev, whose error pages leak stack traces: only the function's own environment,
57+ // or the "env" option, may choose another env than prod (see docs/adr/0006-default-to-the-prod-env.md).
58+ $options['env'] ??= ($_SERVER[$envKey] ?? null) ?: ($_ENV[$envKey] ?? null) ?: getenv($envKey) ?: 'prod';
59+
53 parent::__construct($options); // @phpstan-ignore argument.type (options come from untyped config)60 parent::__construct($options); // @phpstan-ignore argument.type (options come from untyped config)
54 61
62+ // Invocations are web requests served by a long-lived process, as in FrankenPHP's worker mode; in a CLI SAPI,
63+ // 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';
65+
55 $projectDir = $this->options['project_dir'] ?? null;66 $projectDir = $this->options['project_dir'] ?? null;
56 if (\is_string($projectDir) && !is_writable(is_dir($projectDir.'/var') ? $projectDir.'/var' : $projectDir)) {67 if (\is_string($projectDir) && !is_writable(is_dir($projectDir.'/var') ? $projectDir.'/var' : $projectDir)) {
57 // Kernels using MicroKernelTrait read these from $_SERVER only; values set by the app win.68 // Kernels using MicroKernelTrait read these from $_SERVER only; values set by the app win.
added tests/Fixtures/.env +2 -0
new file mode 100644
@@ -0,0 +1,2 @@
1+# As in the .env Symfony generates, which must not make the Handler run dev.
2+APP_ENV=dev
new file mode 100644
@@ -0,0 +1,2 @@
1+# As in the .env Symfony generates, which must not make the Handler run dev.
2+APP_ENV=dev
added tests/Fixtures/App/.env +2 -0
new file mode 100644
@@ -0,0 +1,2 @@
1+# As in the .env Symfony generates, which must not make the Handler run dev.
2+APP_ENV=dev
new file mode 100644
@@ -0,0 +1,2 @@
1+# As in the .env Symfony generates, which must not make the Handler run dev.
2+APP_ENV=dev
modified tests/IntegrationTest.php +13 -4
@@ -72,6 +72,9 @@ final class IntegrationTest extends TestCase
7272 [$response] = $this->invoke([['path' => '/missing', 'method' => 'GET']]);
7373
7474 self::assertSame(404, $response['statusCode']);
75+ self::assertIsString($response['body']);
76+ // The CLI error renderer Symfony picks outside a web SAPI would dump the exception, even in prod.
77+ self::assertStringNotContainsString('NotFoundHttpException', $response['body']);
7578 }
7679
7780 public function testMultipartUploadReachesTheController(): void
@@ -121,6 +124,13 @@ final class IntegrationTest extends TestCase
121124 self::assertSame($first['pid'], $second['pid']);
122125 }
123126
127+ public function testFunctionWithoutAppEnvRunsProdDespiteTheDotenvFile(): void
128+ {
129+ [$response] = $this->invoke([['path' => '/']], ['front_controller' => 'public/hello.php'], []);
130+
131+ self::assertSame('prod', $this->json($response)['env']);
132+ }
133+
124134 public function testRawCallableIsBuiltOnceAndGetsEveryEventUntouchedCronIncluded(): void
125135 {
126136 $cron = ['method' => 'POST', 'path' => '/', 'body' => '{"command":"app:count","secret":"cron-secret"}'];
@@ -220,10 +230,11 @@ final class IntegrationTest extends TestCase
220230 /**
221231 * @param list<array<string, mixed>> $events
222232 * @param array<string, mixed> $options runtime options on top of "project_dir"
233+ * @param array<string, string> $appEnv the APP_* variables of the function's environment
223234 *
224235 * @return array<array<mixed>>
225236 */
226- private function invoke(array $events, array $options = []): array
237+ private function invoke(array $events, array $options = [], array $appEnv = ['APP_ENV' => 'prod', 'APP_DEBUG' => '0']): array
227238 {
228239 $driver = 'require $argv[1]; echo json_encode(array_map(fn ($event) => handle($event, []), json_decode(stream_get_contents(STDIN), true)));';
229240 $process = proc_open(
@@ -231,9 +242,7 @@ final class IntegrationTest extends TestCase
231242 [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
232243 $pipes,
233244 null,
234- [
235- 'APP_ENV' => 'prod',
236- 'APP_DEBUG' => '0',
245+ $appEnv + [
237246 'APP_RUNTIME_OPTIONS' => json_encode(['project_dir' => $this->projectDir] + $options, \JSON_THROW_ON_ERROR),
238247 'TMPDIR' => $this->dir.'/tmp',
239248 'SCALEWAY_CRON_SECRET' => 'cron-secret',
@@ -72,6 +72,9 @@ final class IntegrationTest extends TestCase
72 [$response] = $this->invoke([['path' => '/missing', 'method' => 'GET']]);72 [$response] = $this->invoke([['path' => '/missing', 'method' => 'GET']]);
73 73
74 self::assertSame(404, $response['statusCode']);74 self::assertSame(404, $response['statusCode']);
75+ self::assertIsString($response['body']);
76+ // The CLI error renderer Symfony picks outside a web SAPI would dump the exception, even in prod.
77+ self::assertStringNotContainsString('NotFoundHttpException', $response['body']);
75 }78 }
76 79
77 public function testMultipartUploadReachesTheController(): void80 public function testMultipartUploadReachesTheController(): void
@@ -121,6 +124,13 @@ final class IntegrationTest extends TestCase
121 self::assertSame($first['pid'], $second['pid']);124 self::assertSame($first['pid'], $second['pid']);
122 }125 }
123 126
127+ public function testFunctionWithoutAppEnvRunsProdDespiteTheDotenvFile(): void
128+ {
129+ [$response] = $this->invoke([['path' => '/']], ['front_controller' => 'public/hello.php'], []);
130+
131+ self::assertSame('prod', $this->json($response)['env']);
132+ }
133+
124 public function testRawCallableIsBuiltOnceAndGetsEveryEventUntouchedCronIncluded(): void134 public function testRawCallableIsBuiltOnceAndGetsEveryEventUntouchedCronIncluded(): void
125 {135 {
126 $cron = ['method' => 'POST', 'path' => '/', 'body' => '{"command":"app:count","secret":"cron-secret"}'];136 $cron = ['method' => 'POST', 'path' => '/', 'body' => '{"command":"app:count","secret":"cron-secret"}'];
@@ -220,10 +230,11 @@ final class IntegrationTest extends TestCase
220 /**230 /**
221 * @param list<array<string, mixed>> $events231 * @param list<array<string, mixed>> $events
222 * @param array<string, mixed> $options runtime options on top of "project_dir"232 * @param array<string, mixed> $options runtime options on top of "project_dir"
233+ * @param array<string, string> $appEnv the APP_* variables of the function's environment
223 *234 *
224 * @return array<array<mixed>>235 * @return array<array<mixed>>
225 */236 */
226- private function invoke(array $events, array $options = []): array237+ private function invoke(array $events, array $options = [], array $appEnv = ['APP_ENV' => 'prod', 'APP_DEBUG' => '0']): array
227 {238 {
228 $driver = 'require $argv[1]; echo json_encode(array_map(fn ($event) => handle($event, []), json_decode(stream_get_contents(STDIN), true)));';239 $driver = 'require $argv[1]; echo json_encode(array_map(fn ($event) => handle($event, []), json_decode(stream_get_contents(STDIN), true)));';
229 $process = proc_open(240 $process = proc_open(
@@ -231,9 +242,7 @@ final class IntegrationTest extends TestCase
231 [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],242 [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
232 $pipes,243 $pipes,
233 null,244 null,
234- [245+ $appEnv + [
235- 'APP_ENV' => 'prod',
236- 'APP_DEBUG' => '0',
237 'APP_RUNTIME_OPTIONS' => json_encode(['project_dir' => $this->projectDir] + $options, \JSON_THROW_ON_ERROR),246 'APP_RUNTIME_OPTIONS' => json_encode(['project_dir' => $this->projectDir] + $options, \JSON_THROW_ON_ERROR),
238 'TMPDIR' => $this->dir.'/tmp',247 'TMPDIR' => $this->dir.'/tmp',
239 'SCALEWAY_CRON_SECRET' => 'cron-secret',248 'SCALEWAY_CRON_SECRET' => 'cron-secret',
modified tests/ScalewayRuntimeTest.php +76 -2
@@ -11,27 +11,98 @@ final class ScalewayRuntimeTest extends TestCase
1111 {
1212 /** @var array<mixed> */
1313 private array $server;
14+ /** @var array<mixed> */
15+ private array $env;
16+ private string|false $processEnv;
17+ private int $umask;
1418 private string $projectDir;
1519
1620 protected function setUp(): void
1721 {
1822 $this->server = $_SERVER;
23+ $this->env = $_ENV;
24+ $this->processEnv = getenv('APP_ENV');
25+ // GenericRuntime resets the umask in debug mode.
26+ $this->umask = umask();
1927 unset($_SERVER['APP_BUILD_DIR'], $_SERVER['APP_CACHE_DIR'], $_SERVER['APP_LOG_DIR']);
28+ // As on a function without APP_ENV, whatever the environment running the tests sets.
29+ unset($_SERVER['APP_ENV'], $_ENV['APP_ENV'], $_SERVER['APP_DEBUG'], $_ENV['APP_DEBUG']);
30+ putenv('APP_ENV');
2031 $this->projectDir = sys_get_temp_dir().'/scaleway-runtime-'.bin2hex(random_bytes(4));
2132 mkdir($this->projectDir.'/var', 0o777, true);
33+ file_put_contents($this->projectDir.'/.env', "APP_ENV=dev\n");
2234 }
2335
2436 protected function tearDown(): void
2537 {
2638 $_SERVER = $this->server;
39+ $_ENV = $this->env;
40+ putenv(false === $this->processEnv ? 'APP_ENV' : 'APP_ENV='.$this->processEnv);
41+ umask($this->umask);
2742 chmod($this->projectDir, 0o777);
2843 if (is_dir($this->projectDir.'/var')) {
2944 chmod($this->projectDir.'/var', 0o777);
3045 rmdir($this->projectDir.'/var');
3146 }
47+ unlink($this->projectDir.'/.env');
3248 rmdir($this->projectDir);
3349 }
3450
51+ public function testUnsetEnvDefaultsToProdWithoutDebugWhateverTheDotenvFileSays(): void
52+ {
53+ $this->createRuntime(['debug' => null]);
54+
55+ self::assertSame('prod', $_SERVER['APP_ENV']);
56+ self::assertSame('0', $_SERVER['APP_DEBUG']);
57+ }
58+
59+ public function testEmptyEnvCountsAsUnset(): void
60+ {
61+ $_SERVER['APP_ENV'] = '';
62+
63+ $this->createRuntime(['debug' => null]);
64+
65+ self::assertSame('prod', $_SERVER['APP_ENV']);
66+ }
67+
68+ public function testEnvOfTheProcessWins(): void
69+ {
70+ $_SERVER['APP_ENV'] = 'dev';
71+
72+ $this->createRuntime(['debug' => null]);
73+
74+ self::assertSame('dev', $_SERVER['APP_ENV']);
75+ self::assertSame('1', $_SERVER['APP_DEBUG']);
76+ }
77+
78+ public function testEnvOnlyVisibleThroughGetenvWins(): void
79+ {
80+ putenv('APP_ENV=staging');
81+
82+ $this->createRuntime(['debug' => null]);
83+
84+ self::assertSame('staging', $_SERVER['APP_ENV']);
85+ }
86+
87+ public function testEnvOptionWins(): void
88+ {
89+ $_SERVER['APP_ENV'] = 'dev';
90+
91+ $this->createRuntime(['env' => 'test']);
92+
93+ self::assertSame('test', $_SERVER['APP_ENV']);
94+ }
95+
96+ public function testDebugSetByTheProcessWinsInProd(): void
97+ {
98+ $_SERVER['APP_DEBUG'] = '1';
99+
100+ $this->createRuntime(['debug' => null]);
101+
102+ self::assertSame('prod', $_SERVER['APP_ENV']);
103+ self::assertSame('1', $_SERVER['APP_DEBUG']);
104+ }
105+
35106 public function testWritableProjectKeepsItsDirs(): void
36107 {
37108 $this->createRuntime();
@@ -72,8 +143,11 @@ final class ScalewayRuntimeTest extends TestCase
72143 self::assertSame('/custom/cache', $_SERVER['APP_CACHE_DIR']);
73144 }
74145
75- private function createRuntime(): void
146+ /**
147+ * @param array<string, mixed> $options
148+ */
149+ private function createRuntime(array $options = []): void
76150 {
77- new ScalewayRuntime(['project_dir' => $this->projectDir, 'error_handler' => false, 'debug' => false]);
151+ new ScalewayRuntime($options + ['project_dir' => $this->projectDir, 'error_handler' => false, 'debug' => false]);
78152 }
79153 }
@@ -11,27 +11,98 @@ final class ScalewayRuntimeTest extends TestCase
11 {11 {
12 /** @var array<mixed> */12 /** @var array<mixed> */
13 private array $server;13 private array $server;
14+ /** @var array<mixed> */
15+ private array $env;
16+ private string|false $processEnv;
17+ private int $umask;
14 private string $projectDir;18 private string $projectDir;
15 19
16 protected function setUp(): void20 protected function setUp(): void
17 {21 {
18 $this->server = $_SERVER;22 $this->server = $_SERVER;
23+ $this->env = $_ENV;
24+ $this->processEnv = getenv('APP_ENV');
25+ // GenericRuntime resets the umask in debug mode.
26+ $this->umask = umask();
19 unset($_SERVER['APP_BUILD_DIR'], $_SERVER['APP_CACHE_DIR'], $_SERVER['APP_LOG_DIR']);27 unset($_SERVER['APP_BUILD_DIR'], $_SERVER['APP_CACHE_DIR'], $_SERVER['APP_LOG_DIR']);
28+ // As on a function without APP_ENV, whatever the environment running the tests sets.
29+ unset($_SERVER['APP_ENV'], $_ENV['APP_ENV'], $_SERVER['APP_DEBUG'], $_ENV['APP_DEBUG']);
30+ putenv('APP_ENV');
20 $this->projectDir = sys_get_temp_dir().'/scaleway-runtime-'.bin2hex(random_bytes(4));31 $this->projectDir = sys_get_temp_dir().'/scaleway-runtime-'.bin2hex(random_bytes(4));
21 mkdir($this->projectDir.'/var', 0o777, true);32 mkdir($this->projectDir.'/var', 0o777, true);
33+ file_put_contents($this->projectDir.'/.env', "APP_ENV=dev\n");
22 }34 }
23 35
24 protected function tearDown(): void36 protected function tearDown(): void
25 {37 {
26 $_SERVER = $this->server;38 $_SERVER = $this->server;
39+ $_ENV = $this->env;
40+ putenv(false === $this->processEnv ? 'APP_ENV' : 'APP_ENV='.$this->processEnv);
41+ umask($this->umask);
27 chmod($this->projectDir, 0o777);42 chmod($this->projectDir, 0o777);
28 if (is_dir($this->projectDir.'/var')) {43 if (is_dir($this->projectDir.'/var')) {
29 chmod($this->projectDir.'/var', 0o777);44 chmod($this->projectDir.'/var', 0o777);
30 rmdir($this->projectDir.'/var');45 rmdir($this->projectDir.'/var');
31 }46 }
47+ unlink($this->projectDir.'/.env');
32 rmdir($this->projectDir);48 rmdir($this->projectDir);
33 }49 }
34 50
51+ public function testUnsetEnvDefaultsToProdWithoutDebugWhateverTheDotenvFileSays(): void
52+ {
53+ $this->createRuntime(['debug' => null]);
54+
55+ self::assertSame('prod', $_SERVER['APP_ENV']);
56+ self::assertSame('0', $_SERVER['APP_DEBUG']);
57+ }
58+
59+ public function testEmptyEnvCountsAsUnset(): void
60+ {
61+ $_SERVER['APP_ENV'] = '';
62+
63+ $this->createRuntime(['debug' => null]);
64+
65+ self::assertSame('prod', $_SERVER['APP_ENV']);
66+ }
67+
68+ public function testEnvOfTheProcessWins(): void
69+ {
70+ $_SERVER['APP_ENV'] = 'dev';
71+
72+ $this->createRuntime(['debug' => null]);
73+
74+ self::assertSame('dev', $_SERVER['APP_ENV']);
75+ self::assertSame('1', $_SERVER['APP_DEBUG']);
76+ }
77+
78+ public function testEnvOnlyVisibleThroughGetenvWins(): void
79+ {
80+ putenv('APP_ENV=staging');
81+
82+ $this->createRuntime(['debug' => null]);
83+
84+ self::assertSame('staging', $_SERVER['APP_ENV']);
85+ }
86+
87+ public function testEnvOptionWins(): void
88+ {
89+ $_SERVER['APP_ENV'] = 'dev';
90+
91+ $this->createRuntime(['env' => 'test']);
92+
93+ self::assertSame('test', $_SERVER['APP_ENV']);
94+ }
95+
96+ public function testDebugSetByTheProcessWinsInProd(): void
97+ {
98+ $_SERVER['APP_DEBUG'] = '1';
99+
100+ $this->createRuntime(['debug' => null]);
101+
102+ self::assertSame('prod', $_SERVER['APP_ENV']);
103+ self::assertSame('1', $_SERVER['APP_DEBUG']);
104+ }
105+
35 public function testWritableProjectKeepsItsDirs(): void106 public function testWritableProjectKeepsItsDirs(): void
36 {107 {
37 $this->createRuntime();108 $this->createRuntime();
@@ -72,8 +143,11 @@ final class ScalewayRuntimeTest extends TestCase
72 self::assertSame('/custom/cache', $_SERVER['APP_CACHE_DIR']);143 self::assertSame('/custom/cache', $_SERVER['APP_CACHE_DIR']);
73 }144 }
74 145
75- private function createRuntime(): void146+ /**
147+ * @param array<string, mixed> $options
148+ */
149+ private function createRuntime(array $options = []): void
76 {150 {
77- new ScalewayRuntime(['project_dir' => $this->projectDir, 'error_handler' => false, 'debug' => false]);151+ new ScalewayRuntime($options + ['project_dir' => $this->projectDir, 'error_handler' => false, 'debug' => false]);
78 }152 }
79 }153 }