Skip to content

fix(mqtt): limit SUBSCRIBE rate, filters, keep-alive and connections per user, by plan - #15056

Merged
ArnabChatterjee20k merged 12 commits into
mainfrom
security/mqtt-resource-caps
Oct 28, 2026
Merged

ArnabChatterjee20k merged 12 commits into
mainfrom
security/mqtt-resource-caps

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Adds resource limits to the MQTT broker after CONNECT, mirroring realtime. The two per-plan limits resolve the same way realtime's per-connection limits do: the plan's value if it has one, otherwise an env-driven APP_LIMIT_* default.

Limit Where Default Plan key Over the limit
Open connections per user Appwrite\Mqtt\Handler APP_LIMIT_MQTT_CONNECTIONS = _APP_LIMIT_MQTT_CONNECTIONS (32) per project user per worker mqttConnections CONNACK Quota exceeded (0x97) until a connection closes
Topic filters per SUBSCRIBE Appwrite\Mqtt\Handler APP_LIMIT_MQTT_FILTERS = _APP_LIMIT_MQTT_FILTERS (100) mqttFilters DISCONNECT Quota exceeded (0x97), before any authorization work
SUBSCRIBE rate per user Appwrite\Mqtt\Handler 32/min per authenticated project user, shared by all their connections and kept across reconnects, behind _APP_OPTIONS_ABUSE none (realtime's message limit isn't per plan either) DISCONNECT Message rate too high (0x96), before any authorization work
Keep-alive ceiling packages/mqtt Server (maxKeepAlive) APP_LIMIT_MQTT_KEEP_ALIVE = 1200s none (protocol level) A disabled (0) keep-alive becomes the ceiling, which 3.1.1 allows (3.1.2.10: a server may drop an inactive client). A longer one is lowered only for 5.0 clients, which are told through Server Keep Alive; 3.1.1 can't be told a new interval, so its declared one stands.

Plan hook. app/mqtt.php registers a getPlan container resource, fn (string $projectId): array, before $registerConnectionResources($container) runs. In CE it returns [], so every limit is its default. A wrapper can register its own getPlan inside $registerConnectionResources (the same way it overrides getCache/getConsoleDB) and return a plan array with mqttConnections / mqttFilters. No CE changes are needed for that.

Also, Server no longer answers or records a SUBSCRIBE whose handler closed the connection, and the CONNACK carries a single Server Keep Alive.

MQTT connections always authenticate as a user (there are no guests), so the per-user cap doesn't need realtime's per-IP and IPv6 /64 grouping. The CONNECT auth flow is unchanged.

Test Plan

  • tests/unit/Mqtt/LimitsTest.php:
    • SUBSCRIBE rate: limited, kept across reconnects, shared across a user's connections, separate for each user, off when abuse is disabled; a SUBSCRIBE before CONNECT is refused before the limiter.
    • Filter cap: default limit, and the plan's mqttFilters overriding it.
    • Connection cap: default cap, slot freed on close, other users and projects counted separately, refused CONNECTs never counted, and the plan's mqttConnections overriding it.
  • Package ServerTest: keep-alive ceiling (disabled, above, within, 3.1.1 disabled, 3.1.1 above the ceiling kept, no ceiling), a single Server Keep Alive on the CONNACK, and no SUBACK after the handler closed the connection.
  • Every new test failed before its change and passes after it.
  • Checked by hand against a running broker over TCP:
    • Defaults: keep-alive 0 got Server Keep Alive 1200; 101 filters got DISCONNECT 0x97; the 33rd connection got 0x97; 33 SUBSCRIBEs with abuse enabled got a DISCONNECT 0x96 once the counter reached 32.
    • With _APP_LIMIT_MQTT_CONNECTIONS=2, the 3rd connection got 0x97.
  • composer lint, PHPStan on the touched app files, Rector on tests/unit/Mqtt, and bin/monorepo check mqtt all pass.

Related PRs and Issues

Tracking: appwrite-labs/cloud#7059

🤖 Generated with Claude Code

