diff --git a/src/Channels/Channel.php b/src/Channels/Channel.php index 226ce53..d754451 100644 --- a/src/Channels/Channel.php +++ b/src/Channels/Channel.php @@ -146,6 +146,19 @@ class Channel $this->connections[$connection->socketId] = $connection; } + /** + * Drop the connection from the subscribers list, without the leave + * events unsubscribe() sends. For a socket that was stored without + * subscribing. + * + * @param \Ratchet\ConnectionInterface $connection + * @return void + */ + public function removeConnection(ConnectionInterface $connection): void + { + unset($this->connections[$connection->socketId]); + } + /** * Broadcast a payload to the subscribed connections. * diff --git a/src/Channels/PrivateChannel.php b/src/Channels/PrivateChannel.php index 9a7b6b4..3612cf5 100644 --- a/src/Channels/PrivateChannel.php +++ b/src/Channels/PrivateChannel.php @@ -25,4 +25,19 @@ class PrivateChannel extends Channel return parent::subscribe($connection, $payload); } + + /** + * Check a subscribe signature without joining the channel, for a socket + * that is already on it but was never admitted through subscribe(). + * + * @param \Ratchet\ConnectionInterface $connection + * @param \stdClass $payload + * @return void + * + * @throws InvalidSignature + */ + public function verifySubscription(ConnectionInterface $connection, stdClass $payload): void + { + $this->verifySignature($connection, $payload); + } } diff --git a/src/Websocket/Handler.php b/src/Websocket/Handler.php index 2ede7f2..678deab 100644 --- a/src/Websocket/Handler.php +++ b/src/Websocket/Handler.php @@ -239,8 +239,22 @@ class Handler implements MessageComponentInterface return; } + // The auth step, and consumer overrides of it, call saveConnection() + // on the channel they get. An unsubscribe frame passes + // shouldRejectMessage() without membership, so that put the socket + // on a private or presence channel it never signed for, or back on + // the channel it just left. Membership changes only through + // subscribe and unsubscribe: undo whatever the auth step added. + // (The channel is still passed, because overrides call + // $channel->saveConnection() without a null check.) + $wasMember = (bool) $channel?->hasConnection($connection); + $this->authenticateConnection($connection, $channel, $messageArray); + if ($channel && !$wasMember && $channel->hasConnection($connection)) { + $channel->removeConnection($connection); + } + // Only log in debug mode to reduce I/O if (self::$debug ??= (bool) config('app.debug')) { Log::channel('websocket')->debug('[' . $connection->socketId . ']@' . $channel->getName() . ' | ' . $payload); @@ -1438,19 +1452,29 @@ class Handler implements MessageComponentInterface ConnectionInterface $connection, array $message ): void { - if (!$channel->hasConnection($connection)) { - try { - $channel->subscribe($connection, (object) ($message['data'] ?? [])); - } catch (\Throwable $e) { - // Private and presence channels admit a socket only once its - // signature checks out (InvalidSignature otherwise). - if ($channel instanceof PrivateChannel) { - $this->rejectSubscription($channel, $channel_name, $connection, $message, $e); - return; - } + $payload = (object) ($message['data'] ?? []); - // Public channels need no authorization: track the socket as before. + try { + if (!$channel->hasConnection($connection)) { + $channel->subscribe($connection, $payload); + } elseif ( + $channel instanceof PrivateChannel + && !isset($this->channel_connections[$channel_name][$connection->socketId]) + ) { + // On the channel but never admitted by a subscribe here (a + // hook called saveConnection()): check the signature before + // the socket is tracked and kept there. + $channel->verifySubscription($connection, $payload); } + } catch (\Throwable $e) { + // Private and presence channels admit a socket only once its + // signature checks out (InvalidSignature otherwise). + if ($channel instanceof PrivateChannel) { + $this->rejectSubscription($channel, $channel_name, $connection, $message, $e); + return; + } + + // Public channels need no authorization: track the socket as before. } // Record the socket only once it is on the channel, so neither @@ -1612,7 +1636,9 @@ class Handler implements MessageComponentInterface $connection->user = $cached_auth['type']::find($cached_auth['id']); - if ($channel) { + // Refresh the stored connection, never add one: joining a channel + // goes through subscribe() and its signature check. + if ($channel?->hasConnection($connection)) { $channel->saveConnection($connection); } } @@ -1624,7 +1650,7 @@ class Handler implements MessageComponentInterface } $connection->user = false; - if ($channel) { + if ($channel?->hasConnection($connection)) { $channel->saveConnection($connection); } } diff --git a/tests/HandlerLifecycleTest.php b/tests/HandlerLifecycleTest.php index 6510151..e86817e 100644 --- a/tests/HandlerLifecycleTest.php +++ b/tests/HandlerLifecycleTest.php @@ -2,7 +2,12 @@ namespace BlaxSoftware\LaravelWebSockets\Test; +use BlaxSoftware\LaravelWebSockets\Channels\Channel; +use BlaxSoftware\LaravelWebSockets\Channels\PresenceChannel; +use BlaxSoftware\LaravelWebSockets\Channels\PrivateChannel; use BlaxSoftware\LaravelWebSockets\Services\WebsocketService; +use BlaxSoftware\LaravelWebSockets\Websocket\Handler; +use Ratchet\ConnectionInterface; /** * Comprehensive tests for the full WebSocket Handler lifecycle. @@ -227,10 +232,210 @@ class HandlerLifecycleTest extends TestCase { return [ 'private' => ['private-test'], + 'private-encrypted' => ['private-encrypted-test'], 'presence' => ['presence-test'], ]; } + /** + * @dataProvider authorizedChannels + */ + public function test_unsubscribe_as_first_frame_does_not_join_the_channel(string $channelName) + { + $connection = $this->newConnection(); + $this->wsHandler->onOpen($connection); + + // The first non-ping frame runs the full auth step, which used to + // saveConnection() the socket onto the frame's channel. + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.unsubscribe', + 'channel' => $channelName, + ])); + + $this->assertNotOnChannel($connection, $channelName); + $this->assertUnsignedSubscribeIsRefused($connection, $channelName); + } + + /** + * @dataProvider authorizedChannels + */ + public function test_unsubscribe_after_refused_subscribe_does_not_join_the_channel(string $channelName) + { + $connection = $this->newConnection(); + $this->wsHandler->onOpen($connection); + + // The refused frame ends before the auth step, so the unsubscribe + // after it is still the connection's first auth. + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.subscribe', + 'data' => ['auth' => 'TestKey:invalid-signature', 'channel' => $channelName], + ])); + $this->assertSubscriptionRefused($connection, $channelName); + + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.unsubscribe', + 'data' => ['channel' => $channelName], + ])); + + $this->assertNotOnChannel($connection, $channelName); + $this->assertUnsignedSubscribeIsRefused($connection, $channelName); + } + + /** + * @dataProvider authorizedChannels + */ + public function test_unsubscribe_after_auth_reset_does_not_join_the_channel(string $channelName) + { + $connection = $this->newActiveConnection(['public-channel']); + + // C:RESET from a child (logout) clears authLoaded: the next frame + // runs the full auth step again. + unset($connection->authLoaded); + + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.unsubscribe', + 'channel' => $channelName, + ])); + + $this->assertNotOnChannel($connection, $channelName); + $this->assertTrue($this->channelManager->find('1234', 'public-channel')->hasConnection($connection)); + } + + /** + * @dataProvider authorizedChannels + */ + public function test_auth_override_that_saves_the_connection_does_not_join_the_channel(string $channelName) + { + // Consumer handlers override authenticateConnection() and call + // $channel->saveConnection() themselves, some without a null check. + $this->wsHandler = new class($this->channelManager) extends Handler { + protected function authenticateConnection( + ConnectionInterface $connection, + PrivateChannel|Channel|PresenceChannel|null $channel, + $message = [] + ) { + $channel->saveConnection($connection); + + parent::authenticateConnection($connection, $channel, $message); + } + }; + + $connection = $this->newConnection(); + $this->wsHandler->onOpen($connection); + + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.unsubscribe', + 'channel' => $channelName, + ])); + + $response = collect($connection->sentData)->firstWhere('event', 'websocket.unsubscribe:response'); + $this->assertEquals('Success', $response['data']['message'] ?? null); + $this->assertNotOnChannel($connection, $channelName); + $this->assertUnsignedSubscribeIsRefused($connection, $channelName); + } + + public function test_unsubscribe_on_the_first_auth_frame_leaves_a_public_channel() + { + $connection = $this->newActiveConnection(['public-channel']); + unset($connection->authLoaded); + + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.unsubscribe', + 'channel' => 'public-channel', + ])); + + // The auth step used to put the socket straight back. + $this->assertNotOnChannel($connection, 'public-channel'); + } + + /** + * @dataProvider authorizedChannels + */ + public function test_unsigned_subscribe_of_a_socket_saved_on_the_channel_is_refused(string $channelName) + { + $connection = $this->newConnection(); + $this->wsHandler->onOpen($connection); + + // A hook (e.g. a consumer's authenticateConnection override) saved + // the socket on the channel without a subscribe. + $this->channelManager->findOrCreate('1234', $channelName)->saveConnection($connection); + + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.subscribe', + 'data' => ['channel' => $channelName], + ])); + + $this->assertSubscriptionRefused($connection, $channelName); + } + + public function test_signed_subscribe_of_a_socket_saved_on_the_channel_is_tracked() + { + $connection = $this->newConnection(); + $this->wsHandler->onOpen($connection); + $this->channelManager->findOrCreate('1234', 'private-test')->saveConnection($connection); + + $this->wsHandler->onMessage($connection, new Mocks\SignedMessage([ + 'event' => 'websocket.subscribe', + 'data' => ['channel' => 'private-test'], + ], $connection, 'private-test')); + + $response = collect($connection->sentData)->firstWhere('event', 'websocket.subscribe:response'); + $this->assertEquals('Success', $response['data']['message'] ?? null); + $this->assertTrue($this->channelManager->find('1234', 'private-test')->hasConnection($connection)); + $this->assertArrayHasKey($connection->socketId, $this->handlerChannelConnections()['private-test']); + } + + public function test_repeated_unsigned_subscribe_of_a_member_stays_a_no_op() + { + $connection = $this->newPrivateConnection('private-test'); + $connection->resetEvents(); + + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.subscribe', + 'data' => ['channel' => 'private-test'], + ])); + + $response = collect($connection->sentData)->firstWhere('event', 'websocket.subscribe:response'); + $this->assertEquals('Success', $response['data']['message'] ?? null); + $connection->assertNotSentEvent('websocket.subscribe:error'); + $this->assertTrue($this->channelManager->find('1234', 'private-test')->hasConnection($connection)); + } + + /** + * The socket is not on the channel, not tracked by the handler, not listed + * in the cache, and does not receive what the channel broadcasts. + */ + private function assertNotOnChannel(Mocks\Connection $connection, string $channelName): void + { + $channel = $this->channelManager->find('1234', $channelName); + $this->assertFalse((bool) $channel?->hasConnection($connection), 'Socket must not be on the channel'); + $this->assertArrayNotHasKey($connection->socketId, $this->handlerChannelConnections()[$channelName] ?? []); + + $this->flushHandlerCacheBuffer(); + $this->assertNotContains($connection->socketId, WebsocketService::getChannelConnections($channelName)); + + $connection->resetEvents(); + $channel?->broadcast('1234', (object) ['event' => 'secret.event', 'channel' => $channelName, 'data' => []], false); + $connection->assertNotSentEvent('secret.event'); + } + + /** + * A subscribe without a signature is refused and leaves the socket off the + * channel (it used to be laundered into a tracked subscription). + */ + private function assertUnsignedSubscribeIsRefused(Mocks\Connection $connection, string $channelName): void + { + $connection->resetEvents(); + + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.subscribe', + 'data' => ['channel' => $channelName], + ])); + + $this->assertSubscriptionRefused($connection, $channelName); + $this->assertNotOnChannel($connection, $channelName); + } + public function test_valid_subscribe_after_rejected_signature_succeeds() { $connection = $this->newConnection();