diff --git a/src/Appwrite/Messaging/Adapter/Realtime.php b/src/Appwrite/Messaging/Adapter/Realtime.php index 91697be18a..9cf5866d80 100644 --- a/src/Appwrite/Messaging/Adapter/Realtime.php +++ b/src/Appwrite/Messaging/Adapter/Realtime.php @@ -16,6 +16,11 @@ class Realtime extends MessagingAdapter { public const SUPPORTED_ACTIONS = ['create', 'update', 'upsert', 'delete']; + // The database family is published under several event prefixes (legacy `databases` + // plus the per-type projections). They share the same `databases...…` + // shape, so the tail normalizes them to `databases` for consistent metadata + filtering. + public const DATABASE_EVENT_PREFIXES = ['databases', 'tablesdb', 'documentsdb', 'vectorsdb']; + // Resources whose channels receive an action-suffixed sibling at publish time. // The suffix loop in fromPayload() treats any channel whose last OR second-to-last // segment matches an entry here as a candidate for `.{action}` suffixing. @@ -513,6 +518,12 @@ class Realtime extends MessagingAdapter $count = \count($parts); $type = $parts[0] ?? null; + // The database family is published under several prefixes (databases/tablesdb/ + // documentsdb/vectorsdb). `type` keeps the actual prefix (more informative), but + // scope ids are extracted for all of them so databaseId/collectionId filters work + // across the whole family. + $isDatabaseFamily = \in_array($type, self::DATABASE_EVENT_PREFIXES, true); + $action = null; if ($count >= 1 && \in_array($parts[$count - 1], self::SUPPORTED_ACTIONS, true)) { $action = $parts[$count - 1]; @@ -541,30 +552,31 @@ class Realtime extends MessagingAdapter // name encodes the id at every level — parts[1] is the top-level resource id and // parts[3] the collection/table id. $scope = []; - switch ($type) { - case 'databases': - if (isset($parts[1])) { - $scope['databaseId'] = $parts[1]; - } - if (isset($parts[2], $parts[3]) && \in_array($parts[2], ['collections', 'tables'], true)) { - $scope['collectionId'] = $parts[3]; - } - break; - case 'buckets': - if (isset($parts[1])) { - $scope['bucketId'] = $parts[1]; - } - break; - case 'functions': - if (isset($parts[1])) { - $scope['functionId'] = $parts[1]; - } - break; - case 'teams': - if (isset($parts[1])) { - $scope['teamId'] = $parts[1]; - } - break; + if ($isDatabaseFamily) { + if (isset($parts[1])) { + $scope['databaseId'] = $parts[1]; + } + if (isset($parts[2], $parts[3]) && \in_array($parts[2], ['collections', 'tables'], true)) { + $scope['collectionId'] = $parts[3]; + } + } else { + switch ($type) { + case 'buckets': + if (isset($parts[1])) { + $scope['bucketId'] = $parts[1]; + } + break; + case 'functions': + if (isset($parts[1])) { + $scope['functionId'] = $parts[1]; + } + break; + case 'teams': + if (isset($parts[1])) { + $scope['teamId'] = $parts[1]; + } + break; + } } foreach ($scope as $key => $value) { diff --git a/src/Appwrite/Realtime/Message/Handlers/Subscribe.php b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php index b421aeb424..bb8177cc63 100644 --- a/src/Appwrite/Realtime/Message/Handlers/Subscribe.php +++ b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php @@ -92,9 +92,31 @@ class Subscribe extends Action continue; } - $project = $dbForConsole->getAuthorization()->skip( - fn () => $dbForConsole->getDocument('projects', $targetProjectId) - ); + // Tail channels are console-only. A normal project websocket (even for a + // team member) must not tail — that would expose compact metadata for + // resources the user could not read through the project API. Only a + // connection to the `console` project may register a tail. + if ($projectId !== 'console') { + throw new Exception( + Exception::REALTIME_POLICY_VIOLATION, + 'Console live tail is only available on the console connection.' + ); + } + + // Resolve ownership fresh (projects can move between teams). Treat any + // lookup failure (missing/invalid project) as a policy violation so the + // connection is closed with 1008, consistent with an unauthorized tail — + // rather than leaking a raw not-found error and staying open. + try { + $project = $dbForConsole->getAuthorization()->skip( + fn () => $dbForConsole->getDocument('projects', $targetProjectId) + ); + } catch (\Throwable) { + throw new Exception( + Exception::REALTIME_POLICY_VIOLATION, + 'Not authorized to tail project "' . $targetProjectId . '".' + ); + } $teamId = (string) $project->getAttribute('teamId', ''); if ($teamId === '' || !\in_array(Role::team($teamId)->toString(), $roles, true)) { diff --git a/tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php b/tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php index c7841ebf16..c0c47cf668 100644 --- a/tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php +++ b/tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php @@ -1026,14 +1026,14 @@ final class RealtimeCustomClientQueryTestWithMessage extends Scope $response = \json_decode($client->receive(), true); $this->assertEquals('error', $response['type'] ?? null); $this->assertEquals(1008, $response['data']['code'] ?? null); - } catch (ConnectionException $e) { + } catch (ConnectionException) { $this->addToAssertionCount(1); } // close() can itself throw on an already-closed socket — best effort. try { $client->close(); - } catch (ConnectionException $e) { + } catch (ConnectionException) { // already closed by the server } } @@ -1109,4 +1109,47 @@ final class RealtimeCustomClientQueryTestWithMessage extends Scope $client->close(); } + + public function testProjectConnectionCannotTail(): void + { + // A normal project websocket (not the console project) must not be able to tail, + // even for a team member — only the console connection may. Expect a 1008 reject. + $user = $this->getUser(); + $session = $user['session'] ?? ''; + $projectId = $this->getProject()['$id']; + + $queryString = \http_build_query(['project' => $projectId]); // NOT console + $client = new WebSocketClient( + 'ws://appwrite.test/v1/realtime?' . $queryString, + [ + 'headers' => [ + 'origin' => 'http://localhost', + 'cookie' => 'a_session_' . $projectId . '=' . $session, + ], + 'timeout' => 10, + ] + ); + + $connected = \json_decode($client->receive(), true); + $this->assertEquals('connected', $connected['type'] ?? null); + + $client->send(\json_encode([ + 'type' => 'subscribe', + 'data' => [['channels' => ['console.tail.' . $projectId], 'subscriptionId' => 'tail-proj']], + ])); + + try { + $response = \json_decode($client->receive(), true); + $this->assertEquals('error', $response['type'] ?? null); + $this->assertEquals(1008, $response['data']['code'] ?? null); + } catch (ConnectionException) { + $this->addToAssertionCount(1); + } + + try { + $client->close(); + } catch (ConnectionException) { + // already closed by the server + } + } } diff --git a/tests/unit/Realtime/EventTailRegistryTest.php b/tests/unit/Realtime/EventTailRegistryTest.php index 97d23b5f5f..6d3da66ba0 100644 --- a/tests/unit/Realtime/EventTailRegistryTest.php +++ b/tests/unit/Realtime/EventTailRegistryTest.php @@ -167,6 +167,33 @@ final class EventTailRegistryTest extends TestCase $this->assertSame('t1', $meta['collectionId']); } + public function testTailMetadataExtractsScopeForAllDatabasePrefixes(): void + { + // The database family is published under several prefixes. `type` keeps the + // actual prefix, and databaseId/collectionId are extracted for every one of them + // (so scope filters work across the whole family regardless of the variant). + foreach (['databases', 'tablesdb', 'documentsdb', 'vectorsdb'] as $prefix) { + $meta = Realtime::toTailMetadata([ + 'userId' => 'u1', + 'data' => [ + 'events' => ["{$prefix}.main.collections.posts.documents.p1.create"], + 'payload' => ['$id' => 'p1'], + ], + ]); + $this->assertSame($prefix, $meta['type'], 'type preserves the actual prefix'); + $this->assertSame('main', $meta['databaseId']); + $this->assertSame('posts', $meta['collectionId']); + } + + // `tables` sub-resource under a projected prefix still maps to collectionId. + $rows = Realtime::toTailMetadata([ + 'data' => ['events' => ['tablesdb.main.tables.t1.rows.r1.create'], 'payload' => ['$id' => 'r1']], + ]); + $this->assertSame('tablesdb', $rows['type']); + $this->assertSame('main', $rows['databaseId']); + $this->assertSame('t1', $rows['collectionId']); + } + public function testTailMetadataAttributeTrailingAction(): void { // `users.U.update.email` — action is the second-to-last segment.