Skip to content

fix(realtime): validate presence message ID and metadata like the HTTP endpoint - #14829

Merged
ChiragAgg5k merged 11 commits into
mainfrom
fix/realtime-mqtt-hygiene
Oct 23, 2026
Merged

ChiragAgg5k merged 11 commits into
mainfrom
fix/realtime-mqtt-hygiene

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

The realtime presence message validated presenceId with Text(36) and skipped validation for metadata entirely, unlike PUT /v1/presences/:presenceId. A presence frame could therefore store an ID the HTTP endpoint would refuse, or list-shaped metadata where an object is expected.

Realtime/Message/Handlers/Presence.php now validates presenceId with CustomId (which still accepts unique()) and validates metadata with Nullable(JSONObject) instead of skipping validation, so null is still allowed.

Subscribe frame and per-connection subscription limits are handled in a separate change. The second-CONNECT fix and its coverage already live on main.

Test Plan

  • E2E: PresenceRealtimeClientTest::testPresenceValidationErrorsReturnErrorOnly sends a presence frame with an invalid ID and one with list-shaped metadata, checks each gets an error naming the parameter, and checks no presence event is emitted.
  • Ran locally: Pint and PHPStan on the touched files, and tests/unit/Realtime.

Related PRs and Issues

Related: appwrite-labs/cloud#6674

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs?

ChiragAgg5k and others added 2 commits October 22, 2026 16:12
The realtime presence message accepted any 36-character id and skipped metadata validation, unlike the HTTP presence endpoint. Validate the id like a custom document id and run the metadata validator.

Subscribe messages had no upper bound on channels or queries per subscription, nor on the subscriptions one connection holds. Cap channels and queries at the array parameter limit, channel names at the array element limit, and subscriptions per connection at a limit large enough for an SDK to resend every subscription in one frame on reconnect.

Co-Authored-By: Claude <[email protected]>
…ive topic

A second CONNECT on an accepted connection switched its identity while the broker kept the subscriptions it had granted to the first one. MQTT treats a second CONNECT as a protocol violation, so refuse it, which closes the connection.

Push ledger rows are keyed by the public topic id and outlived topic deletion, so a topic recreated with the same id could replay the deleted topic's messages. Replay only rows written since the current topic was created, and delete the deleted topic's rows with it.

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

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

Copy link
Copy Markdown

Review complete. No issues found — approved ✅.


This PR hardens the MQTT and realtime presence stack: it refuses a second CONNECT on an already-active connection, caps per-connection realtime subscriptions via a new APP_LIMIT_REALTIME_SUBSCRIPTIONS constant, cleans up pushLedger rows when a topic is deleted (preserving rows created after a topic recreation), and tightens presence/subscribe payload validation. Test coverage spans e2e MQTT, presence realtime, and the subscribe payload validator unit test.

