Skip to content

Forward a robot's Matter key request to Roborock's cloud (opt-in) - #252

Merged
Lash-L merged 13 commits into
Python-roborock:mainfrom
virtitnerd:pr/matter-key-forwarding
Nov 29, 2026
Merged

Lash-L merged 13 commits into
Python-roborock:mainfrom
virtitnerd:pr/matter-key-forwarding

Conversation

@virtitnerd

@virtitnerd virtitnerd commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Why

A robot can only join a Matter controller once it has a Matter key, which Roborock's cloud issues. A robot paired to
the local server asks the local server for it, and nothing answers, so Matter setup fails.

What

When the robot is told to download its key, it calls GET /iot.roborock.com/fwapi/matter/key on the server it was
paired to, using the server name with the api- prefix removed (the same rule the camera follows). With
[matter] key_proxy = true (or ROBOROCK_SERVER_MATTER_KEY_PROXY=true, which wins) the server passes that request,
with the robot's own headers, to the regional cloud host and returns the answer unchanged. Off by default.

Enabling it sends the robot's id, its signature and its headers, plus this server's IP address, to Roborock. See
"What is sent to Roborock" in docs/matter.md.

Guards on the route:

  • It forwards only when the request names a paired robot (a did or duid query value this server knows) or, when it
    names none, comes from the address of a robot that has connected to this server. Otherwise 403. The query is limited
    to 16 plain key=value params and 1 KiB (400 otherwise). The check is an identifier, not a credential, and the
    address fallback is weak behind NAT.
  • The query is forwarded exactly as received, with no re-encoding.
  • Headers are filtered with a denylist: hop-by-hop headers, Host, Cookie, Forwarded, Via, Origin,
    Referer, Proxy-*, X-Real-IP, True-Client-IP, X-Forwarded-*, CF-*, Sec-*, X-Envoy-*, X-Amzn-*, this
    server's sync-secret header, and any value over 2 KiB. There is no allowlist of header or query names, because the
    robot's real names have not been captured and the query is signed.
  • Each client address may make 10 requests a minute to the route (429 beyond that, refused requests counted).
  • The region must be us, eu, cn or ru; anything else is refused with a 502 and no request.
  • For this route the request log keeps only header names and query names (values are <redacted>), the answer's
    status and size, and never the key. Two things outside the route are described in docs/matter.md: the device key
    cache still stores signed queries for key recovery, as it does for every robot request, and with the proxy off the
    request is logged like any other unknown path.

The stripped name also needs a DNS record and a certificate. Without the record the robot fails within seconds and no
request ever reaches the server; the new docs/matter.md explains it.

Testing

tests/test_matter_proxy.py has 23 tests (it had 4). They run forward() against an aiohttp test server for header
filtering, query pass-through, response and error relay, the 502 and timeout paths and the region check, plus route
tests for the known and unknown robot, the rate limit, the log contents and the disabled case. Full suite: 524
passed.

On a Qrevo Curv 2 Flow the robot went from KeyNotExit through KeyDownloading to Ready with a setup code, and a
Matter controller (UniFi Network) added it. That run was before the guards above were added. The new code has not been
run against a real robot yet, so a live Matter key run is still to do.

Related

#68 (documentation on Matter versus this integration). #229 (the same stripped-hostname mechanism for the camera).

@Lash-L Lash-L added the feature PR adding capability; under this two-type scheme also covers additive documentation. label Nov 15, 2026

@Lash-L Lash-L left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated review: changes requested

It's opt-in and small, but the docs make a wrong privacy claim, and the forwarding code itself has no tests.

Confirmed:

  • The app's only part is the RPC matter.dnld_key with {} (downloadMatterKey in the tanos bundle). The robot does the HTTP fetch itself.
  • The regional hosts us/eu/cn/ru + iot.roborock.com are real.
  • The documented status names match the bundle's MatterStatus enum.
  • It's off by default, and upstream TLS is verified (the aiohttp default).

Unverifiable: nothing in our references shows the robot's HTTP request, so GET /fwapi/matter/key, its auth and the KeyCorrupt-when-disabled behaviour rest on your observation. One risk: the robot reaches us at /iot.roborock.com/fwapi/matter/key, but the proxy sends /fwapi/matter/key upstream with a different Host. If the robot signs the path or host, the cloud may reject it.

