From ee04c8c731c64cf92a64f8c567a034db71c67b47 Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Wed, 4 Nov 2026 12:25:54 +0100 Subject: [PATCH] BF refuse a broken app key or failed app lookup without stopping the server Ratchet's router merges the query over the route parameters, so /app/?appKey[]=x reached verifyAppKey() (and WebSocketsLogger's onOpen when logging is on) with an array. QueryParameters::get(): string threw a TypeError, onOpen only caught WebSocketException and Ratchet's IoServer only catches \Exception, so the Error left the event loop and the daemon exited. Anyone could do this before authenticating. - QueryParameters::get() reads a non-string parameter as '', so the key becomes an unknown key: websocket.error 4001 and a closed socket. - onOpen catches any other Throwable, logs it with the trace, sends websocket.error "Internal server error" (1011) and closes with 1011. - verifyAppKey() settles the findByKey() promise in place instead of await(). await() on a pending promise would run the server's own loop again from a fiber inside onOpen. A rejected lookup is rethrown, a pending one is refused; the AppManager contract now says findByKey() must settle synchronously. ConfigAppManager already does. - A refused connection (4001 unknown key, 4009 origin) closes with that code instead of 1000. 4000-4099 tells Pusher-style clients not to reconnect. ConnectionLogger::close() passes the code on. - The refusal is logged at warning level without a trace, and the client-supplied key goes into the JSON-encoded context, not the log line. Tests: the array key with and without the logger, QueryParameters on an array, an app manager that rejects, one that never settles and one that throws an Error, the close codes of the 4001/4009 refusals, and the server test now checks the 4001 close code. Co-Authored-By: Claude Opus 5.5 --- src/Contracts/AppManager.php | 5 + src/Server/Loggers/ConnectionLogger.php | 8 +- src/Server/QueryParameters.php | 7 +- src/Websocket/Handler.php | 81 ++++++++++++--- tests/ConnectionTest.php | 125 +++++++++++++++++++++++- tests/Mocks/Connection.php | 11 ++- 6 files changed, 218 insertions(+), 19 deletions(-) diff --git a/src/Contracts/AppManager.php b/src/Contracts/AppManager.php index d594538..0b2b609 100644 --- a/src/Contracts/AppManager.php +++ b/src/Contracts/AppManager.php @@ -25,6 +25,11 @@ interface AppManager /** * Get app by app key. * + * The WebSocket handler reads the result inside onOpen, on the server's + * event loop, so the returned promise must already be settled (resolved + * with the App or null, or rejected). A still pending promise refuses the + * connection. + * * @param string $appKey * @return PromiseInterface */ diff --git a/src/Server/Loggers/ConnectionLogger.php b/src/Server/Loggers/ConnectionLogger.php index a762876..e569593 100644 --- a/src/Server/Loggers/ConnectionLogger.php +++ b/src/Server/Loggers/ConnectionLogger.php @@ -56,18 +56,20 @@ class ConnectionLogger extends Logger implements ConnectionInterface } /** - * Close the connection. + * Close the connection. Passes a close code and reason on to the + * wrapped connection (WsConnection::close($code, $reason)). * + * @param mixed ...$arguments * @return void */ - public function close() + public function close(...$arguments) { $socketId = $this->connection->socketId ?? null; $appId = $this->connection->app->id ?? null; $this->warn("[{$appId}][{$socketId}] Closing connection"); - $this->connection->close(); + $this->connection->close(...$arguments); } /** diff --git a/src/Server/QueryParameters.php b/src/Server/QueryParameters.php index c0dfd47..306e2ad 100644 --- a/src/Server/QueryParameters.php +++ b/src/Server/QueryParameters.php @@ -44,13 +44,16 @@ class QueryParameters } /** - * Get a specific query parameter. + * Get a specific query parameter. A missing parameter, or one sent as an + * array (`?appKey[]=x`), reads as an empty string. * * @param string $name * @return string */ public function get(string $name): string { - return $this->all()[$name] ?? ''; + $value = $this->all()[$name] ?? ''; + + return is_string($value) ? $value : ''; } } diff --git a/src/Websocket/Handler.php b/src/Websocket/Handler.php index 678deab..c94d21f 100644 --- a/src/Websocket/Handler.php +++ b/src/Websocket/Handler.php @@ -28,8 +28,6 @@ use Ratchet\ConnectionInterface; use Ratchet\RFC6455\Messaging\MessageInterface; use Ratchet\WebSocket\MessageComponentInterface; -use function React\Async\await; - class Handler implements MessageComponentInterface { /** @@ -316,17 +314,50 @@ class Handler implements MessageComponentInterface $this->establishConnection($connection); $this->initializeAppConnection($connection); } catch (ExceptionsWebSocketException $e) { - // Unknown app key (4001) or disallowed origin (4009): tell the - // client why and drop the socket. It never joined the app, so it - // must not stay open half set up. - Log::channel('websocket')->error('Root level error: ' . $e->getMessage(), [ + // Unknown app key (4001) or disallowed origin (4009): a client + // misconfiguration, not a server fault. Tell the client why and + // close with the same code (4000-4099 tells Pusher-style clients + // not to reconnect). The key is client input: keep it in the + // JSON-encoded context, never in the log line itself. + Log::channel('websocket')->warning('Connection refused', [ + 'code' => $e->getCode(), + 'reason' => $e->getMessage(), + ]); + + $code = (int) $e->getCode(); + $this->refuseConnection($connection, $e->getPayload(), $code >= 4000 && $code <= 4999 ? $code : 1008); + } catch (\Throwable $e) { + // Anything else (a TypeError, an app manager that rejects or never + // settles) must not leave onOpen: Ratchet only catches \Exception, + // so an Error here would stop the whole server. + Log::channel('websocket')->error('Opening the connection failed: ' . $e->getMessage(), [ + 'exception' => get_class($e), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), ]); - $connection->send(json_encode($e->getPayload())); - $connection->close(); + $this->refuseConnection($connection, [ + 'event' => 'websocket.error', + 'data' => [ + 'message' => 'Internal server error', + 'code' => 1011, + ], + ], 1011); + } + } + + /** + * Send the refusal frame and close the socket with $closeCode. The socket + * never joined the app, so it must not stay open half set up. + */ + protected function refuseConnection(ConnectionInterface $connection, array $payload, int $closeCode): void + { + try { + $connection->send(json_encode($payload)); + $connection->close($closeCode); + } catch (\Throwable) { + // The peer is already gone. } } @@ -1305,9 +1336,37 @@ class Handler implements MessageComponentInterface $appKey = $query->get('appKey'); - // findByKey() returns a promise, and a promise object is always truthy: - // wait for the App it resolves to (ConfigAppManager resolves at once). - if (! $app = await(App::findByKey($appKey))) { + // findByKey() returns a promise, and a promise object is always + // truthy: read the App it settles with. Settle it here instead of + // await(): onOpen runs on the server's event loop, and awaiting a + // pending promise would run that loop again from inside a fiber. + // ConfigAppManager resolves at once; a custom AppManager must too. + $app = null; + $settled = false; + $failure = null; + + App::findByKey($appKey)->then( + function ($found) use (&$app, &$settled) { + $app = $found; + $settled = true; + }, + function ($reason) use (&$failure, &$settled) { + $failure = $reason; + $settled = true; + } + ); + + if ($failure !== null) { + throw $failure instanceof \Throwable + ? $failure + : new \RuntimeException('The app lookup for this connection failed.'); + } + + if (! $settled) { + throw new \RuntimeException('The app manager must settle findByKey() synchronously.'); + } + + if (! $app) { throw new UnknownAppKey($appKey); } diff --git a/tests/ConnectionTest.php b/tests/ConnectionTest.php index 5a48a30..a462f12 100644 --- a/tests/ConnectionTest.php +++ b/tests/ConnectionTest.php @@ -2,7 +2,16 @@ namespace BlaxSoftware\LaravelWebSockets\Test; +use BlaxSoftware\LaravelWebSockets\Apps\ConfigAppManager; +use BlaxSoftware\LaravelWebSockets\Contracts\AppManager; use BlaxSoftware\LaravelWebSockets\Server\Exceptions\UnknownAppKey; +use BlaxSoftware\LaravelWebSockets\Server\Loggers\ConnectionLogger; +use BlaxSoftware\LaravelWebSockets\Server\Loggers\WebSocketsLogger; +use BlaxSoftware\LaravelWebSockets\Server\QueryParameters; +use GuzzleHttp\Psr7\Request; +use React\Promise\Deferred; +use React\Promise\PromiseInterface; +use Symfony\Component\Console\Output\BufferedOutput; class ConnectionTest extends TestCase { @@ -30,13 +39,15 @@ class ConnectionTest extends TestCase $closed->reject($e); }); - // The server closes the socket after the error frame. - $this->await($closed->promise()); + // The server closes the socket after the error frame, with the same + // code so Pusher-style clients do not reconnect. + $code = $this->await($closed->promise()); $this->assertSame( ['{"event":"websocket.error","data":{"message":"Could not find app key `NonWorkingKey`.","code":4001}}'], $messages ); + $this->assertSame(4001, $code); } public function test_unknown_app_key_gets_4001_and_is_closed() @@ -54,6 +65,7 @@ class ConnectionTest extends TestCase ]) ->assertNotSentEvent('websocket.connection_established') ->assertClosed(); + $this->assertSame(4001, $connection->closeCode); $this->assertFalse(isset($connection->app)); // Nothing to clean up, and closing must not throw. @@ -82,6 +94,115 @@ class ConnectionTest extends TestCase ]) ->assertNotSentEvent('websocket.connection_established') ->assertClosed(); + $this->assertSame(4009, $connection->closeCode); + + $this->wsHandler->onClose($connection); + } + + public function test_array_app_key_gets_4001_and_is_closed() + { + // Ratchet's router merges the query over the route parameters, so + // /app/?appKey[]=x reaches the handler with an array. It used + // to throw a TypeError out of QueryParameters::get(), which nothing + // caught, and the whole server stopped. + $connection = new Mocks\Connection; + $connection->httpRequest = new Request('GET', '/?appKey[]=x'); + + $this->wsHandler->onOpen($connection); + + $connection + ->assertSentEvent('websocket.error', [ + 'data' => [ + 'message' => 'Could not find app key ``.', + 'code' => 4001, + ], + ]) + ->assertNotSentEvent('websocket.connection_established') + ->assertClosed(); + $this->assertSame(4001, $connection->closeCode); + } + + public function test_array_app_key_with_logging_on_gets_4001_and_is_closed() + { + // With logging on, WebSocketsLogger reads the key before the handler + // and hands it a ConnectionLogger. + $this->app->bind(ConnectionLogger::class, function () { + return (new ConnectionLogger(new BufferedOutput()))->enable(true); + }); + $logger = WebSocketsLogger::decorate($this->wsHandler); + $logger->enable(true); + + $connection = new Mocks\Connection; + $connection->httpRequest = new Request('GET', '/?appKey[]=x'); + + $logger->onOpen($connection); + + $connection + ->assertSentEvent('websocket.error', ['data' => ['message' => 'Could not find app key ``.', 'code' => 4001]]) + ->assertClosed(); + // ConnectionLogger passes the close code on. + $this->assertSame(4001, $connection->closeCode); + } + + public function test_query_parameters_read_an_array_as_an_empty_string() + { + $query = QueryParameters::create(new Request('GET', '/?appKey[]=x&other=y')); + + $this->assertSame('', $query->get('appKey')); + $this->assertSame('y', $query->get('other')); + $this->assertSame('', $query->get('missing')); + } + + public function test_app_manager_that_rejects_gets_1011_and_is_closed() + { + $this->app->instance(AppManager::class, new class extends ConfigAppManager { + public function findByKey($appKey): PromiseInterface + { + return \React\Promise\reject(new \RuntimeException('app store down')); + } + }); + + $this->assertConnectionRefusedWithInternalError($this->newConnection()); + } + + public function test_app_manager_that_does_not_settle_gets_1011_and_is_closed() + { + $this->app->instance(AppManager::class, new class extends ConfigAppManager { + public function findByKey($appKey): PromiseInterface + { + return (new Deferred())->promise(); + } + }); + + $this->assertConnectionRefusedWithInternalError($this->newConnection()); + } + + public function test_error_thrown_while_opening_gets_1011_and_is_closed() + { + $this->app->instance(AppManager::class, new class extends ConfigAppManager { + public function findByKey($appKey): PromiseInterface + { + throw new \TypeError('broken app manager'); + } + }); + + $this->assertConnectionRefusedWithInternalError($this->newConnection()); + } + + /** + * onOpen must neither throw nor leave the socket open when opening fails + * for a reason other than a WebSocketException. + */ + private function assertConnectionRefusedWithInternalError(Mocks\Connection $connection): void + { + $this->wsHandler->onOpen($connection); + + $connection + ->assertSentEvent('websocket.error', ['data' => ['message' => 'Internal server error', 'code' => 1011]]) + ->assertNotSentEvent('websocket.connection_established') + ->assertClosed(); + $this->assertSame(1011, $connection->closeCode); + $this->assertFalse(isset($connection->app)); $this->wsHandler->onClose($connection); } diff --git a/tests/Mocks/Connection.php b/tests/Mocks/Connection.php index 40525cc..608ea05 100644 --- a/tests/Mocks/Connection.php +++ b/tests/Mocks/Connection.php @@ -48,14 +48,23 @@ class Connection implements ConnectionInterface $this->sentRawData[] = $data; } + /** + * The close code passed to close(), if any. + * + * @var int|null + */ + public $closeCode = null; + /** * Mark the connection as closed. * + * @param int|null $code * @return void */ - public function close() + public function close($code = null) { $this->closed = true; + $this->closeCode = $code; } /**