diff --git a/src/Websocket/Handler.php b/src/Websocket/Handler.php index a69d807..a486276 100644 --- a/src/Websocket/Handler.php +++ b/src/Websocket/Handler.php @@ -36,6 +36,12 @@ class Handler implements MessageComponentInterface */ protected array $channel_connections = []; + /** + * Sockets whose subscribe on the current frame was refused and already + * answered with an `:error` frame. Structure: [socket_id => true] + */ + protected array $rejectedSubscriptions = []; + /** * Cache write buffer for batching operations * Reduces file I/O when multiple rapid requests occur @@ -215,8 +221,18 @@ class Handler implements MessageComponentInterface // Handle protocol messages (client-* broadcasts) $this->handleProtocolMessage($message, $connection, $messageArray); + unset($this->rejectedSubscriptions[$connection->socketId]); + $channel = $this->handleChannelSubscriptions($messageArray, $connection); + // handleSubscription() refused the subscribe and already sent its + // :error frame. Stop here: no Success reply, and shouldRejectMessage() + // must not get the chance to add the socket to the channel. + if (isset($this->rejectedSubscriptions[$connection->socketId])) { + unset($this->rejectedSubscriptions[$connection->socketId]); + return; + } + if ($this->shouldRejectMessage($channel, $connection, $messageArray)) { return; } @@ -297,6 +313,8 @@ class Handler implements MessageComponentInterface */ public function onClose(ConnectionInterface $connection): void { + unset($this->rejectedSubscriptions[$connection->socketId]); + $this->authenticateConnection($connection, null); if (isset($connection->remoteAddress)) { @@ -1405,34 +1423,68 @@ class Handler implements MessageComponentInterface ConnectionInterface $connection, array $message ): void { - $socketId = $connection->socketId; + 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; + } - if (!isset($this->channel_connections[$channel_name])) { - $this->channel_connections[$channel_name] = []; + // Public channels need no authorization: track the socket as before. + } } - if (!isset($this->channel_connections[$channel_name][$socketId])) { - $this->channel_connections[$channel_name][$socketId] = true; + // Record the socket only once it is on the channel, so neither + // shouldRejectMessage() nor the ws_channel_connections_* cache can + // count a socket whose subscribe failed. + $this->trackChannelConnection($channel_name, $connection->socketId); + } - // Only update cache if connection was actually added (avoid redundant writes) - // Pre-compute array_keys once for both updates - $channelSockets = array_keys($this->channel_connections[$channel_name]); - $activeChannels = array_keys($this->channel_connections); - - // Buffer these writes - they can be batched with other subscriptions - $this->bufferCacheWrite('ws_channel_connections_' . $channel_name, $channelSockets); - $this->bufferCacheWrite('ws_active_channels', $activeChannels); - } + /** + * Refuse a private/presence subscribe: leave the socket off the channel and + * out of the tracking, and answer the subscribe event with an `:error` frame. + */ + protected function rejectSubscription( + Channel $channel, + string $channel_name, + ConnectionInterface $connection, + array $message, + \Throwable $e + ): void { + // An entry left from an earlier subscription (the socket was dropped + // from the channel since) would let shouldRejectMessage() re-admit it. + $this->untrackChannelConnection($channel_name, $connection->socketId); + // PresenceChannel saves the connection before it announces the member, + // so a failure after the signature check can leave it on the channel. if ($channel->hasConnection($connection)) { - return; + try { + $channel->unsubscribe($connection); + } catch (\Throwable) { + // The subscribe is refused either way. + } } - try { - $channel->subscribe($connection, (object) ($message['data'] ?? [])); - } catch (\Throwable $e) { - // Silently handle subscription errors (e.g. invalid signatures) + if (!$e instanceof ExceptionsWebSocketException) { + Log::channel('websocket')->error('Subscribe to ' . $channel_name . ' failed: ' . $e->getMessage(), [ + 'file' => $e->getFile(), + 'line' => $e->getLine(), + ]); } + + $this->rejectedSubscriptions[$connection->socketId] = true; + + $connection->send(json_encode([ + 'event' => ($message['event'] ?? 'websocket.subscribe') . ':error', + 'data' => $e instanceof ExceptionsWebSocketException + ? ['message' => $e->getMessage(), 'code' => $e->getCode()] + : ['message' => 'Subscription failed'], + 'channel' => $channel_name, + ])); } protected function handleUnsubscription( @@ -1440,33 +1492,62 @@ class Handler implements MessageComponentInterface string $channel_name, ConnectionInterface $connection ): void { - $socketId = $connection->socketId; - - if (isset($this->channel_connections[$channel_name][$socketId])) { - unset($this->channel_connections[$channel_name][$socketId]); - - // Pre-compute active channels once - $activeChannels = array_keys($this->channel_connections); - - if (empty($this->channel_connections[$channel_name])) { - unset($this->channel_connections[$channel_name]); - - // Buffer delete and update - can be batched - $this->bufferCacheDelete('ws_channel_connections_' . $channel_name); - $this->bufferCacheWrite('ws_active_channels', $activeChannels); - } else { - // Pre-compute channel sockets once - $channelSockets = array_keys($this->channel_connections[$channel_name]); - - // Buffer these writes - $this->bufferCacheWrite('ws_channel_connections_' . $channel_name, $channelSockets); - $this->bufferCacheWrite('ws_active_channels', $activeChannels); - } - } + $this->untrackChannelConnection($channel_name, $connection->socketId); $channel->unsubscribe($connection); } + /** + * Add a socket to $channel_connections and buffer the matching + * ws_channel_connections_* / ws_active_channels cache writes. + */ + protected function trackChannelConnection(string $channel_name, string $socketId): void + { + if (isset($this->channel_connections[$channel_name][$socketId])) { + return; + } + + $this->channel_connections[$channel_name][$socketId] = true; + + // Only update cache if connection was actually added (avoid redundant writes) + // Pre-compute array_keys once for both updates + $channelSockets = array_keys($this->channel_connections[$channel_name]); + $activeChannels = array_keys($this->channel_connections); + + // Buffer these writes - they can be batched with other subscriptions + $this->bufferCacheWrite('ws_channel_connections_' . $channel_name, $channelSockets); + $this->bufferCacheWrite('ws_active_channels', $activeChannels); + } + + /** + * Remove a socket from $channel_connections and buffer the matching + * cache updates. No-op for a socket that is not tracked. + */ + protected function untrackChannelConnection(string $channel_name, string $socketId): void + { + if (!isset($this->channel_connections[$channel_name][$socketId])) { + return; + } + + unset($this->channel_connections[$channel_name][$socketId]); + + // Pre-compute active channels once + $activeChannels = array_keys($this->channel_connections); + + if (empty($this->channel_connections[$channel_name])) { + unset($this->channel_connections[$channel_name]); + + // Buffer delete and update - can be batched + $this->bufferCacheDelete('ws_channel_connections_' . $channel_name); + $this->bufferCacheWrite('ws_active_channels', $activeChannels); + return; + } + + // Buffer these writes + $this->bufferCacheWrite('ws_channel_connections_' . $channel_name, array_keys($this->channel_connections[$channel_name])); + $this->bufferCacheWrite('ws_active_channels', $activeChannels); + } + protected function setRequest($message, $connection) { foreach (request()->keys() as $key) { diff --git a/tests/HandlerLifecycleTest.php b/tests/HandlerLifecycleTest.php index cc7691b..6510151 100644 --- a/tests/HandlerLifecycleTest.php +++ b/tests/HandlerLifecycleTest.php @@ -165,8 +165,125 @@ class HandlerLifecycleTest extends TestCase $this->wsHandler->onMessage($connection, $message); - // Invalid signature is silently caught — no subscription_succeeded - $connection->assertNotSentEvent('websocket_internal.subscription_succeeded'); + // One frame: refused with an error, not on the channel, not tracked. + $this->assertSubscriptionRefused($connection, 'private-test'); + $this->assertNotContains('private-test', WebsocketService::getActiveChannels()); + } + + public function test_subscribe_to_presence_channel_with_invalid_signature_is_rejected() + { + $connection = $this->newConnection(); + $this->wsHandler->onOpen($connection); + + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.subscribe', + 'data' => [ + 'auth' => 'TestKey:invalid-signature', + 'channel' => 'presence-test', + 'channel_data' => json_encode(['user_id' => 1, 'user_info' => ['name' => 'Rick']]), + ], + ])); + + $this->assertSubscriptionRefused($connection, 'presence-test'); + $this->assertNotContains('presence-test', WebsocketService::getActiveChannels()); + } + + /** + * @dataProvider authorizedChannels + */ + public function test_message_after_rejected_subscribe_does_not_resubscribe(string $channelName) + { + $connection = $this->newConnection(); + $this->wsHandler->onOpen($connection); + + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.subscribe', + 'data' => ['auth' => 'TestKey:invalid-signature', 'channel' => $channelName], + ])); + $connection->resetEvents(); + + // An unrelated message on the channel used to re-add the socket + // through shouldRejectMessage()'s auto-resubscribe. + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'app.someAction', + 'data' => ['test' => true], + 'channel' => $channelName, + ])); + + $error = collect($connection->sentData)->firstWhere('event', 'app.someAction:error'); + $this->assertNotNull($error); + $this->assertEquals('Subscription not established', $error['data']['message']); + + $channel = $this->channelManager->find('1234', $channelName); + $this->assertFalse($channel->hasConnection($connection)); + $this->assertArrayNotHasKey($connection->socketId, $this->handlerChannelConnections()[$channelName] ?? []); + + // And it does not receive what the channel broadcasts. + $channel->broadcast('1234', (object) ['event' => 'secret.event', 'channel' => $channelName, 'data' => []], false); + $connection->assertNotSentEvent('secret.event'); + } + + public static function authorizedChannels(): array + { + return [ + 'private' => ['private-test'], + 'presence' => ['presence-test'], + ]; + } + + public function test_valid_subscribe_after_rejected_signature_succeeds() + { + $connection = $this->newConnection(); + $this->wsHandler->onOpen($connection); + + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.subscribe', + 'data' => ['auth' => 'TestKey:invalid-signature', 'channel' => 'private-test'], + ])); + $this->assertSubscriptionRefused($connection, 'private-test'); + $connection->resetEvents(); + + $this->wsHandler->onMessage($connection, new Mocks\SignedMessage([ + 'event' => 'websocket.subscribe', + 'data' => ['channel' => 'private-test'], + ], $connection, 'private-test')); + + $connection->assertSentEvent('websocket_internal.subscription_succeeded'); + $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->flushHandlerCacheBuffer(); + $this->assertContains($connection->socketId, WebsocketService::getChannelConnections('private-test')); + } + + public function test_rejected_resubscribe_drops_the_earlier_tracking() + { + $connection = $this->newPrivateConnection('private-test'); + $channel = $this->channelManager->find('1234', 'private-test'); + $this->assertTrue($channel->hasConnection($connection)); + + // The socket drops off the channel (e.g. removeObsoleteConnections) + // while the handler still tracks it. + $channel->unsubscribe($connection); + $this->assertArrayHasKey($connection->socketId, $this->handlerChannelConnections()['private-test']); + $connection->resetEvents(); + + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'websocket.subscribe', + 'data' => ['auth' => 'TestKey:invalid-signature', 'channel' => 'private-test'], + ])); + + $this->assertSubscriptionRefused($connection, 'private-test'); + + // With the tracking gone, the next message cannot re-admit the socket. + $this->wsHandler->onMessage($connection, new Mocks\Message([ + 'event' => 'app.someAction', + 'data' => [], + 'channel' => 'private-test', + ])); + $this->assertFalse($channel->hasConnection($connection)); + $connection->assertSentEvent('app.someAction:error'); } // ========================================================================= diff --git a/tests/PresenceChannelTest.php b/tests/PresenceChannelTest.php index eb1c89e..d73e45a 100644 --- a/tests/PresenceChannelTest.php +++ b/tests/PresenceChannelTest.php @@ -22,8 +22,12 @@ class PresenceChannelTest extends TestCase $this->wsHandler->onOpen($connection); $this->wsHandler->onMessage($connection, $message); - // Invalid signature should be silently rejected — no subscription_succeeded sent - $connection->assertNotSentEvent('websocket_internal.subscription_succeeded'); + // One frame: refused with an error, not on the channel, not tracked. + $this->assertSubscriptionRefused($connection, 'presence-channel'); + $this->assertNotContains( + 'presence-channel', + \BlaxSoftware\LaravelWebSockets\Services\WebsocketService::getActiveChannels() + ); } public function test_connect_to_presence_channel_with_valid_signature() diff --git a/tests/PrivateChannelTest.php b/tests/PrivateChannelTest.php index 36f5f21..b186888 100644 --- a/tests/PrivateChannelTest.php +++ b/tests/PrivateChannelTest.php @@ -22,8 +22,12 @@ class PrivateChannelTest extends TestCase $this->wsHandler->onOpen($connection); $this->wsHandler->onMessage($connection, $message); - // Invalid signature should be silently rejected — no subscription_succeeded sent - $connection->assertNotSentEvent('websocket_internal.subscription_succeeded'); + // One frame: refused with an error, not on the channel, not tracked. + $this->assertSubscriptionRefused($connection, 'private-channel'); + $this->assertNotContains( + 'private-channel', + \BlaxSoftware\LaravelWebSockets\Services\WebsocketService::getActiveChannels() + ); } public function test_connect_to_private_channel_with_valid_signature() diff --git a/tests/TestCase.php b/tests/TestCase.php index 91a77d8..00f183a 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -457,6 +457,60 @@ abstract class TestCase extends Orchestra return $connection; } + /** + * Assert that the subscribe to $channelName on the frame just handled was + * refused: an `:error` reply (Invalid Signature, 4009) instead of + * Success, the socket is not on the channel, the handler does not track it + * and the ws_channel_connections_* cache does not list it. + */ + protected function assertSubscriptionRefused( + Mocks\Connection $connection, + string $channelName, + string $event = 'websocket.subscribe' + ): void { + $connection->assertNotSentEvent('websocket_internal.subscription_succeeded'); + $connection->assertNotSentEvent($event . ':response'); + + $error = collect($connection->sentData)->firstWhere('event', $event . ':error'); + $this->assertNotNull($error, "Expected a {$event}:error reply"); + $this->assertSame('Invalid Signature', $error['data']['message']); + $this->assertSame(4009, $error['data']['code']); + + $channel = $this->channelManager->find('1234', $channelName); + $this->assertFalse((bool) $channel?->hasConnection($connection), 'Socket must not be on the channel'); + + $tracked = $this->handlerChannelConnections(); + $this->assertArrayNotHasKey( + $connection->socketId, + $tracked[$channelName] ?? [], + 'Handler must not track the socket in $channel_connections' + ); + + $this->flushHandlerCacheBuffer(); + $this->assertNotContains( + $connection->socketId, + \BlaxSoftware\LaravelWebSockets\Services\WebsocketService::getChannelConnections($channelName), + 'Cache must not list the socket on the channel' + ); + } + + /** + * The handler's in-memory [channel => [socket_id => true]] tracking. + */ + protected function handlerChannelConnections(): array + { + return (fn () => $this->channel_connections)->call($this->wsHandler); + } + + /** + * Write the handler's buffered tracking cache writes now instead of on the + * next loop tick. + */ + protected function flushHandlerCacheBuffer(): void + { + (fn () => $this->flushCacheBuffer())->call($this->wsHandler); + } + /** * Get the subscribed client for the replication. *