Repository navigation
fix(mqtt): gate topic subscription on the subscriber list - #14460
Conversation
MQTT subscription was open: any authenticated project user could SUBSCRIBE to any ordinary topic name (or an ordinary wildcard) and receive every message delivered to it, regardless of the topic's subscriber list. The subscriber list and subscribe permission only gated createSubscriber and the email/SMS/FCM/APNS fan-out, never the MQTT receive path, so a user who knew a topic name could read a topic they were never added to. onSubscribe now grants an ordinary topic only when the connection's user is entered as a subscriber of it (the same membership createSubscriber writes), refuses ordinary wildcards (they cannot be matched against one topic's list) and unknown names. The reserved users/<id> namespace is unchanged: it stays owner-gated and needs no membership, so per-user pushes are unaffected. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…cription The subscribe gate only takes effect at the next SUBSCRIBE, so a user already connected and subscribed kept receiving a topic after being removed from it. deleteSubscriber now releases a control event on the mqtt pub/sub channel, mirroring the user block/delete revoke path: every broker worker drops that user's live subscription to the topic, leaving the connection and its other subscriptions open. The event fires only once the user holds no remaining subscriber row for the topic, matching the per-user subscribe gate. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Review complete. 🟡 1 medium 💬 Inline comments (1)
🧹 Nitpicks (1) — 🟢 1 low
This PR gates MQTT SUBSCRIBE packets against subscriber rows in the project DB, denies unknown topics and wildcard filters with reason code 0x80, and makes the messaging subscriber-delete endpoint fire a broker-side unsubscribe when the user's last subscriber row for a topic is removed.
Reviewed commit: dab811f |
🟡 Tier B · Needs changes before merging
Ordinary MQTT subscriptions now require topic subscriber membership, while owned Latest changes: The newest commits reject a topic row whose ID collides with an owned
Fix with agent prompt### Issue 1
src/Appwrite/Messaging/Adapter/Push/Appwrite.php:79
**Preserve the existing MQTT topic-name contract**
This now publishes ordinary campaigns on the topic ID, while the matching subscribe lookup also expects IDs; the existing behavior used `topics.name`, which commonly differs from `$id`. Existing MQTT clients subscribing to topic names will be denied or stop receiving pushes after upgrading; retain the wire name or provide compatibility for existing subscriptions.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.📂 Walkthrough · 14
⏳ Still open from earlier reviews · 1
Reviewed the commits since |
Security rulesNo new WARNING or ERROR findings from security rules. 19 existing findings tracked in
|
There was a problem hiding this comment.
Adds per-user MQTT subscribe authorization with server-initiated unsubscribe for revoked subscribers, wildcard-subscribe refusal, and new unit/e2e coverage.
Key findings
- 🟡 Late async unsubscribe kills a re-created subscription — Handler.php:420
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
The 'mqtt' pub/sub callback inlined the revoke, unsubscribe and deliver logic in one growing closure. Pull each into a named per-action handler ($onRevoke, $onUnsubscribe, $onDeliver) and reduce the callback to a match that dispatches on the event action. Behaviour is unchanged; span init/ finish and the coroutine orchestration stay in the entrypoint, since Handler only Span::add()s. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address review on the subscribe gate: - onSubscribe resolved membership with a findOne per exact filter; a large SUBSCRIBE packet could fan out into many sequential queries. Resolve the whole packet's membership in one paged query keyed on the topic ids (subscribedTopics), paging only to cover a user holding several targets on one topic, and look each filter up in the resulting set. - The unsubscribe control event is applied asynchronously and unordered against the subscriber table, so a late event could drop a subscription the user had re-created. Handler::unsubscribe now re-checks membership and skips the drop when the user is a subscriber of the topic again. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Follow-up to review on the subscriber-list gate: - onSubscribe yields on the replay query between the membership check and the grant being recorded, so a concurrent removal could no-op before the filter exists and leave a stale subscription. Decide grants first, replay, then re-verify the granted ordinary topics and demote any whose membership vanished, emitting the SUBACK last so a demoted grant is never recorded. - Handler::unsubscribe now fails closed: if the membership re-check throws (database error), the subscription is still dropped rather than left in place for a removed user. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
The logical clock that lets admit() detect a revoke landing during a yielding authenticate was three bare fields and inline bookkeeping. Move it into a Clock (start/stop/set/isDrifted) so a second in-flight race can reuse it. Behaviour-preserving; covered by RevokeTest and the new ClockTest. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The post-replay re-check already demotes a grant whose membership vanished so no live subscription is recorded, but the backlog is published to the connection before it runs. A deleteSubscriber committing while the ledger query yields could still hand a removed user the topic's history. onSubscribe reads the access clock before replay; unsubscribe sets it on the drop path. replayBacklog, after the ledger query, withholds an ordinary topic's backlog when the clock drifted and a fresh membership check fails, leaving the cursor so it replays once membership returns. The clock gates the recheck, so the common no-removal path adds no query. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ally Gating the pre-publish recheck on the access clock left a hole: deleteSubscriber commits the row deletion before it publishes the unsubscribe control event, and that event only stamps the clock once the broker consumes it over pub/sub. If the ledger query resumes in between, isDrifted() is false, the recheck is skipped and the backlog is handed to a user whose row is already gone. The subscriber row is the source of truth and commits independently of the event, so read it directly: replayBacklog re-verifies membership for every ordinary topic after the ledger query and before delivering, with no clock gate. The clock stays on the CONNECT path (admit), where the event's later disconnect is the backstop. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The broker resolved a subscribe filter against topics.name, which has no index, scanning the collection on every SUBSCRIBE; it also resolved reserved users/<id> by name even though the producer provisions and addresses them by md5 id. The two sides disagreed and the hot path was unindexed. Make the wire topic the id everywhere. An ordinary filter is the topic id; a reserved users/<id> maps to its md5 id (topicId()), the same the producer uses. The gate, unsubscribe and topicSequence resolve via the $id primary key, the producer fans out on the caller's id (dropping the id->name hop), and deleteSubscriber revokes by id. No name queries remain, so no index or migration is needed. Topic name is now a display label. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
| [], | ||
| [], | ||
| [$name], | ||
| [$to], |
There was a problem hiding this comment.
Preserve the existing MQTT topic-name contract
This now publishes ordinary campaigns on the topic ID, while the matching subscribe lookup also expects IDs; the existing behavior used topics.name, which commonly differs from $id. Existing MQTT clients subscribing to topic names will be denied or stop receiving pushes after upgrading; retain the wire name or provide compatibility for existing subscriptions.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Messaging/Adapter/Push/Appwrite.php
Line: 79
Comment:
**Preserve the existing MQTT topic-name contract**
This now publishes ordinary campaigns on the topic ID, while the matching subscribe lookup also expects IDs; the existing behavior used `topics.name`, which commonly differs from `$id`. Existing MQTT clients subscribing to topic names will be denied or stop receiving pushes after upgrading; retain the wire name or provide compatibility for existing subscriptions.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟠 Major · bug · Reply if this doesn't apply.
There was a problem hiding this comment.
Not applicable: the MQTT (appwrite) push provider is unreleased — it's absent from every server release tag through 2.5.0, so there are no existing clients subscribing by name. This defines the wire contract rather than breaking one. Ordinary topics are now addressed by $id (the primary key), which removes the unindexed topics.name scan the gate ran on every SUBSCRIBE and aligns the broker with the producer, which already addressed reserved users/<id> topics by their md5 id. name remains a display label.
There was a problem hiding this comment.
I checked the release tags: the provider is not absent from every tag through 2.5.0. The Appwrite push adapter, MQTT handler and entrypoint, and MQTT e2e test are present in 2.3.0, 2.4.0, and 2.5.0.
This PR publishes on $to (adapter) and resolves ordinary subscriptions by topic ID (handler). Topic IDs and names are distinct fields (topic creation), so a client using a topic’s name rather than its ID will no longer match the subscription lookup. The finding remains open; please preserve compatibility with the released name-based behavior or provide a migration path.
Resolving users/<id> by md5 id let an ordinary topic hand-crafted with that id (createTopic accepts a custom topicId) be served to the user-topic owner through the ownership-gated path, leaking its backlog without subscriber membership. The gate now verifies the resolved row's name matches the reserved filter before using it, mirroring the producer's createUserTopic collision guard; a mismatch is treated as an unprovisioned topic (granted, no backlog). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Brings in the 23 commits main gained since the last sync: the MQTT subscribe gate that refuses a user topic whose row name is not the reserved filter and addresses topics by id so lookups hit the primary key (#14460), the console preview SDK flow (#14441) and the SDK docs audit (#14482). MqttServerTest conflicted where the branch had added the reconnect regression tests (blocked user, deleted session) next to main's rewrite of the subscription tests. Both are kept: the branch's reconnect tests, then main's membership-gated subscription tests addressed by topic id. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The security issue: MQTT topic subscription was open
Delivery on the Appwrite (MQTT) push channel is pure pub/sub by topic name. The messaging worker publishes a campaign onto the topic's name, and the broker fans it out to every connection subscribed to that name (
src/Appwrite/Mqtt/Handler.php::deliver). The subscribe path placed no per-topic authorization on ordinary topics:onSubscribegranted any non-users/filter — any exact name, and ordinary wildcards likescores/#— to any authenticated, non-blocked project user.subscribepermission and itssubscriberslist gated onlycreateSubscriber(the HTTP endpoint) and the email/SMS/FCM/APNS fan-out. They never gated the MQTT receive path.So the subscriber list behaved as a recipient ACL for four channels and silently did nothing for MQTT. A developer who used topics as a managed recipient list (as the dashboard presents them) got a cross-user read: any authenticated user who knew — or guessed — a topic name could subscribe and receive every message on it, even if they were never added to the topic. Topic names are developer-chosen and listed through the REST topics/subscribers APIs, so they are not a secret; a wildcard such as
scores/#could harvest many topics at once.Scope: this is an insider read within a single project (auth is required and project-bound) — not anonymous or cross-project. The only part already protected was the reserved
users/<id>namespace, which is owner-gated at subscribe and delivery.This was consistent with how the broker was written (there was even a test asserting the topic's roles were ignored), so it was an intended-but-undocumented design with a sharp, broken-access-control edge — this PR closes it.
The fix
1. Gate ordinary topic subscription on the subscriber list (
fix(mqtt): gate ordinary topic subscription…)onSubscribenow grants an ordinary topic only when the connection's user is entered as a subscriber of it — the same membershipcreateSubscriberwrites under the topic'ssubscribepermission. Consequences:0x80).scores/#,foo/+) → refused: it cannot be matched against a single topic's subscriber list.users/<id>namespace is unchanged — still owner-gated, needs no membership, no extra DB read. Per-user pushes are unaffected.Membership is per user (any of their targets), matching the gate; the check is a single
subscriberslookup keyed on the topic id.2. Drop a removed subscriber's live subscription (
fix(messaging): drop a removed subscriber's live MQTT connection subscription)The gate takes effect at the next SUBSCRIBE, so an already-connected user would keep receiving a topic after being removed from it.
deleteSubscribernow releases a control event on themqttpub/sub channel — mirroring the user block/delete revoke path (#14411) — and every broker worker drops that user's live subscription to the topic, leaving the connection and its other subscriptions open. The event fires only once the user holds no remaining subscriber row for the topic, matching the per-user gate.Behavior / contract changes
users/wildcards were already refused; this extends to all ordinary namespaces.users/<id>behavior is unchanged.Tests
tests/unit/Mqtt/SubscribeAuthorizationTest.php— entered subscriber granted; non-subscriber, unknown topic, and ordinary wildcard refused; ownedusers/<id>granted without membership.tests/unit/Mqtt/UnsubscribeTest.php— removal drops the user's live subscription to that topic, keeps the connection and other subscriptions, and ignores other users.tests/unit/Appwrite/Messaging/Adapter/MqttTest.php— the removal control event is published.tests/e2e/Services/Mqtt/MqttServerTest.php— the three subscribe-contract tests were flipped from "open" to membership/refusal; the replay harness seeds membership.All MQTT unit suites and the flipped subscribe e2e tests pass locally. (The pre-existing revoke-family e2e lane is environmentally broken in my local sandbox after a main sync and is unrelated to these changes; the removal path is covered by unit tests.)
Follow-ups (out of scope)
subscribepermission is a separate product decision.🤖 Generated with Claude Code