skipIfServerUnavailable(); $this->startServer(); $messages = []; $closed = new \React\Promise\Deferred(); \Ratchet\Client\connect('ws://localhost:4000/app/NonWorkingKey', [], [], $this->loop) ->then(function ($conn) use (&$messages, $closed) { $conn->on('message', function ($msg) use (&$messages) { $messages[] = (string) $msg; }); $conn->on('close', function ($code) use ($closed) { $closed->resolve($code); }); }, function ($e) use ($closed) { $closed->reject($e); }); // 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() { $connection = $this->newConnection('NonWorkingKey'); $this->wsHandler->onOpen($connection); $connection ->assertSentEvent('websocket.error', [ 'data' => [ 'message' => 'Could not find app key `NonWorkingKey`.', 'code' => 4001, ], ]) ->assertNotSentEvent('websocket.connection_established') ->assertClosed(); $this->assertSame(4001, $connection->closeCode); $this->assertFalse(isset($connection->app)); // Nothing to clean up, and closing must not throw. $this->wsHandler->onClose($connection); $connection->resetEvents(); $this->wsHandler->onMessage($connection, new Mocks\Message([ 'event' => 'websocket.subscribe', 'data' => ['channel' => 'public-channel'], ])); $connection->assertNothingSent(); } public function test_disallowed_origin_gets_4009_and_is_closed() { $connection = $this->newConnection('TestOrigin', ['Origin' => 'https://google.ro']); $this->wsHandler->onOpen($connection); $connection ->assertSentEvent('websocket.error', [ 'data' => [ 'message' => 'The origin is not allowed for `TestOrigin`.', 'code' => 4009, ], ]) ->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); } /** * @group integration * @group requires-server */ public function test_origin_validation_should_fail_for_no_origin() { $this->skipIfServerUnavailable(); $this->startServer(); $response = $this->await($this->joinWebSocketServer(['public-channel'], 'TestOrigin')); $this->assertSame('{"event":"websocket.error","data":{"message":"The origin is not allowed for `TestOrigin`.","code":4009}}', (string) $response); } /** * @group integration * @group requires-server */ public function test_origin_validation_should_fail_for_wrong_origin() { $this->skipIfServerUnavailable(); $this->startServer(); $response = $this->await($this->joinWebSocketServer(['public-channel'], 'TestOrigin', ['Origin' => 'https://google.ro'])); $this->assertSame('{"event":"websocket.error","data":{"message":"The origin is not allowed for `TestOrigin`.","code":4009}}', (string) $response); } public function test_origin_validation_should_pass_for_the_right_origin() { $connection = $this->newConnection('TestOrigin', ['Origin' => 'https://test.origin.com']); $this->wsHandler->onOpen($connection); $connection->assertSentEvent('websocket.connection_established'); } public function test_close_connection() { $connection = $this->newActiveConnection(['public-channel']); $this->channelManager ->getGlobalChannels('1234') ->then(function ($channels) { $this->assertCount(1, $channels); }); $this->channelManager ->getGlobalConnectionsCount('1234') ->then(function ($total) { $this->assertEquals(1, $total); }); $this->wsHandler->onClose($connection); $this->channelManager ->getGlobalConnectionsCount('1234') ->then(function ($total) { $this->assertEquals(0, $total); }); $this->channelManager ->getGlobalChannels('1234') ->then(function ($channels) { $this->assertCount(0, $channels); }); } public function test_websocket_exceptions_are_sent() { $connection = $this->newActiveConnection(['public-channel']); $this->wsHandler->onError($connection, new UnknownAppKey('NonWorkingKey')); $connection->assertSentEvent('websocket.error', [ 'data' => [ 'message' => 'Could not find app key `NonWorkingKey`.', 'code' => 4001, ], ]); } public function test_capacity_limit() { $this->app['config']->set('websockets.apps.0.capacity', 2); $this->newActiveConnection(['test-channel']); $this->newActiveConnection(['test-channel']); $failedConnection = $this->newActiveConnection(['test-channel']); $failedConnection ->assertSentEvent('websocket.error', ['data' => ['message' => 'Over capacity', 'code' => 4100]]) ->assertClosed(); } public function test_close_all_new_connections_after_stating_the_server_does_not_accept_new_connections() { $this->newActiveConnection(['test-channel']) ->assertSentEvent('websocket.connection_established') ->assertSentEvent('websocket_internal.subscription_succeeded'); $this->channelManager->declineNewConnections(); $this->assertFalse( $this->channelManager->acceptsNewConnections() ); $this->newActiveConnection(['test-channel']) ->assertNothingSent() ->assertClosed(); } }