Repository navigation
fix(mqtt): disconnect blocked or deleted users from open connections - #14411
Conversation
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]>
|
Review complete. 🟡 1 medium 📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to🟡 Medium — Add // 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 🧹 Nitpicks (1) — 🟢 1 low
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
Reviewed commit: 99b9f30 |
Security rulesNo new WARNING or ERROR findings from security rules. 19 existing findings tracked in
|
🟢 Tier S · Ready to mergeThe 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.
Note Not approving while a bug finding is open: Publish revocation before fallible cleanup 📂 Walkthrough · 18
Merged |
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
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
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).
users/<id>.PATCH /v1/users/{id}/statuswith{"status": false}.Fix
PATCH /v1/account/statusandDELETE /v1/accountpublish a revoke event (Mqtt::revoke(),ACTION_REVOKE) on themqttpubsub channel through a newmqttresource. 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.authorizerand sends DISCONNECT 0x87 to each connection that lost access, mirroringapp/realtime.php.packages/mqtt:Connection::$closed, so a connection that closes during CONNECT is not CONNACKed, counted active or left in the index.refactor(account)commit: sparse status update, stricthttpscomparison, no unneededclone.Tests
tests/unit/Mqtt/RevokeTest.php(new) andMqttTest::testRevokePublishesControlEvent: 13 of 14 fail on main (the SUBSCRIBE re-check guard already existed).testBlockedUserOpenConnectionIsDisconnected,testDeletedUserOpenConnectionIsDisconnected,testAccountStatusOpenConnectionIsDisconnected,testAccountDeleteOpenConnectionIsDisconnected. Each asserts DISCONNECT 0x87 within a bounded deadline and a refused reconnect. All fail on main.testBlockedUserSubscribeRejectedbecametestBlockedUserOpenConnectionIsDisconnected, because blocking now disconnects instead of refusing the next SUBSCRIBE.Notes
src/Appwrite/Mqtt/Handler.php: they touchreplayBacklog/onPuback/the constructor, this touchesonConnect/onDisconnect/revoke. Whichever merges second needs a small rebase.🤖 Generated with Claude Code