Skip to content

fix(mqtt): disconnect blocked or deleted users from open connections - #14411

Merged
ArnabChatterjee20k merged 8 commits into
mainfrom
fix/mqtt-revoke-blocked-users
Oct 13, 2026
Merged

ArnabChatterjee20k merged 8 commits into
mainfrom
fix/mqtt-revoke-blocked-users

Conversation

@abnegate

Copy link
Copy Markdown
Member

Summary

Blocking or deleting a user now disconnects their open MQTT connections, so they stop receiving pushes right away.

@ArnabChatterjee20k could you review?

Root cause

The broker only authorizes a user at CONNECT and SUBSCRIBE. Blocking (status: false) or deleting a user changed nothing for a connection that was already open and subscribed, so pushes kept arriving until the device reconnected.

Repro (device testing)

Found on Android emulators (native Android and React Native SDKs) against a real Appwrite main instance (Messaging API → Appwrite push provider → MQTT broker).

  1. Open the app so it holds a connection subscribed to users/<id>.
  2. PATCH /v1/users/{id}/status with {"status": false}.
  3. Send a push to that user: the native app still received it on the already-open connection.

Fix

  • HTTP: Users status update (false only), Users delete, PATCH /v1/account/status and DELETE /v1/account publish a revoke event (Mqtt::revoke(), ACTION_REVOKE) on the mqtt pubsub channel through a new mqtt resource. Account delete purges the cached user after its outer transaction, so the broker's re-check reads fresh data. A failed publish is logged as an error and doesn't fail the request.
  • Broker: each worker keeps a per-user connection index. On a revoke it re-checks the user with authorizer and sends DISCONNECT 0x87 to each connection that lost access, mirroring app/realtime.php.
    • The revoke runs in a child coroutine and the subscriber waits for it, so a push published after the block is handled after the disconnect.
    • An authorizer error counts as "not permitted".
    • A revoke that lands while a CONNECT is being authenticated is re-checked before the CONNECT is accepted.
  • packages/mqtt: Connection::$closed, so a connection that closes during CONNECT is not CONNACKed, counted active or left in the index.
  • Separate refactor(account) commit: sparse status update, strict https comparison, no unneeded clone.

Tests

  • tests/unit/Mqtt/RevokeTest.php (new) and MqttTest::testRevokePublishesControlEvent: 13 of 14 fail on main (the SUBSCRIBE re-check guard already existed).
  • E2E: testBlockedUserOpenConnectionIsDisconnected, testDeletedUserOpenConnectionIsDisconnected, testAccountStatusOpenConnectionIsDisconnected, testAccountDeleteOpenConnectionIsDisconnected. Each asserts DISCONNECT 0x87 within a bounded deadline and a refused reconnect. All fail on main.
  • testBlockedUserSubscribeRejected became testBlockedUserOpenConnectionIsDisconnected, because blocking now disconnects instead of refusing the next SUBSCRIBE.

Notes

  • Conflicts with fix(mqtt): stop a truncated replay from pinning the replay cursor #14410 (and the stacked expiry PR) only in src/Appwrite/Mqtt/Handler.php: they touch replayBacklog/onPuback/the constructor, this touches onConnect/onDisconnect/revoke. Whichever merges second needs a small rebase.
  • Follow-up: deleting the session a connection was opened with, or deleting the project, doesn't close the connection yet.

🤖 Generated with Claude Code

abnegate and others added 4 commits October 13, 2026 19:21
Blocking or deleting a user only took effect at their next CONNECT or
SUBSCRIBE, so a connection that was already open kept receiving pushes on
users/<id> and every topic it had subscribed to.

The broker now indexes accepted connections by project and user, keyed on
the project the authenticator resolved ('console' when the CONNECT carries
no projectId), and listens for a revoke control event on the existing mqtt
pub/sub channel. On a revoke it re-checks the user with the authorizer and,
when they are no longer permitted, ends each of their connections with
DISCONNECT 0x87. A user with no connections on this broker costs no
database read.

The authorizer fails closed during a revoke: if it throws, the connections
are ended rather than left open, since the event only arrives after the
user was blocked or deleted.

A revoke that lands while a CONNECT is still authenticating finds nothing
indexed yet. The handler counts revocations and records them per user while
any CONNECT is in flight, so that CONNECT re-checks the user once indexed
and is refused if they lost access. The record is dropped as soon as no
CONNECT is in flight.

A connection can also close while its CONNECT waits on the authenticator
or the rate limiter: the client hangs up, the CONNECT grace timer fires, or
a revoke ends it. The broker drops it then, before the CONNECT resumes, so
indexing it afterwards would leak an entry for the life of the worker (fds
are not reused), and accepting it would count a dead connection as active.
The broker now marks a connection closed when it drops it. A CONNECT that
resumes on a closed connection is not indexed, records no usage, is sent no
CONNACK, and is counted neither as opened nor as active.