ArnabChatterjee20k and others added 6 commits October 28, 2026 16:32
Lets other Server tests reuse it, and lets a test hand it a timer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each filter costs the handler authorization work, and a SUBSCRIBE was bounded
only by the packet size. The broker now disconnects a client whose SUBSCRIBE
carries more than APP_LIMIT_MQTT_FILTERS (100) filters, with Quota exceeded
(0x97) on MQTT 5.0, before the handler runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A CONNECT with keep-alive 0 was never scheduled for reaping, so an idle
authenticated socket held a broker slot forever. The broker now enforces at
most APP_LIMIT_MQTT_KEEP_ALIVE (1200s) and uses it for a disabled keep-alive.
MQTT 5.0 clients are told through Server Keep Alive on the CONNACK; 3.1.1
lets a server disconnect an inactive client whatever its keep-alive.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each SUBSCRIBE runs several project database reads, and one WebSocket frame
can pack thousands of them, all dispatched with no limit. A connection may now
send 32 SUBSCRIBE packets a minute, as a realtime connection may send 32
messages, behind _APP_OPTIONS_ABUSE. Past that the broker disconnects it with
Message rate too high (0x96) before any authorization work, and the Server no
longer answers or records a SUBSCRIBE whose handler closed the connection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Only CONNECT attempts were rate-limited (128 a minute), so one user could keep
opening sockets that count toward the broker's shared connection limit. As
realtime does with APP_LIMIT_REALTIME_CONNECTIONS, a user may now hold at most
APP_LIMIT_MQTT_CONNECTIONS (32) open connections per project on one worker;
another CONNECT is refused with Quota exceeded until one closes. MQTT has no
guest connections, so there is no per-IP owner to aggregate.

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

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

Copy link
Copy Markdown

Review complete. 🟡 2 medium

💬 Inline comments (2)

  • 🟡 Subscribe limiter keyed on fd resets on reconnect — Handler.php:367
  • 🟡 Silent keep-alive cap drops compliant MQTT 3.1.1 clients — Server.php:322

This PR layers anti-abuse controls onto the MQTT realtime path and extends the packages/mqtt broker library with server-side keep-alive handling and protocol-aware disconnect behavior.

