diff --git a/src/Server/WebSocketHandler.php b/src/Server/WebSocketHandler.php index fa9412f..3e5b28a 100644 --- a/src/Server/WebSocketHandler.php +++ b/src/Server/WebSocketHandler.php @@ -122,12 +122,17 @@ class WebSocketHandler implements MessageComponentInterface return; } - // Client events (whisper) — must start with "client-" + // Client events (whisper) — must start with "client-". Only a + // subscribed member of the channel may send them. if (Str::startsWith($event, 'client-')) { + if (! $connection->app->clientMessagesEnabled) { + return; + } + $channel = $payload->channel ?? ($payload->data->channel ?? null); - if ($channel) { + if (is_string($channel) && $channel !== '') { $ch = $this->channelManager->find($connection->app->id, $channel); - if ($ch) { + if ($ch && $ch->hasConnection($connection)) { $ch->broadcastToEveryoneExcept( $payload, $connection->socketId, diff --git a/src/Websocket/Handler.php b/src/Websocket/Handler.php index c94d21f..3b755e8 100644 --- a/src/Websocket/Handler.php +++ b/src/Websocket/Handler.php @@ -218,8 +218,11 @@ class Handler implements MessageComponentInterface // Decode message (we already have payload string) $messageArray = json_decode($payload, true, 512, JSON_THROW_ON_ERROR); - // Handle protocol messages (client-* broadcasts) - $this->handleProtocolMessage($message, $connection, $messageArray); + // Client events (client-*) are relayed or refused here and never + // reach a controller. + if ($this->handleProtocolMessage($message, $connection, $messageArray)) { + return; + } unset($this->rejectedSubscriptions[$connection->socketId]); @@ -268,34 +271,58 @@ class Handler implements MessageComponentInterface /** * Handle pusher protocol messages (formerly in PusherMessageFactory) * Inlined for performance - avoids object creation + * + * Returns true when the frame was a client event and is done with: + * relayed to the other members, or refused with an `:error` frame. */ private function handleProtocolMessage( MessageInterface $message, ConnectionInterface $connection, array $messageArray - ): void { + ): bool { $event = $messageArray['event'] ?? ''; // Check for client- broadcast messages - if (strpos($event, 'client-') === 0) { - if (!$connection->app->clientMessagesEnabled) { - return; - } - - $channelName = $messageArray['channel'] ?? null; - if (!$channelName) { - return; - } - - $channel = $this->channelManager->find($connection->app->id, $channelName); - if ($channel) { - $channel->broadcastToEveryoneExcept( - (object) $messageArray, - $connection->socketId, - $connection->app->id - ); - } + if (!is_string($event) || strpos($event, 'client-') !== 0) { + return false; } + + if (!$connection->app->clientMessagesEnabled) { + return false; + } + + $channelName = $messageArray['channel'] ?? null; + if (!$channelName || !is_string($channelName)) { + return false; + } + + // Only a subscribed member may send client events to a channel. + // Otherwise any socket, even one whose private or presence subscribe + // was refused, could push frames to every member. A tracked socket + // counts as subscribed (see shouldRejectMessage()). + $channel = $this->channelManager->find($connection->app->id, $channelName); + $isMember = $channel?->hasConnection($connection) + || isset($this->channel_connections[$channelName][$connection->socketId]); + + if (!$channel || !$isMember) { + $connection->send(json_encode([ + 'event' => $event . ':error', + 'data' => [ + 'message' => 'Subscription not established', + ], + 'channel' => $channelName, + ])); + + return true; + } + + $channel->broadcastToEveryoneExcept( + (object) $messageArray, + $connection->socketId, + $connection->app->id + ); + + return true; } public function onOpen(ConnectionInterface $connection): void diff --git a/tests/HandlerLifecycleTest.php b/tests/HandlerLifecycleTest.php index e86817e..a0ca444 100644 --- a/tests/HandlerLifecycleTest.php +++ b/tests/HandlerLifecycleTest.php @@ -491,6 +491,97 @@ class HandlerLifecycleTest extends TestCase $connection->assertSentEvent('app.someAction:error'); } + // ========================================================================= + // Client events (client-*) + // ========================================================================= + + /** + * @dataProvider clientEventChannels + */ + public function test_non_member_cannot_send_client_events(string $channelName, bool $refusedFirst) + { + $this->app['config']->set('websockets.apps.0.enable_client_messages', true); + + $member = $this->joinChannel($channelName); + + $intruder = $this->newConnection(); + $this->wsHandler->onOpen($intruder); + + if ($refusedFirst) { + $this->wsHandler->onMessage($intruder, new Mocks\Message([ + 'event' => 'websocket.subscribe', + 'data' => ['auth' => 'TestKey:invalid-signature', 'channel' => $channelName], + ])); + $this->assertSubscriptionRefused($intruder, $channelName); + } + + $member->resetEvents(); + $intruder->resetEvents(); + + $this->wsHandler->onMessage($intruder, new Mocks\Message([ + 'event' => 'client-forged', + 'data' => ['text' => 'from outside'], + 'channel' => $channelName, + ])); + + $member->assertNotSentEvent('client-forged'); + + // One reply, the refusal; the frame goes no further. + $this->assertCount(1, $intruder->sentData); + $this->assertSame('client-forged:error', $intruder->sentData[0]['event']); + $this->assertSame('Subscription not established', $intruder->sentData[0]['data']['message']); + $this->assertFalse($this->channelManager->find('1234', $channelName)->hasConnection($intruder)); + } + + /** + * @dataProvider clientEventChannels + */ + public function test_member_client_events_reach_the_other_members(string $channelName) + { + $this->app['config']->set('websockets.apps.0.enable_client_messages', true); + + $sender = $this->joinChannel($channelName); + $receiver = $this->joinChannel($channelName); + $sender->resetEvents(); + $receiver->resetEvents(); + + $this->wsHandler->onMessage($sender, new Mocks\Message([ + 'event' => 'client-typing', + 'data' => ['text' => 'hi'], + 'channel' => $channelName, + ])); + + $receiver->assertSentEvent('client-typing', ['data' => ['text' => 'hi'], 'channel' => $channelName]); + $sender->assertNotSentEvent('client-typing'); + $sender->assertNotSentEvent('client-typing:error'); + } + + public static function clientEventChannels(): array + { + return [ + 'public' => ['public-channel', false], + 'private' => ['private-test', true], + 'private-encrypted' => ['private-encrypted-test', true], + 'presence' => ['presence-test', true], + ]; + } + + private function joinChannel(string $channelName): Mocks\Connection + { + if (str_starts_with($channelName, 'presence-')) { + return $this->newPresenceConnection($channelName, [ + 'user_id' => random_int(1, 1000000), + 'user_info' => ['name' => 'Rick'], + ]); + } + + if (str_starts_with($channelName, 'private-')) { + return $this->newPrivateConnection($channelName); + } + + return $this->newActiveConnection([$channelName]); + } + // ========================================================================= // Presence channel subscribe/unsubscribe // =========================================================================