BF reject private/presence subscribe with invalid signature

handleSubscription() recorded the socket in $channel_connections and in the
buffered ws_channel_connections_* / ws_active_channels cache before
$channel->subscribe() ran, and swallowed the InvalidSignature it threw. On
the same frame shouldRejectMessage() found the entry and called
saveConnection(), and the client got "websocket.subscribe:response Success".
One subscribe with a bad signature put the socket on the private or presence
channel, where it received broadcasts, and WebsocketService listed it.

- Track the socket only after subscribe() succeeds (or it is already on the
  channel).
- A failed private/presence subscribe answers "<event>:error" with the
  exception's message and code (Invalid Signature, 4009), drops any earlier
  tracking of the socket on that channel, takes it off the channel if the
  subscribe had already saved it, and ends the frame before
  shouldRejectMessage() and the Success reply.
- Public channels behave as before.

Tests assert, after the single subscribe frame, the error reply, no channel
membership, no $channel_connections entry and no cache listing, and that a
later message on the channel does not resubscribe the socket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-11-04 11:56:38 +01:00
parent d61150b126
commit b066d75b33
5 changed files with 308 additions and 48 deletions

View File

@ -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) {

View File

@ -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');
}
// =========================================================================

View File

@ -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()

View File

@ -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()

View File

@ -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 `<event>: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.
*