Skip to content

feat(mqtt): optional broker-side TLS termination for mqtts - #14249

Closed
ArnabChatterjee20k wants to merge 7 commits into
mainfrom
mqtt-tls-termination
Closed

ArnabChatterjee20k wants to merge 7 commits into
mainfrom
mqtt-tls-termination

Conversation

@ArnabChatterjee20k

Copy link
Copy Markdown
Member

What

Let the MQTT broker terminate TLS for raw MQTT (mqtts) itself, instead of always relying on a TLS-terminating proxy in front of it.

When _APP_MQTT_TLS_CERT and _APP_MQTT_TLS_KEY are set, the broker starts an mqtts TLS listener (default port 8883) alongside the existing plaintext listeners. When they are unset, nothing changes: only the plaintext 1883/8083 listeners run and TLS terminates upstream as today.

Why

A load balancer can then reach the broker directly, without a reverse proxy in the path. That removes the broker from a shared proxy's config-reload churn (which briefly disrupts raw-TCP passthrough routes), while HTTP/WebSocket traffic is unaffected.

How

  • Tls becomes a transport decorator. It wraps any transport and adds SWOOLE_SSL to its sock type plus ssl_cert_file/ssl_key_file to its settings, so one class serves both mqtts (over Tcp) and, later, wss (over WebSocket). Transport::isWebSocket() is added and the wrapper delegates it, so a secure WebSocket is still chosen as the Swoole master listener.
  • Worker (app/mqtt.php) adds the mqtts Tls(Tcp(...)) listener only when a cert is configured. It runs next to the plaintext listener, so no cutover.
  • Env _APP_MQTT_TLS_CERT, _APP_MQTT_TLS_KEY, _APP_MQTT_TLS_PORT registered in app/config/variables.php and passed through in docker-compose.yml.

Scope

  • mqtts only. wss termination in the broker is a follow-up (the decorator already supports it, but it is a WebSocket-master cutover).
  • Cert renewal is handled at deploy time (restart on Secret change); the broker loads the cert at startup.

Verification

  • php -l clean on all changed files
  • PHPStan clean (worker + package)
  • Package unit tests pass (E2E require Swoole, run in CI)

🤖 Generated with Claude Code

ArnabChatterjee20k and others added 2 commits October 8, 2026 12:58
Tls now wraps another transport and adds SSL to its sock type and settings, so
one class serves both mqtts (over Tcp) and wss (over WebSocket). Transport gains
isWebSocket(), which the wrapper delegates to the inner transport, so a secure
WebSocket is still selected as the Swoole master listener.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The broker starts an mqtts TLS listener alongside the plaintext one when
_APP_MQTT_TLS_CERT and _APP_MQTT_TLS_KEY are set, so a load balancer can reach it
without a TLS-terminating proxy in the path. The listener is off by default, so
the existing upstream-termination path is unchanged.

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

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

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Misconfigured TLS envs fail silently or crash the broker — mqtt.php:226
🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Tls wrapping WebSocket breaks as a non-master listener (Swoole.php:75) — Tls::isWebSocket() reports true for a wrapped WebSocket transport (packages/mqtt/src/Adapter/Swoole/Tls.php:28), and Adapter\Swoole only dispatches WebSocket message events on the master server (comment at packages/mqtt/src/Adapter/Swoole.php:57).

This PR enables TLS termination in the MQTT broker: env vars are added, Tls is refactored into a wrapper delegating to an inner Transport, the Swoole adapter gains isWebSocket() dispatch, and docker-compose forwards the new variables. The refactor is behaviorally equivalent for the current Tcp usage and SSL settings apply correctly via port->set(). Two low-friction robustness gaps remain around multi-websocket listener setups and TLS env validation.

Files Change
app/config/variables.php, docker-compose.yml New _APP_MQTT_TLS_CERT/_APP_MQTT_TLS_KEY variables and their passthrough into the MQTT container.
app/mqtt.php Conditionally wraps the TCP transport in Tls when both cert and key env vars are set.
packages/mqtt/src/Adapter/Swoole/Tls.php, Transport.php Tls refactored into a delegating wrapper applying SWOOLE_SSL and SSL settings to the listener.
packages/mqtt/src/Adapter/Swoole.php, WebSocket.php Adapter dispatches WebSocket-capable transports to the master server; minor WebSocket adapter touch-ups.

Reviewed commit: 93ab8df

@ghost

ghost commented Oct 8, 2026 •

Copy link
Copy Markdown

🟡 Tier B · Needs changes before merging

The new TLS configuration disables the existing plaintext MQTT-over-WebSocket endpoint for deployments that enable mqtts.