The revoke runs in a child coroutine that the subscriber waits for: the
subscriber coroutine never ends, and the project databases revoke() opens
are cached in the running coroutine's context, so they would otherwise
accumulate there, one per project. When the coroutine limit is reached and
the child cannot start, the revoke runs inline instead, since waiting on a
coroutine that never started would stall every delivery on the worker.

The per-SUBSCRIBE re-check stays as the fallback for a missed revoke.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The broker can only end a revoked user's open connections if it hears
about the revocation. Blocking a user (PATCH /v1/users/:userId/status with
status false, or PATCH /v1/account/status) and deleting one (DELETE
/v1/users/:userId, DELETE /v1/account) now publish a revoke event through
a new mqtt resource.

The publish runs after the change is committed, so the broker's re-check
reads the new state. DELETE /v1/account deletes the user inside an outer
transaction, where the delete's own post-commit cache purge still runs
before the real commit; a concurrent read could re-cache the deleted user
and the broker would keep them connected. That route now purges the user
from the cache once the transaction has committed, before publishing.

A failed publish is logged as an error and does not fail the request: the
block or delete itself succeeded, and the per-SUBSCRIBE re-check and the
next CONNECT still refuse the user.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Behaviour-neutral cleanups in the routes the revoke touched:

- PATCH /v1/account/status updates only the status attribute instead of
  writing the whole injected user back; updateDocument merges it with the
  stored document, so the result is the same.
- The cookie secure flag is a strict comparison, computed once.
- DELETE /v1/users/:userId drops the defensive clone, since deleteDocument
  does not mutate the fetched user, and uses the injected project instead
  of reading it back from the events queue.
- The status param is already a bool, so its cast is gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each route that blocks or deletes a user (Users status and delete, Account
status and delete) is driven against a user holding an open connection
subscribed to users/<id>. The broker must end that connection with
DISCONNECT 0x87 within 15 seconds, well before the 90 second keep-alive
reap, and the user's next CONNECT must be refused with 0x87.

testBlockedUserSubscribeRejected blocked a user on an open connection and
expected the next SUBSCRIBE to be refused. Blocking now ends that
connection, so the SUBSCRIBE never gets an answer. It becomes
testBlockedUserOpenConnectionIsDisconnected. The per-SUBSCRIBE re-check
is now only reachable when a revoke is missed, which an end-to-end test
cannot trigger deterministically, so RevokeTest covers it as a unit test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 1 medium

📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to

🟡 Medium — Add closed re-check after yields in SUBSCRIBE and AUTH dispatch · Server.php:203–208 · unchanged line

// packages/mqtt/src/Server.php
203	            case Packet::SUBSCRIBE:
204	                $subscribe = Subscribe::decode($packet->body, $connection->protocol);
205	                $suback = $this->handler->onSubscribe($subscribe, $connection);
206	                $this->record($subscribe, $suback, $connection);
207	                $this->adapter->send($connection->fd, $this->encodeSuback($suback, $subscribe->packetId, $connection->protocol));
208	                break;

The new $connection->closed guard is applied only on the CONNECT path (packages/mqtt/src/Server.php:178); the AUTH, SUBSCRIBE and UNSUBSCRIBE cases call the handler and then unconditionally send() — and for SUBSCRIBE, record() into the subscription store (packages/mqtt/src/Server.php:203-208). Those handlers do DB/auth/cache I/O, so the coroutine can yield while the fd is closed by the keep-alive reap or by Handler::revoke(); cleanup() already removed the fd, and no further onClose will fire. On resume, the dead fd is re-inserted via store->subscribe(), so subscribers() keeps returning it for delivery, and on Swoole fd reuse the SUBACK can land on an unrelated new connection.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Fix inverted assertion messages in revoke tests (RevokeTest.php:159) — Two custom failure messages state the opposite of what their assertions verify (tests/unit/Mqtt/RevokeTest.php:159 and 183).

This PR closes the gap where a blocked or deleted user's live MQTT connections stayed authenticated until natural disconnect. When a user is blocked or deleted — from the self-service account endpoints or the admin user endpoints — the API now publishes a revoke control event on the mqtt pubsub channel; the broker's subscriber routes it to Handler::revoke(), which untracks the user's connections, closes them, and marks the user revoked so in-flight CONNECTs are refused.