Blocking:

  1. The doc's privacy claim is wrong. docs/matter.md says only header and query names are logged, never their values. The shared request log (server.py:1059, _headers_for_log) writes every header value except the sync secret, plus the query, to http_jsonl, so the robot's cloud credentials end up on disk. Fix the doc, or redact this route's entry.
  2. No auth on the route. /fwapi/... isn't covered by _required_protocol_auth, so anyone who can reach the server can make it send GETs, with any headers and query they choose, to Roborock from the user's IP. Host and path are fixed, so it isn't a general open proxy. Allowlist the forwarded headers and query keys, or require a known DUID.

Should fix:
3. Validate the region against {us, eu, cn, ru} (matter_proxy.py:31).
4. Strip X-Forwarded-*, Cookie and similar headers before forwarding (matter_proxy.py:21).
5. Narrow except Exception to aiohttp.ClientError / asyncio.TimeoutError (matter_proxy.py:51-53).
6. Say in config.example.toml that enabling this sends data to Roborock, and say in the doc which robot identifiers and signatures are sent.
7. Tests: the end-to-end test replaces forward() entirely, so header filtering, the 502 path, the response relay and the timeout never run. Add a test against an aiohttp test server, plus one for the disabled case.

I've converted this PR to draft while these are addressed. Mark it ready for review again once they're fixed and it will go through another review.


This is an automated review by Claude Code, checked against the decompiled Roborock app (APK + device plugin bundles), python-roborock and a vacuum firmware dump. It can be incorrect, so please reply if any finding looks wrong.

@Lash-L Lash-L added the failing auto review Automated review requested changes before merge label Nov 21, 2026
@Lash-L
Lash-L marked this pull request as draft November 21, 2026 16:07
virtitnerd and others added 4 commits November 21, 2026 19:13
A robot paired to this server asks it for its Matter key, which only Roborock's
cloud issues. With [matter] key_proxy = true (or ROBOROCK_SERVER_MATTER_KEY_PROXY=true)
the request is passed on to the regional cloud host with the robot's own headers
and the answer is returned unchanged. Off by default.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…he log

The route had no check on who calls it and forwarded every header and the
query as received. It now refuses requests that do not name a paired robot
(did/duid in the query) or come from a connected robot's address, bounds the
query shape, drops hop, proxy, cookie and X-Forwarded-* headers, accepts only
the regions us/eu/cn/ru, and catches only aiohttp.ClientError and timeouts.
The shared request log keeps only header and query names for this route.
Tests run the real forward() against an aiohttp test server.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The old text said header and query values are never logged, which was wrong
for the shared request log. State what is sent, what is checked and what is
logged, and warn in config.example.toml that enabling it sends data to Roborock.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@virtitnerd
virtitnerd force-pushed the pr/matter-key-forwarding branch from a9fb8a5 to 0377625 Compare November 22, 2026 02:39
@virtitnerd

Copy link
Copy Markdown
Contributor Author

Thanks for the review. The branch is rebased onto current main with four new commits (c887373, 1f6afee, 8752a03, 0377625). Going through it by number.

  1. Privacy claim. You were right. For this route the request log now keeps only header names and query names (values become <redacted>), and raw_path is written without the query string (c887373). The doc says exactly what is logged (1f6afee). Two things outside the route are noted there: the device key cache still stores signed queries for key recovery, as it does for every robot request, and with the proxy switched off the request is logged like any other unknown path.
  2. No auth. The route forwards only when the request names a paired robot (a did or duid query value this server knows) or, when it names none, comes from the address of a robot that has connected to this server. Otherwise it answers 403, and a malformed or oversized query gets 400 (c887373). That gate is an identifier, not a credential, and the second condition is weak behind NAT. The robot's request is not signed with anything this server can verify, so I could not make it stronger. I did not add the strict header and query-key allowlist you suggested. Nobody has captured the robot's real header and query names (the log line we had showed only the path), and the query is signed, so dropping a key could break the signature. Instead the forwarding uses a denylist (see 4), the query is limited to 16 plain key=value params and 1 KiB, and the query is sent upstream exactly as received, with no re-encoding (8752a03). To limit what a known id can be used for, each client address gets 10 requests a minute on this route, counting refused ones, and 429 beyond that (8752a03, documented in docs/matter.md in 0377625). The console log lists the names forwarded, so one real run will give us the actual names if you want a strict allowlist later.
  3. Region. upstream_url accepts only us, eu, cn and ru and raises otherwise. forward answers 502 without making a request for any other value. Before, an unknown value silently fell back to us (c887373).
  4. Headers. Dropped before forwarding: Host, Connection, Content-Length, Accept-Encoding, Transfer-Encoding, Keep-Alive, Upgrade, TE, Trailer, Cookie, Forwarded, Via, Origin, Referer, Proxy-*, X-Real-IP, True-Client-IP, X-Forwarded-*, CF-*, Sec-*, X-Envoy-*, X-Amzn-* and this server's sync-secret header. Values over 2 KiB are dropped too, with a debug log line (c887373, 8752a03).
  5. Exceptions. Now except (aiohttp.ClientError, asyncio.TimeoutError) (c887373).
  6. Disclosure. config.example.toml says that enabling it sends the robot's id, signature and headers, plus this server's IP, to Roborock. docs/matter.md has a "What is sent to Roborock" section (1f6afee).
  7. Tests. forward() is no longer replaced. New tests run it against an aiohttp test server for header filtering, query pass-through (including did=a%zz&sig=%41%7e+x%2Fy arriving unchanged), response and error-status relay, the 502 on an unreachable host, the timeout and an unsupported region. Route tests cover the known robot (200), the unknown robot (403), a log with no header or query values, the rate limit, and the disabled case (nothing forwarded, nothing logged). tests/test_matter_proxy.py has 23 tests, up from 4.

