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; } /**