BF close connections with an unknown app key

verifyAppKey() tested the promise from App::findByKey() for truthiness. A
promise object is always truthy, so UnknownAppKey was never thrown and the
then() callback set $connection->app to null. verifyOrigin() then failed
reading a property of null, an ErrorException the onOpen catch did not
cover. The client kept a 101-upgraded socket with no app, got no 4001
frame, was never registered with the channel manager, and onClose later
dereferenced the missing app.

- verifyAppKey() awaits the lookup (React\Async\await; ConfigAppManager
  resolves at once) and throws UnknownAppKey for a null result.
- onOpen catches WebSocketException (UnknownAppKey 4001, OriginNotAllowed
  4009), sends its websocket.error payload and closes the connection.
- onClose returns early for a connection without an app or socket id.

test_cannot_connect_with_a_wrong_app_key now also waits for the server to
close the socket; new unit tests cover the 4001 and 4009 refusals with
the mock connection.

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

View File

@ -28,6 +28,8 @@ use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface;
use Ratchet\WebSocket\MessageComponentInterface;
use function React\Async\await;
class Handler implements MessageComponentInterface
{
/**
@ -299,12 +301,18 @@ class Handler implements MessageComponentInterface
$this->generateSocketId($connection);
$this->establishConnection($connection);
$this->initializeAppConnection($connection);
} catch (UnknownAppKey $e) {
} catch (ExceptionsWebSocketException $e) {
// Unknown app key (4001) or disallowed origin (4009): tell the
// client why and drop the socket. It never joined the app, so it
// must not stay open half set up.
Log::channel('websocket')->error('Root level error: ' . $e->getMessage(), [
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTraceAsString(),
]);
$connection->send(json_encode($e->getPayload()));
$connection->close();
}
}
@ -313,6 +321,13 @@ class Handler implements MessageComponentInterface
*/
public function onClose(ConnectionInterface $connection): void
{
// A connection refused in onOpen (unknown app key, disallowed origin,
// no new connections accepted) has no app or socket id and joined
// nothing, so there is nothing to clean up.
if (!isset($connection->app, $connection->socketId)) {
return;
}
unset($this->rejectedSubscriptions[$connection->socketId]);
$this->authenticateConnection($connection, null);
@ -1276,13 +1291,13 @@ class Handler implements MessageComponentInterface
$appKey = $query->get('appKey');
if (! $app = App::findByKey($appKey)) {
// findByKey() returns a promise, and a promise object is always truthy:
// wait for the App it resolves to (ConfigAppManager resolves at once).
if (! $app = await(App::findByKey($appKey))) {
throw new UnknownAppKey($appKey);
}
$app->then(function ($app) use ($connection) {
$connection->app = $app;
});
return $this;
}

View File

@ -15,8 +15,75 @@ class ConnectionTest extends TestCase
$this->skipIfServerUnavailable();
$this->startServer();
$response = $this->await($this->joinWebSocketServer(['public-channel'], 'NonWorkingKey'));
$this->assertSame('{"event":"websocket.error","data":{"message":"Could not find app key `NonWorkingKey`.","code":4001}}', (string) $response);
$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.
$this->await($closed->promise());
$this->assertSame(
['{"event":"websocket.error","data":{"message":"Could not find app key `NonWorkingKey`.","code":4001}}'],
$messages
);
}
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->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->wsHandler->onClose($connection);
}
/**