Path and Host. This was observed live on 2026-11-12 with a Qrevo Curv 2 Flow. The robot sent GET /iot.roborock.com/fwapi/matter/key with the server's own name as Host (the api- prefix removed) and an empty body. The server forwarded it as GET https://usiot.roborock.com/fwapi/matter/key with the robot's headers minus Host. Roborock accepted it: the robot went from KeyCorrupt to Ready and returned a setup code. So the cloud did not reject the changed path or Host. I do not know whether the robot signs the path, only that the signature, if any, still validated. That run was one robot and one region (us), and it was before this review's changes.

Not verified. The new code has not been run against a real robot yet. The header filtering is stricter now, the known-robot gate depends on the robot's address and on did or duid in the query, and the rate limit is new, so a live Matter-key run is still needed. It is covered by tests only.

Full suite on this head: 524 passed, plus one failure in tests/test_log_retention.py, which is intermittent on main too. This PR stays in draft as you set it; it is ready for another review whenever you want to run one.

virtitnerd and others added 2 commits November 21, 2026 22:02
… checks

yarl re-encoded the query (%41%7e became A~), which can break a signature the
cloud checks over the raw query; the URL is now built with encoded=True. The
unused MAX_HEADERS is gone and dropped headers are logged at debug. The query
checks now read the raw query, so a client-supplied __host key is not exempt.
A per-address limit of 10 requests a minute returns 429, because the did/duid
gate is an identifier, not a credential.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@virtitnerd
virtitnerd force-pushed the pr/matter-key-forwarding branch from 0377625 to aee8a15 Compare November 22, 2026 03:02

@Lash-L Lash-L left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated review: passed (re-review at aee8a154)

Now that this has passed the automated review, I'll do a human review and then either request changes or merge it. It's still a draft, so mark it ready when you're done.

Earlier findings:

Finding Status
Doc's privacy claim vs. the http_jsonl log Fixed. redact_log_entry keeps only header and query names, and a test checks it. The doc's "What is logged" section is accurate now.
No auth on /fwapi Partly fixed, accepted. It now needs a known did/duid or a known robot's IP, with trusted_proxies respected. Bad queries get 400, and there's a limit of 10 requests a minute per IP. The robot's real header names were never captured, so a strict allowlist isn't possible, and the doc says the gate is weak.
Region validation, header denylist, narrowed except, config/doc disclosure, real forward() tests Fixed.
Path/Host rewrite vs. the robot's signature Unverifiable from our sources. RR_API only has matter.dnld_key/get_status/reset. Your Nov 12 live run reached Ready, but on the code from before these fixes.

Before merge: please do one live matter.dnld_key run on the new code. It's the first time the denylist, the device/IP gate and the rate limit meet a real robot.

Nits:

  • server.py:1278: self.__dict__.setdefault("_matter_limiter", …) should be set up in __init__.
  • This route skips runtime_state.record_http_event.
  • With the proxy off, the signed query is still logged unredacted. Apply redact_log_entry whenever matches() is true.
  • _DID_KEYS includes keys like d/device_id that no robot request is known to use. Trim them, or update the doc.

Checks: all 525 tests pass.


This is an automated review by Claude Code, checked against the decompiled Roborock app (APK + device plugin bundles, refreshed 2026-11-21), python-roborock and a vacuum firmware dump. It can be incorrect, so please reply if any finding looks wrong.