Files Change
src/Appwrite/Mqtt/Handler.php, app/init/constants.php Reject duplicate CONNECTs with a refusal CONNACK and filter backlog by the topic's creation timestamp
src/Appwrite/Realtime/Message/Handlers/Subscribe.php, src/Appwrite/Realtime/Message/Validators/SubscribePayload.php Enforce the connection-level subscription cap consistently across handler and payload validator
src/Appwrite/Platform/Workers/Deletes.php Delete stale pushLedger rows during topic deletion, scoped by the topic's createdAt window
src/Appwrite/Realtime/Message/Handlers/Presence.php Tighten presence ID and metadata validation (CustomId, nullable JSONObject)
tests/e2e/Services/*, tests/unit/Realtime/* Add e2e coverage for MQTT refusal and presence validation plus a unit test for the payload validator

Reviewed commit: 1fb4b7c

@ghost

ghost commented Oct 22, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

The change is otherwise focused, but a less common encoded-string input can still bypass the metadata shape validation and be stored with the wrong type.

The realtime presence handler now validates presence IDs with CustomId and metadata with a nullable JSON-object validator. The E2E coverage exercises invalid IDs and list-shaped metadata frames.

Verdict New comments Fixed Still open
💬 Commented 1 0 0

Note

Not approving while a bug finding is open: Encoded JSON strings pass the metadata object check

Finding Where
🟡 Encoded JSON strings pass the metadata object check src/Appwrite/Realtime/Message/Handlers/Presence.php:34
Fix with agent prompt
### Issue 1
src/Appwrite/Realtime/Message/Handlers/Presence.php:34
**Encoded JSON strings pass the metadata object check**

`JSONObject` also accepts strings containing encoded JSON objects, so a frame like `{"metadata":"{\"x\":1}"}` passes validation. This handler accepts the value as `mixed` and stores it unchanged, unlike the HTTP action's `array|stdClass` parameter, so metadata can be persisted and returned as a string rather than an object.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 2
File Change
src/Appwrite/Realtime/Message/Handlers/Presence.php Validates presence IDs and nullable metadata on realtime presence frames.
tests/e2e/Services/Presences/PresenceRealtimeClientTest.php Adds realtime validation-error coverage for invalid IDs and list metadata.

Reviewed a131164 · 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

A topic recreated after the cleanup read found no replacement could publish before the delete ran, and the unbounded query would remove those new rows. Only delete rows older than the read, or than the recreated topic.

Co-Authored-By: Claude <[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

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/realtime-mqtt-hygiene (after).

Metric Before After Change
🚀 Requests/sec 205.1 209.47 ⚪ +2.1%
⏱️ Latency P50 83.25 ms 83.1 ms ⚪ -0.2%
⏱️ Latency P95 202.35 ms 189.06 ms 🟢 -6.6%
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 83.1 189.06 13,167 209.47 -13.29
Account 150.08 290.27 693 11.53 -8.9
TablesDB 82.07 154.67 7,161 116.15 -14.8
Storage 73.54 178.5 3,465 58.14 +5.09
Functions 111.47 211.96 1,848 31.72 -4.85

Top API waits (after)

API request Max wait (ms)
functions.create 448.81
account.get 392.55
account.name.update 360.03
account.prefs.update 358.74
functions.variables.update 315

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

…CT to close

Replay now only serves ledger rows written since the topic was created, so the fixtures create topics on the test clock before their ledger rows. A second CONNECT on an accepted connection is refused, which replaces the old identity-swap expectation. Adds a regression for rows left by a deleted topic with the same id.

Co-Authored-By: Claude <[email protected]>
@ChiragAgg5k ChiragAgg5k self-assigned this Oct 22, 2026
@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
ChiragAgg5k and others added 2 commits October 22, 2026 20:55
Scoping replay by comparing ledger and topic timestamps depends on clocks agreeing across workers, and a skewed clock could drop a live message from replay. Delete the ledger rows in the same request that deletes the topic instead: a ledger write locks the topic row first, so no row can land for the topic after it is gone, and a topic recreated with the same ID starts with an empty ledger.

Co-Authored-By: Claude <[email protected]>
…iene

# Conflicts:
#	tests/unit/Mqtt/RevokeTest.php
@ChiragAgg5k ChiragAgg5k changed the title fix: realtime presence and subscribe limits, MQTT reconnect and ledger scoping fix: realtime presence and subscribe limits, push ledger cleanup on topic delete Oct 22, 2026
@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

@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

# Conflicts:
#	tests/e2e/Services/Mqtt/MqttServerTest.php
…rker on main

Main now keys pushLedger rows by topicInternalId and the deletes worker removes a deleted topic's rows by that id, so a recreated topic cannot replay the old one's messages. The request-time purge by public topic id duplicated that and could race a recreated topic's first publish, so it is dropped.
…und reused IDs

The per-connection cap was counted before the console-tail lookups, which can yield, so two concurrent frames could both pass on the old state. Both caps are now checked right before the in-memory subscribe, with nothing that yields in between.

A reused subscription ID adds channels to the ones it already has, so the 100-channel cap now applies to its accumulated set, not only to each frame.
@ChiragAgg5k ChiragAgg5k changed the title fix: realtime presence and subscribe limits, push ledger cleanup on topic delete fix: realtime presence and subscribe limits, MQTT second-CONNECT test Oct 23, 2026
@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

… a new unit file

testSubscribeLimits already checked the channel, query and per-connection caps through the realtime API. It now also covers an oversized subscribe frame and an over-long channel name, so the separate SubscribePayloadTest file is dropped.
@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

Subscribe frame and per-connection limits are being handled in a separate change, and the second-CONNECT fix and its coverage already live on main, so this PR now only aligns the realtime presence message with PUT /v1/presences/:presenceId.
@ChiragAgg5k ChiragAgg5k changed the title fix: realtime presence and subscribe limits, MQTT second-CONNECT test fix(realtime): validate presence message ID and metadata like the HTTP endpoint Oct 23, 2026
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@ChiragAgg5k
ChiragAgg5k merged commit 15c1cd4 into main Oct 23, 2026
19 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the fix/realtime-mqtt-hygiene branch October 23, 2026 10:48

@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

->param('presenceId', 'unique()', new Text(36), 'Presence document ID', true)
->param('metadata', null, new JSONObject(), 'Optional metadata payload', true, [], true)
->param('presenceId', CustomId::UNIQUE, new CustomId(), 'Presence document ID', true)
->param('metadata', null, new Nullable(new JSONObject()), 'Optional metadata payload', true)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Encoded JSON strings pass the metadata object check

JSONObject also accepts strings containing encoded JSON objects, so a frame like {"metadata":"{\"x\":1}"} passes validation. This handler accepts the value as mixed and stores it unchanged, unlike the HTTP action's array|stdClass parameter, so metadata can be persisted and returned as a string rather than an object.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Realtime/Message/Handlers/Presence.php
Line: 34

Comment:
**Encoded JSON strings pass the metadata object check**

`JSONObject` also accepts strings containing encoded JSON objects, so a frame like `{"metadata":"{\"x\":1}"}` passes validation. This handler accepts the value as `mixed` and stores it unchanged, unlike the HTTP action's `array|stdClass` parameter, so metadata can be persisted and returned as a string rather than an object.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟡 Minor · bug · Reply if this doesn't apply.

ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ackport #14829)

The realtime presence message accepted any 36-character text as the presence ID and skipped validation of metadata entirely. The ID now uses the custom ID validator and metadata is validated as JSON, matching the HTTP presence endpoints on 1.9.

(cherry picked from commit 15c1cd4)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ackport #14829)

The realtime presence message accepted any 36-character text as the presence ID and skipped validation of metadata entirely. The ID now uses the custom ID validator and metadata is validated as JSON, matching the HTTP presence endpoints on 1.9.

(cherry picked from commit 15c1cd4)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ackport #14829)

The realtime presence message accepted any 36-character text as the presence ID and skipped validation of metadata entirely. The ID now uses the custom ID validator and metadata is validated as JSON, matching the HTTP presence endpoints on 1.9.

(cherry picked from commit 15c1cd4)
Tapraj-Pathak pushed a commit to Tapraj-Pathak/appwrite that referenced this pull request Oct 24, 2026
…iene

fix(realtime): validate presence message ID and metadata like the HTTP endpoint

(cherry picked from commit 15c1cd4)
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.

1 participant