Skip to content

fix(mqtt): gate topic subscription on the subscriber list - #14460

Merged
ArnabChatterjee20k merged 12 commits into
mainfrom
fix/mqtt-topic-subscribe-permission
Oct 14, 2026
Merged

ArnabChatterjee20k merged 12 commits into
mainfrom
fix/mqtt-topic-subscribe-permission

Conversation

@ArnabChatterjee20k

Copy link
Copy Markdown
Member

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:

  • onSubscribe granted any non-users/ filter — any exact name, and ordinary wildcards like scores/# — to any authenticated, non-blocked project user.
  • The topic's subscribe permission and its subscribers list gated only createSubscriber (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…)

onSubscribe now grants an ordinary topic only when the connection's user is entered as a subscriber of it — the same membership createSubscriber writes under the topic's subscribe permission. Consequences:

  • An exact topic the user is not a subscriber of → refused (SUBACK 0x80).
  • An unknown topic name → refused.
  • An ordinary wildcard (scores/#, foo/+) → refused: it cannot be matched against a single topic's subscriber list.
  • The reserved 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 subscribers lookup 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. deleteSubscriber now releases a control event on the mqtt pub/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

  • Ordinary topics are now private by membership: a user must be a subscriber to receive over MQTT. Apps that relied on open subscription must add subscribers (which they already do for the other channels).
  • Ordinary wildcard subscriptions are refused. First-level and 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; owned users/<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)

  • Removal via bulk paths (topic/target deletion, user deletion already revokes) could emit the same drop event.
  • Whether to tighten the default subscribe permission is a separate product decision.

🤖 Generated with Claude Code

ArnabChatterjee20k and others added 2 commits October 14, 2026 11:25
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]>
@luxor-code-review

luxor-code-review Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Late async unsubscribe kills a re-created subscription — Handler.php:420
🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 No coverage for mixed SUBACK ordering or QoS capping (SubscribeAuthorizationTest.php:17) — The new authorization tests only ever subscribe one filter per packet, and every seeded topic uses the default qos = Packet::QOS_1.

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.

Files Change
packages/mqtt/src/Server.php, src/Appwrite/Mqtt/Handler.php Add per-connection subscription store wiring, unsubscribe() support, and per-filter SUBACK authorization with QoS capping
app/mqtt.php, src/Appwrite/Messaging/Adapter/Mqtt.php Wire the broker to pub/sub unsubscribe control events and add revokeTopic on the messaging adapter
src/Appwrite/Platform/Modules/Messaging/Http/Topics/Subscribers/Delete.php Re-check remaining subscriber rows before emitting the broker unsubscribe
tests/unit/Mqtt/*, tests/e2e/Services/Mqtt/MqttServerTest.php New unit tests for authorization and unsubscribe plus updated e2e expectations for refused subscriptions

Reviewed commit: dab811f

@ghost

ghost commented Oct 14, 2026 •

Copy link
Copy Markdown

🟡 Tier B · Needs changes before merging

Limited by an open major finding: Preserve the existing MQTT topic-name contract

Ordinary MQTT subscriptions now require topic subscriber membership, while owned users/<id> topics remain owner-authorized; MQTT replay rechecks membership and avoids serving a colliding topic row as a user topic. The change also removes a user's live topic subscription after their final membership is deleted, updates MQTT campaign delivery and its ledger handling, and adds coverage for authorization, revocation, replay, and delivery behavior.

Latest changes: The newest commits reject a topic row whose ID collides with an owned users/<id> topic unless its stored name matches, and add a regression test confirming its backlog is not replayed.

Verdict New comments Fixed Still open
💬 Commented 0 0 1
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
File Change
app/mqtt.php Routes topic-unsubscribe control events to the broker handler.
packages/mqtt/src/Server.php Adds server-side removal of one connection's subscription to a topic.
src/Appwrite/Messaging/Adapter/Mqtt.php Publishes topic-unsubscribe control events for broker workers.
src/Appwrite/Messaging/Adapter/Push/Appwrite.php Persists campaign messages and fans them out using topic IDs, retaining hashed IDs for user topics.
src/Appwrite/Mqtt/Clock.php Tracks access changes during in-flight CONNECT operations.
src/Appwrite/Mqtt/Handler.php Gates ordinary subscriptions on membership, removes live subscriptions, rechecks membership around replay, and rejects colliding rows for owned user topics.
src/Appwrite/Platform/Modules/Messaging/Http/Topics/Subscribers/Delete.php Publishes a broker event when a user loses their final subscriber row for a topic.
tests/e2e/Services/Mqtt/MqttServerTest.php Covers membership-based subscribe behavior, topic-ID delivery, QoS, and replay.
tests/unit/Appwrite/Messaging/Adapter/MqttTest.php Covers publishing the topic-unsubscribe control event.
tests/unit/Appwrite/Messaging/Adapter/Push/AppwriteTest.php Checks campaign fan-out uses topic IDs.
tests/unit/Mqtt/ClockTest.php Covers access-clock drift detection, identity scoping, and cleanup.
tests/unit/Mqtt/ReplayTestCase.php Seeds subscriber membership and supports topic IDs in replay fixtures.
tests/unit/Mqtt/SubscribeAuthorizationTest.php Covers membership authorization, wildcard refusal, owned user-topic access, and rejection of squatted user-topic rows.
tests/unit/Mqtt/UnsubscribeTest.php Covers removing only the affected user's topic subscription.
⏳ Still open from earlier reviews · 1

Reviewed the commits since 5e943a8 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

Comment thread src/Appwrite/Mqtt/Handler.php Resolved
Comment thread src/Appwrite/Mqtt/Handler.php Resolved
@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/Appwrite/Mqtt/Handler.php Resolved
@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/mqtt-topic-subscribe-permission (after).

Metric Before After Change
🚀 Requests/sec 211.5 214.81 ⚪ +1.6%
⏱️ Latency P50 81.2 ms 81.45 ms ⚪ +0.3%
⏱️ Latency P95 189.38 ms 185.26 ms ⚪ -2.2%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 81.45 185.26 13,623 214.81 -4.12
Account 151 267.67 717 11.96 -12.93
TablesDB 78.72 140.78 7,409 119.72 -20.77
Storage 75.76 165.26 3,585 59.61 +12.56
Functions 116.25 230.23 1,912 32.5 +15.06

Top API waits (after)

API request Max wait (ms)
account.prefs.update 474.38
storage.files.delete 452.96
account.name.update 432.83
functions.variables.create 397.47
storage.files.create 389.98

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]>

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · See the inline comments. Summary

Comment thread src/Appwrite/Mqtt/Handler.php Resolved
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]>

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

Comment thread src/Appwrite/Mqtt/Handler.php Resolved
ArnabChatterjee20k and others added 3 commits October 14, 2026 12:55
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]>

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

ArnabChatterjee20k and others added 2 commits October 14, 2026 17:36
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]>
ghost
ghost previously requested changes Oct 14, 2026

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · 2 blocking findings to address. Summary

Comment thread src/Appwrite/Mqtt/Handler.php Resolved
[],
[],
[$name],
[$to],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@ArnabChatterjee20k
ArnabChatterjee20k merged commit 9f6b643 into main Oct 14, 2026
121 of 123 checks passed
abnegate added a commit that referenced this pull request Oct 14, 2026
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]>
@ChiragAgg5k ChiragAgg5k mentioned this pull request Oct 21, 2026
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants