feat(emulator): build Events shaped like the platform ones, and simulate CRON triggersUnverified
The Emulator now sends the measured Event keys and platform headers (X-Real-Ip, X-Envoy-External-Address, X-Forwarded-Proto: https...), drops Host, keeps the client's X-Forwarded-Host and the platform's isBase64Encoded semantics, and passes the real context shape. As HTTP calls can no longer be Command Invocations, a POST on /_scaleway/cron becomes a CRON Event; the e2e scenarios use it, and check that forged forwarding headers and command bodies sent over HTTP are ignored.
c711fe6 parent: 08955ad modified
bin/scaleway-serve +2 -1 | @@ -10,6 +10,7 @@ require $autoload; | ||
| 10 | 10 | |
| 11 | 11 | if (in_array($argv[1] ?? null, ['-h', '--help'], true)) { |
| 12 | 12 | echo 'Usage: scaleway-serve [<host>:<port>] (default: 127.0.0.1:8000)', \PHP_EOL; |
| 13 | + echo 'A POST on '.JDecool\ScalewayRuntime\Emulator::CRON_PATH.' is a CRON Invocation whose arguments are the request body.', \PHP_EOL; | |
| 13 | 14 | exit(0); |
| 14 | 15 | } |
| 15 | 16 | |
| @@ -83,7 +84,7 @@ if (function_exists('pcntl_async_signals')) { | ||
| 83 | 84 | }); |
| 84 | 85 | } |
| 85 | 86 | } |
| 86 | -fwrite(\STDERR, "Emulator listening on http://{$address}, Warm Process pid ".proc_get_status($warmProcess)['pid'].\PHP_EOL); | |
| 87 | +fwrite(\STDERR, "Emulator listening on http://{$address}, Warm Process pid ".proc_get_status($warmProcess)['pid'].', CRON triggers on POST '.JDecool\ScalewayRuntime\Emulator::CRON_PATH.\PHP_EOL); | |
| 87 | 88 | |
| 88 | 89 | while (($status = proc_get_status($server))['running']) { |
| 89 | 90 | // A dead Warm Process is replaced, as the platform starts a new instance after a crash. |
| @@ -10,6 +10,7 @@ require $autoload; | |||
| 10 | 10 | ||
| 11 | if (in_array($argv[1] ?? null, ['-h', '--help'], true)) { | 11 | if (in_array($argv[1] ?? null, ['-h', '--help'], true)) { |
| 12 | echo 'Usage: scaleway-serve [<host>:<port>] (default: 127.0.0.1:8000)', \PHP_EOL; | 12 | echo 'Usage: scaleway-serve [<host>:<port>] (default: 127.0.0.1:8000)', \PHP_EOL; |
| 13 | + echo 'A POST on '.JDecool\ScalewayRuntime\Emulator::CRON_PATH.' is a CRON Invocation whose arguments are the request body.', \PHP_EOL; | ||
| 13 | exit(0); | 14 | exit(0); |
| 14 | } | 15 | } |
| 15 | 16 | ||
| @@ -83,7 +84,7 @@ if (function_exists('pcntl_async_signals')) { | |||
| 83 | }); | 84 | }); |
| 84 | } | 85 | } |
| 85 | } | 86 | } |
| 86 | -fwrite(\STDERR, "Emulator listening on http://{$address}, Warm Process pid ".proc_get_status($warmProcess)['pid'].\PHP_EOL); | 87 | +fwrite(\STDERR, "Emulator listening on http://{$address}, Warm Process pid ".proc_get_status($warmProcess)['pid'].', CRON triggers on POST '.JDecool\ScalewayRuntime\Emulator::CRON_PATH.\PHP_EOL); |
| 87 | 88 | ||
| 88 | while (($status = proc_get_status($server))['running']) { | 89 | while (($status = proc_get_status($server))['running']) { |
| 89 | // A dead Warm Process is replaced, as the platform starts a new instance after a crash. | 90 | // A dead Warm Process is replaced, as the platform starts a new instance after a crash. |
modified
example/e2e/run.sh +39 -20 | @@ -69,6 +69,12 @@ status=$(request headers -H 'X-Custom: hello' -H 'Accept-Language: fr' --cookie | ||
| 69 | 69 | expect "custom request header" "$(field headers headers.x-custom)" hello |
| 70 | 70 | expect "cookies" "$(field headers cookies)" '{"flavor":"chocolate","size":"large"}' |
| 71 | 71 | expect "client IP is set" "$(field headers clientIp | grep -cE '^[0-9a-f.:]+$')" 1 |
| 72 | +expect "HTTPS, as the platform terminates TLS" "$(field headers secure)" true | |
| 73 | + | |
| 74 | +# Clients can forge these, so the Application must not trust them. | |
| 75 | +status=$(request forwarded -H 'X-Forwarded-For: 203.0.113.66' -H 'X-Forwarded-Host: spoofed.example' -H 'X-Real-Ip: 203.0.113.66' "$base_url/echo") | |
| 76 | +expect "forged X-Forwarded-Host ignored" "$(field forwarded uri | grep -c spoofed.example)" 0 | |
| 77 | +expect "forged client IP ignored" "$(field forwarded clientIp | grep -c 203.0.113.66)" 0 | |
| 72 | 78 | |
| 73 | 79 | status=$(request json -X POST -H 'Content-Type: application/json' --data '{"answer":42}' "$base_url/echo") |
| 74 | 80 | expect "POST JSON body" "$(field json body)" '{"answer":42}' |
| @@ -112,33 +118,46 @@ fi | ||
| 112 | 118 | status=$(request missing "$base_url/missing") |
| 113 | 119 | expect "unknown route" "$status" 404 |
| 114 | 120 | |
| 115 | -# How a CRON trigger calls the function: a POST on "/" with its arguments as JSON body. | |
| 116 | -status=$(request cron -X POST -H 'Content-Type: application/json' --data '{"job":"cleanup"}' "$base_url/") | |
| 117 | -expect "CRON-like Invocation" "$(field cron args.job)" cleanup | |
| 121 | +status=$(request postroot -X POST -H 'Content-Type: application/json' --data '{"job":"cleanup"}' "$base_url/") | |
| 122 | +expect "POST / JSON body" "$(field postroot args.job)" cleanup | |
| 118 | 123 | |
| 119 | -# A body naming a command runs nothing without the CRON secret: it is a plain HTTP body. | |
| 124 | +# A body naming a command runs nothing over HTTP: it is a plain HTTP body. | |
| 120 | 125 | status=$(request forged -X POST -H 'Content-Type: application/json' \ |
| 121 | 126 | --data '{"command":"app:greet","args":{"name":"Mallory"},"secret":"guess"}' "$base_url/") |
| 122 | 127 | expect "command without the CRON secret stays HTTP" "$status $(field forged args.command)" "200 app:greet" |
| 123 | 128 | |
| 129 | +# command_body <name> <args JSON>: the arguments a CRON trigger running a command carries. | |
| 130 | +# The secret goes through the environment and stdin, as command lines are visible to other local users. | |
| 131 | +command_body() { | |
| 132 | + php -r 'echo json_encode(["command" => $argv[1], "args" => json_decode($argv[2]), "secret" => getenv("SCALEWAY_CRON_SECRET")]);' "$1" "$2" | |
| 133 | +} | |
| 134 | + | |
| 124 | 135 | if [[ -n "${SCALEWAY_CRON_SECRET:-}" ]]; then |
| 125 | - # command_body <name> <args JSON>: the arguments a CRON trigger running a command carries. | |
| 126 | - # The secret goes through the environment and stdin, as command lines are visible to other local users. | |
| 127 | - command_body() { | |
| 128 | - php -r 'echo json_encode(["command" => $argv[1], "args" => json_decode($argv[2]), "secret" => getenv("SCALEWAY_CRON_SECRET")]);' "$1" "$2" | |
| 129 | - } | |
| 130 | - status=$(command_body app:greet '{"name":"Scaleway","--yell":true}' | request command -X POST --data-binary @- "$base_url/") | |
| 131 | - expect "Command Invocation status" "$status" 200 | |
| 132 | - expect "Command Invocation output" "$(cat "$tmp/command.body")" "HELLO SCALEWAY!" | |
| 133 | - | |
| 134 | - status=$(command_body app:greet '{"--fail":true}' | request failed -X POST --data-binary @- "$base_url/") | |
| 135 | - expect "failed command status" "$status" 500 | |
| 136 | - expect "failed command output" "$(grep -c 'Failing on purpose.' "$tmp/failed.body")" 1 | |
| 137 | - | |
| 138 | - request after "$base_url/hello?name=again" > /dev/null | |
| 139 | - expect "HTTP Invocation after commands" "$(field after message)" "Hello again!" | |
| 136 | + status=$(command_body app:greet '{"name":"Mallory"}' | request leaked -X POST -H 'Content-Type: application/json' --data-binary @- "$base_url/") | |
| 137 | + expect "command with the CRON secret stays HTTP over HTTP" "$status $(field leaked args.command)" "200 app:greet" | |
| 138 | +fi | |
| 139 | + | |
| 140 | +# Only the Emulator can trigger a CRON Invocation on demand, on its reserved path. | |
| 141 | +status=$(request cron -X POST --data '{"job":"cleanup"}' "$base_url/_scaleway/cron") | |
| 142 | +if [[ "$status" == 404 ]]; then | |
| 143 | + echo "skip CRON Invocations: only the Emulator triggers them on demand" | |
| 140 | 144 | else |
| 141 | - echo "skip Command Invocations: set SCALEWAY_CRON_SECRET to the function's" | |
| 145 | + expect "CRON Invocation lands on POST /" "$status $(field cron args.job)" "200 cleanup" | |
| 146 | + | |
| 147 | + if [[ -n "${SCALEWAY_CRON_SECRET:-}" ]]; then | |
| 148 | + status=$(command_body app:greet '{"name":"Scaleway","--yell":true}' | request command -X POST --data-binary @- "$base_url/_scaleway/cron") | |
| 149 | + expect "Command Invocation status" "$status" 200 | |
| 150 | + expect "Command Invocation output" "$(cat "$tmp/command.body")" "HELLO SCALEWAY!" | |
| 151 | + | |
| 152 | + status=$(command_body app:greet '{"--fail":true}' | request failed -X POST --data-binary @- "$base_url/_scaleway/cron") | |
| 153 | + expect "failed command status" "$status" 500 | |
| 154 | + expect "failed command output" "$(grep -c 'Failing on purpose.' "$tmp/failed.body")" 1 | |
| 155 | + | |
| 156 | + request after "$base_url/hello?name=again" > /dev/null | |
| 157 | + expect "HTTP Invocation after commands" "$(field after message)" "Hello again!" | |
| 158 | + else | |
| 159 | + echo "skip Command Invocations: set SCALEWAY_CRON_SECRET to the function's" | |
| 160 | + fi | |
| 142 | 161 | fi |
| 143 | 162 | |
| 144 | 163 | if ((failures > 0)); then |
| @@ -69,6 +69,12 @@ status=$(request headers -H 'X-Custom: hello' -H 'Accept-Language: fr' --cookie | |||
| 69 | expect "custom request header" "$(field headers headers.x-custom)" hello | 69 | expect "custom request header" "$(field headers headers.x-custom)" hello |
| 70 | expect "cookies" "$(field headers cookies)" '{"flavor":"chocolate","size":"large"}' | 70 | expect "cookies" "$(field headers cookies)" '{"flavor":"chocolate","size":"large"}' |
| 71 | expect "client IP is set" "$(field headers clientIp | grep -cE '^[0-9a-f.:]+$')" 1 | 71 | expect "client IP is set" "$(field headers clientIp | grep -cE '^[0-9a-f.:]+$')" 1 |
| 72 | +expect "HTTPS, as the platform terminates TLS" "$(field headers secure)" true | ||
| 73 | + | ||
| 74 | +# Clients can forge these, so the Application must not trust them. | ||
| 75 | +status=$(request forwarded -H 'X-Forwarded-For: 203.0.113.66' -H 'X-Forwarded-Host: spoofed.example' -H 'X-Real-Ip: 203.0.113.66' "$base_url/echo") | ||
| 76 | +expect "forged X-Forwarded-Host ignored" "$(field forwarded uri | grep -c spoofed.example)" 0 | ||
| 77 | +expect "forged client IP ignored" "$(field forwarded clientIp | grep -c 203.0.113.66)" 0 | ||
| 72 | 78 | ||
| 73 | status=$(request json -X POST -H 'Content-Type: application/json' --data '{"answer":42}' "$base_url/echo") | 79 | status=$(request json -X POST -H 'Content-Type: application/json' --data '{"answer":42}' "$base_url/echo") |
| 74 | expect "POST JSON body" "$(field json body)" '{"answer":42}' | 80 | expect "POST JSON body" "$(field json body)" '{"answer":42}' |
| @@ -112,33 +118,46 @@ fi | |||
| 112 | status=$(request missing "$base_url/missing") | 118 | status=$(request missing "$base_url/missing") |
| 113 | expect "unknown route" "$status" 404 | 119 | expect "unknown route" "$status" 404 |
| 114 | 120 | ||
| 115 | -# How a CRON trigger calls the function: a POST on "/" with its arguments as JSON body. | 121 | +status=$(request postroot -X POST -H 'Content-Type: application/json' --data '{"job":"cleanup"}' "$base_url/") |
| 116 | -status=$(request cron -X POST -H 'Content-Type: application/json' --data '{"job":"cleanup"}' "$base_url/") | 122 | +expect "POST / JSON body" "$(field postroot args.job)" cleanup |
| 117 | -expect "CRON-like Invocation" "$(field cron args.job)" cleanup | ||
| 118 | 123 | ||
| 119 | -# A body naming a command runs nothing without the CRON secret: it is a plain HTTP body. | 124 | +# A body naming a command runs nothing over HTTP: it is a plain HTTP body. |
| 120 | status=$(request forged -X POST -H 'Content-Type: application/json' \ | 125 | status=$(request forged -X POST -H 'Content-Type: application/json' \ |
| 121 | --data '{"command":"app:greet","args":{"name":"Mallory"},"secret":"guess"}' "$base_url/") | 126 | --data '{"command":"app:greet","args":{"name":"Mallory"},"secret":"guess"}' "$base_url/") |
| 122 | expect "command without the CRON secret stays HTTP" "$status $(field forged args.command)" "200 app:greet" | 127 | expect "command without the CRON secret stays HTTP" "$status $(field forged args.command)" "200 app:greet" |
| 123 | 128 | ||
| 129 | +# command_body <name> <args JSON>: the arguments a CRON trigger running a command carries. | ||
| 130 | +# The secret goes through the environment and stdin, as command lines are visible to other local users. | ||
| 131 | +command_body() { | ||
| 132 | + php -r 'echo json_encode(["command" => $argv[1], "args" => json_decode($argv[2]), "secret" => getenv("SCALEWAY_CRON_SECRET")]);' "$1" "$2" | ||
| 133 | +} | ||
| 134 | + | ||
| 124 | if [[ -n "${SCALEWAY_CRON_SECRET:-}" ]]; then | 135 | if [[ -n "${SCALEWAY_CRON_SECRET:-}" ]]; then |
| 125 | - # command_body <name> <args JSON>: the arguments a CRON trigger running a command carries. | 136 | + status=$(command_body app:greet '{"name":"Mallory"}' | request leaked -X POST -H 'Content-Type: application/json' --data-binary @- "$base_url/") |
| 126 | - # The secret goes through the environment and stdin, as command lines are visible to other local users. | 137 | + expect "command with the CRON secret stays HTTP over HTTP" "$status $(field leaked args.command)" "200 app:greet" |
| 127 | - command_body() { | 138 | +fi |
| 128 | - php -r 'echo json_encode(["command" => $argv[1], "args" => json_decode($argv[2]), "secret" => getenv("SCALEWAY_CRON_SECRET")]);' "$1" "$2" | 139 | + |
| 129 | - } | 140 | +# Only the Emulator can trigger a CRON Invocation on demand, on its reserved path. |
| 130 | - status=$(command_body app:greet '{"name":"Scaleway","--yell":true}' | request command -X POST --data-binary @- "$base_url/") | 141 | +status=$(request cron -X POST --data '{"job":"cleanup"}' "$base_url/_scaleway/cron") |
| 131 | - expect "Command Invocation status" "$status" 200 | 142 | +if [[ "$status" == 404 ]]; then |
| 132 | - expect "Command Invocation output" "$(cat "$tmp/command.body")" "HELLO SCALEWAY!" | 143 | + echo "skip CRON Invocations: only the Emulator triggers them on demand" |
| 133 | - | ||
| 134 | - status=$(command_body app:greet '{"--fail":true}' | request failed -X POST --data-binary @- "$base_url/") | ||
| 135 | - expect "failed command status" "$status" 500 | ||
| 136 | - expect "failed command output" "$(grep -c 'Failing on purpose.' "$tmp/failed.body")" 1 | ||
| 137 | - | ||
| 138 | - request after "$base_url/hello?name=again" > /dev/null | ||
| 139 | - expect "HTTP Invocation after commands" "$(field after message)" "Hello again!" | ||
| 140 | else | 144 | else |
| 141 | - echo "skip Command Invocations: set SCALEWAY_CRON_SECRET to the function's" | 145 | + expect "CRON Invocation lands on POST /" "$status $(field cron args.job)" "200 cleanup" |
| 146 | + | ||
| 147 | + if [[ -n "${SCALEWAY_CRON_SECRET:-}" ]]; then | ||
| 148 | + status=$(command_body app:greet '{"name":"Scaleway","--yell":true}' | request command -X POST --data-binary @- "$base_url/_scaleway/cron") | ||
| 149 | + expect "Command Invocation status" "$status" 200 | ||
| 150 | + expect "Command Invocation output" "$(cat "$tmp/command.body")" "HELLO SCALEWAY!" | ||
| 151 | + | ||
| 152 | + status=$(command_body app:greet '{"--fail":true}' | request failed -X POST --data-binary @- "$base_url/_scaleway/cron") | ||
| 153 | + expect "failed command status" "$status" 500 | ||
| 154 | + expect "failed command output" "$(grep -c 'Failing on purpose.' "$tmp/failed.body")" 1 | ||
| 155 | + | ||
| 156 | + request after "$base_url/hello?name=again" > /dev/null | ||
| 157 | + expect "HTTP Invocation after commands" "$(field after message)" "Hello again!" | ||
| 158 | + else | ||
| 159 | + echo "skip Command Invocations: set SCALEWAY_CRON_SECRET to the function's" | ||
| 160 | + fi | ||
| 142 | fi | 161 | fi |
| 143 | 162 | ||
| 144 | if ((failures > 0)); then | 163 | if ((failures > 0)); then |
modified
resources/emulator/router.php +5 -8 | @@ -18,14 +18,11 @@ foreach (getallheaders() as $name => $value) { | ||
| 18 | 18 | $headers[(string) $name] = $value; |
| 19 | 19 | } |
| 20 | 20 | } |
| 21 | -$event = Emulator::toEvent( | |
| 22 | - $server('REQUEST_METHOD'), | |
| 23 | - $server('REQUEST_URI'), | |
| 24 | - $headers, | |
| 25 | - // Raw even for form posts, as the server runs with enable_post_data_reading=0. | |
| 26 | - (string) file_get_contents('php://input'), | |
| 27 | - $server('REMOTE_ADDR'), | |
| 28 | -); | |
| 21 | +// Raw even for form posts, as the server runs with enable_post_data_reading=0. | |
| 22 | +$body = (string) file_get_contents('php://input'); | |
| 23 | +$event = 'POST' === $server('REQUEST_METHOD') && Emulator::CRON_PATH === parse_url($server('REQUEST_URI'), \PHP_URL_PATH) | |
| 24 | + ? Emulator::toCronEvent($body) | |
| 25 | + : Emulator::toEvent($server('REQUEST_METHOD'), $server('REQUEST_URI'), $headers, $body, $server('REMOTE_ADDR')); | |
| 29 | 26 | |
| 30 | 27 | $response = null; |
| 31 | 28 | $connection = @stream_socket_client((string) getenv('SCALEWAY_EMULATOR_SOCKET'), $errorCode, $errorMessage); |
| @@ -18,14 +18,11 @@ foreach (getallheaders() as $name => $value) { | |||
| 18 | $headers[(string) $name] = $value; | 18 | $headers[(string) $name] = $value; |
| 19 | } | 19 | } |
| 20 | } | 20 | } |
| 21 | -$event = Emulator::toEvent( | 21 | +// Raw even for form posts, as the server runs with enable_post_data_reading=0. |
| 22 | - $server('REQUEST_METHOD'), | 22 | +$body = (string) file_get_contents('php://input'); |
| 23 | - $server('REQUEST_URI'), | 23 | +$event = 'POST' === $server('REQUEST_METHOD') && Emulator::CRON_PATH === parse_url($server('REQUEST_URI'), \PHP_URL_PATH) |
| 24 | - $headers, | 24 | + ? Emulator::toCronEvent($body) |
| 25 | - // Raw even for form posts, as the server runs with enable_post_data_reading=0. | 25 | + : Emulator::toEvent($server('REQUEST_METHOD'), $server('REQUEST_URI'), $headers, $body, $server('REMOTE_ADDR')); |
| 26 | - (string) file_get_contents('php://input'), | ||
| 27 | - $server('REMOTE_ADDR'), | ||
| 28 | -); | ||
| 29 | 26 | ||
| 30 | $response = null; | 27 | $response = null; |
| 31 | $connection = @stream_socket_client((string) getenv('SCALEWAY_EMULATOR_SOCKET'), $errorCode, $errorMessage); | 28 | $connection = @stream_socket_client((string) getenv('SCALEWAY_EMULATOR_SOCKET'), $errorCode, $errorMessage); |
modified
resources/emulator/warm-process.php +1 -2 | @@ -31,8 +31,7 @@ while (false !== $connection = @stream_socket_accept($server, -1)) { | ||
| 31 | 31 | if (!is_array($event)) { |
| 32 | 32 | throw new UnexpectedValueException('The Event must be a JSON object.'); |
| 33 | 33 | } |
| 34 | - // Scaleway's context shape is not documented; the probe function records it. | |
| 35 | - $response = handle($event, []); | |
| 34 | + $response = handle($event, JDecool\ScalewayRuntime\Emulator::CONTEXT); | |
| 36 | 35 | fwrite($connection, json_encode($response, \JSON_THROW_ON_ERROR)); |
| 37 | 36 | } catch (Throwable $e) { |
| 38 | 37 | // Scaleway would fail the Invocation too, e.g. for a Function Response that is not JSON-encodable. |
| @@ -31,8 +31,7 @@ while (false !== $connection = @stream_socket_accept($server, -1)) { | |||
| 31 | if (!is_array($event)) { | 31 | if (!is_array($event)) { |
| 32 | throw new UnexpectedValueException('The Event must be a JSON object.'); | 32 | throw new UnexpectedValueException('The Event must be a JSON object.'); |
| 33 | } | 33 | } |
| 34 | - // Scaleway's context shape is not documented; the probe function records it. | 34 | + $response = handle($event, JDecool\ScalewayRuntime\Emulator::CONTEXT); |
| 35 | - $response = handle($event, []); | ||
| 36 | fwrite($connection, json_encode($response, \JSON_THROW_ON_ERROR)); | 35 | fwrite($connection, json_encode($response, \JSON_THROW_ON_ERROR)); |
| 37 | } catch (Throwable $e) { | 36 | } catch (Throwable $e) { |
| 38 | // Scaleway would fail the Invocation too, e.g. for a Function Response that is not JSON-encodable. | 37 | // Scaleway would fail the Invocation too, e.g. for a Function Response that is not JSON-encodable. |
modified
src/Emulator.php +94 -19 | @@ -5,22 +5,31 @@ declare(strict_types=1); | ||
| 5 | 5 | namespace JDecool\ScalewayRuntime; |
| 6 | 6 | |
| 7 | 7 | /** |
| 8 | - * Turns a real HTTP request into the Event Scaleway would pass to the Handler. | |
| 9 | - * | |
| 10 | - * Shape from https://www.scaleway.com/en/docs/serverless-functions/reference-content/code-examples/; | |
| 11 | - * how the platform canonicalizes headers, folds repeated query keys and fills X-Forwarded-* is | |
| 12 | - * an assumption until the probe function settles it. | |
| 8 | + * Turns a real HTTP request into the Event Scaleway would pass to the Handler, as measured by the probe | |
| 9 | + * (docs/probe-results.md); the values of "resource", "stageVariables" and "requestContext" are approximations. | |
| 13 | 10 | */ |
| 14 | 11 | final class Emulator |
| 15 | 12 | { |
| 13 | + /** The local path the Emulator answers with a CRON Invocation instead of an HTTP one, as no HTTP call can be one. */ | |
| 14 | + public const string CRON_PATH = '/_scaleway/cron'; | |
| 15 | + | |
| 16 | + /** The context the platform passes, with the default memory of a function. */ | |
| 17 | + public const array CONTEXT = ['memoryLimitInMb' => 256, 'functionName' => 'emulator', 'functionVersion' => '']; | |
| 18 | + | |
| 19 | + /** | |
| 20 | + * The platform sets these itself on every HTTP call, whatever the client sends; Host never reaches the function. | |
| 21 | + */ | |
| 22 | + private const array PLATFORM_HEADERS = ['Host', 'X-Real-Ip', 'X-Envoy-External-Address', 'X-Request-Id', 'K-Proxy-Request', 'X-Forwarded-Proto']; | |
| 23 | + | |
| 16 | 24 | /** |
| 17 | 25 | * @param array<string, string> $headers |
| 18 | 26 | * |
| 19 | - * @return array{path: string, queryStringParameters: array<string, string>, body: string, headers: array<string, string>, method: string, isBase64Encoded: bool} | |
| 27 | + * @return array{resource: string, path: string, httpMethod: string, headers: array<string, string>, multiValueHeaders: null, queryStringParameters: array<string, string>, multiValueQueryStringParameters: null, pathParameters: null, stageVariables: array{}, requestContext: array{httpMethod: string}, body: string, isBase64Encoded?: true} | |
| 20 | 28 | */ |
| 21 | 29 | public static function toEvent(string $method, string $uri, array $headers, string $body, string $clientAddress): array |
| 22 | 30 | { |
| 23 | 31 | [$path, $queryString] = explode('?', $uri, 2) + [1 => '']; |
| 32 | + $method = strtoupper($method); | |
| 24 | 33 | |
| 25 | 34 | // A map of strings, like the platform's: the last value of a repeated key wins and "a[]" stays a plain key. |
| 26 | 35 | $query = []; |
| @@ -31,25 +40,91 @@ final class Emulator | ||
| 31 | 40 | } |
| 32 | 41 | } |
| 33 | 42 | |
| 43 | + $canonical = self::canonicalize($headers); | |
| 44 | + $contentType = $canonical['Content-Type'] ?? ''; | |
| 45 | + $canonical = array_diff_key($canonical, array_flip(self::PLATFORM_HEADERS)); | |
| 46 | + // The client's X-Forwarded-For is kept in front, and its Forwarded replaces the platform's. | |
| 47 | + $canonical['X-Forwarded-For'] = isset($canonical['X-Forwarded-For']) ? $canonical['X-Forwarded-For'].','.$clientAddress : $clientAddress; | |
| 48 | + $canonical['Forwarded'] ??= \sprintf(str_contains($clientAddress, ':') ? 'for="[%s]";proto=https' : 'for=%s;proto=https', $clientAddress); | |
| 49 | + $canonical += [ | |
| 50 | + 'K-Proxy-Request' => 'activator', | |
| 51 | + 'X-Envoy-External-Address' => $clientAddress, | |
| 52 | + 'X-Forwarded-Proto' => 'https', | |
| 53 | + 'X-Real-Ip' => $clientAddress, | |
| 54 | + 'X-Request-Id' => self::uuid(), | |
| 55 | + ]; | |
| 56 | + ksort($canonical); | |
| 57 | + | |
| 58 | + $event = [ | |
| 59 | + 'resource' => $path, | |
| 60 | + 'path' => $path, | |
| 61 | + 'httpMethod' => $method, | |
| 62 | + 'headers' => $canonical, | |
| 63 | + 'multiValueHeaders' => null, | |
| 64 | + 'queryStringParameters' => $query, | |
| 65 | + 'multiValueQueryStringParameters' => null, | |
| 66 | + 'pathParameters' => null, | |
| 67 | + 'stageVariables' => [], | |
| 68 | + 'requestContext' => ['httpMethod' => $method], | |
| 69 | + 'body' => $body, | |
| 70 | + ]; | |
| 71 | + // Text bodies come without the flag; empty, binary and multipart ones base64-encoded. | |
| 72 | + if ('' === $body || 1 !== preg_match('//u', $body) || str_starts_with(strtolower($contentType), 'multipart/')) { | |
| 73 | + $event['body'] = base64_encode($body); | |
| 74 | + $event['isBase64Encoded'] = true; | |
| 75 | + } | |
| 76 | + | |
| 77 | + return $event; | |
| 78 | + } | |
| 79 | + | |
| 80 | + /** | |
| 81 | + * The Event of a CRON trigger whose arguments are the given JSON: it comes from inside the platform, without | |
| 82 | + * the client address headers of HTTP calls. | |
| 83 | + * | |
| 84 | + * @return array{path: string, httpMethod: string, headers: array<string, string>, queryStringParameters: array{}, body: string} | |
| 85 | + */ | |
| 86 | + public static function toCronEvent(string $args): array | |
| 87 | + { | |
| 88 | + return [ | |
| 89 | + 'path' => '/', | |
| 90 | + 'httpMethod' => 'POST', | |
| 91 | + 'headers' => [ | |
| 92 | + 'Content-Length' => (string) \strlen($args), | |
| 93 | + 'Content-Type' => 'application/json', | |
| 94 | + 'Forwarded' => 'for=127.0.0.1;proto=http', | |
| 95 | + 'K-Proxy-Request' => 'activator', | |
| 96 | + 'User-Agent' => 'Go-http-client/1.1', | |
| 97 | + 'X-Forwarded-For' => '127.0.0.1', | |
| 98 | + 'X-Forwarded-Proto' => 'http', | |
| 99 | + 'X-Request-Id' => self::uuid(), | |
| 100 | + ], | |
| 101 | + 'queryStringParameters' => [], | |
| 102 | + 'body' => $args, | |
| 103 | + ]; | |
| 104 | + } | |
| 105 | + | |
| 106 | + /** | |
| 107 | + * @param array<string, string> $headers | |
| 108 | + * | |
| 109 | + * @return array<string, string> | |
| 110 | + */ | |
| 111 | + private static function canonicalize(array $headers): array | |
| 112 | + { | |
| 34 | 113 | $canonical = []; |
| 35 | 114 | foreach ($headers as $name => $value) { |
| 36 | 115 | $name = ucwords(strtolower($name), '-'); |
| 37 | 116 | $canonical[$name] = isset($canonical[$name]) ? $canonical[$name].', '.$value : $value; |
| 38 | 117 | } |
| 39 | - // As a reverse proxy does: the peer is appended to the client's chain. | |
| 40 | - $canonical['X-Forwarded-For'] = isset($canonical['X-Forwarded-For']) ? $canonical['X-Forwarded-For'].', '.$clientAddress : $clientAddress; | |
| 41 | - $canonical['X-Forwarded-Proto'] = 'http'; | |
| 42 | 118 | |
| 43 | - // JSON carries the Event, so a body that is not UTF-8 text travels base64-encoded. | |
| 44 | - $binary = 1 !== preg_match('//u', $body); | |
| 119 | + return $canonical; | |
| 120 | + } | |
| 45 | 121 | |
| 46 | - return [ | |
| 47 | - 'path' => $path, | |
| 48 | - 'queryStringParameters' => $query, | |
| 49 | - 'body' => $binary ? base64_encode($body) : $body, | |
| 50 | - 'headers' => $canonical, | |
| 51 | - 'method' => strtoupper($method), | |
| 52 | - 'isBase64Encoded' => $binary, | |
| 53 | - ]; | |
| 122 | + private static function uuid(): string | |
| 123 | + { | |
| 124 | + $bytes = random_bytes(16); | |
| 125 | + $bytes[6] = \chr(\ord($bytes[6]) & 0x0F | 0x40); | |
| 126 | + $bytes[8] = \chr(\ord($bytes[8]) & 0x3F | 0x80); | |
| 127 | + | |
| 128 | + return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4)); | |
| 54 | 129 | } |
| 55 | 130 | } |
| @@ -5,22 +5,31 @@ declare(strict_types=1); | |||
| 5 | namespace JDecool\ScalewayRuntime; | 5 | namespace JDecool\ScalewayRuntime; |
| 6 | 6 | ||
| 7 | /** | 7 | /** |
| 8 | - * Turns a real HTTP request into the Event Scaleway would pass to the Handler. | 8 | + * Turns a real HTTP request into the Event Scaleway would pass to the Handler, as measured by the probe |
| 9 | - * | 9 | + * (docs/probe-results.md); the values of "resource", "stageVariables" and "requestContext" are approximations. |
| 10 | - * Shape from https://www.scaleway.com/en/docs/serverless-functions/reference-content/code-examples/; | ||
| 11 | - * how the platform canonicalizes headers, folds repeated query keys and fills X-Forwarded-* is | ||
| 12 | - * an assumption until the probe function settles it. | ||
| 13 | */ | 10 | */ |
| 14 | final class Emulator | 11 | final class Emulator |
| 15 | { | 12 | { |
| 13 | + /** The local path the Emulator answers with a CRON Invocation instead of an HTTP one, as no HTTP call can be one. */ | ||
| 14 | + public const string CRON_PATH = '/_scaleway/cron'; | ||
| 15 | + | ||
| 16 | + /** The context the platform passes, with the default memory of a function. */ | ||
| 17 | + public const array CONTEXT = ['memoryLimitInMb' => 256, 'functionName' => 'emulator', 'functionVersion' => '']; | ||
| 18 | + | ||
| 19 | + /** | ||
| 20 | + * The platform sets these itself on every HTTP call, whatever the client sends; Host never reaches the function. | ||
| 21 | + */ | ||
| 22 | + private const array PLATFORM_HEADERS = ['Host', 'X-Real-Ip', 'X-Envoy-External-Address', 'X-Request-Id', 'K-Proxy-Request', 'X-Forwarded-Proto']; | ||
| 23 | + | ||
| 16 | /** | 24 | /** |
| 17 | * @param array<string, string> $headers | 25 | * @param array<string, string> $headers |
| 18 | * | 26 | * |
| 19 | - * @return array{path: string, queryStringParameters: array<string, string>, body: string, headers: array<string, string>, method: string, isBase64Encoded: bool} | 27 | + * @return array{resource: string, path: string, httpMethod: string, headers: array<string, string>, multiValueHeaders: null, queryStringParameters: array<string, string>, multiValueQueryStringParameters: null, pathParameters: null, stageVariables: array{}, requestContext: array{httpMethod: string}, body: string, isBase64Encoded?: true} |
| 20 | */ | 28 | */ |
| 21 | public static function toEvent(string $method, string $uri, array $headers, string $body, string $clientAddress): array | 29 | public static function toEvent(string $method, string $uri, array $headers, string $body, string $clientAddress): array |
| 22 | { | 30 | { |
| 23 | [$path, $queryString] = explode('?', $uri, 2) + [1 => '']; | 31 | [$path, $queryString] = explode('?', $uri, 2) + [1 => '']; |
| 32 | + $method = strtoupper($method); | ||
| 24 | 33 | ||
| 25 | // A map of strings, like the platform's: the last value of a repeated key wins and "a[]" stays a plain key. | 34 | // A map of strings, like the platform's: the last value of a repeated key wins and "a[]" stays a plain key. |
| 26 | $query = []; | 35 | $query = []; |
| @@ -31,25 +40,91 @@ final class Emulator | |||
| 31 | } | 40 | } |
| 32 | } | 41 | } |
| 33 | 42 | ||
| 43 | + $canonical = self::canonicalize($headers); | ||
| 44 | + $contentType = $canonical['Content-Type'] ?? ''; | ||
| 45 | + $canonical = array_diff_key($canonical, array_flip(self::PLATFORM_HEADERS)); | ||
| 46 | + // The client's X-Forwarded-For is kept in front, and its Forwarded replaces the platform's. | ||
| 47 | + $canonical['X-Forwarded-For'] = isset($canonical['X-Forwarded-For']) ? $canonical['X-Forwarded-For'].','.$clientAddress : $clientAddress; | ||
| 48 | + $canonical['Forwarded'] ??= \sprintf(str_contains($clientAddress, ':') ? 'for="[%s]";proto=https' : 'for=%s;proto=https', $clientAddress); | ||
| 49 | + $canonical += [ | ||
| 50 | + 'K-Proxy-Request' => 'activator', | ||
| 51 | + 'X-Envoy-External-Address' => $clientAddress, | ||
| 52 | + 'X-Forwarded-Proto' => 'https', | ||
| 53 | + 'X-Real-Ip' => $clientAddress, | ||
| 54 | + 'X-Request-Id' => self::uuid(), | ||
| 55 | + ]; | ||
| 56 | + ksort($canonical); | ||
| 57 | + | ||
| 58 | + $event = [ | ||
| 59 | + 'resource' => $path, | ||
| 60 | + 'path' => $path, | ||
| 61 | + 'httpMethod' => $method, | ||
| 62 | + 'headers' => $canonical, | ||
| 63 | + 'multiValueHeaders' => null, | ||
| 64 | + 'queryStringParameters' => $query, | ||
| 65 | + 'multiValueQueryStringParameters' => null, | ||
| 66 | + 'pathParameters' => null, | ||
| 67 | + 'stageVariables' => [], | ||
| 68 | + 'requestContext' => ['httpMethod' => $method], | ||
| 69 | + 'body' => $body, | ||
| 70 | + ]; | ||
| 71 | + // Text bodies come without the flag; empty, binary and multipart ones base64-encoded. | ||
| 72 | + if ('' === $body || 1 !== preg_match('//u', $body) || str_starts_with(strtolower($contentType), 'multipart/')) { | ||
| 73 | + $event['body'] = base64_encode($body); | ||
| 74 | + $event['isBase64Encoded'] = true; | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + return $event; | ||
| 78 | + } | ||
| 79 | + | ||
| 80 | + /** | ||
| 81 | + * The Event of a CRON trigger whose arguments are the given JSON: it comes from inside the platform, without | ||
| 82 | + * the client address headers of HTTP calls. | ||
| 83 | + * | ||
| 84 | + * @return array{path: string, httpMethod: string, headers: array<string, string>, queryStringParameters: array{}, body: string} | ||
| 85 | + */ | ||
| 86 | + public static function toCronEvent(string $args): array | ||
| 87 | + { | ||
| 88 | + return [ | ||
| 89 | + 'path' => '/', | ||
| 90 | + 'httpMethod' => 'POST', | ||
| 91 | + 'headers' => [ | ||
| 92 | + 'Content-Length' => (string) \strlen($args), | ||
| 93 | + 'Content-Type' => 'application/json', | ||
| 94 | + 'Forwarded' => 'for=127.0.0.1;proto=http', | ||
| 95 | + 'K-Proxy-Request' => 'activator', | ||
| 96 | + 'User-Agent' => 'Go-http-client/1.1', | ||
| 97 | + 'X-Forwarded-For' => '127.0.0.1', | ||
| 98 | + 'X-Forwarded-Proto' => 'http', | ||
| 99 | + 'X-Request-Id' => self::uuid(), | ||
| 100 | + ], | ||
| 101 | + 'queryStringParameters' => [], | ||
| 102 | + 'body' => $args, | ||
| 103 | + ]; | ||
| 104 | + } | ||
| 105 | + | ||
| 106 | + /** | ||
| 107 | + * @param array<string, string> $headers | ||
| 108 | + * | ||
| 109 | + * @return array<string, string> | ||
| 110 | + */ | ||
| 111 | + private static function canonicalize(array $headers): array | ||
| 112 | + { | ||
| 34 | $canonical = []; | 113 | $canonical = []; |
| 35 | foreach ($headers as $name => $value) { | 114 | foreach ($headers as $name => $value) { |
| 36 | $name = ucwords(strtolower($name), '-'); | 115 | $name = ucwords(strtolower($name), '-'); |
| 37 | $canonical[$name] = isset($canonical[$name]) ? $canonical[$name].', '.$value : $value; | 116 | $canonical[$name] = isset($canonical[$name]) ? $canonical[$name].', '.$value : $value; |
| 38 | } | 117 | } |
| 39 | - // As a reverse proxy does: the peer is appended to the client's chain. | ||
| 40 | - $canonical['X-Forwarded-For'] = isset($canonical['X-Forwarded-For']) ? $canonical['X-Forwarded-For'].', '.$clientAddress : $clientAddress; | ||
| 41 | - $canonical['X-Forwarded-Proto'] = 'http'; | ||
| 42 | 118 | ||
| 43 | - // JSON carries the Event, so a body that is not UTF-8 text travels base64-encoded. | 119 | + return $canonical; |
| 44 | - $binary = 1 !== preg_match('//u', $body); | 120 | + } |
| 45 | 121 | ||
| 46 | - return [ | 122 | + private static function uuid(): string |
| 47 | - 'path' => $path, | 123 | + { |
| 48 | - 'queryStringParameters' => $query, | 124 | + $bytes = random_bytes(16); |
| 49 | - 'body' => $binary ? base64_encode($body) : $body, | 125 | + $bytes[6] = \chr(\ord($bytes[6]) & 0x0F | 0x40); |
| 50 | - 'headers' => $canonical, | 126 | + $bytes[8] = \chr(\ord($bytes[8]) & 0x3F | 0x80); |
| 51 | - 'method' => strtoupper($method), | 127 | + |
| 52 | - 'isBase64Encoded' => $binary, | 128 | + return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4)); |
| 53 | - ]; | ||
| 54 | } | 129 | } |
| 55 | } | 130 | } |
modified
tests/EmulatorTest.php +78 -16 | @@ -4,51 +4,113 @@ declare(strict_types=1); | ||
| 4 | 4 | |
| 5 | 5 | namespace JDecool\ScalewayRuntime\Tests; |
| 6 | 6 | |
| 7 | +use JDecool\ScalewayRuntime\CommandInvocation; | |
| 7 | 8 | use JDecool\ScalewayRuntime\Emulator; |
| 8 | 9 | use JDecool\ScalewayRuntime\HttpConverter; |
| 9 | 10 | use PHPUnit\Framework\TestCase; |
| 10 | 11 | |
| 11 | 12 | final class EmulatorTest extends TestCase |
| 12 | 13 | { |
| 13 | - public function testTextRequestBecomesAPlainEvent(): void | |
| 14 | + public function testTextRequestBecomesAnEventShapedLikeThePlatformOnes(): void | |
| 14 | 15 | { |
| 15 | 16 | $event = Emulator::toEvent('post', '/users/42?sort=name&filter%5Brole%5D=admin+user&flag', [ |
| 16 | 17 | 'content-type' => 'application/json', |
| 17 | - 'X-Forwarded-For' => '203.0.113.7', | |
| 18 | - ], '{"name":"Zoé"}', '127.0.0.1'); | |
| 18 | + 'Host' => '127.0.0.1:8000', | |
| 19 | + 'x-custom' => 'hello', | |
| 20 | + ], '{"name":"Zoé"}', '2001:db8::1'); | |
| 19 | 21 | |
| 22 | + self::assertMatchesRegularExpression('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $event['headers']['X-Request-Id']); | |
| 23 | + unset($event['headers']['X-Request-Id']); | |
| 20 | 24 | self::assertSame([ |
| 25 | + 'resource' => '/users/42', | |
| 21 | 26 | 'path' => '/users/42', |
| 22 | - 'queryStringParameters' => ['sort' => 'name', 'filter[role]' => 'admin user', 'flag' => ''], | |
| 23 | - 'body' => '{"name":"Zoé"}', | |
| 27 | + 'httpMethod' => 'POST', | |
| 24 | 28 | 'headers' => [ |
| 25 | 29 | 'Content-Type' => 'application/json', |
| 26 | - 'X-Forwarded-For' => '203.0.113.7, 127.0.0.1', | |
| 27 | - 'X-Forwarded-Proto' => 'http', | |
| 30 | + 'Forwarded' => 'for="[2001:db8::1]";proto=https', | |
| 31 | + 'K-Proxy-Request' => 'activator', | |
| 32 | + 'X-Custom' => 'hello', | |
| 33 | + 'X-Envoy-External-Address' => '2001:db8::1', | |
| 34 | + 'X-Forwarded-For' => '2001:db8::1', | |
| 35 | + 'X-Forwarded-Proto' => 'https', | |
| 36 | + 'X-Real-Ip' => '2001:db8::1', | |
| 28 | 37 | ], |
| 29 | - 'method' => 'POST', | |
| 30 | - 'isBase64Encoded' => false, | |
| 38 | + 'multiValueHeaders' => null, | |
| 39 | + 'queryStringParameters' => ['sort' => 'name', 'filter[role]' => 'admin user', 'flag' => ''], | |
| 40 | + 'multiValueQueryStringParameters' => null, | |
| 41 | + 'pathParameters' => null, | |
| 42 | + 'stageVariables' => [], | |
| 43 | + 'requestContext' => ['httpMethod' => 'POST'], | |
| 44 | + 'body' => '{"name":"Zoé"}', | |
| 31 | 45 | ], $event); |
| 32 | 46 | } |
| 33 | 47 | |
| 34 | - public function testBinaryBodyIsBase64Encoded(): void | |
| 48 | + public function testClientHeadersAreOverwrittenOrKeptLikeThePlatformDoes(): void | |
| 35 | 49 | { |
| 36 | - $event = Emulator::toEvent('PUT', '/', [], "\xFF\x00\xFE", '127.0.0.1'); | |
| 50 | + $headers = Emulator::toEvent('GET', '/', [ | |
| 51 | + 'X-Forwarded-For' => '203.0.113.66', | |
| 52 | + 'X-Forwarded-Proto' => 'http', | |
| 53 | + 'X-Forwarded-Host' => 'spoofed.example', | |
| 54 | + 'X-Real-Ip' => '203.0.113.66', | |
| 55 | + 'X-Envoy-External-Address' => '203.0.113.66', | |
| 56 | + 'X-Request-Id' => 'forged', | |
| 57 | + 'Forwarded' => 'for=203.0.113.66', | |
| 58 | + ], '', '192.0.2.1')['headers']; | |
| 37 | 59 | |
| 38 | - self::assertTrue($event['isBase64Encoded']); | |
| 39 | - self::assertSame("\xFF\x00\xFE", base64_decode($event['body'], true)); | |
| 60 | + self::assertSame('203.0.113.66,192.0.2.1', $headers['X-Forwarded-For']); | |
| 61 | + self::assertSame('https', $headers['X-Forwarded-Proto']); | |
| 62 | + self::assertSame('spoofed.example', $headers['X-Forwarded-Host']); | |
| 63 | + self::assertSame('192.0.2.1', $headers['X-Real-Ip']); | |
| 64 | + self::assertSame('192.0.2.1', $headers['X-Envoy-External-Address']); | |
| 65 | + self::assertNotSame('forged', $headers['X-Request-Id']); | |
| 66 | + self::assertSame('for=203.0.113.66', $headers['Forwarded']); | |
| 40 | 67 | } |
| 41 | 68 | |
| 42 | - public function testRepeatedQueryKeyKeepsTheLastValue(): void | |
| 69 | + public function testEmptyBinaryAndMultipartBodiesAreBase64Encoded(): void | |
| 43 | 70 | { |
| 44 | - self::assertSame(['a' => '2'], Emulator::toEvent('GET', '/?a=1&a=2', [], '', '::1')['queryStringParameters']); | |
| 71 | + $empty = Emulator::toEvent('GET', '/', [], '', '::1'); | |
| 72 | + self::assertSame(['', true], [$empty['body'], $empty['isBase64Encoded'] ?? false]); | |
| 73 | + | |
| 74 | + $binary = Emulator::toEvent('PUT', '/', [], "\xFF\x00\xFE", '::1'); | |
| 75 | + self::assertTrue($binary['isBase64Encoded'] ?? false); | |
| 76 | + self::assertSame("\xFF\x00\xFE", base64_decode($binary['body'], true)); | |
| 77 | + | |
| 78 | + $multipart = Emulator::toEvent('POST', '/', ['Content-Type' => 'multipart/form-data; boundary=b'], "--b--\r\n", '::1'); | |
| 79 | + self::assertSame([base64_encode("--b--\r\n"), true], [$multipart['body'], $multipart['isBase64Encoded'] ?? false]); | |
| 80 | + } | |
| 81 | + | |
| 82 | + public function testQueryStringParametersKeepTheLastValueAndAreAnEmptyListWithoutQueryString(): void | |
| 83 | + { | |
| 84 | + self::assertSame(['a' => '2', 'list[]' => 'y'], Emulator::toEvent('GET', '/?a=1&a=2&list[]=x&list[]=y', [], '', '::1')['queryStringParameters']); | |
| 85 | + self::assertSame('[]', json_encode(Emulator::toEvent('GET', '/', [], '', '::1')['queryStringParameters'])); | |
| 45 | 86 | } |
| 46 | 87 | |
| 47 | 88 | public function testEventRoundTripsThroughTheConverter(): void |
| 48 | 89 | { |
| 49 | - $request = HttpConverter::toRequest(Emulator::toEvent('GET', '/search?q=caf%C3%A9&page%5Bsize%5D=10', ['Host' => 'example.test'], '', '192.0.2.1')); | |
| 90 | + $request = HttpConverter::toRequest(Emulator::toEvent('GET', '/search?q=caf%C3%A9&page%5Bsize%5D=10', [], '', '192.0.2.1')); | |
| 50 | 91 | |
| 51 | 92 | self::assertSame('/search', $request->getPathInfo()); |
| 52 | 93 | self::assertSame(['q' => 'café', 'page' => ['size' => '10']], $request->query->all()); |
| 94 | + self::assertSame('192.0.2.1', $request->getClientIp()); | |
| 95 | + self::assertTrue($request->isSecure()); | |
| 96 | + } | |
| 97 | + | |
| 98 | + public function testCronEventIsACommandInvocationAndHttpEventsAreNot(): void | |
| 99 | + { | |
| 100 | + $server = $_SERVER; | |
| 101 | + $_SERVER[CommandInvocation::SECRET_VAR] = 's3cret'; | |
| 102 | + $errorLog = fopen('php://memory', 'w+'); | |
| 103 | + self::assertNotFalse($errorLog); | |
| 104 | + $args = '{"command":"app:sync","secret":"s3cret"}'; | |
| 105 | + try { | |
| 106 | + $cron = Emulator::toCronEvent($args); | |
| 107 | + self::assertSame('app:sync', CommandInvocation::fromEvent($cron, $errorLog)?->command); | |
| 108 | + self::assertNull(CommandInvocation::fromEvent(Emulator::toEvent('POST', '/', ['Content-Type' => 'application/json'], $args, '::1'), $errorLog)); | |
| 109 | + } finally { | |
| 110 | + $_SERVER = $server; | |
| 111 | + } | |
| 112 | + | |
| 113 | + self::assertSame($args, $cron['body']); | |
| 114 | + self::assertArrayNotHasKey('X-Real-Ip', $cron['headers']); | |
| 53 | 115 | } |
| 54 | 116 | } |
| @@ -4,51 +4,113 @@ 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\Emulator; | 8 | use JDecool\ScalewayRuntime\Emulator; |
| 8 | use JDecool\ScalewayRuntime\HttpConverter; | 9 | use JDecool\ScalewayRuntime\HttpConverter; |
| 9 | use PHPUnit\Framework\TestCase; | 10 | use PHPUnit\Framework\TestCase; |
| 10 | 11 | ||
| 11 | final class EmulatorTest extends TestCase | 12 | final class EmulatorTest extends TestCase |
| 12 | { | 13 | { |
| 13 | - public function testTextRequestBecomesAPlainEvent(): void | 14 | + public function testTextRequestBecomesAnEventShapedLikeThePlatformOnes(): void |
| 14 | { | 15 | { |
| 15 | $event = Emulator::toEvent('post', '/users/42?sort=name&filter%5Brole%5D=admin+user&flag', [ | 16 | $event = Emulator::toEvent('post', '/users/42?sort=name&filter%5Brole%5D=admin+user&flag', [ |
| 16 | 'content-type' => 'application/json', | 17 | 'content-type' => 'application/json', |
| 17 | - 'X-Forwarded-For' => '203.0.113.7', | 18 | + 'Host' => '127.0.0.1:8000', |
| 18 | - ], '{"name":"Zoé"}', '127.0.0.1'); | 19 | + 'x-custom' => 'hello', |
| 20 | + ], '{"name":"Zoé"}', '2001:db8::1'); | ||
| 19 | 21 | ||
| 22 | + self::assertMatchesRegularExpression('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $event['headers']['X-Request-Id']); | ||
| 23 | + unset($event['headers']['X-Request-Id']); | ||
| 20 | self::assertSame([ | 24 | self::assertSame([ |
| 25 | + 'resource' => '/users/42', | ||
| 21 | 'path' => '/users/42', | 26 | 'path' => '/users/42', |
| 22 | - 'queryStringParameters' => ['sort' => 'name', 'filter[role]' => 'admin user', 'flag' => ''], | 27 | + 'httpMethod' => 'POST', |
| 23 | - 'body' => '{"name":"Zoé"}', | ||
| 24 | 'headers' => [ | 28 | 'headers' => [ |
| 25 | 'Content-Type' => 'application/json', | 29 | 'Content-Type' => 'application/json', |
| 26 | - 'X-Forwarded-For' => '203.0.113.7, 127.0.0.1', | 30 | + 'Forwarded' => 'for="[2001:db8::1]";proto=https', |
| 27 | - 'X-Forwarded-Proto' => 'http', | 31 | + 'K-Proxy-Request' => 'activator', |
| 32 | + 'X-Custom' => 'hello', | ||
| 33 | + 'X-Envoy-External-Address' => '2001:db8::1', | ||
| 34 | + 'X-Forwarded-For' => '2001:db8::1', | ||
| 35 | + 'X-Forwarded-Proto' => 'https', | ||
| 36 | + 'X-Real-Ip' => '2001:db8::1', | ||
| 28 | ], | 37 | ], |
| 29 | - 'method' => 'POST', | 38 | + 'multiValueHeaders' => null, |
| 30 | - 'isBase64Encoded' => false, | 39 | + 'queryStringParameters' => ['sort' => 'name', 'filter[role]' => 'admin user', 'flag' => ''], |
| 40 | + 'multiValueQueryStringParameters' => null, | ||
| 41 | + 'pathParameters' => null, | ||
| 42 | + 'stageVariables' => [], | ||
| 43 | + 'requestContext' => ['httpMethod' => 'POST'], | ||
| 44 | + 'body' => '{"name":"Zoé"}', | ||
| 31 | ], $event); | 45 | ], $event); |
| 32 | } | 46 | } |
| 33 | 47 | ||
| 34 | - public function testBinaryBodyIsBase64Encoded(): void | 48 | + public function testClientHeadersAreOverwrittenOrKeptLikeThePlatformDoes(): void |
| 35 | { | 49 | { |
| 36 | - $event = Emulator::toEvent('PUT', '/', [], "\xFF\x00\xFE", '127.0.0.1'); | 50 | + $headers = Emulator::toEvent('GET', '/', [ |
| 51 | + 'X-Forwarded-For' => '203.0.113.66', | ||
| 52 | + 'X-Forwarded-Proto' => 'http', | ||
| 53 | + 'X-Forwarded-Host' => 'spoofed.example', | ||
| 54 | + 'X-Real-Ip' => '203.0.113.66', | ||
| 55 | + 'X-Envoy-External-Address' => '203.0.113.66', | ||
| 56 | + 'X-Request-Id' => 'forged', | ||
| 57 | + 'Forwarded' => 'for=203.0.113.66', | ||
| 58 | + ], '', '192.0.2.1')['headers']; | ||
| 37 | 59 | ||
| 38 | - self::assertTrue($event['isBase64Encoded']); | 60 | + self::assertSame('203.0.113.66,192.0.2.1', $headers['X-Forwarded-For']); |
| 39 | - self::assertSame("\xFF\x00\xFE", base64_decode($event['body'], true)); | 61 | + self::assertSame('https', $headers['X-Forwarded-Proto']); |
| 62 | + self::assertSame('spoofed.example', $headers['X-Forwarded-Host']); | ||
| 63 | + self::assertSame('192.0.2.1', $headers['X-Real-Ip']); | ||
| 64 | + self::assertSame('192.0.2.1', $headers['X-Envoy-External-Address']); | ||
| 65 | + self::assertNotSame('forged', $headers['X-Request-Id']); | ||
| 66 | + self::assertSame('for=203.0.113.66', $headers['Forwarded']); | ||
| 40 | } | 67 | } |
| 41 | 68 | ||
| 42 | - public function testRepeatedQueryKeyKeepsTheLastValue(): void | 69 | + public function testEmptyBinaryAndMultipartBodiesAreBase64Encoded(): void |
| 43 | { | 70 | { |
| 44 | - self::assertSame(['a' => '2'], Emulator::toEvent('GET', '/?a=1&a=2', [], '', '::1')['queryStringParameters']); | 71 | + $empty = Emulator::toEvent('GET', '/', [], '', '::1'); |
| 72 | + self::assertSame(['', true], [$empty['body'], $empty['isBase64Encoded'] ?? false]); | ||
| 73 | + | ||
| 74 | + $binary = Emulator::toEvent('PUT', '/', [], "\xFF\x00\xFE", '::1'); | ||
| 75 | + self::assertTrue($binary['isBase64Encoded'] ?? false); | ||
| 76 | + self::assertSame("\xFF\x00\xFE", base64_decode($binary['body'], true)); | ||
| 77 | + | ||
| 78 | + $multipart = Emulator::toEvent('POST', '/', ['Content-Type' => 'multipart/form-data; boundary=b'], "--b--\r\n", '::1'); | ||
| 79 | + self::assertSame([base64_encode("--b--\r\n"), true], [$multipart['body'], $multipart['isBase64Encoded'] ?? false]); | ||
| 80 | + } | ||
| 81 | + | ||
| 82 | + public function testQueryStringParametersKeepTheLastValueAndAreAnEmptyListWithoutQueryString(): void | ||
| 83 | + { | ||
| 84 | + self::assertSame(['a' => '2', 'list[]' => 'y'], Emulator::toEvent('GET', '/?a=1&a=2&list[]=x&list[]=y', [], '', '::1')['queryStringParameters']); | ||
| 85 | + self::assertSame('[]', json_encode(Emulator::toEvent('GET', '/', [], '', '::1')['queryStringParameters'])); | ||
| 45 | } | 86 | } |
| 46 | 87 | ||
| 47 | public function testEventRoundTripsThroughTheConverter(): void | 88 | public function testEventRoundTripsThroughTheConverter(): void |
| 48 | { | 89 | { |
| 49 | - $request = HttpConverter::toRequest(Emulator::toEvent('GET', '/search?q=caf%C3%A9&page%5Bsize%5D=10', ['Host' => 'example.test'], '', '192.0.2.1')); | 90 | + $request = HttpConverter::toRequest(Emulator::toEvent('GET', '/search?q=caf%C3%A9&page%5Bsize%5D=10', [], '', '192.0.2.1')); |
| 50 | 91 | ||
| 51 | self::assertSame('/search', $request->getPathInfo()); | 92 | self::assertSame('/search', $request->getPathInfo()); |
| 52 | self::assertSame(['q' => 'café', 'page' => ['size' => '10']], $request->query->all()); | 93 | self::assertSame(['q' => 'café', 'page' => ['size' => '10']], $request->query->all()); |
| 94 | + self::assertSame('192.0.2.1', $request->getClientIp()); | ||
| 95 | + self::assertTrue($request->isSecure()); | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + public function testCronEventIsACommandInvocationAndHttpEventsAreNot(): void | ||
| 99 | + { | ||
| 100 | + $server = $_SERVER; | ||
| 101 | + $_SERVER[CommandInvocation::SECRET_VAR] = 's3cret'; | ||
| 102 | + $errorLog = fopen('php://memory', 'w+'); | ||
| 103 | + self::assertNotFalse($errorLog); | ||
| 104 | + $args = '{"command":"app:sync","secret":"s3cret"}'; | ||
| 105 | + try { | ||
| 106 | + $cron = Emulator::toCronEvent($args); | ||
| 107 | + self::assertSame('app:sync', CommandInvocation::fromEvent($cron, $errorLog)?->command); | ||
| 108 | + self::assertNull(CommandInvocation::fromEvent(Emulator::toEvent('POST', '/', ['Content-Type' => 'application/json'], $args, '::1'), $errorLog)); | ||
| 109 | + } finally { | ||
| 110 | + $_SERVER = $server; | ||
| 111 | + } | ||
| 112 | + | ||
| 113 | + self::assertSame($args, $cron['body']); | ||
| 114 | + self::assertArrayNotHasKey('X-Real-Ip', $cron['headers']); | ||
| 53 | } | 115 | } |
| 54 | } | 116 | } |