Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
78 changes: 78 additions & 0 deletions docs/matter.md
Original file line number Diff line number Diff line change
@@ -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://<region>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.
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions src/roborock_local_server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from dataclasses import dataclass
import ipaddress
import os
from pathlib import Path
import re
import tomllib
Expand Down Expand Up @@ -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
Expand All @@ -113,6 +121,7 @@ class AppConfig:
admin: AdminConfig
turn: TurnConfig = TurnConfig()
logging: LoggingConfig = LoggingConfig()
matter: MatterConfig = MatterConfig()


@dataclass(frozen=True)
Expand Down Expand Up @@ -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"))
Expand All @@ -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"}:
Expand Down Expand Up @@ -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"),
Expand Down
143 changes: 143 additions & 0 deletions src/roborock_local_server/matter_proxy.py
Original file line number Diff line number Diff line change
@@ -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: "<redacted>" for key in headers}
query = entry.get("query")
if isinstance(query, dict):
entry["query"] = {key: "<redacted>" 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)
40 changes: 40 additions & 0 deletions src/roborock_local_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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,
Expand Down
Loading