From 9ead3a65ecd845e8efea74d828ca92424ec517f5 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Sun, 7 Jun 2026 12:36:44 +0530 Subject: [PATCH] feat: enhance Realtime event handling with improved scope extraction and authorization for subscriptions --- src/Appwrite/Messaging/Adapter/Realtime.php | 46 ++++++++++++----- .../Realtime/Message/Handlers/Subscribe.php | 49 ++++++++++--------- tests/unit/Realtime/EventTailRegistryTest.php | 40 +++++++++++++-- 3 files changed, 97 insertions(+), 38 deletions(-) diff --git a/src/Appwrite/Messaging/Adapter/Realtime.php b/src/Appwrite/Messaging/Adapter/Realtime.php index f7602f8c9d..91697be18a 100644 --- a/src/Appwrite/Messaging/Adapter/Realtime.php +++ b/src/Appwrite/Messaging/Adapter/Realtime.php @@ -534,20 +534,42 @@ class Realtime extends MessagingAdapter 'resourceId' => $payload['$id'] ?? null, ]; - // Attach only the scope ids that belong to this resource type. - $scope = match ($type) { - 'databases' => [ - 'databaseId' => $payload['$databaseId'] ?? null, - 'collectionId' => $payload['$collectionId'] ?? $payload['$tableId'] ?? null, - ], - 'buckets' => ['bucketId' => $payload['bucketId'] ?? null], - 'functions' => ['functionId' => $payload['functionId'] ?? null], - 'teams' => ['teamId' => $payload['teamId'] ?? null], - default => [], - }; + // Attach only the scope ids that belong to this resource type. Derived from the + // (concrete) event name rather than the payload: for a top-level resource event + // (e.g. `teams.T.create`) the payload's id lives at $id, not at a teamId field, + // so a payload lookup would drop the scope and silently break filters. The event + // 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; + } foreach ($scope as $key => $value) { - if ($value !== null) { + // Skip wildcard/empty segments (defensive: events[0] is concrete, but guard anyway). + if ($value !== '' && $value !== '*') { $metadata[$key] = $value; } } diff --git a/src/Appwrite/Realtime/Message/Handlers/Subscribe.php b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php index 158277bbb4..b421aeb424 100644 --- a/src/Appwrite/Realtime/Message/Handlers/Subscribe.php +++ b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php @@ -76,26 +76,14 @@ class Subscribe extends Action ]; } - foreach ($parsedPayloads as $parsedPayload) { - $realtime->subscribe( - $projectId, - $connectionId, - $parsedPayload['subscriptionId'], - $roles, - $parsedPayload['convertedChannels'], - $parsedPayload['queries'], - ); - } - - // Console live event tail: any `console.tail.` channel is authorized by - // team membership of the target project's owning team, then registered with its - // compiled filter so the worker's pub/sub loop can filter+sample before delivery. - // - // Registration is additive, mirroring Realtime::subscribe(): a reused subscription - // id accumulates channels (it never drops the ones already subscribed), and the - // registry is keyed by (connId, subId, projectId) so re-subscribing the same - // channel overwrites its filter in place rather than leaving a stale entry. + // Console live event tail: authorize every `console.tail.` channel + // FIRST — before any subscription state is mutated — so a batch mixing authorized + // and unauthorized tails can't leave partial state behind. Each tail is authorized + // by team membership of the target project's owning team, with ownership resolved + // fresh (projects can be transferred between teams, so a cached teamId could + // authorize the wrong team). $now = \microtime(true); + $pendingTails = []; foreach ($parsedPayloads as $parsedPayload) { $compiled = null; foreach ($parsedPayload['convertedChannels'] as $channel) { @@ -104,8 +92,6 @@ class Subscribe extends Action continue; } - // Resolve ownership fresh on every subscribe — projects can be transferred - // between teams, so a cached teamId could authorize the wrong team. $project = $dbForConsole->getAuthorization()->skip( fn () => $dbForConsole->getDocument('projects', $targetProjectId) ); @@ -119,10 +105,29 @@ class Subscribe extends Action } $compiled ??= RuntimeQuery::compile($parsedPayload['queries']); - $eventTailRegistry->add($connectionId, $parsedPayload['subscriptionId'], $targetProjectId, $compiled, $now); + $pendingTails[] = [$parsedPayload['subscriptionId'], $targetProjectId, $compiled]; } } + foreach ($parsedPayloads as $parsedPayload) { + $realtime->subscribe( + $projectId, + $connectionId, + $parsedPayload['subscriptionId'], + $roles, + $parsedPayload['convertedChannels'], + $parsedPayload['queries'], + ); + } + + // All tail channels passed authorization above — register them additively. The + // registry is keyed by (connId, subId, projectId): re-subscribing the same channel + // overwrites its filter in place, while a reused subscription id that names a new + // tail channel keeps the ones already registered (mirrors the tree). + foreach ($pendingTails as [$subId, $targetProjectId, $compiled]) { + $eventTailRegistry->add($connectionId, $subId, $targetProjectId, $compiled, $now); + } + $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connectionId)); $subscriptionDelta = $subscriptionsAfter - $subscriptionsBefore; $subscriptionsRequested = \count($parsedPayloads); diff --git a/tests/unit/Realtime/EventTailRegistryTest.php b/tests/unit/Realtime/EventTailRegistryTest.php index e806e148cc..97d23b5f5f 100644 --- a/tests/unit/Realtime/EventTailRegistryTest.php +++ b/tests/unit/Realtime/EventTailRegistryTest.php @@ -53,7 +53,7 @@ final class EventTailRegistryTest extends TestCase return $server; } - /** @param array $payload */ + /** @param array $queries */ private function compile(array $queries): array { return RuntimeQuery::compile($queries); @@ -114,11 +114,43 @@ final class EventTailRegistryTest extends TestCase $this->assertArrayNotHasKey('functionId', $file); $this->assertArrayNotHasKey('collectionId', $file); - // A null scope id is omitted rather than emitted. - $fnNoScope = Realtime::toTailMetadata([ + // Scope comes from the event name, so it's present even when the payload (here an + // execution doc) carries no functionId field — resourceId is the leaf ($id). + $exec = Realtime::toTailMetadata([ 'data' => ['events' => ['functions.fn1.executions.e1.create'], 'payload' => ['$id' => 'e1']], ]); - $this->assertArrayNotHasKey('functionId', $fnNoScope); + $this->assertSame('fn1', $exec['functionId']); + $this->assertSame('e1', $exec['resourceId']); + } + + public function testTailMetadataTopLevelResourceEventsCarryScope(): void + { + // Top-level resource events: the payload is the resource doc itself (id at $id, + // not at a teamId/bucketId/functionId field). Scope must still be present so a + // filter like equal('teamId', ['T']) matches the team's own create/update events. + $teamCreate = Realtime::toTailMetadata([ + 'data' => ['events' => ['teams.T.create'], 'payload' => ['$id' => 'T', 'name' => 'Acme']], + ]); + $this->assertSame('teams', $teamCreate['type']); + $this->assertSame('T', $teamCreate['teamId']); + $this->assertSame('T', $teamCreate['resourceId']); + + // Nested membership event: same teamId scope, leaf resourceId is the membership. + $membership = Realtime::toTailMetadata([ + 'data' => ['events' => ['teams.T.memberships.M.create'], 'payload' => ['$id' => 'M', 'teamId' => 'T']], + ]); + $this->assertSame('T', $membership['teamId']); + $this->assertSame('M', $membership['resourceId']); + + $bucketCreate = Realtime::toTailMetadata([ + 'data' => ['events' => ['buckets.B.create'], 'payload' => ['$id' => 'B']], + ]); + $this->assertSame('B', $bucketCreate['bucketId']); + + $functionCreate = Realtime::toTailMetadata([ + 'data' => ['events' => ['functions.F.create'], 'payload' => ['$id' => 'F']], + ]); + $this->assertSame('F', $functionCreate['functionId']); } public function testTailMetadataTablesUsesTableIdAsCollection(): void