jdecool/scaleway-runtimepublic Fork
⑂ ff07ec9
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: run Command Invocations authenticated by a CRON secretUnverified

A CRON Invocation whose JSON body names a command and carries the secret of
SCALEWAY_CRON_SECRET runs that command through the Console Application of the
Kernel, without interaction and with its output as body: 200 on exit code 0,
500 otherwise. Any other body, and every body while the variable is unset,
stays a plain HTTP body, so internet clients cannot run commands. Front
Controllers returning a Console Application or a Command run Command
Invocations only and answer 403 to the rest.
Jérémy DECOOL committed 2026-11-13T23:01:15+01:00 Browse files
ff07ec9 parent: 9fccae2
modified GLOSSARY.md +5 -1
@@ -40,7 +40,11 @@ An Invocation triggered by a Scaleway CRON trigger, carrying the trigger's confi
4040 _Avoid_: Scheduled job, cron task
4141
4242 **Command Invocation**:
43-A CRON Invocation whose body names a console command to run instead of an HTTP route.
43+A CRON Invocation whose body names a console command to run instead of an HTTP route, and carries the CRON Secret.
44+
45+**CRON Secret**:
46+The shared secret, known to the function and to its CRON triggers, that proves a CRON Invocation may run a console command.
47+_Avoid_: Token, API key
4448
4549 **Emulator**:
4650 The local server that turns real HTTP requests into Events and calls the Handler, to run an application without deploying it.
@@ -40,7 +40,11 @@ An Invocation triggered by a Scaleway CRON trigger, carrying the trigger's confi
40 _Avoid_: Scheduled job, cron task40 _Avoid_: Scheduled job, cron task
41 41
42 **Command Invocation**:42 **Command Invocation**:
43-A CRON Invocation whose body names a console command to run instead of an HTTP route.43+A CRON Invocation whose body names a console command to run instead of an HTTP route, and carries the CRON Secret.
44+
45+**CRON Secret**:
46+The shared secret, known to the function and to its CRON triggers, that proves a CRON Invocation may run a console command.
47+_Avoid_: Token, API key
44 48
45 **Emulator**:49 **Emulator**:
46 The local server that turns real HTTP requests into Events and calls the Handler, to run an application without deploying it.50 The local server that turns real HTTP requests into Events and calls the Handler, to run an application without deploying it.
modified README.md +18 -1
@@ -14,12 +14,29 @@ See the [implementation plan](docs/plan.md) for the design and the roadmap, and
1414 - `vendor/bin/scaleway-package [function.zip]` builds the deployment zip: a copy of the application without local, test and secret files (see `Packager::EXCLUDES`), production dependencies installed from `composer.lock` with an authoritative class map, and the prod cache warmed up by `bin/console cache:warmup`.
1515 It needs the `zip` PHP extension and `composer` on the `PATH`, and warns when the zip exceeds Scaleway's limits (100 MiB zipped, 500 MiB unzipped).
1616 - `vendor/bin/scaleway-serve [127.0.0.1:8000]` starts the Emulator: each HTTP request becomes an Event passed to the application's `handle()`, and the Function Response becomes the HTTP response.
17- A CRON Invocation is simulated with a `POST /` carrying the trigger's arguments as JSON body.
17+ A CRON Invocation is simulated with a `POST /` carrying the trigger's arguments as JSON body, a Command Invocation by starting the Emulator with `SCALEWAY_CRON_SECRET` set and sending its body the same way.
1818
1919 The Emulator runs `handle()` in one long-lived PHP process, as a Warm Process on Scaleway: code changes need a restart, and a crashed process is replaced by a fresh one.
2020 PHP's built-in server alone could not do this, since it keeps its process but wipes all PHP state after each request.
2121 How Scaleway fills `X-Forwarded-*`, folds repeated query keys and names headers is still assumed.
2222
23+## CRON triggers and console commands
24+
25+A CRON trigger calls the Application with a `POST /` whose JSON body holds the trigger's arguments.
26+To run a console command instead, set a random `SCALEWAY_CRON_SECRET` as a secret environment variable of the function (for instance `openssl rand -hex 32`), and give the trigger these arguments:
27+
28+```json
29+{"command": "app:sync", "args": {"source": "s3", "--force": true, "--tag": ["a", "b"]}, "secret": "<SCALEWAY_CRON_SECRET>"}
30+```
31+
32+`args` maps argument names, and option names with their dashes, to values, as Symfony's `ArrayInput` does; the command runs without interaction, through the Console Application of the same Kernel.
33+Exit code 0 answers a 200 and any other exit code a 500, both with the command output as plain text body; a failure is also logged to stderr with that output.
34+Without the variable, or with another secret, the body is a plain HTTP body and reaches `POST /`: an HTTP client cannot run commands without knowing the secret (see [ADR 0005](docs/adr/0005-authenticate-command-invocations-with-a-shared-secret.md)).
35+
36+A Front Controller may also return a Console `Application` or a `Command`, as with SymfonyRuntime: the function then only runs Command Invocations, and answers any other Invocation with a 403.
37+A single `Command` runs whatever `command` the arguments name.
38+Running commands needs `symfony/console`, and `symfony/framework-bundle` for a Kernel.
39+
2340 ## License
2441
2542 Released under the [MIT License](LICENSE).
@@ -14,12 +14,29 @@ See the [implementation plan](docs/plan.md) for the design and the roadmap, and
14 - `vendor/bin/scaleway-package [function.zip]` builds the deployment zip: a copy of the application without local, test and secret files (see `Packager::EXCLUDES`), production dependencies installed from `composer.lock` with an authoritative class map, and the prod cache warmed up by `bin/console cache:warmup`.14 - `vendor/bin/scaleway-package [function.zip]` builds the deployment zip: a copy of the application without local, test and secret files (see `Packager::EXCLUDES`), production dependencies installed from `composer.lock` with an authoritative class map, and the prod cache warmed up by `bin/console cache:warmup`.
15 It needs the `zip` PHP extension and `composer` on the `PATH`, and warns when the zip exceeds Scaleway's limits (100 MiB zipped, 500 MiB unzipped).15 It needs the `zip` PHP extension and `composer` on the `PATH`, and warns when the zip exceeds Scaleway's limits (100 MiB zipped, 500 MiB unzipped).
16 - `vendor/bin/scaleway-serve [127.0.0.1:8000]` starts the Emulator: each HTTP request becomes an Event passed to the application's `handle()`, and the Function Response becomes the HTTP response.16 - `vendor/bin/scaleway-serve [127.0.0.1:8000]` starts the Emulator: each HTTP request becomes an Event passed to the application's `handle()`, and the Function Response becomes the HTTP response.
17- A CRON Invocation is simulated with a `POST /` carrying the trigger's arguments as JSON body.17+ A CRON Invocation is simulated with a `POST /` carrying the trigger's arguments as JSON body, a Command Invocation by starting the Emulator with `SCALEWAY_CRON_SECRET` set and sending its body the same way.
18 18
19 The Emulator runs `handle()` in one long-lived PHP process, as a Warm Process on Scaleway: code changes need a restart, and a crashed process is replaced by a fresh one.19 The Emulator runs `handle()` in one long-lived PHP process, as a Warm Process on Scaleway: code changes need a restart, and a crashed process is replaced by a fresh one.
20 PHP's built-in server alone could not do this, since it keeps its process but wipes all PHP state after each request.20 PHP's built-in server alone could not do this, since it keeps its process but wipes all PHP state after each request.
21 How Scaleway fills `X-Forwarded-*`, folds repeated query keys and names headers is still assumed.21 How Scaleway fills `X-Forwarded-*`, folds repeated query keys and names headers is still assumed.
22 22
23+## CRON triggers and console commands
24+
25+A CRON trigger calls the Application with a `POST /` whose JSON body holds the trigger's arguments.
26+To run a console command instead, set a random `SCALEWAY_CRON_SECRET` as a secret environment variable of the function (for instance `openssl rand -hex 32`), and give the trigger these arguments:
27+
28+```json
29+{"command": "app:sync", "args": {"source": "s3", "--force": true, "--tag": ["a", "b"]}, "secret": "<SCALEWAY_CRON_SECRET>"}
30+```
31+
32+`args` maps argument names, and option names with their dashes, to values, as Symfony's `ArrayInput` does; the command runs without interaction, through the Console Application of the same Kernel.
33+Exit code 0 answers a 200 and any other exit code a 500, both with the command output as plain text body; a failure is also logged to stderr with that output.
34+Without the variable, or with another secret, the body is a plain HTTP body and reaches `POST /`: an HTTP client cannot run commands without knowing the secret (see [ADR 0005](docs/adr/0005-authenticate-command-invocations-with-a-shared-secret.md)).
35+
36+A Front Controller may also return a Console `Application` or a `Command`, as with SymfonyRuntime: the function then only runs Command Invocations, and answers any other Invocation with a 403.
37+A single `Command` runs whatever `command` the arguments name.
38+Running commands needs `symfony/console`, and `symfony/framework-bundle` for a Kernel.
39+
23 ## License40 ## License
24 41
25 Released under the [MIT License](LICENSE).42 Released under the [MIT License](LICENSE).
modified composer.json +2 -0
@@ -19,6 +19,7 @@
1919 "suggest": {
2020 "ext-zip": "To build the deployment zip with vendor/bin/scaleway-package",
2121 "nyholm/psr7": "To run Front Controllers returning a PSR-15 request handler",
22+ "symfony/console": "To run Command Invocations and Front Controllers returning a Console Application or a Command",
2223 "symfony/psr-http-message-bridge": "To run Front Controllers returning a PSR-15 request handler"
2324 },
2425 "require-dev": {
@@ -28,6 +29,7 @@
2829 "phpstan/phpstan-phpunit": "^2.1",
2930 "phpunit/phpunit": "^13.4",
3031 "psr/http-server-handler": "^1.0",
32+ "symfony/console": "^7.4 || ^8.0",
3133 "symfony/framework-bundle": "^7.4 || ^8.0",
3234 "symfony/psr-http-message-bridge": "^7.4 || ^8.0"
3335 },
@@ -19,6 +19,7 @@
19 "suggest": {19 "suggest": {
20 "ext-zip": "To build the deployment zip with vendor/bin/scaleway-package",20 "ext-zip": "To build the deployment zip with vendor/bin/scaleway-package",
21 "nyholm/psr7": "To run Front Controllers returning a PSR-15 request handler",21 "nyholm/psr7": "To run Front Controllers returning a PSR-15 request handler",
22+ "symfony/console": "To run Command Invocations and Front Controllers returning a Console Application or a Command",
22 "symfony/psr-http-message-bridge": "To run Front Controllers returning a PSR-15 request handler"23 "symfony/psr-http-message-bridge": "To run Front Controllers returning a PSR-15 request handler"
23 },24 },
24 "require-dev": {25 "require-dev": {
@@ -28,6 +29,7 @@
28 "phpstan/phpstan-phpunit": "^2.1",29 "phpstan/phpstan-phpunit": "^2.1",
29 "phpunit/phpunit": "^13.4",30 "phpunit/phpunit": "^13.4",
30 "psr/http-server-handler": "^1.0",31 "psr/http-server-handler": "^1.0",
32+ "symfony/console": "^7.4 || ^8.0",
31 "symfony/framework-bundle": "^7.4 || ^8.0",33 "symfony/framework-bundle": "^7.4 || ^8.0",
32 "symfony/psr-http-message-bridge": "^7.4 || ^8.0"34 "symfony/psr-http-message-bridge": "^7.4 || ^8.0"
33 },35 },
added docs/adr/0005-authenticate-command-invocations-with-a-shared-secret.md +18 -0
new file mode 100644
@@ -0,0 +1,18 @@
1+# Command Invocations are authenticated by a shared secret carried in the CRON arguments
2+
3+A CRON Invocation reaches the function as an Event whose body holds the trigger's arguments, and nothing documented tells it apart from an HTTP Invocation: a public function would otherwise run any console command an internet client POSTs as `{"command": ...}`.
4+We therefore only run a Command Invocation when its body also carries a `secret` equal, in constant time, to the `SCALEWAY_CRON_SECRET` environment variable (a secret one on Scaleway); otherwise, and always when that variable is unset or empty, the body goes to the Application as a plain HTTP body, so Command Invocations are off by default.
5+The check lives in `CommandInvocation::fromEvent()` alone, to be replaced or complemented once the probe finds a platform marker that HTTP clients cannot forge.
6+
7+## Considered Options
8+
9+- Trusting a body naming a command, or a CRON-looking Event shape (method, path, missing headers): rejected, any HTTP client can send the same.
10+- A platform marker (header, context field): preferred once known, but the CRON Event shape is still unmeasured, and a header is only a marker if the platform strips it from HTTP calls.
11+- Private functions, authenticated by Scaleway tokens: rejected as the default, as the Application could no longer serve public HTTP Invocations, and whether CRON Invocations of a private function carry anything verifiable is unknown.
12+- An allowlist of commands: rejected, as the CRON arguments that name the commands already live next to the secret, in the Scaleway project and its Terraform state, so whoever can read the secret can usually redeploy the function too.
13+
14+## Consequences
15+
16+- The secret is stored in clear in the CRON arguments, visible to anyone who can read the function's triggers or the Terraform state, and it is the same for every run: rotating it means updating the variable and every CRON trigger together.
17+- A body carrying a wrong `secret` is logged, without its value, so a misconfigured trigger shows up in the logs instead of silently landing on `POST /`.
18+- A Front Controller returning a Console Application or a Command serves Command Invocations only, and answers every other Invocation with a 403.
new file mode 100644
@@ -0,0 +1,18 @@
1+# Command Invocations are authenticated by a shared secret carried in the CRON arguments
2+
3+A CRON Invocation reaches the function as an Event whose body holds the trigger's arguments, and nothing documented tells it apart from an HTTP Invocation: a public function would otherwise run any console command an internet client POSTs as `{"command": ...}`.
4+We therefore only run a Command Invocation when its body also carries a `secret` equal, in constant time, to the `SCALEWAY_CRON_SECRET` environment variable (a secret one on Scaleway); otherwise, and always when that variable is unset or empty, the body goes to the Application as a plain HTTP body, so Command Invocations are off by default.
5+The check lives in `CommandInvocation::fromEvent()` alone, to be replaced or complemented once the probe finds a platform marker that HTTP clients cannot forge.
6+
7+## Considered Options
8+
9+- Trusting a body naming a command, or a CRON-looking Event shape (method, path, missing headers): rejected, any HTTP client can send the same.
10+- A platform marker (header, context field): preferred once known, but the CRON Event shape is still unmeasured, and a header is only a marker if the platform strips it from HTTP calls.
11+- Private functions, authenticated by Scaleway tokens: rejected as the default, as the Application could no longer serve public HTTP Invocations, and whether CRON Invocations of a private function carry anything verifiable is unknown.
12+- An allowlist of commands: rejected, as the CRON arguments that name the commands already live next to the secret, in the Scaleway project and its Terraform state, so whoever can read the secret can usually redeploy the function too.
13+
14+## Consequences
15+
16+- The secret is stored in clear in the CRON arguments, visible to anyone who can read the function's triggers or the Terraform state, and it is the same for every run: rotating it means updating the variable and every CRON trigger together.
17+- A body carrying a wrong `secret` is logged, without its value, so a misconfigured trigger shows up in the logs instead of silently landing on `POST /`.
18+- A Front Controller returning a Console Application or a Command serves Command Invocations only, and answers every other Invocation with a 403.
modified docs/plan.md +2 -1
@@ -16,7 +16,8 @@ Vocabulary follows [GLOSSARY.md](../GLOSSARY.md); decisions are recorded in [doc
1616 - Errors escaping the Application are logged to stderr and returned as a 500 Function Response (generic body, details when `APP_DEBUG=1`).
1717 - Cache is warmed at build time; cache and log dirs fall back to `/tmp` when the project dir is not writable; logs go to stderr.
1818 - `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": {...}}` makes it a Command Invocation run through the Console Application of the same Kernel; a non-zero exit code yields a 500 with the command output.
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+- A Front Controller returning a Console `Application` or a `Command` serves Command Invocations only and answers a 403 to the others; services are reset before and after each command, as no HTTP request follows to trigger the Kernel's own reset.
2021 - Tests: PHPUnit on conversions, GitHub Actions CI (PHPUnit, PHPStan max, PHP-CS-Fixer; PHP 8.4/8.5 x Symfony 7.4/8.x), local Emulator `vendor/bin/scaleway-serve`, manual real E2E deployed with Terraform.
2122
2223 ## Phases
@@ -16,7 +16,8 @@ Vocabulary follows [GLOSSARY.md](../GLOSSARY.md); decisions are recorded in [doc
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 - Cache is warmed at build time; cache and log dirs fall back to `/tmp` when the project dir is not writable; logs go to stderr.17 - Cache is warmed at build time; cache and log dirs fall back to `/tmp` when the project dir is not writable; logs go to stderr.
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).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-- CRON Invocations become `POST /` HTTP requests by default; a JSON body `{"command": "...", "args": {...}}` makes it a Command Invocation run through the Console Application of the same Kernel; a non-zero exit code yields a 500 with the command output.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+- A Front Controller returning a Console `Application` or a `Command` serves Command Invocations only and answers a 403 to the others; services are reset before and after each command, as no HTTP request follows to trigger the Kernel's own reset.
20 - Tests: PHPUnit on conversions, GitHub Actions CI (PHPUnit, PHPStan max, PHP-CS-Fixer; PHP 8.4/8.5 x Symfony 7.4/8.x), local Emulator `vendor/bin/scaleway-serve`, manual real E2E deployed with Terraform.21 - Tests: PHPUnit on conversions, GitHub Actions CI (PHPUnit, PHPStan max, PHP-CS-Fixer; PHP 8.4/8.5 x Symfony 7.4/8.x), local Emulator `vendor/bin/scaleway-serve`, manual real E2E deployed with Terraform.
21 22
22 ## Phases23 ## Phases
added src/CommandInvocation.php +60 -0
new file mode 100644
@@ -0,0 +1,60 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime;
6+
7+/**
8+ * A console command an authenticated CRON Invocation asks to run.
9+ *
10+ * Nothing known in an Event tells a CRON Invocation from an HTTP one, so the CRON arguments must carry
11+ * the secret set in SCALEWAY_CRON_SECRET; without it, a body naming a command is a plain HTTP body
12+ * (see docs/adr/0005-authenticate-command-invocations-with-a-shared-secret.md).
13+ * This is the one place to change once the probe finds a platform marker HTTP clients cannot forge.
14+ */
15+final readonly class CommandInvocation
16+{
17+ public const string SECRET_VAR = 'SCALEWAY_CRON_SECRET';
18+
19+ /**
20+ * @param array<string, mixed> $args ArrayInput parameters: argument names and "--option" names to values
21+ */
22+ private function __construct(
23+ public string $command,
24+ public array $args,
25+ ) {
26+ }
27+
28+ /**
29+ * @param array<mixed> $event
30+ * @param resource $errorLog
31+ */
32+ public static function fromEvent(array $event, mixed $errorLog): ?self
33+ {
34+ $secret = $_SERVER[self::SECRET_VAR] ?? $_ENV[self::SECRET_VAR] ?? getenv(self::SECRET_VAR);
35+ $body = \is_string($event['body'] ?? null) ? $event['body'] : '';
36+ if (true === ($event['isBase64Encoded'] ?? false)) {
37+ $body = (string) base64_decode($body, true);
38+ }
39+ $data = json_decode($body, true);
40+ if (!\is_array($data) || !\is_string($data['command'] ?? null)) {
41+ return null;
42+ }
43+
44+ if (!\is_string($secret) || '' === $secret || !\is_string($data['secret'] ?? null) || !hash_equals($secret, $data['secret'])) {
45+ // Only bodies meant as Command Invocations are worth a line: APIs may legitimately take a "command" field.
46+ if (\array_key_exists('secret', $data)) {
47+ fwrite($errorLog, \sprintf('Command Invocation rejected: the "secret" does not match %s, the body goes to the Application as a plain HTTP body.', self::SECRET_VAR).\PHP_EOL);
48+ }
49+
50+ return null;
51+ }
52+
53+ $args = $data['args'] ?? [];
54+ if (!\is_array($args) || array_any($args, static fn (mixed $value, int|string $name): bool => \is_int($name))) {
55+ throw new \UnexpectedValueException('The "args" of a Command Invocation must be a JSON object mapping argument and "--option" names to values.');
56+ }
57+
58+ return new self($data['command'], array_filter($args, \is_string(...), \ARRAY_FILTER_USE_KEY));
59+ }
60+}
new file mode 100644
@@ -0,0 +1,60 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime;
6+
7+/**
8+ * A console command an authenticated CRON Invocation asks to run.
9+ *
10+ * Nothing known in an Event tells a CRON Invocation from an HTTP one, so the CRON arguments must carry
11+ * the secret set in SCALEWAY_CRON_SECRET; without it, a body naming a command is a plain HTTP body
12+ * (see docs/adr/0005-authenticate-command-invocations-with-a-shared-secret.md).
13+ * This is the one place to change once the probe finds a platform marker HTTP clients cannot forge.
14+ */
15+final readonly class CommandInvocation
16+{
17+ public const string SECRET_VAR = 'SCALEWAY_CRON_SECRET';
18+
19+ /**
20+ * @param array<string, mixed> $args ArrayInput parameters: argument names and "--option" names to values
21+ */
22+ private function __construct(
23+ public string $command,
24+ public array $args,
25+ ) {
26+ }
27+
28+ /**
29+ * @param array<mixed> $event
30+ * @param resource $errorLog
31+ */
32+ public static function fromEvent(array $event, mixed $errorLog): ?self
33+ {
34+ $secret = $_SERVER[self::SECRET_VAR] ?? $_ENV[self::SECRET_VAR] ?? getenv(self::SECRET_VAR);
35+ $body = \is_string($event['body'] ?? null) ? $event['body'] : '';
36+ if (true === ($event['isBase64Encoded'] ?? false)) {
37+ $body = (string) base64_decode($body, true);
38+ }
39+ $data = json_decode($body, true);
40+ if (!\is_array($data) || !\is_string($data['command'] ?? null)) {
41+ return null;
42+ }
43+
44+ if (!\is_string($secret) || '' === $secret || !\is_string($data['secret'] ?? null) || !hash_equals($secret, $data['secret'])) {
45+ // Only bodies meant as Command Invocations are worth a line: APIs may legitimately take a "command" field.
46+ if (\array_key_exists('secret', $data)) {
47+ fwrite($errorLog, \sprintf('Command Invocation rejected: the "secret" does not match %s, the body goes to the Application as a plain HTTP body.', self::SECRET_VAR).\PHP_EOL);
48+ }
49+
50+ return null;
51+ }
52+
53+ $args = $data['args'] ?? [];
54+ if (!\is_array($args) || array_any($args, static fn (mixed $value, int|string $name): bool => \is_int($name))) {
55+ throw new \UnexpectedValueException('The "args" of a Command Invocation must be a JSON object mapping argument and "--option" names to values.');
56+ }
57+
58+ return new self($data['command'], array_filter($args, \is_string(...), \ARRAY_FILTER_USE_KEY));
59+ }
60+}
added src/Runner/ConsoleRunner.php +75 -0
new file mode 100644
@@ -0,0 +1,75 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime\Runner;
6+
7+use JDecool\ScalewayRuntime\CommandInvocation;
8+use JDecool\ScalewayRuntime\HttpConverter;
9+use Symfony\Component\Console\Application;
10+use Symfony\Component\Console\Input\ArrayInput;
11+use Symfony\Component\Console\Output\BufferedOutput;
12+use Symfony\Component\HttpFoundation\Response;
13+
14+/**
15+ * Runs Command Invocations through the Console Application, and hands every other Invocation to the HTTP runner.
16+ *
17+ * A command exiting with 0 answers a 200, any other exit code a 500, both with the command output as body.
18+ */
19+final class ConsoleRunner implements InvocationRunner
20+{
21+ private ?Application $console = null;
22+
23+ /**
24+ * @param \Closure(): Application $createConsole called on the first Command Invocation only, so HTTP-only
25+ * Applications never need symfony/console
26+ * @param InvocationRunner|null $httpRunner null for Applications serving Command Invocations only
27+ * @param resource $errorLog
28+ */
29+ public function __construct(
30+ private readonly \Closure $createConsole,
31+ private readonly ?InvocationRunner $httpRunner,
32+ private readonly mixed $errorLog,
33+ ) {
34+ }
35+
36+ public function invoke(array $event, mixed $context): array
37+ {
38+ $invocation = CommandInvocation::fromEvent($event, $this->errorLog);
39+ if (null === $invocation) {
40+ return $this->httpRunner?->invoke($event, $context)
41+ ?? ['statusCode' => 403, 'headers' => ['Content-Type' => 'text/plain; charset=UTF-8'], 'body' => 'Forbidden'];
42+ }
43+
44+ if (null === $this->console) {
45+ $console = ($this->createConsole)();
46+ // A Warm Process must survive the command, and its output must reach the Function Response.
47+ $console->setAutoExit(false);
48+ $console->setCatchExceptions(true);
49+ $console->setCatchErrors(true);
50+ $this->console = $console;
51+ }
52+
53+ // A single-command Application has no "command" argument: it runs its command whatever the name, as from a shell.
54+ $input = new ArrayInput($this->console->isSingleCommand() ? $invocation->args : ['command' => $invocation->command] + $invocation->args);
55+ // Nobody can answer a question during a CRON Invocation: questions get their default answer.
56+ $input->setInteractive(false);
57+ $output = new BufferedOutput(decorated: false);
58+
59+ // The Kernel resets its services before handling a request, not before a command, nor after one.
60+ $this->console->reset();
61+ try {
62+ $exitCode = $this->console->run($input, $output);
63+ } finally {
64+ $this->console->reset();
65+ }
66+
67+ $body = $output->fetch();
68+ if (0 !== $exitCode) {
69+ // A CRON trigger may drop the Function Response, so the log is where the failure stays visible.
70+ fwrite($this->errorLog, \sprintf('Command "%s" failed with exit code %d: %s', $invocation->command, $exitCode, $body).\PHP_EOL);
71+ }
72+
73+ return HttpConverter::toFunctionResponse(new Response($body, 0 === $exitCode ? 200 : 500, ['Content-Type' => 'text/plain; charset=UTF-8']));
74+ }
75+}
new file mode 100644
@@ -0,0 +1,75 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime\Runner;
6+
7+use JDecool\ScalewayRuntime\CommandInvocation;
8+use JDecool\ScalewayRuntime\HttpConverter;
9+use Symfony\Component\Console\Application;
10+use Symfony\Component\Console\Input\ArrayInput;
11+use Symfony\Component\Console\Output\BufferedOutput;
12+use Symfony\Component\HttpFoundation\Response;
13+
14+/**
15+ * Runs Command Invocations through the Console Application, and hands every other Invocation to the HTTP runner.
16+ *
17+ * A command exiting with 0 answers a 200, any other exit code a 500, both with the command output as body.
18+ */
19+final class ConsoleRunner implements InvocationRunner
20+{
21+ private ?Application $console = null;
22+
23+ /**
24+ * @param \Closure(): Application $createConsole called on the first Command Invocation only, so HTTP-only
25+ * Applications never need symfony/console
26+ * @param InvocationRunner|null $httpRunner null for Applications serving Command Invocations only
27+ * @param resource $errorLog
28+ */
29+ public function __construct(
30+ private readonly \Closure $createConsole,
31+ private readonly ?InvocationRunner $httpRunner,
32+ private readonly mixed $errorLog,
33+ ) {
34+ }
35+
36+ public function invoke(array $event, mixed $context): array
37+ {
38+ $invocation = CommandInvocation::fromEvent($event, $this->errorLog);
39+ if (null === $invocation) {
40+ return $this->httpRunner?->invoke($event, $context)
41+ ?? ['statusCode' => 403, 'headers' => ['Content-Type' => 'text/plain; charset=UTF-8'], 'body' => 'Forbidden'];
42+ }
43+
44+ if (null === $this->console) {
45+ $console = ($this->createConsole)();
46+ // A Warm Process must survive the command, and its output must reach the Function Response.
47+ $console->setAutoExit(false);
48+ $console->setCatchExceptions(true);
49+ $console->setCatchErrors(true);
50+ $this->console = $console;
51+ }
52+
53+ // A single-command Application has no "command" argument: it runs its command whatever the name, as from a shell.
54+ $input = new ArrayInput($this->console->isSingleCommand() ? $invocation->args : ['command' => $invocation->command] + $invocation->args);
55+ // Nobody can answer a question during a CRON Invocation: questions get their default answer.
56+ $input->setInteractive(false);
57+ $output = new BufferedOutput(decorated: false);
58+
59+ // The Kernel resets its services before handling a request, not before a command, nor after one.
60+ $this->console->reset();
61+ try {
62+ $exitCode = $this->console->run($input, $output);
63+ } finally {
64+ $this->console->reset();
65+ }
66+
67+ $body = $output->fetch();
68+ if (0 !== $exitCode) {
69+ // A CRON trigger may drop the Function Response, so the log is where the failure stays visible.
70+ fwrite($this->errorLog, \sprintf('Command "%s" failed with exit code %d: %s', $invocation->command, $exitCode, $body).\PHP_EOL);
71+ }
72+
73+ return HttpConverter::toFunctionResponse(new Response($body, 0 === $exitCode ? 200 : 500, ['Content-Type' => 'text/plain; charset=UTF-8']));
74+ }
75+}
modified src/ScalewayRuntime.php +49 -5
@@ -4,14 +4,19 @@ declare(strict_types=1);
44
55 namespace JDecool\ScalewayRuntime;
66
7+use JDecool\ScalewayRuntime\Runner\ConsoleRunner;
78 use JDecool\ScalewayRuntime\Runner\HttpKernelRunner;
89 use JDecool\ScalewayRuntime\Runner\InvocationRunner;
910 use JDecool\ScalewayRuntime\Runner\RequestHandlerKernel;
1011 use JDecool\ScalewayRuntime\Runner\ResponseKernel;
1112 use Psr\Http\Server\RequestHandlerInterface;
13+use Symfony\Bundle\FrameworkBundle\Console\Application as FrameworkApplication;
14+use Symfony\Component\Console\Application;
15+use Symfony\Component\Console\Command\Command;
1216 use Symfony\Component\HttpFoundation\Request;
1317 use Symfony\Component\HttpFoundation\Response;
1418 use Symfony\Component\HttpKernel\HttpKernelInterface;
19+use Symfony\Component\HttpKernel\KernelInterface;
1520 use Symfony\Component\Runtime\SymfonyRuntime;
1621
1722 /**
@@ -27,6 +32,9 @@ use Symfony\Component\Runtime\SymfonyRuntime;
2732 * A Front Controller closure returning a Response is called again for every Invocation, and one
2833 * taking a Request gets the Invocation's Request (see docs/adr/0004-call-response-front-controllers-per-invocation.md).
2934 * A PSR-15 request handler is built once and reused like a Kernel; it needs symfony/psr-http-message-bridge and nyholm/psr7.
35+ *
36+ * Command Invocations run through the Console Application of a Kernel, or of a Front Controller returning a
37+ * Console Application or a Command, which then answers any other Invocation with a 403.
3038 */
3139 class ScalewayRuntime extends SymfonyRuntime
3240 {
@@ -85,19 +93,55 @@ class ScalewayRuntime extends SymfonyRuntime
8593 foreach (new \ReflectionFunction($app(...))->getParameters() as $parameter) {
8694 $type = $parameter->getType();
8795 if ($type instanceof \ReflectionNamedType && Request::class === $type->getName()) {
88- return new HttpKernelRunner(new ResponseKernel($respond), $errorLog);
96+ return $this->withCommands(new ResponseKernel($respond), $app(...), $errorLog);
8997 }
9098 }
9199
92100 [$app, $args] = $resolver->resolve();
93101 $application = $app(...$args);
94102
95- return match (true) {
96- $application instanceof HttpKernelInterface => new HttpKernelRunner($application, $errorLog),
97- $application instanceof Response => new HttpKernelRunner(new ResponseKernel($respond, $application), $errorLog),
98- $application instanceof RequestHandlerInterface => new HttpKernelRunner(new RequestHandlerKernel($application), $errorLog),
103+ if ($application instanceof Command) {
104+ $command = $application;
105+ $application = new Application();
106+ // SymfonyRuntime names a nameless command after argv[0], the script path: the Front Controller here.
107+ if (!$command->getName()) {
108+ $command->setName($frontController);
109+ }
110+ $application->addCommand($command);
111+ $application->setDefaultCommand((string) $command->getName(), true);
112+ }
113+ if ($application instanceof Application) {
114+ return new ConsoleRunner(static fn (): Application => $application, null, $errorLog);
115+ }
116+
117+ $kernel = match (true) {
118+ $application instanceof HttpKernelInterface => $application,
119+ $application instanceof Response => new ResponseKernel($respond, $application),
120+ $application instanceof RequestHandlerInterface => new RequestHandlerKernel($application),
99121 default => throw new \LogicException(\sprintf('"%s" cannot run Applications of type "%s".', static::class, get_debug_type($application))),
100122 };
123+
124+ return $this->withCommands($kernel, $application, $errorLog);
125+ }
126+
127+ /**
128+ * Serves an HTTP Application, which also runs Command Invocations when it is a Kernel.
129+ *
130+ * @param resource $errorLog
131+ */
132+ private function withCommands(HttpKernelInterface $kernel, object $application, mixed $errorLog): ConsoleRunner
133+ {
134+ return new ConsoleRunner(static function () use ($kernel, $application): Application {
135+ if (!$kernel instanceof KernelInterface) {
136+ throw new \LogicException(\sprintf('Command Invocations need a Front Controller returning a Kernel, a Console Application or a Command, not "%s".', get_debug_type($application)));
137+ }
138+ // Checked in this order since FrameworkBundle's Application extends the Console one, which may be missing.
139+ if (!class_exists(Application::class) || !class_exists(FrameworkApplication::class)) {
140+ throw new \LogicException('Running Command Invocations through a Kernel requires symfony/console and symfony/framework-bundle.');
141+ }
142+
143+ return new FrameworkApplication($kernel);
144+ }, new HttpKernelRunner($kernel, $errorLog), $errorLog);
101145 }
102146
103147 protected function getArgument(\ReflectionParameter $parameter, ?string $type): mixed
@@ -4,14 +4,19 @@ declare(strict_types=1);
4 4
5 namespace JDecool\ScalewayRuntime;5 namespace JDecool\ScalewayRuntime;
6 6
7+use JDecool\ScalewayRuntime\Runner\ConsoleRunner;
7 use JDecool\ScalewayRuntime\Runner\HttpKernelRunner;8 use JDecool\ScalewayRuntime\Runner\HttpKernelRunner;
8 use JDecool\ScalewayRuntime\Runner\InvocationRunner;9 use JDecool\ScalewayRuntime\Runner\InvocationRunner;
9 use JDecool\ScalewayRuntime\Runner\RequestHandlerKernel;10 use JDecool\ScalewayRuntime\Runner\RequestHandlerKernel;
10 use JDecool\ScalewayRuntime\Runner\ResponseKernel;11 use JDecool\ScalewayRuntime\Runner\ResponseKernel;
11 use Psr\Http\Server\RequestHandlerInterface;12 use Psr\Http\Server\RequestHandlerInterface;
13+use Symfony\Bundle\FrameworkBundle\Console\Application as FrameworkApplication;
14+use Symfony\Component\Console\Application;
15+use Symfony\Component\Console\Command\Command;
12 use Symfony\Component\HttpFoundation\Request;16 use Symfony\Component\HttpFoundation\Request;
13 use Symfony\Component\HttpFoundation\Response;17 use Symfony\Component\HttpFoundation\Response;
14 use Symfony\Component\HttpKernel\HttpKernelInterface;18 use Symfony\Component\HttpKernel\HttpKernelInterface;
19+use Symfony\Component\HttpKernel\KernelInterface;
15 use Symfony\Component\Runtime\SymfonyRuntime;20 use Symfony\Component\Runtime\SymfonyRuntime;
16 21
17 /**22 /**
@@ -27,6 +32,9 @@ use Symfony\Component\Runtime\SymfonyRuntime;
27 * A Front Controller closure returning a Response is called again for every Invocation, and one32 * A Front Controller closure returning a Response is called again for every Invocation, and one
28 * taking a Request gets the Invocation's Request (see docs/adr/0004-call-response-front-controllers-per-invocation.md).33 * taking a Request gets the Invocation's Request (see docs/adr/0004-call-response-front-controllers-per-invocation.md).
29 * A PSR-15 request handler is built once and reused like a Kernel; it needs symfony/psr-http-message-bridge and nyholm/psr7.34 * A PSR-15 request handler is built once and reused like a Kernel; it needs symfony/psr-http-message-bridge and nyholm/psr7.
35+ *
36+ * Command Invocations run through the Console Application of a Kernel, or of a Front Controller returning a
37+ * Console Application or a Command, which then answers any other Invocation with a 403.
30 */38 */
31 class ScalewayRuntime extends SymfonyRuntime39 class ScalewayRuntime extends SymfonyRuntime
32 {40 {
@@ -85,19 +93,55 @@ class ScalewayRuntime extends SymfonyRuntime
85 foreach (new \ReflectionFunction($app(...))->getParameters() as $parameter) {93 foreach (new \ReflectionFunction($app(...))->getParameters() as $parameter) {
86 $type = $parameter->getType();94 $type = $parameter->getType();
87 if ($type instanceof \ReflectionNamedType && Request::class === $type->getName()) {95 if ($type instanceof \ReflectionNamedType && Request::class === $type->getName()) {
88- return new HttpKernelRunner(new ResponseKernel($respond), $errorLog);96+ return $this->withCommands(new ResponseKernel($respond), $app(...), $errorLog);
89 }97 }
90 }98 }
91 99
92 [$app, $args] = $resolver->resolve();100 [$app, $args] = $resolver->resolve();
93 $application = $app(...$args);101 $application = $app(...$args);
94 102
95- return match (true) {103+ if ($application instanceof Command) {
96- $application instanceof HttpKernelInterface => new HttpKernelRunner($application, $errorLog),104+ $command = $application;
97- $application instanceof Response => new HttpKernelRunner(new ResponseKernel($respond, $application), $errorLog),105+ $application = new Application();
98- $application instanceof RequestHandlerInterface => new HttpKernelRunner(new RequestHandlerKernel($application), $errorLog),106+ // SymfonyRuntime names a nameless command after argv[0], the script path: the Front Controller here.
107+ if (!$command->getName()) {
108+ $command->setName($frontController);
109+ }
110+ $application->addCommand($command);
111+ $application->setDefaultCommand((string) $command->getName(), true);
112+ }
113+ if ($application instanceof Application) {
114+ return new ConsoleRunner(static fn (): Application => $application, null, $errorLog);
115+ }
116+
117+ $kernel = match (true) {
118+ $application instanceof HttpKernelInterface => $application,
119+ $application instanceof Response => new ResponseKernel($respond, $application),
120+ $application instanceof RequestHandlerInterface => new RequestHandlerKernel($application),
99 default => throw new \LogicException(\sprintf('"%s" cannot run Applications of type "%s".', static::class, get_debug_type($application))),121 default => throw new \LogicException(\sprintf('"%s" cannot run Applications of type "%s".', static::class, get_debug_type($application))),
100 };122 };
123+
124+ return $this->withCommands($kernel, $application, $errorLog);
125+ }
126+
127+ /**
128+ * Serves an HTTP Application, which also runs Command Invocations when it is a Kernel.
129+ *
130+ * @param resource $errorLog
131+ */
132+ private function withCommands(HttpKernelInterface $kernel, object $application, mixed $errorLog): ConsoleRunner
133+ {
134+ return new ConsoleRunner(static function () use ($kernel, $application): Application {
135+ if (!$kernel instanceof KernelInterface) {
136+ throw new \LogicException(\sprintf('Command Invocations need a Front Controller returning a Kernel, a Console Application or a Command, not "%s".', get_debug_type($application)));
137+ }
138+ // Checked in this order since FrameworkBundle's Application extends the Console one, which may be missing.
139+ if (!class_exists(Application::class) || !class_exists(FrameworkApplication::class)) {
140+ throw new \LogicException('Running Command Invocations through a Kernel requires symfony/console and symfony/framework-bundle.');
141+ }
142+
143+ return new FrameworkApplication($kernel);
144+ }, new HttpKernelRunner($kernel, $errorLog), $errorLog);
101 }145 }
102 146
103 protected function getArgument(\ReflectionParameter $parameter, ?string $type): mixed147 protected function getArgument(\ReflectionParameter $parameter, ?string $type): mixed
added tests/CommandInvocationTest.php +114 -0
new file mode 100644
@@ -0,0 +1,114 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime\Tests;
6+
7+use JDecool\ScalewayRuntime\CommandInvocation;
8+use PHPUnit\Framework\Attributes\DataProvider;
9+use PHPUnit\Framework\TestCase;
10+
11+final class CommandInvocationTest extends TestCase
12+{
13+ /** @var array<mixed> */
14+ private array $server;
15+ /** @var resource */
16+ private $errorLog;
17+
18+ protected function setUp(): void
19+ {
20+ $this->server = $_SERVER;
21+ $_SERVER[CommandInvocation::SECRET_VAR] = 's3cret';
22+ $errorLog = fopen('php://memory', 'w+');
23+ self::assertNotFalse($errorLog);
24+ $this->errorLog = $errorLog;
25+ }
26+
27+ protected function tearDown(): void
28+ {
29+ $_SERVER = $this->server;
30+ }
31+
32+ public function testAuthenticatedBodyNamingACommandIsACommandInvocation(): void
33+ {
34+ $invocation = $this->fromBody(['command' => 'app:sync', 'args' => ['source' => 'a', '--force' => true], 'secret' => 's3cret']);
35+
36+ self::assertNotNull($invocation);
37+ self::assertSame('app:sync', $invocation->command);
38+ self::assertSame(['source' => 'a', '--force' => true], $invocation->args);
39+ }
40+
41+ public function testArgsDefaultToNone(): void
42+ {
43+ self::assertSame([], $this->fromBody(['command' => 'app:sync', 'secret' => 's3cret'])?->args);
44+ self::assertSame([], $this->fromBody(['command' => 'app:sync', 'args' => [], 'secret' => 's3cret'])?->args);
45+ }
46+
47+ public function testBase64BodyIsDecoded(): void
48+ {
49+ $event = ['body' => base64_encode('{"command":"app:sync","secret":"s3cret"}'), 'isBase64Encoded' => true];
50+
51+ self::assertSame('app:sync', CommandInvocation::fromEvent($event, $this->errorLog)?->command);
52+ }
53+
54+ /**
55+ * @return iterable<string, array{mixed}>
56+ */
57+ public static function plainHttpBodies(): iterable
58+ {
59+ yield 'no secret' => [['command' => 'app:sync']];
60+ yield 'wrong secret' => [['command' => 'app:sync', 'secret' => 'guess']];
61+ yield 'secret of another type' => [['command' => 'app:sync', 'secret' => true]];
62+ yield 'no command' => [['args' => [], 'secret' => 's3cret']];
63+ yield 'command of another type' => [['command' => ['app:sync'], 'secret' => 's3cret']];
64+ yield 'not an object' => [['app:sync', 's3cret']];
65+ }
66+
67+ #[DataProvider('plainHttpBodies')]
68+ public function testOtherBodiesAreNotCommandInvocations(mixed $body): void
69+ {
70+ self::assertNull($this->fromBody($body));
71+ }
72+
73+ public function testBodyThatIsNotJsonIsNotACommandInvocation(): void
74+ {
75+ self::assertNull(CommandInvocation::fromEvent(['body' => 'command=app:sync&secret=s3cret'], $this->errorLog));
76+ }
77+
78+ public function testNothingRunsWithoutAConfiguredSecret(): void
79+ {
80+ $_SERVER[CommandInvocation::SECRET_VAR] = '';
81+
82+ self::assertNull($this->fromBody(['command' => 'app:sync', 'secret' => '']));
83+ self::assertStringContainsString('Command Invocation rejected', $this->errorLog());
84+ }
85+
86+ public function testRejectionIsLoggedOnlyForBodiesCarryingASecret(): void
87+ {
88+ $this->fromBody(['command' => 'app:sync']);
89+ self::assertSame('', $this->errorLog());
90+
91+ $this->fromBody(['command' => 'app:sync', 'secret' => 'guess']);
92+ self::assertStringContainsString('Command Invocation rejected', $this->errorLog());
93+ self::assertStringNotContainsString('guess', $this->errorLog());
94+ }
95+
96+ public function testArgsMustNameTheirParameters(): void
97+ {
98+ $this->expectException(\UnexpectedValueException::class);
99+
100+ $this->fromBody(['command' => 'app:sync', 'args' => ['a', '--force'], 'secret' => 's3cret']);
101+ }
102+
103+ private function fromBody(mixed $body): ?CommandInvocation
104+ {
105+ return CommandInvocation::fromEvent(['method' => 'POST', 'path' => '/', 'body' => json_encode($body, \JSON_THROW_ON_ERROR)], $this->errorLog);
106+ }
107+
108+ private function errorLog(): string
109+ {
110+ rewind($this->errorLog);
111+
112+ return (string) stream_get_contents($this->errorLog);
113+ }
114+}
new file mode 100644
@@ -0,0 +1,114 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime\Tests;
6+
7+use JDecool\ScalewayRuntime\CommandInvocation;
8+use PHPUnit\Framework\Attributes\DataProvider;
9+use PHPUnit\Framework\TestCase;
10+
11+final class CommandInvocationTest extends TestCase
12+{
13+ /** @var array<mixed> */
14+ private array $server;
15+ /** @var resource */
16+ private $errorLog;
17+
18+ protected function setUp(): void
19+ {
20+ $this->server = $_SERVER;
21+ $_SERVER[CommandInvocation::SECRET_VAR] = 's3cret';
22+ $errorLog = fopen('php://memory', 'w+');
23+ self::assertNotFalse($errorLog);
24+ $this->errorLog = $errorLog;
25+ }
26+
27+ protected function tearDown(): void
28+ {
29+ $_SERVER = $this->server;
30+ }
31+
32+ public function testAuthenticatedBodyNamingACommandIsACommandInvocation(): void
33+ {
34+ $invocation = $this->fromBody(['command' => 'app:sync', 'args' => ['source' => 'a', '--force' => true], 'secret' => 's3cret']);
35+
36+ self::assertNotNull($invocation);
37+ self::assertSame('app:sync', $invocation->command);
38+ self::assertSame(['source' => 'a', '--force' => true], $invocation->args);
39+ }
40+
41+ public function testArgsDefaultToNone(): void
42+ {
43+ self::assertSame([], $this->fromBody(['command' => 'app:sync', 'secret' => 's3cret'])?->args);
44+ self::assertSame([], $this->fromBody(['command' => 'app:sync', 'args' => [], 'secret' => 's3cret'])?->args);
45+ }
46+
47+ public function testBase64BodyIsDecoded(): void
48+ {
49+ $event = ['body' => base64_encode('{"command":"app:sync","secret":"s3cret"}'), 'isBase64Encoded' => true];
50+
51+ self::assertSame('app:sync', CommandInvocation::fromEvent($event, $this->errorLog)?->command);
52+ }
53+
54+ /**
55+ * @return iterable<string, array{mixed}>
56+ */
57+ public static function plainHttpBodies(): iterable
58+ {
59+ yield 'no secret' => [['command' => 'app:sync']];
60+ yield 'wrong secret' => [['command' => 'app:sync', 'secret' => 'guess']];
61+ yield 'secret of another type' => [['command' => 'app:sync', 'secret' => true]];
62+ yield 'no command' => [['args' => [], 'secret' => 's3cret']];
63+ yield 'command of another type' => [['command' => ['app:sync'], 'secret' => 's3cret']];
64+ yield 'not an object' => [['app:sync', 's3cret']];
65+ }
66+
67+ #[DataProvider('plainHttpBodies')]
68+ public function testOtherBodiesAreNotCommandInvocations(mixed $body): void
69+ {
70+ self::assertNull($this->fromBody($body));
71+ }
72+
73+ public function testBodyThatIsNotJsonIsNotACommandInvocation(): void
74+ {
75+ self::assertNull(CommandInvocation::fromEvent(['body' => 'command=app:sync&secret=s3cret'], $this->errorLog));
76+ }
77+
78+ public function testNothingRunsWithoutAConfiguredSecret(): void
79+ {
80+ $_SERVER[CommandInvocation::SECRET_VAR] = '';
81+
82+ self::assertNull($this->fromBody(['command' => 'app:sync', 'secret' => '']));
83+ self::assertStringContainsString('Command Invocation rejected', $this->errorLog());
84+ }
85+
86+ public function testRejectionIsLoggedOnlyForBodiesCarryingASecret(): void
87+ {
88+ $this->fromBody(['command' => 'app:sync']);
89+ self::assertSame('', $this->errorLog());
90+
91+ $this->fromBody(['command' => 'app:sync', 'secret' => 'guess']);
92+ self::assertStringContainsString('Command Invocation rejected', $this->errorLog());
93+ self::assertStringNotContainsString('guess', $this->errorLog());
94+ }
95+
96+ public function testArgsMustNameTheirParameters(): void
97+ {
98+ $this->expectException(\UnexpectedValueException::class);
99+
100+ $this->fromBody(['command' => 'app:sync', 'args' => ['a', '--force'], 'secret' => 's3cret']);
101+ }
102+
103+ private function fromBody(mixed $body): ?CommandInvocation
104+ {
105+ return CommandInvocation::fromEvent(['method' => 'POST', 'path' => '/', 'body' => json_encode($body, \JSON_THROW_ON_ERROR)], $this->errorLog);
106+ }
107+
108+ private function errorLog(): string
109+ {
110+ rewind($this->errorLog);
111+
112+ return (string) stream_get_contents($this->errorLog);
113+ }
114+}
added tests/Fixtures/App/CountCommand.php +41 -0
new file mode 100644
@@ -0,0 +1,41 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime\Tests\Fixtures\App;
6+
7+use Symfony\Component\Console\Attribute\AsCommand;
8+use Symfony\Component\Console\Command\Command;
9+use Symfony\Component\Console\Input\InputInterface;
10+use Symfony\Component\Console\Input\InputOption;
11+use Symfony\Component\Console\Output\OutputInterface;
12+
13+/**
14+ * Shares the Counter with the HTTP routes, to tell whether state leaks between Command and HTTP Invocations.
15+ */
16+#[AsCommand('app:count')]
17+final class CountCommand extends Command
18+{
19+ public function __construct(
20+ private readonly Counter $counter,
21+ ) {
22+ parent::__construct();
23+ }
24+
25+ protected function configure(): void
26+ {
27+ $this->addOption('times', null, InputOption::VALUE_REQUIRED, '', '1');
28+ }
29+
30+ protected function execute(InputInterface $input, OutputInterface $output): int
31+ {
32+ $times = $input->getOption('times');
33+ \assert(is_numeric($times));
34+ for ($i = (int) $times; $i > 0; --$i) {
35+ $count = $this->counter->increment();
36+ }
37+ $output->write(\sprintf('count=%d kernelInstances=%d pid=%d', $count ?? 0, Kernel::$instances, getmypid()));
38+
39+ return Command::SUCCESS;
40+ }
41+}
new file mode 100644
@@ -0,0 +1,41 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime\Tests\Fixtures\App;
6+
7+use Symfony\Component\Console\Attribute\AsCommand;
8+use Symfony\Component\Console\Command\Command;
9+use Symfony\Component\Console\Input\InputInterface;
10+use Symfony\Component\Console\Input\InputOption;
11+use Symfony\Component\Console\Output\OutputInterface;
12+
13+/**
14+ * Shares the Counter with the HTTP routes, to tell whether state leaks between Command and HTTP Invocations.
15+ */
16+#[AsCommand('app:count')]
17+final class CountCommand extends Command
18+{
19+ public function __construct(
20+ private readonly Counter $counter,
21+ ) {
22+ parent::__construct();
23+ }
24+
25+ protected function configure(): void
26+ {
27+ $this->addOption('times', null, InputOption::VALUE_REQUIRED, '', '1');
28+ }
29+
30+ protected function execute(InputInterface $input, OutputInterface $output): int
31+ {
32+ $times = $input->getOption('times');
33+ \assert(is_numeric($times));
34+ for ($i = (int) $times; $i > 0; --$i) {
35+ $count = $this->counter->increment();
36+ }
37+ $output->write(\sprintf('count=%d kernelInstances=%d pid=%d', $count ?? 0, Kernel::$instances, getmypid()));
38+
39+ return Command::SUCCESS;
40+ }
41+}
modified tests/Fixtures/App/Kernel.php +4 -1
@@ -68,7 +68,10 @@ final class Kernel extends BaseKernel
6868 $container->services()
6969 ->set(Counter::class)
7070 ->public()
71- ->tag('kernel.reset', ['method' => 'reset']);
71+ ->tag('kernel.reset', ['method' => 'reset'])
72+ ->set(CountCommand::class)
73+ ->autowire()
74+ ->autoconfigure();
7275 }
7376
7477 private function configureRoutes(RoutingConfigurator $routes): void
@@ -68,7 +68,10 @@ final class Kernel extends BaseKernel
68 $container->services()68 $container->services()
69 ->set(Counter::class)69 ->set(Counter::class)
70 ->public()70 ->public()
71- ->tag('kernel.reset', ['method' => 'reset']);71+ ->tag('kernel.reset', ['method' => 'reset'])
72+ ->set(CountCommand::class)
73+ ->autowire()
74+ ->autoconfigure();
72 }75 }
73 76
74 private function configureRoutes(RoutingConfigurator $routes): void77 private function configureRoutes(RoutingConfigurator $routes): void
added tests/Fixtures/front-controllers/command.php +24 -0
new file mode 100644
@@ -0,0 +1,24 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+use Symfony\Component\Console\Command\Command;
6+use Symfony\Component\Console\Input\InputArgument;
7+use Symfony\Component\Console\Input\InputInterface;
8+use Symfony\Component\Console\Input\InputOption;
9+use Symfony\Component\Console\Output\OutputInterface;
10+
11+// The SymfonyRuntime way: the runtime passes a blank Command for the Front Controller to configure.
12+return static function (Command $command): Command {
13+ $command->addArgument('name', InputArgument::REQUIRED);
14+ $command->addOption('yell', null, InputOption::VALUE_NONE);
15+ $command->setCode(static function (InputInterface $input, OutputInterface $output) use ($command): int {
16+ $name = $input->getArgument('name');
17+ assert(is_string($name));
18+ $output->write(sprintf('%s: hello %s', $command->getName(), $input->getOption('yell') ? strtoupper($name) : $name));
19+
20+ return Command::SUCCESS;
21+ });
22+
23+ return $command;
24+};
new file mode 100644
@@ -0,0 +1,24 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+use Symfony\Component\Console\Command\Command;
6+use Symfony\Component\Console\Input\InputArgument;
7+use Symfony\Component\Console\Input\InputInterface;
8+use Symfony\Component\Console\Input\InputOption;
9+use Symfony\Component\Console\Output\OutputInterface;
10+
11+// The SymfonyRuntime way: the runtime passes a blank Command for the Front Controller to configure.
12+return static function (Command $command): Command {
13+ $command->addArgument('name', InputArgument::REQUIRED);
14+ $command->addOption('yell', null, InputOption::VALUE_NONE);
15+ $command->setCode(static function (InputInterface $input, OutputInterface $output) use ($command): int {
16+ $name = $input->getArgument('name');
17+ assert(is_string($name));
18+ $output->write(sprintf('%s: hello %s', $command->getName(), $input->getOption('yell') ? strtoupper($name) : $name));
19+
20+ return Command::SUCCESS;
21+ });
22+
23+ return $command;
24+};
added tests/Fixtures/front-controllers/console.php +38 -0
new file mode 100644
@@ -0,0 +1,38 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+use Symfony\Component\Console\Application;
6+use Symfony\Component\Console\Command\Command;
7+use Symfony\Component\Console\Input\InputArgument;
8+use Symfony\Component\Console\Input\InputInterface;
9+use Symfony\Component\Console\Input\InputOption;
10+use Symfony\Component\Console\Output\OutputInterface;
11+use Symfony\Component\Console\Style\SymfonyStyle;
12+
13+return static function (): Application {
14+ $greet = new Command('app:greet');
15+ $greet->addArgument('name', InputArgument::OPTIONAL);
16+ $greet->addOption('tag', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY);
17+ $greet->addOption('fail', null, InputOption::VALUE_NONE);
18+ $greet->setCode(static function (InputInterface $input, OutputInterface $output): int {
19+ $name = $input->getArgument('name') ?? new SymfonyStyle($input, $output)->ask('Who?', 'nobody');
20+ assert(is_string($name));
21+ $tags = $input->getOption('tag');
22+ assert(is_array($tags));
23+ $output->writeln(sprintf('<info>Hello %s</info> [%s]', $name, implode(',', array_filter($tags, is_string(...)))));
24+
25+ return $input->getOption('fail') ? 3 : Command::SUCCESS;
26+ });
27+
28+ $throw = new Command('app:throw');
29+ $throw->setCode(static fn (): never => throw new LogicException('Thrown on purpose.'));
30+
31+ $error = new Command('app:error');
32+ $error->setCode(static fn (): never => throw new Error('Error on purpose.'));
33+
34+ $application = new Application();
35+ $application->addCommands([$greet, $throw, $error]);
36+
37+ return $application;
38+};
new file mode 100644
@@ -0,0 +1,38 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+use Symfony\Component\Console\Application;
6+use Symfony\Component\Console\Command\Command;
7+use Symfony\Component\Console\Input\InputArgument;
8+use Symfony\Component\Console\Input\InputInterface;
9+use Symfony\Component\Console\Input\InputOption;
10+use Symfony\Component\Console\Output\OutputInterface;
11+use Symfony\Component\Console\Style\SymfonyStyle;
12+
13+return static function (): Application {
14+ $greet = new Command('app:greet');
15+ $greet->addArgument('name', InputArgument::OPTIONAL);
16+ $greet->addOption('tag', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY);
17+ $greet->addOption('fail', null, InputOption::VALUE_NONE);
18+ $greet->setCode(static function (InputInterface $input, OutputInterface $output): int {
19+ $name = $input->getArgument('name') ?? new SymfonyStyle($input, $output)->ask('Who?', 'nobody');
20+ assert(is_string($name));
21+ $tags = $input->getOption('tag');
22+ assert(is_array($tags));
23+ $output->writeln(sprintf('<info>Hello %s</info> [%s]', $name, implode(',', array_filter($tags, is_string(...)))));
24+
25+ return $input->getOption('fail') ? 3 : Command::SUCCESS;
26+ });
27+
28+ $throw = new Command('app:throw');
29+ $throw->setCode(static fn (): never => throw new LogicException('Thrown on purpose.'));
30+
31+ $error = new Command('app:error');
32+ $error->setCode(static fn (): never => throw new Error('Error on purpose.'));
33+
34+ $application = new Application();
35+ $application->addCommands([$greet, $throw, $error]);
36+
37+ return $application;
38+};
modified tests/HandlerTest.php +110 -0
@@ -4,8 +4,10 @@ declare(strict_types=1);
44
55 namespace JDecool\ScalewayRuntime\Tests;
66
7+use JDecool\ScalewayRuntime\CommandInvocation;
78 use JDecool\ScalewayRuntime\Handler;
89 use JDecool\ScalewayRuntime\Tests\Fixtures\RecordingKernel;
10+use PHPUnit\Framework\Attributes\DataProvider;
911 use PHPUnit\Framework\TestCase;
1012 use Symfony\Component\HttpFoundation\Request;
1113
@@ -31,6 +33,7 @@ final class HandlerTest extends TestCase
3133 self::assertNotFalse($errorLog);
3234 $this->errorLog = $errorLog;
3335 RecordingKernel::reset();
36+ $_SERVER[CommandInvocation::SECRET_VAR] = 's3cret';
3437 }
3538
3639 protected function tearDown(): void
@@ -144,6 +147,99 @@ final class HandlerTest extends TestCase
144147 self::assertSame(3, $this->decode($third)['handled'], 'The request handler must be reused across Invocations.');
145148 }
146149
150+ public function testConsoleApplicationRunsCommandInvocationsWithTheirArgs(): void
151+ {
152+ $handler = $this->handler(['front_controller' => 'front-controllers/console.php']);
153+
154+ $response = $handler->invoke($this->commandEvent('app:greet', ['name' => 'Ada', '--tag' => ['a', 'b']]), []);
155+
156+ self::assertSame(200, $response['statusCode']);
157+ self::assertSame('text/plain; charset=UTF-8', $response['headers']['Content-Type'] ?? null);
158+ self::assertSame("Hello Ada [a,b]\n", $response['body'], 'Output must be captured undecorated.');
159+ self::assertSame('', $this->errorLog());
160+ }
161+
162+ public function testCommandInvocationsAreNotInteractive(): void
163+ {
164+ $response = $this->handler(['front_controller' => 'front-controllers/console.php'])->invoke($this->commandEvent('app:greet'), []);
165+
166+ self::assertSame(200, $response['statusCode']);
167+ self::assertStringContainsString('Hello nobody', $response['body']);
168+ }
169+
170+ public function testNonZeroExitCodeIsA500WithTheOutputAndIsLogged(): void
171+ {
172+ $response = $this->handler(['front_controller' => 'front-controllers/console.php'])
173+ ->invoke($this->commandEvent('app:greet', ['name' => 'Ada', '--fail' => true]), []);
174+
175+ self::assertSame(500, $response['statusCode']);
176+ self::assertSame("Hello Ada []\n", $response['body']);
177+ self::assertStringContainsString('Command "app:greet" failed with exit code 3: Hello Ada []', $this->errorLog());
178+ }
179+
180+ /**
181+ * @return iterable<string, array{string, string}>
182+ */
183+ public static function failingCommands(): iterable
184+ {
185+ yield 'exception' => ['app:throw', 'Thrown on purpose.'];
186+ yield 'error' => ['app:error', 'Error on purpose.'];
187+ yield 'unknown command' => ['app:missing', 'Command "app:missing" is not defined.'];
188+ }
189+
190+ #[DataProvider('failingCommands')]
191+ public function testFailingCommandIsRenderedInA500AndTheProcessKeepsServing(string $command, string $message): void
192+ {
193+ $handler = $this->handler(['front_controller' => 'front-controllers/console.php', 'debug' => false]);
194+
195+ $response = $handler->invoke($this->commandEvent($command), []);
196+
197+ self::assertSame(500, $response['statusCode']);
198+ self::assertStringContainsString($message, $response['body']);
199+ self::assertStringContainsString($message, $this->errorLog());
200+ self::assertSame(200, $handler->invoke($this->commandEvent('app:greet', ['name' => 'Ada']), [])['statusCode']);
201+ }
202+
203+ public function testConsoleApplicationForbidsHttpInvocations(): void
204+ {
205+ $handler = $this->handler(['front_controller' => 'front-controllers/console.php']);
206+
207+ self::assertSame(403, $handler->invoke(['path' => '/'], [])['statusCode']);
208+ $forged = $handler->invoke(['method' => 'POST', 'path' => '/', 'body' => '{"command":"app:greet","secret":"guess"}'], []);
209+ self::assertSame(403, $forged['statusCode']);
210+ self::assertStringContainsString('Command Invocation rejected', $this->errorLog());
211+ }
212+
213+ public function testCommandFrontControllerRunsItsCommandWhateverTheName(): void
214+ {
215+ $handler = $this->handler(['front_controller' => 'front-controllers/command.php']);
216+
217+ $first = $handler->invoke($this->commandEvent('anything', ['name' => 'Ada', '--yell' => true]), []);
218+ $second = $handler->invoke($this->commandEvent('front-controllers/command.php', ['name' => 'Grace']), []);
219+
220+ self::assertSame(['statusCode' => 200, 'body' => 'front-controllers/command.php: hello ADA'], array_intersect_key($first, ['statusCode' => 0, 'body' => 0]));
221+ self::assertSame('front-controllers/command.php: hello Grace', $second['body']);
222+ self::assertSame(403, $handler->invoke(['path' => '/'], [])['statusCode']);
223+ }
224+
225+ public function testCommandBodyWithoutTheSecretReachesTheHttpApplication(): void
226+ {
227+ $handler = $this->handler(['front_controller' => 'front-controllers/recording.php']);
228+
229+ $response = $handler->invoke(['method' => 'POST', 'path' => '/', 'body' => '{"command":"cache:clear"}'], []);
230+
231+ self::assertSame('handled #1 /', $response['body']);
232+ }
233+
234+ public function testCommandInvocationOfAnApplicationWithoutConsoleFails(): void
235+ {
236+ $handler = $this->handler(['front_controller' => 'front-controllers/recording.php', 'debug' => false]);
237+
238+ self::assertSame(500, $handler->invoke($this->commandEvent('app:greet'), [])['statusCode']);
239+ self::assertStringContainsString('Command Invocations need a Front Controller returning a Kernel, a Console Application or a Command, not "'.RecordingKernel::class.'"', $this->errorLog());
240+ self::assertSame('handled #1 /', $handler->invoke(['path' => '/'], [])['body']);
241+ }
242+
147243 public function testFrontControllerMustReturnACallable(): void
148244 {
149245 $this->handler(['front_controller' => 'front-controllers/not-callable.php', 'debug' => false])->invoke([], []);
@@ -188,6 +284,20 @@ final class HandlerTest extends TestCase
188284 return new Handler($composerDir, $this->errorLog);
189285 }
190286
287+ /**
288+ * @param array<string, mixed> $args
289+ *
290+ * @return array<mixed>
291+ */
292+ private function commandEvent(string $command, array $args = []): array
293+ {
294+ return [
295+ 'method' => 'POST',
296+ 'path' => '/',
297+ 'body' => json_encode(['command' => $command, 'args' => (object) $args, 'secret' => 's3cret'], \JSON_THROW_ON_ERROR),
298+ ];
299+ }
300+
191301 /**
192302 * @param array<mixed> $response
193303 *
@@ -4,8 +4,10 @@ declare(strict_types=1);
4 4
5 namespace JDecool\ScalewayRuntime\Tests;5 namespace JDecool\ScalewayRuntime\Tests;
6 6
7+use JDecool\ScalewayRuntime\CommandInvocation;
7 use JDecool\ScalewayRuntime\Handler;8 use JDecool\ScalewayRuntime\Handler;
8 use JDecool\ScalewayRuntime\Tests\Fixtures\RecordingKernel;9 use JDecool\ScalewayRuntime\Tests\Fixtures\RecordingKernel;
10+use PHPUnit\Framework\Attributes\DataProvider;
9 use PHPUnit\Framework\TestCase;11 use PHPUnit\Framework\TestCase;
10 use Symfony\Component\HttpFoundation\Request;12 use Symfony\Component\HttpFoundation\Request;
11 13
@@ -31,6 +33,7 @@ final class HandlerTest extends TestCase
31 self::assertNotFalse($errorLog);33 self::assertNotFalse($errorLog);
32 $this->errorLog = $errorLog;34 $this->errorLog = $errorLog;
33 RecordingKernel::reset();35 RecordingKernel::reset();
36+ $_SERVER[CommandInvocation::SECRET_VAR] = 's3cret';
34 }37 }
35 38
36 protected function tearDown(): void39 protected function tearDown(): void
@@ -144,6 +147,99 @@ final class HandlerTest extends TestCase
144 self::assertSame(3, $this->decode($third)['handled'], 'The request handler must be reused across Invocations.');147 self::assertSame(3, $this->decode($third)['handled'], 'The request handler must be reused across Invocations.');
145 }148 }
146 149
150+ public function testConsoleApplicationRunsCommandInvocationsWithTheirArgs(): void
151+ {
152+ $handler = $this->handler(['front_controller' => 'front-controllers/console.php']);
153+
154+ $response = $handler->invoke($this->commandEvent('app:greet', ['name' => 'Ada', '--tag' => ['a', 'b']]), []);
155+
156+ self::assertSame(200, $response['statusCode']);
157+ self::assertSame('text/plain; charset=UTF-8', $response['headers']['Content-Type'] ?? null);
158+ self::assertSame("Hello Ada [a,b]\n", $response['body'], 'Output must be captured undecorated.');
159+ self::assertSame('', $this->errorLog());
160+ }
161+
162+ public function testCommandInvocationsAreNotInteractive(): void
163+ {
164+ $response = $this->handler(['front_controller' => 'front-controllers/console.php'])->invoke($this->commandEvent('app:greet'), []);
165+
166+ self::assertSame(200, $response['statusCode']);
167+ self::assertStringContainsString('Hello nobody', $response['body']);
168+ }
169+
170+ public function testNonZeroExitCodeIsA500WithTheOutputAndIsLogged(): void
171+ {
172+ $response = $this->handler(['front_controller' => 'front-controllers/console.php'])
173+ ->invoke($this->commandEvent('app:greet', ['name' => 'Ada', '--fail' => true]), []);
174+
175+ self::assertSame(500, $response['statusCode']);
176+ self::assertSame("Hello Ada []\n", $response['body']);
177+ self::assertStringContainsString('Command "app:greet" failed with exit code 3: Hello Ada []', $this->errorLog());
178+ }
179+
180+ /**
181+ * @return iterable<string, array{string, string}>
182+ */
183+ public static function failingCommands(): iterable
184+ {
185+ yield 'exception' => ['app:throw', 'Thrown on purpose.'];
186+ yield 'error' => ['app:error', 'Error on purpose.'];
187+ yield 'unknown command' => ['app:missing', 'Command "app:missing" is not defined.'];
188+ }
189+
190+ #[DataProvider('failingCommands')]
191+ public function testFailingCommandIsRenderedInA500AndTheProcessKeepsServing(string $command, string $message): void
192+ {
193+ $handler = $this->handler(['front_controller' => 'front-controllers/console.php', 'debug' => false]);
194+
195+ $response = $handler->invoke($this->commandEvent($command), []);
196+
197+ self::assertSame(500, $response['statusCode']);
198+ self::assertStringContainsString($message, $response['body']);
199+ self::assertStringContainsString($message, $this->errorLog());
200+ self::assertSame(200, $handler->invoke($this->commandEvent('app:greet', ['name' => 'Ada']), [])['statusCode']);
201+ }
202+
203+ public function testConsoleApplicationForbidsHttpInvocations(): void
204+ {
205+ $handler = $this->handler(['front_controller' => 'front-controllers/console.php']);
206+
207+ self::assertSame(403, $handler->invoke(['path' => '/'], [])['statusCode']);
208+ $forged = $handler->invoke(['method' => 'POST', 'path' => '/', 'body' => '{"command":"app:greet","secret":"guess"}'], []);
209+ self::assertSame(403, $forged['statusCode']);
210+ self::assertStringContainsString('Command Invocation rejected', $this->errorLog());
211+ }
212+
213+ public function testCommandFrontControllerRunsItsCommandWhateverTheName(): void
214+ {
215+ $handler = $this->handler(['front_controller' => 'front-controllers/command.php']);
216+
217+ $first = $handler->invoke($this->commandEvent('anything', ['name' => 'Ada', '--yell' => true]), []);
218+ $second = $handler->invoke($this->commandEvent('front-controllers/command.php', ['name' => 'Grace']), []);
219+
220+ self::assertSame(['statusCode' => 200, 'body' => 'front-controllers/command.php: hello ADA'], array_intersect_key($first, ['statusCode' => 0, 'body' => 0]));
221+ self::assertSame('front-controllers/command.php: hello Grace', $second['body']);
222+ self::assertSame(403, $handler->invoke(['path' => '/'], [])['statusCode']);
223+ }
224+
225+ public function testCommandBodyWithoutTheSecretReachesTheHttpApplication(): void
226+ {
227+ $handler = $this->handler(['front_controller' => 'front-controllers/recording.php']);
228+
229+ $response = $handler->invoke(['method' => 'POST', 'path' => '/', 'body' => '{"command":"cache:clear"}'], []);
230+
231+ self::assertSame('handled #1 /', $response['body']);
232+ }
233+
234+ public function testCommandInvocationOfAnApplicationWithoutConsoleFails(): void
235+ {
236+ $handler = $this->handler(['front_controller' => 'front-controllers/recording.php', 'debug' => false]);
237+
238+ self::assertSame(500, $handler->invoke($this->commandEvent('app:greet'), [])['statusCode']);
239+ self::assertStringContainsString('Command Invocations need a Front Controller returning a Kernel, a Console Application or a Command, not "'.RecordingKernel::class.'"', $this->errorLog());
240+ self::assertSame('handled #1 /', $handler->invoke(['path' => '/'], [])['body']);
241+ }
242+
147 public function testFrontControllerMustReturnACallable(): void243 public function testFrontControllerMustReturnACallable(): void
148 {244 {
149 $this->handler(['front_controller' => 'front-controllers/not-callable.php', 'debug' => false])->invoke([], []);245 $this->handler(['front_controller' => 'front-controllers/not-callable.php', 'debug' => false])->invoke([], []);
@@ -188,6 +284,20 @@ final class HandlerTest extends TestCase
188 return new Handler($composerDir, $this->errorLog);284 return new Handler($composerDir, $this->errorLog);
189 }285 }
190 286
287+ /**
288+ * @param array<string, mixed> $args
289+ *
290+ * @return array<mixed>
291+ */
292+ private function commandEvent(string $command, array $args = []): array
293+ {
294+ return [
295+ 'method' => 'POST',
296+ 'path' => '/',
297+ 'body' => json_encode(['command' => $command, 'args' => (object) $args, 'secret' => 's3cret'], \JSON_THROW_ON_ERROR),
298+ ];
299+ }
300+
191 /**301 /**
192 * @param array<mixed> $response302 * @param array<mixed> $response
193 *303 *
modified tests/IntegrationTest.php +30 -0
@@ -157,6 +157,35 @@ final class IntegrationTest extends TestCase
157157 self::assertSame($first['pid'], $second['pid']);
158158 }
159159
160+ public function testCommandInvocationsRunThroughTheKernelAndShareNoStateWithHttpInvocations(): void
161+ {
162+ $command = static fn (array $args, string $secret = 'cron-secret'): array => [
163+ 'path' => '/',
164+ 'method' => 'POST',
165+ 'body' => json_encode(['command' => 'app:count', 'args' => $args, 'secret' => $secret], \JSON_THROW_ON_ERROR),
166+ ];
167+ [$http, $first, $second, $httpAfter, $third, $forged] = $this->invoke([
168+ ['path' => '/state'],
169+ $command(['--times' => '2']),
170+ $command([]),
171+ ['path' => '/state'],
172+ $command([]),
173+ $command([], 'guess'),
174+ ]);
175+
176+ self::assertSame(1, $this->json($http)['count']);
177+ self::assertSame(200, $first['statusCode']);
178+ self::assertIsString($first['body']);
179+ self::assertStringStartsWith('count=2 kernelInstances=1 ', $first['body'], 'The command must start from reset services.');
180+ self::assertIsString($second['body']);
181+ self::assertStringStartsWith('count=1 kernelInstances=1 ', $second['body'], 'The Console Application must reset services after a command.');
182+ self::assertSame(1, $this->json($httpAfter)['count'], 'A command must leave no state to the next HTTP Invocation.');
183+ self::assertSame(1, $this->json($httpAfter)['kernelInstances']);
184+ self::assertIsString($third['body']);
185+ self::assertStringStartsWith('count=1 ', $third['body'], 'An HTTP Invocation must leave no state to the next command.');
186+ self::assertSame(404, $forged['statusCode'], 'A body with a wrong secret is a plain HTTP POST.');
187+ }
188+
160189 /**
161190 * @param list<array<string, mixed>> $events
162191 * @param array<string, mixed> $options runtime options on top of "project_dir"
@@ -176,6 +205,7 @@ final class IntegrationTest extends TestCase
176205 'APP_DEBUG' => '0',
177206 'APP_RUNTIME_OPTIONS' => json_encode(['project_dir' => $this->projectDir] + $options, \JSON_THROW_ON_ERROR),
178207 'TMPDIR' => $this->dir.'/tmp',
208+ 'SCALEWAY_CRON_SECRET' => 'cron-secret',
179209 'PATH' => getenv('PATH') ?: '',
180210 ],
181211 );
@@ -157,6 +157,35 @@ final class IntegrationTest extends TestCase
157 self::assertSame($first['pid'], $second['pid']);157 self::assertSame($first['pid'], $second['pid']);
158 }158 }
159 159
160+ public function testCommandInvocationsRunThroughTheKernelAndShareNoStateWithHttpInvocations(): void
161+ {
162+ $command = static fn (array $args, string $secret = 'cron-secret'): array => [
163+ 'path' => '/',
164+ 'method' => 'POST',
165+ 'body' => json_encode(['command' => 'app:count', 'args' => $args, 'secret' => $secret], \JSON_THROW_ON_ERROR),
166+ ];
167+ [$http, $first, $second, $httpAfter, $third, $forged] = $this->invoke([
168+ ['path' => '/state'],
169+ $command(['--times' => '2']),
170+ $command([]),
171+ ['path' => '/state'],
172+ $command([]),
173+ $command([], 'guess'),
174+ ]);
175+
176+ self::assertSame(1, $this->json($http)['count']);
177+ self::assertSame(200, $first['statusCode']);
178+ self::assertIsString($first['body']);
179+ self::assertStringStartsWith('count=2 kernelInstances=1 ', $first['body'], 'The command must start from reset services.');
180+ self::assertIsString($second['body']);
181+ self::assertStringStartsWith('count=1 kernelInstances=1 ', $second['body'], 'The Console Application must reset services after a command.');
182+ self::assertSame(1, $this->json($httpAfter)['count'], 'A command must leave no state to the next HTTP Invocation.');
183+ self::assertSame(1, $this->json($httpAfter)['kernelInstances']);
184+ self::assertIsString($third['body']);
185+ self::assertStringStartsWith('count=1 ', $third['body'], 'An HTTP Invocation must leave no state to the next command.');
186+ self::assertSame(404, $forged['statusCode'], 'A body with a wrong secret is a plain HTTP POST.');
187+ }
188+
160 /**189 /**
161 * @param list<array<string, mixed>> $events190 * @param list<array<string, mixed>> $events
162 * @param array<string, mixed> $options runtime options on top of "project_dir"191 * @param array<string, mixed> $options runtime options on top of "project_dir"
@@ -176,6 +205,7 @@ final class IntegrationTest extends TestCase
176 'APP_DEBUG' => '0',205 'APP_DEBUG' => '0',
177 'APP_RUNTIME_OPTIONS' => json_encode(['project_dir' => $this->projectDir] + $options, \JSON_THROW_ON_ERROR),206 'APP_RUNTIME_OPTIONS' => json_encode(['project_dir' => $this->projectDir] + $options, \JSON_THROW_ON_ERROR),
178 'TMPDIR' => $this->dir.'/tmp',207 'TMPDIR' => $this->dir.'/tmp',
208+ 'SCALEWAY_CRON_SECRET' => 'cron-secret',
179 'PATH' => getenv('PATH') ?: '',209 'PATH' => getenv('PATH') ?: '',
180 ],210 ],
181 );211 );