@Lash-L Lash-L added passed auto review Automated review found no blocking issues and removed failing auto review Automated review requested changes before merge labels Nov 22, 2026
virtitnerd and others added 4 commits November 22, 2026 11:09
The limiter was created lazily through self.__dict__.setdefault in the request handler. Building it once in the constructor is simpler and has the same behaviour.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Every other route calls runtime_state.record_http_event, so this one was missing from the recent events. The event carries the path without the signed query, and the ids are left out when the request was refused so an unauthenticated id cannot create a robot record.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The signed query and the headers were written to http_jsonl unredacted whenever key_proxy was off, because redaction only ran inside the proxy branch. It now runs for every request that matches the route, and the doc no longer lists the proxy-off log as an exception.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The other keys (d, device_id, deviceId, device_did, deviceDid) were copied from the generic id extractor and no robot request is known to use them on this route. The doc already described the gate as did or duid.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@Lash-L Lash-L left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated review: passed (nits)

Now that this has passed the automated review, I'll do a human review and then either request changes or merge it.

This PR is still a draft. It was converted after the 2026-11-21 review and nobody has marked it ready since, so please mark it ready for review when you're done.

Since the last review (aee8a15 → 0a8fd30)

Earlier nit Status
_matter_limiter set up lazily via __dict__.setdefault Fixed. Now created in ReleaseSupervisor.__init__ (server.py:352).
Route skipped record_http_event Fixed. It now records the event (server.py:1293-1308) with raw_path=clean_path, and ids are recorded only when the request was admitted. A test covers it.
Signed query logged unredacted with the proxy off Fixed for http_jsonl. redact_log_entry now runs whenever matches() is true (server.py:1066-1067). The disabled-case test checks that header and query values are gone.
_DID_KEYS included d/device_id/... Fixed. The gate now matches only did and duid (matter_proxy.py:42), and a test confirms that device_id no longer passes.

Unchanged and still fine: it's off by default (MatterConfig.key_proxy = False, and the env var only overrides when set). The upstream host is fixed to {us,eu,cn,ru}iot.roborock.com/fwapi/matter/key, so it isn't an open proxy. The rate limiter is synchronous inside one event-loop step, so there's no race, and it uses the client address after ProxyHeadersMiddleware, which is scoped to trusted_proxies.

Nits

  1. An admitted request can still create a robot record for an unchecked id (server.py:1305). The gate checks only did/duid, but the event records explicit_did, which comes from _DEVICE_ID_KEYS (did, d, duid, device_id, ..., context.py:20) with d ahead of duid. So ?duid=<known>&d=ghost passes the gate and records did=ghost, and record_http_event then creates a robot ghost with the caller's IP in its ips. I reproduced this against the PR head. The same happens through the address fallback with no did/duid and just d=ghost. The code comment says the ids are left out so the event can't create a robot record, but that only holds for refused requests. Fix: record the id that actually matched. Have known_device return the matched paired robot's duid/did (or None), and pass that, not explicit_did.
  2. With the proxy off, the in-memory event still has the signed query. The catch-all (server.py:1412-1416) passes the unredacted local raw_path to record_http_event. recent_events() isn't served by any route today, so nothing leaks. Still, setting raw_path = clean_path when matches() is true (next to the redaction at line 1067) keeps it consistent with the doc.
  3. docs/matter.md: one line in the "What is logged" paragraph now runs past the 120-column wrap the rest of the file uses.

Before merge (unchanged): one live matter.dnld_key run on this code. Path/Host rewriting and the robot's real header/query names are still unverifiable from our sources (RR_API only has the matter.dnld_key/get_status/reset RPCs).

Overlap: merges cleanly with main and #261. It conflicts with #255 in config.py, server.py (imports), config.example.toml and mkdocs.yml. In every one, both sides add a sibling (MatterConfig/OtaConfig, nav entries), so keeping both resolves it.

Checks: all 526 tests pass on 0a8fd30.


This is an automated review by Claude Code, checked against the decompiled Roborock app (APK + device plugin bundles), python-roborock and a vacuum firmware dump. It can be incorrect, so please reply if any finding looks wrong.

@Lash-L
Lash-L marked this pull request as ready for review November 25, 2026 01:38
Copilot AI balanced review requested due to automatic review settings November 25, 2026 01:38

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

virtitnerd and others added 3 commits November 24, 2026 20:48
known_device now returns the matched robot's id instead of a bool, and that id is what the HTTP event records. Before, the event used the first id found among all id keys, so ?duid=<known>&d=ghost (or d=ghost alone through the address fallback) passed the gate and then created a robot record for the unchecked id.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The catch-all passed the unredacted local raw_path to record_http_event, so the recent-events list still carried the robot's signed query when the proxy was off. The path is now reduced to clean_path next to the log redaction.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
One line ran past the 120-column wrap used in the rest of the file.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@Lash-L Lash-L left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated review: passed