Adds optional broker-side TLS termination for MQTT TCP, configured with certificate, key, and port environment variables, and generalizes the Swoole TLS transport wrapper. The PR also adds TLS fixture coverage for the MQTT package and configures the application broker to use TLS on its WebSocket listener when TLS credentials are present.

Latest changes: The newest commits wrap the application WebSocket listener in TLS on the existing WebSocket port whenever MQTT TLS credentials are configured, replacing the plaintext WebSocket listener in that mode.

Verdict New comments Fixed Still open
🛑 Changes requested 1 0 0
Finding Where
🟠 Keep the plaintext WebSocket listener when enabling mqtts app/mqtt.php:247
Fix with agent prompt
### Issue 1
app/mqtt.php:247-253
**Keep the plaintext WebSocket listener when enabling mqtts**

When operators set these credentials to enable mqtts, this replaces the existing plaintext WebSocket listener on `_APP_MQTT_WS_PORT` with a TLS WebSocket listener. Existing MQTT-over-WebSocket clients or TLS-terminating proxies still connecting there send plaintext and fail the TLS handshake, contrary to the PR's mqtts-only, additive behavior; keep the plaintext listener and introduce WSS separately.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 11
File Change
app/config/variables.php Registers environment variables for the optional MQTT TLS certificate, key, and port.
app/mqtt.php Validates optional TLS credentials and configures TLS-wrapped TCP and WebSocket transports alongside the plaintext TCP listener.
docker-compose.yml Passes the MQTT TLS environment variables through to the broker container and mounts certificate files.
packages/mqtt/README.md Updates the transport example to wrap a TCP transport with TLS.
packages/mqtt/src/Adapter/Swoole.php Uses the transport WebSocket marker to select the Swoole master listener.
packages/mqtt/src/Adapter/Swoole/Tls.php Implements TLS as a transport decorator that preserves the wrapped transport's type and settings.
packages/mqtt/src/Adapter/Swoole/Transport.php Adds a default non-WebSocket transport marker.
packages/mqtt/src/Adapter/Swoole/WebSocket.php Marks WebSocket transports for Swoole listener selection.
packages/mqtt/tests/E2E/TlsAdapterTest.php Exercises an MQTT 5 session through a TLS listener.
packages/mqtt/tests/Fixtures/Swoole/server.php Optionally starts a TLS-wrapped TCP transport for end-to-end tests.
packages/mqtt/tests/e2e.sh Generates a temporary certificate and waits for the TLS fixture listener before running E2E tests.

Reviewed the commits since f13730b · 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 docker-compose.yml Resolved
@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

32 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (17)
  • php.appwrite.permissive-write-permission (8)
  • 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.

@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 broker-side MQTT-over-TLS support (mqtts on port 8883) via a refactored Tls transport wrapper, new _APP_MQTT_TLS_* env vars, and docker-compose wiring.

Key findings

  • 🟡 Misconfigured TLS envs fail silently or crash the broker — mqtt.php:226

