diff --git a/config.example.toml b/config.example.toml index 02302870..4bd28e38 100644 --- a/config.example.toml +++ b/config.example.toml @@ -74,3 +74,8 @@ username = "" password = "" 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 new file mode 100644 index 00000000..ee0f095b --- /dev/null +++ b/docs/matter.md @@ -0,0 +1,78 @@ +# 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 sends data 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`, 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. 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 + +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. + +## 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 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..45c315d7 --- /dev/null +++ b/src/roborock_local_server/matter_proxy.py @@ -0,0 +1,143 @@ +"""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 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") + +_PATH = re.compile(r"^/(?:[A-Za-z0-9.-]+/)?fwapi/matter/key/?$") +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 +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") + + +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() + 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 "") + + +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: + logger.debug("Matter key request: header %r not forwarded", name) + continue + kept[name] = value + return kept + + +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) -> 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 str(vac.get("duid") or vac.get("did")) + if named: + 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: + """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)", + 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(url, encoded=True), headers=headers) as upstream: + body = await upstream.read() + content_type = upstream.headers.get("Content-Type", "application/octet-stream") + status = upstream.status + 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 99371d23..80352661 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 ( @@ -348,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) @@ -1061,6 +1063,9 @@ 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) + raw_path = clean_path if explicit_did: entry["did"] = explicit_did if explicit_pid: @@ -1271,6 +1276,41 @@ 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_query = matter_proxy.parse_query(request.url.query) + client_ip = request.client.host if request.client else "" + 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) + else: + 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: + # 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", + clean_path=clean_path, + raw_path=clean_path, + method=request.method, + host=host, + remote=str(entry["remote"]), + 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) + 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..40bb6910 --- /dev/null +++ b/tests/test_matter_proxy.py @@ -0,0 +1,307 @@ +import asyncio +import json +import logging + +import pytest +from aiohttp import web +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 +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") + 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("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: + 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 _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: + 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: + 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") == "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: + monkeypatch.setenv("ROBOROCK_SERVER_MATTER_KEY_PROXY", "true" if enabled else "false") + config_file = write_release_config(tmp_path) + config = load_config(config_file) + 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"] + + +def test_when_disabled_nothing_is_forwarded(tmp_path, monkeypatch) -> None: + supervisor = _supervisor(tmp_path, monkeypatch, False) + called = [] + + async def fail_forward(request, region): + called.append(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&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: + 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] + + +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() == [] + + +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"] + + +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())