Skip to content

fix(mqtt): end connections with the session or token they were opened with - #14804

Merged
ChiragAgg5k merged 12 commits into
mainfrom
fix/mqtt-session-binding
Oct 23, 2026
Merged

ChiragAgg5k merged 12 commits into
mainfrom
fix/mqtt-session-binding

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

MQTT connections now end with the credential they were opened with. The connection identity carries the session and the token's expiry, the session must hold its required MFA factors as over HTTP, and ending a session or changing MFA asks the broker to revoke. The CONNECT limiter is also keyed per project.

Builds on #14803 (it uses User::sessionFactorsMet() from there); please merge that first. Until then this diff includes its commits.

Changes

  • app/init/mqtt/connection.php: the authenticator returns sessionId, expire (the JWT exp) and sessionExpire (the session's expiry at connect) with the identity, and refuses a session, or a JWT bound to one, that lacks its required factors. The authorizer refuses an expired token, and a session that has ended or lacks its factors.
  • Mqtt\Handler::revoke() checks each of the user's connections against its own identity (one check per distinct credential), so ending one session closes only the connections opened with it. The disconnect reason is now the generic unauthorized message, since a revoke is no longer only a block.
  • Mqtt\Handler::deliver() closes a connection whose token has expired. Once a session passes its recorded expiry, delivery checks it again (it may have been extended) and closes the connection only if it no longer authorizes.
  • The CONNECT limiter key is mqtt:connect:{projectId}:{userId}, as user ids are only unique within a project.
  • Mqtt::revoke() is now called when sessions are deleted (DELETE /account/sessions, DELETE /account/sessions/:sessionId, DELETE /users/:userId/sessions, DELETE /users/:userId/sessions/:sessionId), after the password changes that end sessions (PATCH /account/password, PUT /account/recovery, PUT /account/recovery/otp, PATCH /users/:userId/password), and when MFA requirements change (PATCH /account/mfa, PATCH /users/:userId/mfa, PUT /account/mfa/authenticators/:type), following the existing pattern in Users/Status/Update.php.

Tests

  • Unit (tests/unit/Mqtt): RevokeTest::testRevokeDisconnectsOnlyEndedSession, RevokeTest::testRevokeChecksEachCredentialOnce, RevokeTest::testConnectLimitIsKeptPerProject (with a recording Redis fake), HandlerTest::testExpiredCredentialIsDisconnectedOnDelivery, HandlerTest::testExtendedSessionKeepsReceiving, HandlerTest::testEndedSessionIsDisconnectedOnDelivery.
  • E2E (verified by CI, mqtt group): testSessionMissingFactorConnectRejected, testDeletedSessionOpenConnectionIsDisconnected (the other session's connection stays open), testEnablingMfaDisconnectsSessionMissingFactor, testAccountLogoutOpenConnectionIsDisconnected, testSessionJwtOpenConnectionIsDisconnectedWithSessions.

Related: appwrite-labs/cloud#6666

Issue (private, full explanation): https://github.com/appwrite-labs/cloud/issues/6908

@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Realtime impersonation skips impersonator MFA factor check — realtime.php:963

This PR reworks how realtime and MQTT connections authenticate and stay authenticated: credential expiry is tracked per connection, revocations propagate to live connections, and MFA factor enforcement moves onto shared User document helpers.

Files Change
app/init/mqtt/connection.php, app/init/realtime/connection.php, app/realtime.php Connection auth setup: expiry-aware credentials, impersonation gating, per-project connect rate limits
src/Appwrite/Mqtt/Handler.php, src/Appwrite/Realtime/Message/Handlers/Authentication.php Mid-connection re-authentication, revocation delivery, and unauthorized disconnect handling
src/Appwrite/Utopia/Database/Documents/User.php New getMinimumFactors() / sessionFactorsMet() helpers shared by HTTP and realtime paths
app/controllers/api/account.php, app/controllers/shared/api.php, Users session/password endpoints Refactor to use the shared helpers and trigger revocations on session delete, logout, and password change
tests/unit/Mqtt/**, tests/unit/Utopia/Database/Documents/UserTest.php, e2e suites Unit fakes and tests for expiry, revocation dedupe, and factor helpers; e2e coverage for MQTT and realtime

Reviewed commit: 5024007

@ChiragAgg5k ChiragAgg5k self-assigned this Oct 22, 2026
@ghost

ghost commented Oct 22, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

I found no correctness issues after tracing the credential validation, revocation, and delivery paths.

MQTT connection identities now retain their session and token expiry, and the broker rechecks those credentials during revocation and message delivery. Session, password, and MFA changes publish revocation events, and CONNECT rate limits are scoped per project. Unit and E2E tests cover credential-specific disconnects, session checks, expiry, and limiter keys.

Verdict New comments Fixed Still open
✅ Approved 0 1 0
📂 Walkthrough · 18
File Change
app/controllers/api/account.php Publish MQTT revocations after account session removal, password recovery, and session replacement.
app/controllers/shared/api.php Publish a revocation after the session-limit hook deletes older sessions.
app/init/constants.php Define the MQTT session recheck interval.
app/init/mqtt/connection.php Authenticate MQTT credentials with session factors and retain session and token expiry metadata.
src/Appwrite/Mqtt/Handler.php Scope CONNECT limiting by project and user; revoke per credential and check expiry and session status before delivery.
src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Authenticators/Update.php Revoke MQTT connections after authenticator confirmation changes session factors.
src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Update.php Revoke MQTT connections after account MFA settings change.
src/Appwrite/Platform/Modules/Account/Http/Account/Sessions/IdToken/Create.php Revoke MQTT connections when ID-token sign-in replaces the current session.
src/Appwrite/Platform/Modules/Users/Http/Users/MFA/Update.php Revoke MQTT connections after an administrative MFA update.
src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php Revoke MQTT connections after a user password change.
src/Appwrite/Platform/Modules/Users/Http/Users/Sessions/Bulk/Delete.php Revoke MQTT connections after deleting a user's sessions.
src/Appwrite/Platform/Modules/Users/Http/Users/Sessions/Delete.php Revoke MQTT connections after deleting an individual user session.
tests/e2e/Services/Mqtt/MqttServerTest.php Exercise session-factor rejection, session and MFA revocation, and ID-token sign-in replacement over MQTT.
tests/unit/Mqtt/Fakes/Accounts.php Model session-specific identity, session revocation, and authorization for Handler tests.
tests/unit/Mqtt/Fakes/GrantingHandler.php Carry session and expiry metadata through the fake broker handler.
tests/unit/Mqtt/Fakes/RecordingRedis.php Record keys used by the CONNECT limiter tests.
tests/unit/Mqtt/HandlerTest.php Test credential expiry and periodic session authorization during delivery.
tests/unit/Mqtt/RevokeTest.php Test per-session revocation, credential-check deduplication, and project-scoped limiter keys.
✅ Fixed since the last review · 1
  • Reject JWTs at their exact expiration timestamp · src/Appwrite/Mqtt/Handler.php:537

Merged main (5707dba); no changes to this PR's code since 9167195 · 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 S · Looks good to merge. Summary

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

This PR revamps realtime/MQTT authentication with centralized credential-expiry tracking, revocation propagation, and MFA factor enforcement helpers on the User document.

Key findings

  • 🟡 Realtime impersonation skips impersonator MFA factor check — realtime.php:963

Comment thread app/realtime.php Resolved
@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/mqtt-session-binding (after).

Metric Before After Change
🚀 Requests/sec 189.95 187.28 ⚪ -1.4%
⏱️ Latency P50 89.75 ms 92.57 ms ⚪ +3.1%
⏱️ Latency P95 214.12 ms 211.84 ms ⚪ -1.1%
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 92.57 211.84 11,628 187.28 -2.29
Account 171.25 309.36 612 10.15 -11.8
TablesDB 89.6 165.6 6,324 103.55 +2.05
Storage 85.69 197.65 3,060 52.32 +0.35
Functions 129.12 254 1,632 28.62 -9.5

Top API waits (after)

API request Max wait (ms)
account.name.update 550.08
account.prefs.update 440.17
functions.create 435.18
functions.delete 429.05
storage.buckets.create 422.4

@ChiragAgg5k
ChiragAgg5k force-pushed the fix/mqtt-session-binding branch from 5024007 to 6cb2374 Compare October 22, 2026 16:03
@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • 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.

@ChiragAgg5k
ChiragAgg5k force-pushed the fix/mqtt-session-binding branch from 6cb2374 to 7cd38bd Compare October 22, 2026 16:04

@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

@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 app/init/mqtt/connection.php Resolved
ChiragAgg5k and others added 2 commits October 22, 2026 18:15
… with

An MQTT connection only remembered its project and user, so it outlived a sign out, a deleted session and an expired token, and the broker could only drop users who were blocked or removed. The identity now carries the session and the credential's expiry; the authorizer checks them, the session must hold its required MFA factors as over HTTP, delivery closes connections whose credential expired, and revoking checks each connection against its own session. Session deletion and the password changes that end sessions now ask the broker to revoke.

The CONNECT limiter is also keyed on the project, since user ids are only unique within one.

Co-Authored-By: Claude <[email protected]>
Enabling MFA or verifying an authenticator can leave other sessions short of factors, so those paths now ask the broker to revoke. A session's recorded expiry is no longer a hard limit: once it passes, delivery checks the session again, since it may have been extended, while a token's own expiry still ends the connection.

Co-Authored-By: Claude <[email protected]>
@ChiragAgg5k
ChiragAgg5k force-pushed the fix/mqtt-session-binding branch from 7cd38bd to 9b08918 Compare October 22, 2026 17:27
ChiragAgg5k and others added 2 commits October 22, 2026 19:21
A session can end or fall short of its MFA factors without a revoke reaching the broker, for example when verifying an email or phone raises the factors MFA requires. Delivery now checks a session-bound connection again at least once a minute and when its session is due to expire, so it ends with the session as HTTP access would.

Co-Authored-By: Claude <[email protected]>
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@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

@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

A check on the session's expiry second still read the session as active and pushed the next check a minute out. The check now waits until that second has passed.

Co-Authored-By: Claude <[email protected]>
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@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

@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
OAuth and ID-token sign-in replace the caller's current session, and the session limit evicts the oldest ones, without telling the broker. These paths now ask it to revoke, so MQTT connections on those sessions end straight away instead of at their next session check.

Co-Authored-By: Claude <[email protected]>
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@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 · Looks good to merge. Summary

@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 · Looks good to merge. Summary

@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@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

@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 · Looks good to merge. Summary

Comment thread src/Appwrite/Mqtt/Handler.php Resolved
…dential

The per-credential check keyed on the whole identity, including when each connection is next due for a session check, so connections opened at different times on the same session were each checked against the database.

Co-Authored-By: Claude <[email protected]>
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@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

@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
After a periodic session check passed, the next one was set a full interval later even when the session expired sooner. It is now never set past the expiry the session had at connect.

Co-Authored-By: Claude <[email protected]>
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@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

@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
The JWT library rejects a token once the clock reaches its exp, while the broker kept accepting it through that second.

Co-Authored-By: Claude <[email protected]>
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@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

@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

@ChiragAgg5k
ChiragAgg5k merged commit 5ce150d into main Oct 23, 2026
69 checks passed
Tapraj-Pathak pushed a commit to Tapraj-Pathak/appwrite that referenced this pull request Oct 24, 2026
fix(mqtt): end connections with the session or token they were opened with

(cherry picked from commit 5ce150d)
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