Comment thread app/mqtt.php Outdated
Comment on lines +226 to +232
if ($tlsCert !== '' && $tlsKey !== '') {
$transports[] = new Adapter\Swoole\Tls(
new Adapter\Swoole\Tcp('0.0.0.0', (int) System::getEnv('_APP_MQTT_TLS_PORT', '8883'), $maxPacketSize),
$tlsCert,
$tlsKey,
);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 bug · medium

Misconfigured TLS envs fail silently or crash the broker

TLS is enabled only when both _APP_MQTT_TLS_CERT and _APP_MQTT_TLS_KEY are non-empty (app/mqtt.php:226); setting just one is accepted silently and 8883 never opens, with no server-side signal. Setting both to missing or unreadable paths gives no pre-check either — the values flow straight into Swoole ssl_cert_file/ssl_key_file and abort server startup opaquely, taking down plain MQTT 1883 and WebSocket 8083 along with mqtts. Operators misconfiguring TLS thus get either a silently insecure broker or an undiagnosed crash.

📋 Prompt for AI Agents

In app/mqtt.php around lines 224-232, before the if ($tlsCert !== '' && $tlsKey !== '') block, add validation: if exactly one of _APP_MQTT_TLS_CERT/_APP_MQTT_TLS_KEY is set (logical XOR), log a Console::error naming the missing variable and stating TLS stays disabled. Inside the block, check is_readable($tlsCert) && is_readable($tlsKey) and fail fast with an error naming the offending path, so operators get an actionable diagnostic instead of a silent plaintext fallback or an opaque Swoole startup abort.

ArnabChatterjee20k and others added 3 commits October 8, 2026 13:06
The broker now reads its TLS cert/key from disk, so give appwrite-mqtt the same
read-only /storage/certificates volume Traefik and the app containers already have.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The fixture broker adds an mqtts listener on 18832 from a self-signed cert that
e2e.sh generates, and a new E2E test runs a full v5 session over it. This exercises
the Tls transport's socket flags and SSL listener settings against real Swoole.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → mqtt-tls-termination (after).

Metric Before After Change
🚀 Requests/sec 182.86 188.88 ⚪ +3.3%
⏱️ Latency P50 93.25 ms 91.24 ms ⚪ -2.2%
⏱️ Latency P95 232.23 ms 217.29 ms 🟢 -6.4%
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 91.24 217.29 11,856 188.88 -14.93
Account 177.39 340.11 624 10.34 -17.38
TablesDB 87.02 164.57 6,448 104.82 -18.1
Storage 85.2 187.29 3,120 52.33 +11.97
Functions 134.63 262.54 1,664 28.61 -16.91

Top API waits (after)

API request Max wait (ms)
account.name.update 491.35
account.prefs.update 455.11
functions.create 445.96
functions.delete 439.18
functions.variables.update 423.23

@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

Require both _APP_MQTT_TLS_CERT and _APP_MQTT_TLS_KEY together, and check each
path is readable, before building the listener. A half-configured or unreadable
cert now exits with a clear message instead of silently skipping mqtts or letting
Swoole abort startup and take the plaintext listeners down with it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
When a certificate is set the broker serves the WebSocket listener over TLS (wss)
too, so a load balancer can reach both transports directly without a proxy. Only
one WebSocket listener can be the Swoole master, so wss replaces the plaintext
WebSocket rather than running beside it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ghost
ghost previously requested changes Oct 8, 2026

@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 · 1 blocking finding to address. Summary

Comment thread app/mqtt.php
Comment on lines +247 to +253
$transports[] = new Adapter\Swoole\Tls(
new Adapter\Swoole\WebSocket('0.0.0.0', $wsPort, $maxPacketSize),
$tlsCert,
$tlsKey,
);
} else {
$transports[] = new Adapter\Swoole\WebSocket('0.0.0.0', $wsPort, $maxPacketSize);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Keep the plaintext WebSocket listener when enabling mqtts

When operators set these credentials to enable mqtts, this replaces the existing plaintext WebSocket listener on _APP_MQTT_WS_PORT with a TLS WebSocket listener. Existing MQTT-over-WebSocket clients or TLS-terminating proxies still connecting there send plaintext and fail the TLS handshake, contrary to the PR's mqtts-only, additive behavior; keep the plaintext listener and introduce WSS separately.

Prompt To Fix With AI
This is a comment left during a code review.
Path: app/mqtt.php
Line: 247-253

Comment:
**Keep the plaintext WebSocket listener when enabling mqtts**

When operators set these credentials to enable mqtts, this replaces the existing plaintext WebSocket listener on `_APP_MQTT_WS_PORT` with a TLS WebSocket listener. Existing MQTT-over-WebSocket clients or TLS-terminating proxies still connecting there send plaintext and fail the TLS handshake, contrary to the PR's mqtts-only, additive behavior; keep the plaintext listener and introduce WSS separately.

---

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

🟠 Major · bug · Reply if this doesn't apply.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@hansi-codes the swoole websocket doesn't allow both wss and ws listener together on the same server

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

That Swoole limitation is real: this adapter handles WebSocket messages only on the primary WebSocket listener (Swoole.php). But the PR is scoped to mqtts, so it should not add a WSS listener at all. Keep the existing plaintext WebSocket transport and add only Tls(Tcp(...)) for mqtts; WSS can be handled separately if needed. As written, setting the mqtts cert changes the existing WebSocket port to TLS (app/mqtt.php), breaking existing plaintext WebSocket clients and proxy routes.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@hansi-codes we need to do it for both mqtts and wss as both are used. so can you approve

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I can’t approve this as-is. The existing WSS route terminates TLS at Traefik and forwards plaintext to the broker on port 8083 (compose config). With these certs set, the code instead makes that same broker listener expect TLS (app/mqtt.php), so the existing proxy route will fail.

The Swoole limitation explains why both WebSocket modes can’t share this server; it doesn’t make changing the existing listener safe. For this mqtts change, keep the plaintext WebSocket listener and add only the TLS-wrapped TCP transport. Broker-side WSS needs a deliberate migration, including updating the proxy’s upstream behavior.

@ArnabChatterjee20k
ArnabChatterjee20k dismissed ghost ’s stale review October 8, 2026 08:24

stale review

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