Files Change
app/controllers/api/account.php, src/Appwrite/Platform/Modules/Users/Http/Users/Delete.php, src/Appwrite/Platform/Modules/Users/Http/Users/Status/Update.php Publish $mqtt->revoke() on the four block/delete paths, with best-effort catch-and-log
src/Appwrite/Messaging/Adapter/Mqtt.php, app/mqtt.php New revoke() publisher emitting the JSON control event; broker subscriber dispatches it to the handler and spawns the handler work in a child coroutine
src/Appwrite/Mqtt/Handler.php, packages/mqtt/src/Server.php, packages/mqtt/src/Connection.php Revocation bookkeeping (revoked, connecting counters) and a closed guard on the dispatch paths
app/init/resources.php Registers the mqtt resource in DI
tests/unit/Mqtt/*, tests/unit/Appwrite/Messaging/Adapter/*, tests/e2e/Services/Mqtt/*, packages/mqtt/tests/ConnectionTest.php Unit and e2e coverage for revoke semantics, races, and fakes for adapter/pubsub/accounts

Reviewed commit: 99b9f30

@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.

@ghost

ghost commented Oct 13, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The PR publishes MQTT revoke events when users are blocked, deleted, or their account is disabled/deleted, and has broker workers re-check authorization to disconnect connections that have lost access. It tracks connections by user, handles revocation during CONNECT, and adds package, unit, and E2E coverage. The latest test updates add a non-null acknowledgement helper and guard the recording adapter against delivery before a server is attached.

Latest changes: The latest commits updated ConnectionTest to fail explicitly when a tracked delivery is unexpectedly absent, added a server-attached guard to the recording adapter, and removed the now-obsolete PHPStan baseline entries.

Verdict New comments Fixed Still open
💬 Commented 0 0 0

Note

Not approving while a bug finding is open: Publish revocation before fallible cleanup

📂 Walkthrough · 18
File Change
app/controllers/api/account.php Publishes MQTT revocations for account status changes and account deletion, purging the cached user after deletion.
app/init/resources.php Registers the MQTT publisher resource for HTTP actions.
app/mqtt.php Handles revoke events in a child coroutine and waits for revocation before processing the next pub/sub event.
packages/mqtt/phpstan-baseline.neon Removes obsolete PHPStan baseline entries for ConnectionTest.
packages/mqtt/src/Connection.php Adds closed-state tracking for connections removed during a yielding callback.
packages/mqtt/src/Server.php Skips CONNECT responses for closed connections and marks cleaned-up connections closed.
packages/mqtt/tests/ConnectionTest.php Tests closure during CONNECT and adds helpers and guards for its recording adapter.
src/Appwrite/Messaging/Adapter/Mqtt.php Adds publishing of MQTT revoke control events.
src/Appwrite/Mqtt/Handler.php Indexes connections by user, re-checks authorization on revocation, and guards CONNECT races.
src/Appwrite/Platform/Modules/Users/Http/Users/Delete.php Publishes a revoke event when deleting a user.
src/Appwrite/Platform/Modules/Users/Http/Users/Status/Update.php Publishes a revoke event when blocking a user.
tests/e2e/Services/Mqtt/MqttServerTest.php Adds E2E coverage for revoking open connections after user and account status changes or deletion.
tests/e2e/Services/Mqtt/MqttSubscriber.php Adds bounded waiting for broker DISCONNECT packets.
tests/unit/Appwrite/Messaging/Adapter/Fakes/RecordingPubSub.php Adds a recording pub/sub fake for MQTT publisher tests.
tests/unit/Appwrite/Messaging/Adapter/MqttTest.php Tests publishing the MQTT revoke control event.
tests/unit/Mqtt/Fakes/Accounts.php Adds an in-memory authenticator and authorizer for broker tests.
tests/unit/Mqtt/Fakes/RecordingAdapter.php Records broker disconnects and closes for handler tests.
tests/unit/Mqtt/RevokeTest.php Covers revocation, user/project isolation, and CONNECT races.

Merged main (421d8c8); no changes to this PR's code since 6cb0c56 · 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

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/mqtt-revoke-blocked-users (after).

Metric Before After Change
🚀 Requests/sec 219.32 226.54 ⚪ +3.3%
⏱️ Latency P50 79.18 ms 76.38 ms ⚪ -3.5%
⏱️ Latency P95 178.54 ms 179.34 ms ⚪ +0.5%
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 76.38 179.34 14,193 226.54 +0.8
Account 148.81 278.22 747 12.39 +15.18
TablesDB 73.82 131.13 7,719 125.62 -19.06
Storage 69.83 143.37 3,735 62.35 -11.74
Functions 115.62 222.21 1,992 33.96 +26.16

Top API waits (after)

API request Max wait (ms)
account.prefs.update 416.44
account.name.update 414.51
functions.variables.update 352.93
functions.create 340.52
tablesdb.rows.create 335.18

abnegate and others added 2 commits October 13, 2026 21:13
The package runs phpstan at max level over its tests. The closed-during-connect
test added offset accesses on acknowledge()'s nullable result beyond the
baseline's count, and the recording adapter invoked nullable callbacks, failing
the Packages / mqtt check. Narrow both instead of growing the baseline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… targets

The user row is gone once deleteDocument returns, but the revoke was published
only after identity and target cleanup, which can fail or take long on a user
with many targets. A failure there left the API erroring with the user already
deleted while their open MQTT connection kept receiving pushes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	packages/mqtt/tests/ConnectionTest.php
# Conflicts:
#	src/Appwrite/Mqtt/Handler.php
@ArnabChatterjee20k
ArnabChatterjee20k merged commit 37b6798 into main Oct 13, 2026
12 checks passed
@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