Files Change
app/init/constants.php, app/mqtt.php Add MQTT limit constants (_APP_LIMIT_MQTT_*) and wire the capped keep-alive and abuse adapter into the Swoole server bootstrap.
packages/mqtt/src/Server.php, packages/mqtt/src/Packet/Disconnect.php Enforce maxKeepAlive on connect, send protocol-appropriate DISCONNECT/refusal reason codes, and skip SUBACK on handler-closed connections.
src/Appwrite/Mqtt/Handler.php Add Redis-backed per-user connection quota, per-fd subscribe rate limiter, and untrack-on-refusal logic.
tests/unit/Mqtt/*, packages/mqtt/tests/* Add limit/replay unit tests plus RecordingRedis/RecordingTimer fakes faithful to the abuse TimeLimit Redis script.

Note: one test-shard scan (test-only files) ended without publishing a report; its interim conclusion reported no defects in those files.

Reviewed commit: d99c287

@ghost

ghost commented Oct 28, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

This change adds plan- and environment-backed limits for MQTT connections and SUBSCRIBE work, a per-user SUBSCRIBE rate limit, and a broker keep-alive ceiling. It also updates the MQTT server and tests for quota disconnects, keep-alive negotiation, and handling SUBSCRIBE packets after a handler closes a connection.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 17
File Change
app/init/constants.php Adds MQTT keep-alive, connection, and filter limit constants.
app/mqtt.php Registers the default plan hook and configures the broker keep-alive ceiling.
packages/mqtt/README.md Documents the optional broker keep-alive ceiling.
packages/mqtt/src/Connection.php Clarifies that the stored keep-alive is the broker-enforced interval.
packages/mqtt/src/Packet/Disconnect.php Adds MQTT 5 quota and message-rate reason codes.
packages/mqtt/src/Server.php Enforces the keep-alive ceiling and checks connection state before answering SUBSCRIBE.
packages/mqtt/tests/AcceptingHandler.php Supports SUBSCRIBE and configurable CONNACK properties in broker tests.
packages/mqtt/tests/ConnectionTest.php Moves the recording adapter into a dedicated test file.
packages/mqtt/tests/RecordingAdapter.php Adds a recording transport for server tests.
packages/mqtt/tests/RecordingTimer.php Adds a timer fake for keep-alive tests.
packages/mqtt/tests/ServerTest.php Covers keep-alive negotiation and SUBSCRIBE handling after close.
src/Appwrite/Mqtt/Handler.php Adds per-user connection and SUBSCRIBE limits, plan resolution, and quota responses.
tests/unit/Mqtt/Fakes/RecordingRedis.php Tracks limiter hits for MQTT rate-limit tests.
tests/unit/Mqtt/LimitsTest.php Covers MQTT connection, filter, and SUBSCRIBE-rate limits.
tests/unit/Mqtt/ReplayTestCase.php Adds plan and Redis resources to the shared MQTT test container.
tests/unit/Mqtt/RevokeTest.php Adds the plan resource to the MQTT test container.
tests/unit/Mqtt/UnsubscribeTest.php Adds the plan resource to the MQTT test container.
🔇 Filtered out · 2

Findings Hansi considered but did not post.

Finding Why
Read the keep-alive ceiling from its env var Verifier: The claimed documented environment setting does not exist in the repository: searching for _APP_LIMIT_MQTT_KEEP_ALIVE finds no occurrences, including the MQTT environment-variable catalog. The new constant intentionally supplies a fixed 1200-second policy to app/mqtt.php. Other limits being configurable does not establish a requirement that this one must be; there is no demonstrated broken configuration contract.
Do not rely on the asynchronous close callback here Verifier: The production adapter uses SWOOLE_BASE (Adapter/Swoole.php:67-69), with one worker in app/mqtt.php. Inspection of Swoole 6.0.2 source shows Server::close calls BaseFactory::end, which invokes onClose inline before returning, even when socket closure must wait for buffered output. The registered callback reaches Server::closed and cleanup, setting connection->closed=true. Appwrite's onDisconnect only untracks the connection and records a synchronous lifetime metric; it performs no yielding I/O. Thus the asserted delayed callback does not apply to the configured production path, and this guard prevents the follow-up SUBACK.

Reviewed c62be94 · 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 packages/mqtt/src/Server.php Resolved
@github-actions

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.

A handler's own Server Keep Alive was kept next to the broker's, and the
property may appear only once. The broker's enforced value now replaces it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → security/mqtt-resource-caps (after).

Metric Before After Change
🚀 Requests/sec 210.98 194.93 🔴 -7.6%
⏱️ Latency P50 81.71 ms 89.09 ms 🔴 +9%
⏱️ Latency P95 185.63 ms 205.96 ms 🔴 +11%
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 89.09 205.96 12,483 194.93 +20.34
Account 164.29 303.5 657 11 +27.28
TablesDB 86.33 158.39 6,789 109.41 +6.96
Storage 82.04 191.99 3,285 54.1 +12.6
Functions 126.19 246.15 1,752 29.64 +19.96

Top API waits (after)

API request Max wait (ms)
account.name.update 430.03
functions.create 412.86
storage.buckets.create 387.69
functions.variables.update 349.89
account.prefs.update 349.21

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

Adds MQTT broker abuse limits (per-user connection, per-fd subscribe rate, keep-alive cap) and unit-test fakes for the realtime MQTT server.

Key findings

  • 🟡 Subscribe limiter keyed on fd resets on reconnect — Handler.php:367
  • 🟡 Silent keep-alive cap drops compliant MQTT 3.1.1 clients — Server.php:322

Comment thread src/Appwrite/Mqtt/Handler.php Resolved
Comment thread packages/mqtt/src/Server.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 S · Looks good to merge. Summary

ArnabChatterjee20k and others added 2 commits October 28, 2026 17:08
As realtime takes its per-connection limits from the plan, the broker now
reads mqttConnections from the plan its getPlan resource resolves for a
project, falling back to APP_LIMIT_MQTT_CONNECTIONS. That default reads
_APP_LIMIT_MQTT_CONNECTIONS (32), and the CE getPlan returns no plan, so
self-hosted behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The filter cap now lives in the handler, which reads mqttFilters from the
project's plan and falls back to APP_LIMIT_MQTT_FILTERS, read from
_APP_LIMIT_MQTT_FILTERS (100), as realtime does for its channel limit. A
per-plan value cannot be a broker-wide Server option, so maxFilters leaves
the package. An oversized SUBSCRIBE is still refused with Quota exceeded
before any authorization work.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ArnabChatterjee20k ArnabChatterjee20k changed the title fix(mqtt): limit SUBSCRIBE rate, filters, keep-alive and connections per user fix(mqtt): limit SUBSCRIBE rate, filters, keep-alive and connections per user, by plan Oct 28, 2026
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@hansi-codes review

ArnabChatterjee20k and others added 2 commits October 28, 2026 17:26
The limiter was keyed on the socket, so reconnecting or opening more
connections reset or multiplied the 32 a minute. It is now keyed on the
authenticated project and user, and a SUBSCRIBE on a connection that never
completed CONNECT is refused before the limiter or the authorizer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
3.1.1 has no way to tell a client a shorter interval, so lowering a long
keep-alive dropped compliant clients that pinged as they declared. A 3.1.1
keep-alive now stands; only a disabled one is replaced by the ceiling,
which 3.1.2.10 allows. 5.0 clients are still lowered and told through
Server Keep Alive.

Co-Authored-By: Claude Opus 5.5 <[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 · Looks good to merge. Summary

Comment thread tests/unit/Mqtt/LimitsTest.php Resolved
@ArnabChatterjee20k

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

@ArnabChatterjee20k
ArnabChatterjee20k merged commit 3e79435 into main Oct 28, 2026
76 checks passed
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