Now that this has passed the automated review, I'll do a human review and then either request changes or merge it.

This PR is still a draft, so please mark it ready for review when you're done.

Since the last review (0a8fd30 → 8752d45)

Three commits landed after the 2026-11-25 review. Together they address all three of its nits.

Earlier nit Status
An admitted request could create a robot record for an unchecked id (?duid=<known>&d=ghost) Fixed (4092083). known_device now returns the matched robot's duid (or did), or None (matter_proxy.py:96-107). The route records only that id (server.py:1305). pid and model are recorded only when a robot matched. New tests cover both the duid + d=ghost case and the address-fallback case.
Signed query in the in-memory event with the proxy off Fixed (fb9670b). raw_path = clean_path now sits next to the redaction whenever matches() is true (server.py:1066-1068). After that line, raw_path is only passed to record_http_event, so the catch-all and the blocked-flow branches get the clean path too. The device key cache reads request.url.query directly (server.py:1032-1041) and is unaffected, as the doc says. A new test confirms that the secret value is absent from every recent event.
docs/matter.md line past 120 columns Fixed (8752d45). Rewrap only, same wording.

The gate order changed slightly: rate limit, then query shape, then known_device. The outcomes are the same as before (429 / 400 / 403 / forward). The 400 and 429 paths now also record did=None, which is correct.

Re-confirmed, unchanged by these commits:

  • Off by default. MatterConfig.key_proxy = False, and ROBOROCK_SERVER_MATTER_KEY_PROXY overrides only when it is set (confirmed, config.py).
  • No open proxy. The upstream is fixed per region to {us,eu,cn,ru}iot.roborock.com/fwapi/matter/key, the path is not taken from the request, the query is capped at 16 key=value params / 1 KiB, and Host and hop-by-hop headers are dropped (confirmed, matter_proxy.py).
  • Secrets stay out of http_jsonl and the console log, with the proxy on or off (confirmed, redact_log_entry).
  • The only app-side part is the matter.dnld_key RPC. The robot makes the HTTP request itself (confirmed in the device plugin bundles).

Nit (optional)

  1. In the address fallback (matter_proxy.py:104-106), several robots behind one NAT address all resolve to the first one in the snapshot. The event then updates that robot's last_http_* fields even if a different robot made the request. Without a did/duid in the query this is inherent, so a code comment noting it would be enough.

Before merge (unchanged): one live matter.dnld_key run on this code. The robot's real header and query names, and whether it needs Host or path rewriting, are still unverifiable from our sources. The firmware dump has no fwapi Matter request we could match, and iOS is not covered.

Overlap: merges cleanly with main and #261. It still conflicts with #255 in config.example.toml, mkdocs.yml, config.py and server.py. In each file both sides add a sibling block (MatterConfig/OtaConfig, nav entries), so keeping both sides resolves it.

Checks: all 529 tests pass on 8752d45 (526 before, plus 3 new).


This is an automated review by Claude Code, checked against the decompiled Roborock app (APK + device plugin bundles), python-roborock and a vacuum firmware dump. It can be incorrect, so please reply if any finding looks wrong.

@virtitnerd

Copy link
Copy Markdown
Contributor Author
  1. Robot record for an unchecked id: fixed in 4092083. Confirmed: the gate looked only at did/duid, but the event used the first id found among all id keys, so ?duid=<known>&d=ghost (and ?d=ghost through the address fallback) created a robot "ghost". known_device now returns the matched robot's id (or None) and that id is what the event records. pid and model are only recorded for an admitted request. Two new tests cover the d=ghost with known duid case and the address-fallback case; both fail without the change and check that no "ghost" robot exists.

  2. Signed query in the in-memory event with the proxy off: fixed in fb9670b. Confirmed: the catch-all passed the unredacted local raw_path to record_http_event. raw_path is now set to clean_path next to the log redaction. New test checks the recent events carry no query value.

  3. Doc line over 120 columns: fixed in 8752d45. The "What is logged" paragraph is rewrapped.

The full suite passes (529 passed), and tests/test_matter_proxy.py now has 27 tests. known_device returns the matched robot id instead of a bool; I will update the description to say so.

@Lash-L

Lash-L commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Hey @virtitnerd - this looks good. I will admit I am not fully familiar with how matter all works. I think this could benefit from some experimentation/ results from your real server (e.g. does it hit multiple times or is it truly a one and done. Can the same token be reused, etc.)

But good for now and a welcomed addition!

@Lash-L
Lash-L merged commit 60560ac into Python-roborock:main Nov 29, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature PR adding capability; under this two-type scheme also covers additive documentation. passed auto review Automated review found no blocking issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants