From 4a5daf18b62353d0e7fd5d38f589d39f9b601f23 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:19:49 -0500 Subject: [PATCH 01/13] Forward a robot's Matter key request to Roborock's cloud 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 --- src/roborock_local_server/config.py | 21 +++++++++ src/roborock_local_server/matter_proxy.py | 56 +++++++++++++++++++++++ src/roborock_local_server/server.py | 8 ++++ tests/test_matter_proxy.py | 51 +++++++++++++++++++++ 4 files changed, 136 insertions(+) create mode 100644 src/roborock_local_server/matter_proxy.py create mode 100644 tests/test_matter_proxy.py diff --git a/src/roborock_local_server/config.py b/src/roborock_local_server/config.py index 14696311..6fb12c5e 100644 --- a/src/roborock_local_server/config.py +++ b/src/roborock_local_server/config.py @@ -4,6 +4,7 @@ from dataclasses import dataclass import ipaddress +import os from pathlib import Path import re import tomllib @@ -104,6 +105,13 @@ class TurnConfig: ttl: int = 86400 +@dataclass(frozen=True) +class MatterConfig: + """Matter setup for robots: the key a robot downloads comes from Roborock's cloud.""" + + key_proxy: bool = False + + @dataclass(frozen=True) class AppConfig: network: NetworkConfig @@ -113,6 +121,7 @@ class AppConfig: admin: AdminConfig turn: TurnConfig = TurnConfig() logging: LoggingConfig = LoggingConfig() + matter: MatterConfig = MatterConfig() @dataclass(frozen=True) @@ -249,6 +258,16 @@ def _as_bool(value: object, default: bool) -> bool: return bool(value) +def _matter_key_proxy_enabled(from_file: bool) -> bool: + """The env var wins when set, so the proxy can also be switched on for a config.toml that already exists.""" + override = os.environ.get("ROBOROCK_SERVER_MATTER_KEY_PROXY", "").strip().lower() + if override in {"1", "true", "yes", "on"}: + return True + if override in {"0", "false", "no", "off"}: + return False + return from_file + + def load_config(path: str | Path) -> AppConfig: config_path = Path(path).resolve() parsed = tomllib.loads(config_path.read_text(encoding="utf-8")) @@ -260,6 +279,7 @@ def load_config(path: str | Path) -> AppConfig: tls = _get_section(parsed, "tls") admin = _get_section(parsed, "admin") turn = _get_section(parsed, "turn") + matter = _get_section(parsed, "matter") turn_mode = str(turn.get("mode", "external" if _as_bool(turn.get("enabled"), False) else "disabled")).strip().lower() broker_mode = str(broker.get("mode", "embedded")).strip().lower() if broker_mode not in {"embedded", "external"}: @@ -347,6 +367,7 @@ def load_config(path: str | Path) -> AppConfig: cert_file=str(tls.get("cert_file", "")).strip(), key_file=str(tls.get("key_file", "")).strip(), ), + matter=MatterConfig(key_proxy=_matter_key_proxy_enabled(_as_bool(matter.get("key_proxy"), False))), admin=AdminConfig( password_hash=_require_non_empty(admin.get("password_hash"), "admin.password_hash"), session_secret=_require_non_empty(admin.get("session_secret"), "admin.session_secret"), diff --git a/src/roborock_local_server/matter_proxy.py b/src/roborock_local_server/matter_proxy.py new file mode 100644 index 00000000..3ddeb06e --- /dev/null +++ b/src/roborock_local_server/matter_proxy.py @@ -0,0 +1,56 @@ +"""Forwards a robot's Matter key request to Roborock's cloud. + +A robot asked to download its Matter key (``matter.dnld_key``) calls ``GET /iot.roborock.com/fwapi/matter/key`` +on the server it was paired to. The key is issued by Roborock's cloud, so with this switched on the request is +passed on to the regional cloud host and the answer handed back unchanged. Off by default: it sends the robot's +own request, with its own headers, to Roborock. +""" + +from __future__ import annotations + +import logging +import re + +from fastapi import Request +from fastapi.responses import Response + +logger = logging.getLogger("real_stack.api") + +_PATH = re.compile(r"^/(?:[A-Za-z0-9.-]+/)?fwapi/matter/key/?$") +# Headers that describe this hop, not the robot's request. +_DROPPED = {"host", "connection", "content-length", "accept-encoding", "transfer-encoding", "keep-alive", "upgrade"} +TIMEOUT_SECONDS = 20 + + +def matches(clean_path: str, method: str) -> bool: + return method.upper() == "GET" and _PATH.match(clean_path) is not None + + +def upstream_url(region: str, query: str) -> str: + code = region.strip().lower() + host = f"{code if re.fullmatch(r'[a-z]{2,3}', code) else 'us'}iot.roborock.com" + return f"https://{host}/fwapi/matter/key" + (f"?{query}" if query else "") + + +async def forward(request: Request, region: str) -> Response: + import aiohttp + + url = upstream_url(region, request.url.query) + headers = {name: value for name, value in request.headers.items() if name.lower() not in _DROPPED} + # Names only: the values are the robot's credentials for the cloud. + logger.info( + "Matter key request from %s: forwarding to %s (header names: %s; query names: %s)", + request.client.host if request.client else "-", url.split("?")[0], sorted(headers), sorted(request.query_params), + ) + try: + async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=TIMEOUT_SECONDS)) as session: + async with session.get(url, headers=headers) as upstream: + body = await upstream.read() + content_type = upstream.headers.get("Content-Type", "application/octet-stream") + status = upstream.status + except Exception as exc: # noqa: BLE001 + logger.warning("Matter key request could not reach Roborock: %s", exc) + return Response(content=b"", status_code=502) + logger.info("Matter key answer from Roborock: HTTP %d, %d bytes, %s", status, len(body), content_type) + return Response(content=body, status_code=status, media_type=content_type) + diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py index 99371d23..33caf98e 100644 --- a/src/roborock_local_server/server.py +++ b/src/roborock_local_server/server.py @@ -31,6 +31,7 @@ from .cloud import CloudImportManager from .config import AppConfig, AppPaths, load_config, resolve_paths from .log_retention import configure_jsonl_logging +from . import matter_proxy from .turn_relay import EmbeddedTurnRelay from .standalone_admin import register_standalone_admin_routes from .backend import ( @@ -1271,6 +1272,13 @@ async def _handle_roborock_request(self, request: Request) -> Response: ) return JSONResponse(response_payload, status_code=status_code) + if self.config.matter.key_proxy and matter_proxy.matches(clean_path, request.method): + proxied = await matter_proxy.forward(request, self.config.network.region) + entry["route"] = "matter_key_proxy" + entry["response_meta"] = {"status_code": proxied.status_code, "bytes": len(proxied.body)} + append_jsonl(self.context.http_jsonl, entry) + return proxied + try: plugin_dispatch = await dispatch_plugin_zip_request( clean_path=clean_path, diff --git a/tests/test_matter_proxy.py b/tests/test_matter_proxy.py new file mode 100644 index 00000000..75b2d410 --- /dev/null +++ b/tests/test_matter_proxy.py @@ -0,0 +1,51 @@ +import asyncio + +from fastapi.testclient import TestClient + +from conftest import write_release_config +from roborock_local_server import matter_proxy +from roborock_local_server.config import load_config, resolve_paths +from roborock_local_server.server import ReleaseSupervisor + + +def test_only_the_matter_key_get_matches() -> None: + assert matter_proxy.matches("/iot.roborock.com/fwapi/matter/key", "GET") + assert matter_proxy.matches("/fwapi/matter/key", "get") + assert not matter_proxy.matches("/iot.roborock.com/fwapi/matter/key", "POST") + assert not matter_proxy.matches("/iot.roborock.com/fwapi/createca", "GET") + assert not matter_proxy.matches("/fwapi/matter/keys", "GET") + + +def test_the_upstream_is_the_regional_cloud_host() -> None: + assert matter_proxy.upstream_url("us", "did=1") == "https://usiot.roborock.com/fwapi/matter/key?did=1" + assert matter_proxy.upstream_url("eu", "") == "https://euiot.roborock.com/fwapi/matter/key" + assert matter_proxy.upstream_url("../x", "") == "https://usiot.roborock.com/fwapi/matter/key" + + +def test_it_is_off_unless_enabled(tmp_path, monkeypatch) -> None: + monkeypatch.delenv("ROBOROCK_SERVER_MATTER_KEY_PROXY", raising=False) + config_file = write_release_config(tmp_path) + assert load_config(config_file).matter.key_proxy is False + monkeypatch.setenv("ROBOROCK_SERVER_MATTER_KEY_PROXY", "true") + assert load_config(config_file).matter.key_proxy is True + + +def test_a_request_is_forwarded_and_the_answer_returned(tmp_path, monkeypatch) -> None: + monkeypatch.setenv("ROBOROCK_SERVER_MATTER_KEY_PROXY", "true") + config_file = write_release_config(tmp_path) + config = load_config(config_file) + supervisor = ReleaseSupervisor(config=config, paths=resolve_paths(config_file, config)) + seen = {} + + async def fake_forward(request, region): + from fastapi.responses import Response + + seen["region"], seen["auth"] = region, request.headers.get("authorization") + return Response(content=b"KEYBYTES", status_code=200, media_type="application/octet-stream") + + monkeypatch.setattr(matter_proxy, "forward", fake_forward) + client = TestClient(supervisor.app) + response = client.get("/iot.roborock.com/fwapi/matter/key?x=1", headers={"Authorization": "abc"}) + + assert response.status_code == 200 and response.content == b"KEYBYTES" + assert seen["auth"] == "abc" and seen["region"] From 4fb28581fdea2627e55fd8cce3514206f170c76a Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:19:50 -0500 Subject: [PATCH 02/13] Document Matter setup for robots paired to this server Co-Authored-By: Claude Sonnet 5.5 --- config.example.toml | 4 ++++ docs/matter.md | 54 +++++++++++++++++++++++++++++++++++++++++++++ mkdocs.yml | 1 + 3 files changed, 59 insertions(+) create mode 100644 docs/matter.md diff --git a/config.example.toml b/config.example.toml index 02302870..9c135590 100644 --- a/config.example.toml +++ b/config.example.toml @@ -74,3 +74,7 @@ username = "" password = "" realm = "api-roborock.example.com" ttl = 86400 + +# Forwards a robot's Matter key request to Roborock's cloud (see docs/matter.md). +[matter] +key_proxy = false diff --git a/docs/matter.md b/docs/matter.md new file mode 100644 index 00000000..8a7c9410 --- /dev/null +++ b/docs/matter.md @@ -0,0 +1,54 @@ +# Matter + +Many Roborock robots can join a Matter controller (Apple Home, Google Home, Alexa, SmartThings, Home Assistant, or +a router with Matter support). To do that the robot first needs a Matter key, which Roborock's cloud issues. A robot +paired to this server asks this server for it, so two things are needed: a DNS name the robot can find, and a way to +reach Roborock for the key. + +## How the robot asks + +When it is told to download its key (`matter.dnld_key`), the robot sends `GET /iot.roborock.com/fwapi/matter/key` +to the server it was paired to. It builds the host name from the server name it was given during pairing, with the +`api-` prefix removed: a server called `api-vac.example.com` is reached as `vac.example.com`. The same rule applies +to the camera (see [Camera](camera.md)). + +1. **Add a DNS record for the stripped name**, pointing at this server. If your stack is `api-vac.example.com`, add + `vac.example.com`. Without it the robot cannot connect, and its Matter status goes from `KeyDownloading` to + `KeyDownloadFailure` within seconds without a single request reaching the server. +2. **Make sure the certificate covers that name.** A wildcard for the base domain does. +3. **Let the server forward the request to Roborock.** It is off by default, because it passes the robot's own + request, with its own headers, to Roborock: + +```toml +[matter] +key_proxy = true +``` + +or `ROBOROCK_SERVER_MATTER_KEY_PROXY=true`, which wins when it is set. The request goes to the regional cloud host +(`https://iot.roborock.com/fwapi/matter/key`, region from `network.region`) and the answer goes back to the +robot unchanged. The server logs the header and query names it forwarded and the answer's status and size, never the +values and never the key. + +Without the proxy, the robot's request reaches the catch-all route and the robot reports `KeyCorrupt`, because it got +something that is not a key. + +## Reading the robot's progress + +The robot answers `matter.get_status` with one of `KeyNotExit`, `KeyDownloading`, `KeyDownloadSuccess`, +`KeyDownloadFailure`, `KeyCorrupt`, `Preparing`, `Ready`, `Joined` or `RPCError`. `Ready` and `Joined` come with a +`ManualPairingCode` and a `QrCode` (`MT:...`) that stay valid for 15 minutes. A new key request (`matter.dnld_key`) +produces a fresh code. + +## Joining a controller + +Use the code or the QR text in the controller's add-device flow. A controller has to be able to find the robot on the +network: Matter discovery uses multicast DNS and IPv6, which do not cross VLANs unless the network forwards mDNS. A +robot on a separate VLAN from the controller is the usual reason a valid code does nothing. + +A robot that has joined one controller reports `Joined`. To add it to a second controller, request a new code and use +it while it is valid, or share the robot from the controller that joined it. + +## Notes + +- This does not change how the robot is controlled by the server. Matter is an additional way in. +- Whether the robot needs Roborock again after it has joined is not known. It keeps the key it downloaded. diff --git a/mkdocs.yml b/mkdocs.yml index 7dd21531..d1fe3314 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -57,6 +57,7 @@ nav: - Integrations: - Mobile App Options: roborock_app.md - Camera (Live Video): camera.md + - Matter: matter.md - Reference: - Log Retention: logging.md - Known Limitations: known_limitations.md From c8873736b1a7ed583dd5c3b1235538b4d22a012b Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:19:31 -0500 Subject: [PATCH 03/13] Harden the Matter key proxy and keep the robot's credentials out of the 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 --- src/roborock_local_server/matter_proxy.py | 77 +++++++-- src/roborock_local_server/server.py | 10 +- tests/test_matter_proxy.py | 183 ++++++++++++++++++++-- 3 files changed, 245 insertions(+), 25 deletions(-) diff --git a/src/roborock_local_server/matter_proxy.py b/src/roborock_local_server/matter_proxy.py index 3ddeb06e..ec2e5ead 100644 --- a/src/roborock_local_server/matter_proxy.py +++ b/src/roborock_local_server/matter_proxy.py @@ -8,18 +8,34 @@ from __future__ import annotations +import asyncio import logging import re +from typing import Any +import aiohttp from fastapi import Request from fastapi.responses import Response logger = logging.getLogger("real_stack.api") _PATH = re.compile(r"^/(?:[A-Za-z0-9.-]+/)?fwapi/matter/key/?$") -# Headers that describe this hop, not the robot's request. -_DROPPED = {"host", "connection", "content-length", "accept-encoding", "transfer-encoding", "keep-alive", "upgrade"} +REGIONS = frozenset({"us", "eu", "cn", "ru"}) +UPSTREAM_BASE = "https://{region}iot.roborock.com" +# Hop headers, proxy-added headers and browser state: none of these belong to the robot's own request. +_DROPPED = { + "host", "connection", "content-length", "accept-encoding", "transfer-encoding", "keep-alive", "upgrade", + "te", "trailer", "proxy-authorization", "proxy-connection", "cookie", "forwarded", "via", "origin", "referer", + "x-real-ip", "true-client-ip", "cf-connecting-ip", "x-local-sync-secret", +} +_DROPPED_PREFIXES = ("x-forwarded-", "cf-", "x-envoy-", "x-amzn-", "sec-") TIMEOUT_SECONDS = 20 +MAX_QUERY_LENGTH = 1024 +MAX_QUERY_PARAMS = 16 +MAX_HEADERS = 32 +MAX_HEADER_VALUE = 2048 +_QUERY_KEY = re.compile(r"^[A-Za-z0-9_.-]{1,32}$") +_DID_KEYS = ("did", "duid", "d", "device_id", "deviceId", "device_did", "deviceDid") def matches(clean_path: str, method: str) -> bool: @@ -28,15 +44,57 @@ def matches(clean_path: str, method: str) -> bool: def upstream_url(region: str, query: str) -> str: code = region.strip().lower() - host = f"{code if re.fullmatch(r'[a-z]{2,3}', code) else 'us'}iot.roborock.com" - return f"https://{host}/fwapi/matter/key" + (f"?{query}" if query else "") + if code not in REGIONS: + raise ValueError(f"unsupported region {region!r}") + return UPSTREAM_BASE.format(region=code) + "/fwapi/matter/key" + (f"?{query}" if query else "") -async def forward(request: Request, region: str) -> Response: - import aiohttp +def forwardable_headers(headers: Any) -> dict[str, str]: + kept: dict[str, str] = {} + for name, value in headers.items(): + lowered = name.lower() + if lowered in _DROPPED or lowered.startswith(_DROPPED_PREFIXES) or len(value) > MAX_HEADER_VALUE: + continue + kept[name] = value + return kept + + +def query_is_acceptable(query_params: dict[str, list[str]], query: str) -> bool: + """Plain key=value pairs of bounded size; the query is signed, so it is passed on byte for byte.""" + keys = [key for key in query_params if key != "__host"] + return len(query) <= MAX_QUERY_LENGTH and len(keys) <= MAX_QUERY_PARAMS and all(_QUERY_KEY.match(k) for k in keys) + + +def known_device(vacuums: list[dict[str, Any]], query_params: dict[str, list[str]], client_ip: str) -> bool: + """A request names a paired robot (did/duid in the query), or comes from the address of one that is connected.""" + named = {value for key in _DID_KEYS for value in query_params.get(key, []) if value} + for vac in vacuums: + if named & {str(vac.get("duid") or ""), str(vac.get("did") or "")}: + return True + if named: + return False + ips = {ip for vac in vacuums for ip in [*(vac.get("ips") or []), vac.get("last_ip")] if ip} + return client_ip in ips + - url = upstream_url(region, request.url.query) - headers = {name: value for name, value in request.headers.items() if name.lower() not in _DROPPED} +def redact_log_entry(entry: dict[str, object]) -> None: + """The robot's header and query values are its cloud credentials: keep names only, drop the query from the path.""" + headers = entry.get("headers") + if isinstance(headers, dict): + entry["headers"] = {key: "" for key in headers} + query = entry.get("query") + if isinstance(query, dict): + entry["query"] = {key: "" for key in query} + entry["raw_path"] = str(entry.get("clean_path") or "") + + +async def forward(request: Request, region: str) -> Response: + try: + url = upstream_url(region, request.url.query) + except ValueError as exc: + logger.warning("Matter key request not forwarded: %s (expected one of %s)", exc, sorted(REGIONS)) + return Response(content=b"", status_code=502) + headers = forwardable_headers(request.headers) # Names only: the values are the robot's credentials for the cloud. logger.info( "Matter key request from %s: forwarding to %s (header names: %s; query names: %s)", @@ -48,9 +106,8 @@ async def forward(request: Request, region: str) -> Response: body = await upstream.read() content_type = upstream.headers.get("Content-Type", "application/octet-stream") status = upstream.status - except Exception as exc: # noqa: BLE001 + except (aiohttp.ClientError, asyncio.TimeoutError) as exc: logger.warning("Matter key request could not reach Roborock: %s", exc) return Response(content=b"", status_code=502) logger.info("Matter key answer from Roborock: HTTP %d, %d bytes, %s", status, len(body), content_type) return Response(content=body, status_code=status, media_type=content_type) - diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py index 33caf98e..09afdbfc 100644 --- a/src/roborock_local_server/server.py +++ b/src/roborock_local_server/server.py @@ -1273,7 +1273,15 @@ async def _handle_roborock_request(self, request: Request) -> Response: return JSONResponse(response_payload, status_code=status_code) if self.config.matter.key_proxy and matter_proxy.matches(clean_path, request.method): - proxied = await matter_proxy.forward(request, self.config.network.region) + matter_proxy.redact_log_entry(entry) + if not matter_proxy.query_is_acceptable(query_params, request.url.query): + proxied: Response = Response(content=b"", status_code=400) + elif not matter_proxy.known_device( + self.runtime_state.vacuum_snapshot(), query_params, request.client.host if request.client else "" + ): + proxied = Response(content=b"", status_code=403) + else: + proxied = await matter_proxy.forward(request, self.config.network.region) entry["route"] = "matter_key_proxy" entry["response_meta"] = {"status_code": proxied.status_code, "bytes": len(proxied.body)} append_jsonl(self.context.http_jsonl, entry) diff --git a/tests/test_matter_proxy.py b/tests/test_matter_proxy.py index 75b2d410..7215eb1d 100644 --- a/tests/test_matter_proxy.py +++ b/tests/test_matter_proxy.py @@ -1,12 +1,19 @@ import asyncio +import json +import pytest +from aiohttp import web +from aiohttp.test_utils import TestServer from fastapi.testclient import TestClient +from starlette.requests import Request from conftest import write_release_config from roborock_local_server import matter_proxy from roborock_local_server.config import load_config, resolve_paths from roborock_local_server.server import ReleaseSupervisor +PATH = "/iot.roborock.com/fwapi/matter/key" + def test_only_the_matter_key_get_matches() -> None: assert matter_proxy.matches("/iot.roborock.com/fwapi/matter/key", "GET") @@ -19,7 +26,14 @@ def test_only_the_matter_key_get_matches() -> None: def test_the_upstream_is_the_regional_cloud_host() -> None: assert matter_proxy.upstream_url("us", "did=1") == "https://usiot.roborock.com/fwapi/matter/key?did=1" assert matter_proxy.upstream_url("eu", "") == "https://euiot.roborock.com/fwapi/matter/key" - assert matter_proxy.upstream_url("../x", "") == "https://usiot.roborock.com/fwapi/matter/key" + assert matter_proxy.upstream_url("cn", "") == "https://cniot.roborock.com/fwapi/matter/key" + assert matter_proxy.upstream_url("ru", "") == "https://ruiot.roborock.com/fwapi/matter/key" + + +@pytest.mark.parametrize("region", ["../x", "de", "", "usiot.evil.example/", "u s"]) +def test_an_unknown_region_is_refused(region) -> None: + with pytest.raises(ValueError): + matter_proxy.upstream_url(region, "") def test_it_is_off_unless_enabled(tmp_path, monkeypatch) -> None: @@ -30,22 +44,163 @@ def test_it_is_off_unless_enabled(tmp_path, monkeypatch) -> None: assert load_config(config_file).matter.key_proxy is True -def test_a_request_is_forwarded_and_the_answer_returned(tmp_path, monkeypatch) -> None: - monkeypatch.setenv("ROBOROCK_SERVER_MATTER_KEY_PROXY", "true") +def _request(query: str = "", headers: dict[str, str] | None = None) -> Request: + raw = [(k.lower().encode(), v.encode()) for k, v in (headers or {}).items()] + return Request( + { + "type": "http", + "method": "GET", + "path": PATH, + "query_string": query.encode(), + "headers": raw, + "client": ("10.0.0.7", 5000), + } + ) + + +async def _forward_to(handler, monkeypatch, region="us", query="", headers=None, timeout=None): + app = web.Application() + app.router.add_get("/fwapi/matter/key", handler) + async with TestServer(app) as server: + monkeypatch.setattr(matter_proxy, "UPSTREAM_BASE", str(server.make_url("")).rstrip("/")) + if timeout is not None: + monkeypatch.setattr(matter_proxy, "TIMEOUT_SECONDS", timeout) + return await matter_proxy.forward(_request(query, headers), region) + + +def test_forward_filters_headers_and_relays_the_answer(monkeypatch) -> None: + seen = {} + + async def handler(request): + seen["headers"], seen["query"] = {k.lower(): v for k, v in request.headers.items()}, request.query_string + return web.Response(body=b"KEYBYTES", status=200, content_type="application/x-test") + + sent = {"Authorization": "tok", "Cookie": "a=b", "X-Forwarded-For": "1.2.3.4", "Via": "x", "X-Custom": "keep"} + response = asyncio.run( + _forward_to(handler, monkeypatch, query="did=D1&signature=abc%3D", headers=sent) + ) + + assert response.status_code == 200 and response.body == b"KEYBYTES" + assert response.media_type == "application/x-test" + assert seen["query"] == "did=D1&signature=abc%3D" + assert seen["headers"]["authorization"] == "tok" and seen["headers"]["x-custom"] == "keep" + assert not {name.lower() for name in seen["headers"]} & {"cookie", "x-forwarded-for", "via"} + + +def test_an_upstream_error_status_is_relayed(monkeypatch) -> None: + async def handler(request): + return web.Response(body=b"nope", status=403) + + response = asyncio.run(_forward_to(handler, monkeypatch)) + assert response.status_code == 403 and response.body == b"nope" + + +def test_an_unreachable_upstream_is_a_502(monkeypatch) -> None: + monkeypatch.setattr(matter_proxy, "UPSTREAM_BASE", "http://127.0.0.1:1") + response = asyncio.run(matter_proxy.forward(_request(), "us")) + assert response.status_code == 502 and response.body == b"" + + +def test_a_slow_upstream_times_out_as_a_502(monkeypatch) -> None: + async def handler(request): + await asyncio.sleep(2) + return web.Response(body=b"late") + + response = asyncio.run(_forward_to(handler, monkeypatch, timeout=0.2)) + assert response.status_code == 502 + + +def test_an_unsupported_region_is_a_502_without_a_request(monkeypatch) -> None: + monkeypatch.setattr(matter_proxy, "UPSTREAM_BASE", "http://127.0.0.1:1") + assert asyncio.run(matter_proxy.forward(_request(), "de")).status_code == 502 + + +def test_hop_proxy_and_cookie_headers_are_dropped() -> None: + kept = matter_proxy.forwardable_headers( + { + "Host": "h", + "X-Forwarded-Proto": "https", + "Forwarded": "x", + "Cookie": "c", + "Proxy-Authorization": "p", + "Authorization": "a", + "User-Agent": "robot", + } + ) + assert kept == {"Authorization": "a", "User-Agent": "robot"} + + +def test_the_query_must_be_plain_and_small() -> None: + ok = {"did": ["1"], "signature": ["x"]} + assert matter_proxy.query_is_acceptable(ok, "did=1&signature=x") + assert not matter_proxy.query_is_acceptable({"a b": ["1"]}, "a b=1") + assert not matter_proxy.query_is_acceptable({f"k{i}": ["1"] for i in range(17)}, "k=1") + assert not matter_proxy.query_is_acceptable(ok, "x" * 2000) + + +def test_a_request_must_name_or_come_from_a_known_robot() -> None: + robots = [{"duid": "D1", "did": "d1", "ips": ["10.0.0.7"], "last_ip": "10.0.0.7"}] + assert matter_proxy.known_device(robots, {"did": ["d1"]}, "9.9.9.9") + assert matter_proxy.known_device(robots, {"duid": ["D1"]}, "9.9.9.9") + assert not matter_proxy.known_device(robots, {"did": ["other"]}, "10.0.0.7") + assert matter_proxy.known_device(robots, {}, "10.0.0.7") + assert not matter_proxy.known_device(robots, {}, "9.9.9.9") + assert not matter_proxy.known_device([], {}, "10.0.0.7") + + +def _supervisor(tmp_path, monkeypatch, enabled: bool) -> ReleaseSupervisor: + monkeypatch.setenv("ROBOROCK_SERVER_MATTER_KEY_PROXY", "true" if enabled else "false") config_file = write_release_config(tmp_path) config = load_config(config_file) - supervisor = ReleaseSupervisor(config=config, paths=resolve_paths(config_file, config)) - seen = {} + return ReleaseSupervisor(config=config, paths=resolve_paths(config_file, config)) + + +def test_the_route_forwards_for_a_known_robot_and_keeps_values_out_of_the_log(tmp_path, monkeypatch) -> None: + supervisor = _supervisor(tmp_path, monkeypatch, True) + calls = [] + + async def handler(request): + calls.append(request.query_string) + return web.Response(body=b"KEYBYTES") + + def drive(): + client = TestClient(supervisor.app) + unknown = client.get(PATH + "?did=ghost", headers={"Authorization": "SECRETVALUE"}) + supervisor.runtime_state.upsert_vacuum("D1", did="d1", name="Robot") + known = client.get(PATH + "?did=d1&signature=QUERYSECRET", headers={"Authorization": "SECRETVALUE"}) + return unknown, known + + async def run(): + app = web.Application() + app.router.add_get("/fwapi/matter/key", handler) + async with TestServer(app) as upstream: + monkeypatch.setattr(matter_proxy, "UPSTREAM_BASE", str(upstream.make_url("")).rstrip("/")) + return await asyncio.to_thread(drive) + + unknown, known = asyncio.run(run()) + + assert unknown.status_code == 403 + assert known.status_code == 200 and known.content == b"KEYBYTES" + assert calls == ["did=d1&signature=QUERYSECRET"] + log_text = supervisor.context.http_jsonl.read_text(encoding="utf-8") + assert "SECRETVALUE" not in log_text and "QUERYSECRET" not in log_text + entries = [json.loads(line) for line in log_text.splitlines() if "matter_key_proxy" in line] + assert len(entries) == 2 + assert entries[1]["headers"]["authorization"] == "" + assert entries[1]["raw_path"] == PATH and "signature" in entries[1]["query"] + - async def fake_forward(request, region): - from fastapi.responses import Response +def test_when_disabled_nothing_is_forwarded(tmp_path, monkeypatch) -> None: + supervisor = _supervisor(tmp_path, monkeypatch, False) + called = [] - seen["region"], seen["auth"] = region, request.headers.get("authorization") - return Response(content=b"KEYBYTES", status_code=200, media_type="application/octet-stream") + async def fail_forward(request, region): + called.append(region) - monkeypatch.setattr(matter_proxy, "forward", fake_forward) - client = TestClient(supervisor.app) - response = client.get("/iot.roborock.com/fwapi/matter/key?x=1", headers={"Authorization": "abc"}) + monkeypatch.setattr(matter_proxy, "forward", fail_forward) + supervisor.runtime_state.upsert_vacuum("D1", did="d1", name="Robot") + response = TestClient(supervisor.app).get(PATH + "?did=d1") - assert response.status_code == 200 and response.content == b"KEYBYTES" - assert seen["auth"] == "abc" and seen["region"] + assert called == [] + assert response.content != b"KEYBYTES" + assert "matter_key_proxy" not in supervisor.context.http_jsonl.read_text(encoding="utf-8") From 1f6afeed870d22ead650f8dd414d19d636bb5141 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:19:31 -0500 Subject: [PATCH 04/13] Document what the Matter key proxy sends to Roborock and what it logs 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 --- config.example.toml | 1 + docs/matter.md | 32 +++++++++++++++++++++++++++----- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/config.example.toml b/config.example.toml index 9c135590..4bd28e38 100644 --- a/config.example.toml +++ b/config.example.toml @@ -76,5 +76,6 @@ realm = "api-roborock.example.com" ttl = 86400 # Forwards a robot's Matter key request to Roborock's cloud (see docs/matter.md). +# When true, the robot's id, its signature and its request headers are sent to Roborock, along with this server's IP. [matter] key_proxy = false diff --git a/docs/matter.md b/docs/matter.md index 8a7c9410..355fe00c 100644 --- a/docs/matter.md +++ b/docs/matter.md @@ -16,8 +16,7 @@ to the camera (see [Camera](camera.md)). `vac.example.com`. Without it the robot cannot connect, and its Matter status goes from `KeyDownloading` to `KeyDownloadFailure` within seconds without a single request reaching the server. 2. **Make sure the certificate covers that name.** A wildcard for the base domain does. -3. **Let the server forward the request to Roborock.** It is off by default, because it passes the robot's own - request, with its own headers, to Roborock: +3. **Let the server forward the request to Roborock.** It is off by default, because it sends data to Roborock: ```toml [matter] @@ -25,9 +24,32 @@ key_proxy = true ``` or `ROBOROCK_SERVER_MATTER_KEY_PROXY=true`, which wins when it is set. The request goes to the regional cloud host -(`https://iot.roborock.com/fwapi/matter/key`, region from `network.region`) and the answer goes back to the -robot unchanged. The server logs the header and query names it forwarded and the answer's status and size, never the -values and never the key. +(`https://iot.roborock.com/fwapi/matter/key`, with `network.region` one of `us`, `eu`, `cn` or `ru`) and the +answer goes back to the robot unchanged. + +### What is sent to Roborock + +The robot's own request, as it arrived: its query string (which may name the robot by `did` or `duid` and carry +its signature) and its headers, minus hop-by-hop and proxy headers (`Host`, `Connection`, `Cookie`, +`X-Forwarded-*`, `Forwarded`, `Via` and similar). Roborock also sees this server's public IP address. Nothing from +the app account, the admin password or other robots is added. + +### What is checked first + +The route is open to anything that can reach the server, so it only forwards a request when it names a paired robot +(a `did` or `duid` in the query that this server knows) or, when it names none, when it comes from the address of a +robot that has connected to this server. Anything else gets 403, and a malformed or oversized query gets 400. The +destination host and path are fixed, so this is never a general proxy. The address check is the weaker of the two: +a request without a robot id from a machine at a robot's address passes it. + +### What is logged + +The shared request log (`http_jsonl`) normally stores every header and query value. For this route it keeps only the +header and query names, the path without its query string, the response status and size, and the robot id if the +request carried one. The console log has the same names and the answer's status and size. The key itself is never +logged. Two things outside this route still see the robot's signed query: the device key cache, which stores signed +queries for key recovery as for any robot request, and the request log of a server that has the proxy switched off, +which treats the request like any other unknown path. Without the proxy, the robot's request reaches the catch-all route and the robot reports `KeyCorrupt`, because it got something that is not a key. From 16eeb60fd086a31d05b16b094f885d93c469f928 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:11:38 -0500 Subject: [PATCH 05/13] Forward the Matter key query unchanged, rate limit the route, tighten 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 --- src/roborock_local_server/matter_proxy.py | 40 +++++++++++++--- src/roborock_local_server/server.py | 13 ++++-- tests/test_matter_proxy.py | 57 +++++++++++++++++++++-- 3 files changed, 94 insertions(+), 16 deletions(-) diff --git a/src/roborock_local_server/matter_proxy.py b/src/roborock_local_server/matter_proxy.py index ec2e5ead..e623bcb3 100644 --- a/src/roborock_local_server/matter_proxy.py +++ b/src/roborock_local_server/matter_proxy.py @@ -11,11 +11,14 @@ import asyncio import logging import re +import time from typing import Any +from urllib.parse import parse_qs import aiohttp from fastapi import Request from fastapi.responses import Response +from yarl import URL logger = logging.getLogger("real_stack.api") @@ -32,7 +35,8 @@ TIMEOUT_SECONDS = 20 MAX_QUERY_LENGTH = 1024 MAX_QUERY_PARAMS = 16 -MAX_HEADERS = 32 +RATE_LIMIT_REQUESTS = 10 +RATE_LIMIT_WINDOW_SECONDS = 60 MAX_HEADER_VALUE = 2048 _QUERY_KEY = re.compile(r"^[A-Za-z0-9_.-]{1,32}$") _DID_KEYS = ("did", "duid", "d", "device_id", "deviceId", "device_did", "deviceDid") @@ -54,15 +58,39 @@ def forwardable_headers(headers: Any) -> dict[str, str]: for name, value in headers.items(): lowered = name.lower() if lowered in _DROPPED or lowered.startswith(_DROPPED_PREFIXES) or len(value) > MAX_HEADER_VALUE: + logger.debug("Matter key request: header %r not forwarded", name) continue kept[name] = value return kept -def query_is_acceptable(query_params: dict[str, list[str]], query: str) -> bool: - """Plain key=value pairs of bounded size; the query is signed, so it is passed on byte for byte.""" - keys = [key for key in query_params if key != "__host"] - return len(query) <= MAX_QUERY_LENGTH and len(keys) <= MAX_QUERY_PARAMS and all(_QUERY_KEY.match(k) for k in keys) +def parse_query(query: str) -> dict[str, list[str]]: + return parse_qs(query, keep_blank_values=True) + + +def query_is_acceptable(query: str) -> bool: + """Plain key=value pairs of bounded size; the raw query is signed, so it is passed on unchanged.""" + if len(query) > MAX_QUERY_LENGTH: + return False + keys = [part.split("=", 1)[0] for part in query.split("&") if part] + return len(keys) <= MAX_QUERY_PARAMS and all(_QUERY_KEY.match(key) for key in keys) + + +class RateLimiter: + def __init__(self, limit: int = RATE_LIMIT_REQUESTS, window: float = RATE_LIMIT_WINDOW_SECONDS) -> None: + self._limit, self._window = limit, window + self._hits: dict[str, list[float]] = {} + + def allow(self, client: str) -> bool: + now = time.monotonic() + recent = [t for t in self._hits.get(client, []) if now - t < self._window] + allowed = len(recent) < self._limit + if allowed: + recent.append(now) + self._hits[client] = recent + if len(self._hits) > 1024: + self._hits = {k: v for k, v in self._hits.items() if v and now - v[-1] < self._window} + return allowed def known_device(vacuums: list[dict[str, Any]], query_params: dict[str, list[str]], client_ip: str) -> bool: @@ -102,7 +130,7 @@ async def forward(request: Request, region: str) -> Response: ) try: async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=TIMEOUT_SECONDS)) as session: - async with session.get(url, headers=headers) as upstream: + async with session.get(URL(url, encoded=True), headers=headers) as upstream: body = await upstream.read() content_type = upstream.headers.get("Content-Type", "application/octet-stream") status = upstream.status diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py index 09afdbfc..502a6b71 100644 --- a/src/roborock_local_server/server.py +++ b/src/roborock_local_server/server.py @@ -1274,11 +1274,14 @@ async def _handle_roborock_request(self, request: Request) -> Response: if self.config.matter.key_proxy and matter_proxy.matches(clean_path, request.method): matter_proxy.redact_log_entry(entry) - if not matter_proxy.query_is_acceptable(query_params, request.url.query): - proxied: Response = Response(content=b"", status_code=400) - elif not matter_proxy.known_device( - self.runtime_state.vacuum_snapshot(), query_params, request.client.host if request.client else "" - ): + matter_query = matter_proxy.parse_query(request.url.query) + limiter = self.__dict__.setdefault("_matter_limiter", matter_proxy.RateLimiter()) + client_ip = request.client.host if request.client else "" + if not limiter.allow(client_ip): + proxied: Response = Response(content=b"", status_code=429) + elif not matter_proxy.query_is_acceptable(request.url.query): + proxied = Response(content=b"", status_code=400) + elif not matter_proxy.known_device(self.runtime_state.vacuum_snapshot(), matter_query, client_ip): proxied = Response(content=b"", status_code=403) else: proxied = await matter_proxy.forward(request, self.config.network.region) diff --git a/tests/test_matter_proxy.py b/tests/test_matter_proxy.py index 7215eb1d..5315dde3 100644 --- a/tests/test_matter_proxy.py +++ b/tests/test_matter_proxy.py @@ -1,5 +1,6 @@ import asyncio import json +import logging import pytest from aiohttp import web @@ -131,11 +132,50 @@ def test_hop_proxy_and_cookie_headers_are_dropped() -> None: def test_the_query_must_be_plain_and_small() -> None: - ok = {"did": ["1"], "signature": ["x"]} - assert matter_proxy.query_is_acceptable(ok, "did=1&signature=x") - assert not matter_proxy.query_is_acceptable({"a b": ["1"]}, "a b=1") - assert not matter_proxy.query_is_acceptable({f"k{i}": ["1"] for i in range(17)}, "k=1") - assert not matter_proxy.query_is_acceptable(ok, "x" * 2000) + assert matter_proxy.query_is_acceptable("did=1&signature=x%3D") + assert matter_proxy.query_is_acceptable("") + assert not matter_proxy.query_is_acceptable("a b=1") + assert not matter_proxy.query_is_acceptable("&".join(f"k{i}=1" for i in range(17))) + assert not matter_proxy.query_is_acceptable("x" * 2000) + + +def test_a_client_supplied_host_key_counts_like_any_other() -> None: + assert matter_proxy.query_is_acceptable("__host=evil&did=1") + assert not matter_proxy.query_is_acceptable("&".join(["__host=1"] + [f"k{i}=1" for i in range(16)])) + + +def test_the_raw_query_reaches_the_upstream_unchanged(monkeypatch) -> None: + seen = {} + + async def handler(request): + seen["raw"] = request.rel_url.raw_query_string + return web.Response(body=b"ok") + + query = "did=a%zz&sig=%41%7e+x%2Fy" + response = asyncio.run(_forward_to(handler, monkeypatch, query=query)) + assert response.status_code == 200 and seen["raw"] == query + + +def test_an_unusable_header_is_logged_at_debug() -> None: + messages: list[str] = [] + handler = logging.Handler(level=logging.DEBUG) + handler.emit = lambda record: messages.append(record.getMessage()) # type: ignore[method-assign] + logger = matter_proxy.logger + previous = logger.level + logger.addHandler(handler) + logger.setLevel(logging.DEBUG) + try: + assert matter_proxy.forwardable_headers({"Authorization": "x" * 5000}) == {} + finally: + logger.removeHandler(handler) + logger.setLevel(previous) + assert any("Authorization" in message for message in messages) + + +def test_the_rate_limit_is_per_client() -> None: + limiter = matter_proxy.RateLimiter(limit=3, window=60) + assert [limiter.allow("a") for _ in range(4)] == [True, True, True, False] + assert limiter.allow("b") def test_a_request_must_name_or_come_from_a_known_robot() -> None: @@ -204,3 +244,10 @@ async def fail_forward(request, region): assert called == [] assert response.content != b"KEYBYTES" assert "matter_key_proxy" not in supervisor.context.http_jsonl.read_text(encoding="utf-8") + + +def test_the_route_answers_429_after_too_many_requests(tmp_path, monkeypatch) -> None: + supervisor = _supervisor(tmp_path, monkeypatch, True) + client = TestClient(supervisor.app) + codes = [client.get(PATH + "?did=ghost").status_code for _ in range(12)] + assert codes[:10] == [403] * 10 and codes[10:] == [429, 429] From aee8a1544324e6277140185c068b8e8243ca5f33 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:11:46 -0500 Subject: [PATCH 06/13] Document the Matter proxy rate limit and unchanged query Co-Authored-By: Claude Sonnet 5.5 --- docs/matter.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/matter.md b/docs/matter.md index 355fe00c..22c9ff0c 100644 --- a/docs/matter.md +++ b/docs/matter.md @@ -38,8 +38,11 @@ the app account, the admin password or other robots is added. The route is open to anything that can reach the server, so it only forwards a request when it names a paired robot (a `did` or `duid` in the query that this server knows) or, when it names none, when it comes from the address of a -robot that has connected to this server. Anything else gets 403, and a malformed or oversized query gets 400. The -destination host and path are fixed, so this is never a general proxy. The address check is the weaker of the two: +robot that has connected to this server. Anything else gets 403, and a malformed or oversized query gets 400. Each +client address may make 10 requests a minute to this route (429 beyond that, refused requests counted), so a known +id cannot be used to make the server send requests to Roborock in bulk. The query is forwarded exactly as the robot +sent it, without re-encoding, because the signature covers it. The destination host and path are fixed, so this is +never a general proxy. The address check is the weaker of the two: a request without a robot id from a machine at a robot's address passes it. ### What is logged From 1b5b8e9f6f9387f9b7a4b0efc5664b2c0040eba2 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:09:40 -0500 Subject: [PATCH 07/13] Create the Matter key rate limiter in __init__ 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 --- src/roborock_local_server/server.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py index 502a6b71..ec017b9d 100644 --- a/src/roborock_local_server/server.py +++ b/src/roborock_local_server/server.py @@ -349,6 +349,7 @@ def __init__( self.config = config self.paths = paths self.enable_standalone_admin = bool(enable_standalone_admin) + self._matter_limiter = matter_proxy.RateLimiter() self.root_logger = logging.getLogger("roborock_local_server") self.root_logger.setLevel(logging.INFO) @@ -1275,9 +1276,8 @@ async def _handle_roborock_request(self, request: Request) -> Response: if self.config.matter.key_proxy and matter_proxy.matches(clean_path, request.method): matter_proxy.redact_log_entry(entry) matter_query = matter_proxy.parse_query(request.url.query) - limiter = self.__dict__.setdefault("_matter_limiter", matter_proxy.RateLimiter()) client_ip = request.client.host if request.client else "" - if not limiter.allow(client_ip): + if not self._matter_limiter.allow(client_ip): proxied: Response = Response(content=b"", status_code=429) elif not matter_proxy.query_is_acceptable(request.url.query): proxied = Response(content=b"", status_code=400) From c9afa5c9444f9213446c8659c840032742419849 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:10:08 -0500 Subject: [PATCH 08/13] Record the Matter key request as an HTTP event 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 --- src/roborock_local_server/server.py | 18 ++++++++++++++++++ tests/test_matter_proxy.py | 8 ++++++++ 2 files changed, 26 insertions(+) diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py index ec017b9d..03b377af 100644 --- a/src/roborock_local_server/server.py +++ b/src/roborock_local_server/server.py @@ -1277,6 +1277,7 @@ async def _handle_roborock_request(self, request: Request) -> Response: matter_proxy.redact_log_entry(entry) matter_query = matter_proxy.parse_query(request.url.query) client_ip = request.client.host if request.client else "" + admitted = False if not self._matter_limiter.allow(client_ip): proxied: Response = Response(content=b"", status_code=429) elif not matter_proxy.query_is_acceptable(request.url.query): @@ -1284,9 +1285,26 @@ async def _handle_roborock_request(self, request: Request) -> Response: elif not matter_proxy.known_device(self.runtime_state.vacuum_snapshot(), matter_query, client_ip): proxied = Response(content=b"", status_code=403) else: + admitted = True proxied = await matter_proxy.forward(request, self.config.network.region) entry["route"] = "matter_key_proxy" entry["response_meta"] = {"status_code": proxied.status_code, "bytes": len(proxied.body)} + try: + # Ids from a refused request are unverified: leaving them out keeps the event from creating a robot record. + self.runtime_state.record_http_event( + event_time=str(entry["time"]), + route_name="matter_key_proxy", + clean_path=clean_path, + raw_path=clean_path, + method=request.method, + host=host, + remote=str(entry["remote"]), + did=(explicit_did or None) if admitted else None, + pid=(explicit_pid or None) if admitted else None, + model=(explicit_model or None) if admitted else None, + ) + except Exception as exc: # noqa: BLE001 + logger.warning("runtime_state record_http_event failed: %s", exc) append_jsonl(self.context.http_jsonl, entry) return proxied diff --git a/tests/test_matter_proxy.py b/tests/test_matter_proxy.py index 5315dde3..eaac6e0d 100644 --- a/tests/test_matter_proxy.py +++ b/tests/test_matter_proxy.py @@ -251,3 +251,11 @@ def test_the_route_answers_429_after_too_many_requests(tmp_path, monkeypatch) -> client = TestClient(supervisor.app) codes = [client.get(PATH + "?did=ghost").status_code for _ in range(12)] assert codes[:10] == [403] * 10 and codes[10:] == [429, 429] + + +def test_the_route_records_an_event_without_creating_a_robot_for_a_refused_id(tmp_path, monkeypatch) -> None: + supervisor = _supervisor(tmp_path, monkeypatch, True) + TestClient(supervisor.app).get(PATH + "?did=ghost&signature=QUERYSECRET") + events = [e for e in supervisor.runtime_state.recent_events() if e.get("route") == "matter_key_proxy"] + assert len(events) == 1 and events[0]["raw_path"] == PATH and events[0]["did"] is None + assert supervisor.runtime_state.vacuum_snapshot() == [] From 8023f32a472f9b02cf08d3348c03a220bfdc5b7b Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:10:40 -0500 Subject: [PATCH 09/13] Redact the Matter key request in the log even with the proxy off 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 --- docs/matter.md | 11 +++++------ src/roborock_local_server/server.py | 3 ++- tests/test_matter_proxy.py | 4 +++- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/matter.md b/docs/matter.md index 22c9ff0c..7e0e0e41 100644 --- a/docs/matter.md +++ b/docs/matter.md @@ -47,12 +47,11 @@ a request without a robot id from a machine at a robot's address passes it. ### What is logged -The shared request log (`http_jsonl`) normally stores every header and query value. For this route it keeps only the -header and query names, the path without its query string, the response status and size, and the robot id if the -request carried one. The console log has the same names and the answer's status and size. The key itself is never -logged. Two things outside this route still see the robot's signed query: the device key cache, which stores signed -queries for key recovery as for any robot request, and the request log of a server that has the proxy switched off, -which treats the request like any other unknown path. +The shared request log (`http_jsonl`) normally stores every header and query value. For this route, with the proxy +on or off, it keeps only the header and query names, the path without its query string, and the robot id if the +request carried one. With the proxy on it also records the response status and size. The console log has the same names and the answer's status and size. The key itself is never +logged. One thing outside this route still sees the robot's signed query: the device key cache, which stores signed +queries for key recovery as for any robot request. Without the proxy, the robot's request reaches the catch-all route and the robot reports `KeyCorrupt`, because it got something that is not a key. diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py index 03b377af..6a4a1f64 100644 --- a/src/roborock_local_server/server.py +++ b/src/roborock_local_server/server.py @@ -1063,6 +1063,8 @@ async def _handle_roborock_request(self, request: Request) -> Response: "body_sha256": body_sha256, "remote": f"{client_host}:{client_port}", } + if matter_proxy.matches(clean_path, request.method): + matter_proxy.redact_log_entry(entry) if explicit_did: entry["did"] = explicit_did if explicit_pid: @@ -1274,7 +1276,6 @@ async def _handle_roborock_request(self, request: Request) -> Response: return JSONResponse(response_payload, status_code=status_code) if self.config.matter.key_proxy and matter_proxy.matches(clean_path, request.method): - matter_proxy.redact_log_entry(entry) matter_query = matter_proxy.parse_query(request.url.query) client_ip = request.client.host if request.client else "" admitted = False diff --git a/tests/test_matter_proxy.py b/tests/test_matter_proxy.py index eaac6e0d..7c0468d8 100644 --- a/tests/test_matter_proxy.py +++ b/tests/test_matter_proxy.py @@ -239,11 +239,13 @@ async def fail_forward(request, region): monkeypatch.setattr(matter_proxy, "forward", fail_forward) supervisor.runtime_state.upsert_vacuum("D1", did="d1", name="Robot") - response = TestClient(supervisor.app).get(PATH + "?did=d1") + response = TestClient(supervisor.app).get(PATH + "?did=d1&signature=QUERYSECRET", headers={"Authorization": "SECRETVALUE"}) assert called == [] assert response.content != b"KEYBYTES" assert "matter_key_proxy" not in supervisor.context.http_jsonl.read_text(encoding="utf-8") + log_text = supervisor.context.http_jsonl.read_text(encoding="utf-8") + assert PATH in log_text and "QUERYSECRET" not in log_text and "SECRETVALUE" not in log_text def test_the_route_answers_429_after_too_many_requests(tmp_path, monkeypatch) -> None: From 0a8fd30ffcfa1327536efae36dfe0f35e5a53f55 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:12:31 -0500 Subject: [PATCH 10/13] Only match did and duid for the Matter key device gate 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 --- src/roborock_local_server/matter_proxy.py | 2 +- tests/test_matter_proxy.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/roborock_local_server/matter_proxy.py b/src/roborock_local_server/matter_proxy.py index e623bcb3..b54a53f3 100644 --- a/src/roborock_local_server/matter_proxy.py +++ b/src/roborock_local_server/matter_proxy.py @@ -39,7 +39,7 @@ RATE_LIMIT_WINDOW_SECONDS = 60 MAX_HEADER_VALUE = 2048 _QUERY_KEY = re.compile(r"^[A-Za-z0-9_.-]{1,32}$") -_DID_KEYS = ("did", "duid", "d", "device_id", "deviceId", "device_did", "deviceDid") +_DID_KEYS = ("did", "duid") def matches(clean_path: str, method: str) -> bool: diff --git a/tests/test_matter_proxy.py b/tests/test_matter_proxy.py index 7c0468d8..e076d6f2 100644 --- a/tests/test_matter_proxy.py +++ b/tests/test_matter_proxy.py @@ -186,6 +186,7 @@ def test_a_request_must_name_or_come_from_a_known_robot() -> None: assert matter_proxy.known_device(robots, {}, "10.0.0.7") assert not matter_proxy.known_device(robots, {}, "9.9.9.9") assert not matter_proxy.known_device([], {}, "10.0.0.7") + assert not matter_proxy.known_device(robots, {"device_id": ["d1"]}, "9.9.9.9") def _supervisor(tmp_path, monkeypatch, enabled: bool) -> ReleaseSupervisor: From 4092083734ca52e78aed272093644e76ea18c90c Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:48:42 -0500 Subject: [PATCH 11/13] Record only the id the Matter key gate matched 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=&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 --- src/roborock_local_server/matter_proxy.py | 14 ++++--- src/roborock_local_server/server.py | 19 +++++---- tests/test_matter_proxy.py | 50 +++++++++++++++++++---- 3 files changed, 61 insertions(+), 22 deletions(-) diff --git a/src/roborock_local_server/matter_proxy.py b/src/roborock_local_server/matter_proxy.py index b54a53f3..45c315d7 100644 --- a/src/roborock_local_server/matter_proxy.py +++ b/src/roborock_local_server/matter_proxy.py @@ -93,16 +93,18 @@ def allow(self, client: str) -> bool: return allowed -def known_device(vacuums: list[dict[str, Any]], query_params: dict[str, list[str]], client_ip: str) -> bool: - """A request names a paired robot (did/duid in the query), or comes from the address of one that is connected.""" +def known_device(vacuums: list[dict[str, Any]], query_params: dict[str, list[str]], client_ip: str) -> str | None: + """The id of the paired robot the request names (did/duid in the query) or comes from, else None.""" named = {value for key in _DID_KEYS for value in query_params.get(key, []) if value} for vac in vacuums: if named & {str(vac.get("duid") or ""), str(vac.get("did") or "")}: - return True + return str(vac.get("duid") or vac.get("did")) if named: - return False - ips = {ip for vac in vacuums for ip in [*(vac.get("ips") or []), vac.get("last_ip")] if ip} - return client_ip in ips + return None + for vac in vacuums: + if client_ip in {ip for ip in [*(vac.get("ips") or []), vac.get("last_ip")] if ip}: + return str(vac.get("duid") or vac.get("did") or "") or None + return None def redact_log_entry(entry: dict[str, object]) -> None: diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py index 6a4a1f64..652fb349 100644 --- a/src/roborock_local_server/server.py +++ b/src/roborock_local_server/server.py @@ -1278,20 +1278,21 @@ async def _handle_roborock_request(self, request: Request) -> Response: if self.config.matter.key_proxy and matter_proxy.matches(clean_path, request.method): matter_query = matter_proxy.parse_query(request.url.query) client_ip = request.client.host if request.client else "" - admitted = False + matched_id: str | None = None if not self._matter_limiter.allow(client_ip): proxied: Response = Response(content=b"", status_code=429) elif not matter_proxy.query_is_acceptable(request.url.query): proxied = Response(content=b"", status_code=400) - elif not matter_proxy.known_device(self.runtime_state.vacuum_snapshot(), matter_query, client_ip): - proxied = Response(content=b"", status_code=403) else: - admitted = True - proxied = await matter_proxy.forward(request, self.config.network.region) + matched_id = matter_proxy.known_device(self.runtime_state.vacuum_snapshot(), matter_query, client_ip) + if matched_id is None: + proxied = Response(content=b"", status_code=403) + else: + proxied = await matter_proxy.forward(request, self.config.network.region) entry["route"] = "matter_key_proxy" entry["response_meta"] = {"status_code": proxied.status_code, "bytes": len(proxied.body)} try: - # Ids from a refused request are unverified: leaving them out keeps the event from creating a robot record. + # Only the id the gate matched is recorded: other id keys in the query are unverified and must not create a robot. self.runtime_state.record_http_event( event_time=str(entry["time"]), route_name="matter_key_proxy", @@ -1300,9 +1301,9 @@ async def _handle_roborock_request(self, request: Request) -> Response: method=request.method, host=host, remote=str(entry["remote"]), - did=(explicit_did or None) if admitted else None, - pid=(explicit_pid or None) if admitted else None, - model=(explicit_model or None) if admitted else None, + did=matched_id, + pid=(explicit_pid or None) if matched_id else None, + model=(explicit_model or None) if matched_id else None, ) except Exception as exc: # noqa: BLE001 logger.warning("runtime_state record_http_event failed: %s", exc) diff --git a/tests/test_matter_proxy.py b/tests/test_matter_proxy.py index e076d6f2..29c2e224 100644 --- a/tests/test_matter_proxy.py +++ b/tests/test_matter_proxy.py @@ -7,6 +7,7 @@ from aiohttp.test_utils import TestServer from fastapi.testclient import TestClient from starlette.requests import Request +from starlette.responses import Response from conftest import write_release_config from roborock_local_server import matter_proxy @@ -180,13 +181,13 @@ def test_the_rate_limit_is_per_client() -> None: def test_a_request_must_name_or_come_from_a_known_robot() -> None: robots = [{"duid": "D1", "did": "d1", "ips": ["10.0.0.7"], "last_ip": "10.0.0.7"}] - assert matter_proxy.known_device(robots, {"did": ["d1"]}, "9.9.9.9") - assert matter_proxy.known_device(robots, {"duid": ["D1"]}, "9.9.9.9") - assert not matter_proxy.known_device(robots, {"did": ["other"]}, "10.0.0.7") - assert matter_proxy.known_device(robots, {}, "10.0.0.7") - assert not matter_proxy.known_device(robots, {}, "9.9.9.9") - assert not matter_proxy.known_device([], {}, "10.0.0.7") - assert not matter_proxy.known_device(robots, {"device_id": ["d1"]}, "9.9.9.9") + assert matter_proxy.known_device(robots, {"did": ["d1"]}, "9.9.9.9") == "D1" + assert matter_proxy.known_device(robots, {"duid": ["D1"]}, "9.9.9.9") == "D1" + assert matter_proxy.known_device(robots, {"did": ["other"]}, "10.0.0.7") is None + assert matter_proxy.known_device(robots, {}, "10.0.0.7") == "D1" + assert matter_proxy.known_device(robots, {}, "9.9.9.9") is None + assert matter_proxy.known_device([], {}, "10.0.0.7") is None + assert matter_proxy.known_device(robots, {"device_id": ["d1"]}, "9.9.9.9") is None def _supervisor(tmp_path, monkeypatch, enabled: bool) -> ReleaseSupervisor: @@ -262,3 +263,38 @@ def test_the_route_records_an_event_without_creating_a_robot_for_a_refused_id(tm events = [e for e in supervisor.runtime_state.recent_events() if e.get("route") == "matter_key_proxy"] assert len(events) == 1 and events[0]["raw_path"] == PATH and events[0]["did"] is None assert supervisor.runtime_state.vacuum_snapshot() == [] + + +def _ghost_ids(supervisor) -> list[str]: + return [str(v.get("duid") or v.get("did")) for v in supervisor.runtime_state.vacuum_snapshot()] + + +def test_an_extra_id_key_cannot_create_a_robot_beside_a_known_duid(tmp_path, monkeypatch) -> None: + supervisor = _supervisor(tmp_path, monkeypatch, True) + supervisor.runtime_state.upsert_vacuum("D1", did="d1", name="Robot") + + async def fake_forward(request, region): + return Response(content=b"K") + + monkeypatch.setattr(matter_proxy, "forward", fake_forward) + TestClient(supervisor.app).get(PATH + "?duid=D1&d=ghost") + events = [e for e in supervisor.runtime_state.recent_events() if e.get("route") == "matter_key_proxy"] + assert len(events) == 1 and events[0]["did"] == "D1" + assert "ghost" not in _ghost_ids(supervisor) + + +def test_an_extra_id_key_cannot_create_a_robot_through_the_address_fallback(tmp_path, monkeypatch) -> None: + supervisor = _supervisor(tmp_path, monkeypatch, True) + supervisor.runtime_state.upsert_vacuum("D1", did="d1", name="Robot") + supervisor.runtime_state.record_http_event( + event_time="2026-01-01T00:00:00+00:00", route_name="region", clean_path="/region", raw_path="/region", + method="GET", host="h", remote="10.0.0.7:1", did="D1", + ) + + async def fake_forward(request, region): + return Response(content=b"K") + + monkeypatch.setattr(matter_proxy, "forward", fake_forward) + TestClient(supervisor.app, client=("10.0.0.7", 5000)).get(PATH + "?d=ghost") + assert "ghost" not in _ghost_ids(supervisor) + assert [e["did"] for e in supervisor.runtime_state.recent_events() if e.get("route") == "matter_key_proxy"] == ["D1"] From fb9670b82d72b8bc58088ba933d546ac78114e75 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:48:59 -0500 Subject: [PATCH 12/13] Keep the signed query out of the in-memory event with the proxy off 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 --- src/roborock_local_server/server.py | 1 + tests/test_matter_proxy.py | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py index 652fb349..80352661 100644 --- a/src/roborock_local_server/server.py +++ b/src/roborock_local_server/server.py @@ -1065,6 +1065,7 @@ async def _handle_roborock_request(self, request: Request) -> Response: } if matter_proxy.matches(clean_path, request.method): matter_proxy.redact_log_entry(entry) + raw_path = clean_path if explicit_did: entry["did"] = explicit_did if explicit_pid: diff --git a/tests/test_matter_proxy.py b/tests/test_matter_proxy.py index 29c2e224..40bb6910 100644 --- a/tests/test_matter_proxy.py +++ b/tests/test_matter_proxy.py @@ -298,3 +298,10 @@ async def fake_forward(request, region): TestClient(supervisor.app, client=("10.0.0.7", 5000)).get(PATH + "?d=ghost") assert "ghost" not in _ghost_ids(supervisor) assert [e["did"] for e in supervisor.runtime_state.recent_events() if e.get("route") == "matter_key_proxy"] == ["D1"] + + +def test_the_in_memory_event_has_no_signed_query_with_the_proxy_off(tmp_path, monkeypatch) -> None: + supervisor = _supervisor(tmp_path, monkeypatch, False) + TestClient(supervisor.app).get(PATH + "?did=d1&signature=QUERYSECRET") + events = [e for e in supervisor.runtime_state.recent_events() if e.get("path") == PATH] + assert events and all("QUERYSECRET" not in json.dumps(e) for e in supervisor.runtime_state.recent_events()) From 8752d453ffde9bc070bd3b78a37fb9531a4f092b Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:49:12 -0500 Subject: [PATCH 13/13] Rewrap the what-is-logged paragraph in the Matter doc One line ran past the 120-column wrap used in the rest of the file. Co-Authored-By: Claude Sonnet 5.5 --- docs/matter.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/matter.md b/docs/matter.md index 7e0e0e41..ee0f095b 100644 --- a/docs/matter.md +++ b/docs/matter.md @@ -49,9 +49,9 @@ a request without a robot id from a machine at a robot's address passes it. The shared request log (`http_jsonl`) normally stores every header and query value. For this route, with the proxy on or off, it keeps only the header and query names, the path without its query string, and the robot id if the -request carried one. With the proxy on it also records the response status and size. The console log has the same names and the answer's status and size. The key itself is never -logged. One thing outside this route still sees the robot's signed query: the device key cache, which stores signed -queries for key recovery as for any robot request. +request carried one. With the proxy on it also records the response status and size. The console log has the same +names and the answer's status and size. The key itself is never logged. One thing outside this route still sees the +robot's signed query: the device key cache, which stores signed queries for key recovery as for any robot request. Without the proxy, the robot's request reaches the catch-all route and the robot reports `KeyCorrupt`, because it got something that is not a key.