diff --git a/docs/device-info.md b/docs/device-info.md index e90eb7ab..0b243a2c 100644 --- a/docs/device-info.md +++ b/docs/device-info.md @@ -23,12 +23,27 @@ against the device public key recovered during onboarding and checks that the body DID matches the URL DID. Only unambiguous reports with one value per field are persisted. Query parameters do not supply or override metadata. -This handler accepts exactly these six fields, nonempty metadata values of -1–128 ASCII letters, digits, dots, underscores or hyphens, decimal `featureset`, -and hexadecimal `newfeatureset`. These conservative limits match the observed -reports; authentic firmware variants outside them are acknowledged and logged as -unsupported without writing. They require further evidence before expanding the -accepted contract. +The Saros 20 Flow (`roborock.vacuum.a307`) uses a V2 form instead. It sends the +five metadata fields as `multipart/form-data` parts, without a `signature` part. +Four headers carry the signature: `v` is `v2`, `n` is a nonce, `t` is a Unix +timestamp and `s` is the base64 signature. The device signs the form above, +followed by the nonce and the timestamp, with PKCS#1 v1.5 and SHA-384: + +```text +did=&featureset=&newfeatureset=&pid=&sn=:: +``` + +The server rebuilds this text in the field order above, whatever the order of +the parts. It verifies the signature with the same device public key and applies +the same checks. An upload of the five fields counts as malformed if a header is +missing or `v` is not `v2`. + +This handler accepts exactly the fields of either form, nonempty metadata +values of 1–128 ASCII letters, digits, dots, underscores or hyphens, decimal +`featureset`, and hexadecimal `newfeatureset`. These conservative limits match +the observed reports; authentic firmware variants outside them are acknowledged +and logged as unsupported without writing. They require further evidence before +expanding the accepted contract. For an existing inventory device matched by DID, or by its runtime DID-to-DUID link, verified reports update `sn`, `featureSet`, and `newFeatureSet` in @@ -45,8 +60,10 @@ acknowledgement behavior. Responses retain the previous fallback body, including The inspected G10S firmware ignores that body; preserving it avoids changing the response contract for other models whose callback has not been audited. -There is no nonce or timestamp in this form. A valid recorded report can be -replayed; signature verification establishes its origin, not its freshness. +The form with a `signature` field has no nonce or timestamp. The V2 form has +both, but the server does not check them for freshness or reuse. A valid +recorded report of either form can be replayed; signature verification +establishes its origin, not its freshness. No replayed report can change identity or credentials through this handler. The server logs the DID, an outcome (`stored`, `unchanged`, `unmatched`, @@ -90,3 +107,7 @@ acknowledgement for other contracts and refuses metadata writes when verificatio fails. A cloud response capture is unnecessary for the inspected G10S callback, but would be needed to describe the cloud's exact response body or another model's response parser. + +One a307 upload was verified with its recovered RSA public key against the V2 +form and its PKCS#1 v1.5/SHA-384 contract. No raw signatures, serial numbers, +nonces or keys are included here. diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/bootstrap/device_info.py b/src/roborock_local_server/bundled_backend/https_server/routes/bootstrap/device_info.py index d9e24d7c..d92983db 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/bootstrap/device_info.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/bootstrap/device_info.py @@ -1,8 +1,10 @@ """Acknowledge signed firmware metadata uploads and update known devices. The G10S rriot_rr upload callback accepts HTTP 200/201 and ignores the response -body. Its form is RSA PKCS#1 v1.5/SHA-256 signed in the field order below. See -docs/device-info.md for firmware evidence and the limits of this contract. +body. Its form is RSA PKCS#1 v1.5/SHA-256 signed in the field order below. The +a307 omits the signature field and sends a V2 header signature instead: SHA-384 +over the same fields, followed by the nonce and timestamp headers. See +docs/device-info.md for firmware evidence and the limits of these contracts. """ from __future__ import annotations @@ -17,6 +19,7 @@ from cryptography.hazmat.primitives.asymmetric import padding from shared.context import ServerContext +from shared.http_helpers import route_header from shared.inventory_io import WEB_API_INVENTORY_FILE, inventory_transaction, load_inventory, write_inventory from .catchall import build as _build_catchall @@ -31,13 +34,33 @@ def match(path: str, method: str = "POST") -> bool: return method.upper() == "POST" and _PATH.fullmatch(path) is not None +def _signature_contract( + query_params: dict[str, list[str]], params: dict[str, list[str]] +) -> tuple[str, str, hashes.HashAlgorithm] | None: + """Pick the signature form of an upload, or None if the form is unknown. + + The result is the base64 signature, the text that follows the canonical + fields in the signed message, and the hash algorithm. + """ + if set(params) == {*_FIELDS, "signature"}: + return params["signature"][0], "", hashes.SHA256() + if set(params) != set(_FIELDS) or route_header(query_params, "v") != "v2": + return None + nonce, timestamp, signature = (route_header(query_params, name) for name in ("n", "t", "s")) + if not (nonce and timestamp and signature): + return None + return signature, f":{nonce}:{timestamp}", hashes.SHA384() + + def _verified_report( - ctx: ServerContext, params: dict[str, list[str]], did: str + ctx: ServerContext, query_params: dict[str, list[str]], params: dict[str, list[str]], did: str ) -> tuple[dict[str, str] | None, str]: # Duplicates and extra fields would make reconstructing the signed message # ambiguous. Unsupported forms retain the acknowledgement but cannot write. - if set(params) != {*_FIELDS, "signature"} or any(len(v) != 1 for v in params.values()): + contract = _signature_contract(query_params, params) + if contract is None or any(len(v) != 1 for v in params.values()): return None, "malformed_fields" + signature_b64, suffix, algorithm = contract fields = {name: params[name][0] for name in _FIELDS} if fields["did"] != did: return None, "did_mismatch" @@ -50,8 +73,8 @@ def _verified_report( return None, "missing_key" canonical = "&".join(f"{name}={fields[name]}" for name in _FIELDS) try: - signature = base64.b64decode(params["signature"][0], validate=True) - key.verify(signature, canonical.encode("ascii"), padding.PKCS1v15(), hashes.SHA256()) + signature = base64.b64decode(signature_b64, validate=True) + key.verify(signature, (canonical + suffix).encode("ascii"), padding.PKCS1v15(), algorithm) except (InvalidSignature, ValueError, TypeError): return None, "invalid_signature" return fields, "verified" @@ -59,14 +82,14 @@ def _verified_report( def build( ctx: ServerContext, - _query_params: dict[str, list[str]], + query_params: dict[str, list[str]], body_params: dict[str, list[str]], clean_path: str, ) -> dict[str, Any]: path_match = _PATH.fullmatch(clean_path) assert path_match is not None # Route matcher already checked the path. did = path_match.group(1) - report, outcome = _verified_report(ctx, body_params, did) + report, outcome = _verified_report(ctx, query_params, body_params, did) updated_count = 0 if report is not None: identities = {did} @@ -106,7 +129,9 @@ def build( outcome = "stored" else: outcome, updated_count = "write_failed", 0 - _LOGGER.info("Device info did=%s outcome=%s updated=%d", did, outcome, updated_count) + # A module logger has no handler, so INFO would be dropped. The context + # loggers write to the server log files and stdout. + ctx.loggers.get("api", _LOGGER).info("Device info did=%s outcome=%s updated=%d", did, outcome, updated_count) # No response data is consumed by the verified firmware. Continue accepting # unsupported/unverifiable reports without allowing them to alter inventory. - return _build_catchall(ctx, _query_params, body_params, clean_path) + return _build_catchall(ctx, query_params, body_params, clean_path) diff --git a/src/roborock_local_server/bundled_backend/shared/http_helpers.py b/src/roborock_local_server/bundled_backend/shared/http_helpers.py index d4864108..12c7df76 100644 --- a/src/roborock_local_server/bundled_backend/shared/http_helpers.py +++ b/src/roborock_local_server/bundled_backend/shared/http_helpers.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Any +from typing import Any, Mapping def classify_host(host: str) -> str: @@ -34,6 +34,34 @@ def pick_first(values: list[str]) -> str: return "" +# Route builders receive no request headers. These headers reach them as +# "__header_" query pseudo-params, like "__host". The a307 sends these +# four names with its device info upload. The key capture in server.py also +# tries aliases like "sign", "nonce" and "ts", but no device info upload is +# known to use them. +_ROUTE_HEADERS = ("v", "n", "t", "s") +_ROUTE_HEADER_PREFIX = "__header_" + + +def with_route_headers(query_params: dict[str, list[str]], headers: Mapping[str, str]) -> dict[str, list[str]]: + """Return query_params with the route headers added as pseudo-params. + + A query cannot supply them: pseudo-params from the query are dropped. + """ + params = {key: values for key, values in query_params.items() if not key.startswith(_ROUTE_HEADER_PREFIX)} + for name in _ROUTE_HEADERS: + value = str(headers.get(name) or "").strip() + if value: + params[f"{_ROUTE_HEADER_PREFIX}{name}"] = [value] + return params + + +def route_header(query_params: dict[str, list[str]], name: str) -> str: + """Return a header that with_route_headers added, or "" if it was absent.""" + values = query_params.get(f"{_ROUTE_HEADER_PREFIX}{name}") or [""] + return values[0] + + def wrap_response(data: Any) -> dict[str, Any]: return { "success": True, diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py index 424ac0c9..06d5f1b3 100644 --- a/src/roborock_local_server/server.py +++ b/src/roborock_local_server/server.py @@ -52,6 +52,7 @@ start_broker, strip_roborock_prefix, ) +from shared.http_helpers import with_route_headers from shared.inventory_io import atomic_write_inventory, inventory_transaction from shared.protocol_auth import ProtocolAuthStore from shared.schedule_runner import ScheduleRunner @@ -1364,7 +1365,7 @@ async def _handle_roborock_request(self, request: Request) -> Response: rules=self.endpoint_rules, context=self.context, clean_path=clean_path, - query_params=query_params, + query_params=with_route_headers(query_params, request_headers), body_params=body_params, method=request.method, ) diff --git a/tests/test_device_info.py b/tests/test_device_info.py index f6a240a9..f5f48c13 100644 --- a/tests/test_device_info.py +++ b/tests/test_device_info.py @@ -12,11 +12,22 @@ import roborock_local_server.backend as backend from https_server.routes.bootstrap import catchall, device_info +from shared import http_helpers + +# Synthetic V2 header values; the signature header is added per test. +V2_HEADERS = {"v": "v2", "n": "q7Xk2P", "t": "1767225600"} +# Stands in for the real_stack.api logger of the server context. +API_LOGGER = "test_device_info.api" + + +@pytest.fixture +def signing_key(): + return rsa.generate_private_key(public_exponent=65537, key_size=2048) @pytest.fixture -def setup_report(tmp_path): - key = rsa.generate_private_key(public_exponent=65537, key_size=2048) +def setup_report(tmp_path, signing_key): + key = signing_key inventory = { "home": {"name": "Home"}, "devices": [ @@ -27,7 +38,8 @@ def setup_report(tmp_path): path = tmp_path / "web_api_inventory.json" path.write_text(json.dumps(inventory)) ctx = SimpleNamespace(http_jsonl=tmp_path / "http.jsonl", runtime_credentials=None, - device_public_key=lambda did: key.public_key() if did == "123" else None) + device_public_key=lambda did: key.public_key() if did == "123" else None, + loggers={"api": logging.getLogger(API_LOGGER)}) fields = {"did": "123", "featureset": "123456789", "newfeatureset": "0000000AbCD", "pid": "roborock.vacuum.a87", "sn": "TESTSERIAL"} canonical = "&".join(f"{name}={value}" for name, value in fields.items()).encode() params = {name: [value] for name, value in fields.items()} @@ -35,9 +47,28 @@ def setup_report(tmp_path): return ctx, path, inventory, params -def _request(ctx, params, *, path="/devices/123/info", method="POST"): +def _sign_v2(key, params, headers, algorithm=None): + canonical = "&".join(f"{name}={values[0]}" for name, values in params.items()) + message = f"{canonical}:{headers['n']}:{headers['t']}".encode() + return base64.b64encode(key.sign(message, padding.PKCS1v15(), algorithm or hashes.SHA384())).decode() + + +@pytest.fixture +def setup_v2_report(setup_report, signing_key): + ctx, path, inventory, params = setup_report + del params["signature"] + headers = {**V2_HEADERS, "s": _sign_v2(signing_key, params, V2_HEADERS)} + return ctx, path, inventory, params, headers + + +def _request(ctx, params, *, path="/devices/123/info", method="POST", headers=None): + query_params = {} if headers is None else http_helpers.with_route_headers({}, headers) return backend.resolve_route(rules=backend.default_endpoint_rules(), context=ctx, clean_path=path, - query_params={}, body_params=params, method=method) + query_params=query_params, body_params=params, method=method) + + +def _outcome_log(caplog): + return "\n".join(r.getMessage() for r in caplog.records if r.name == API_LOGGER) def test_verified_upload_updates_only_metadata(setup_report): @@ -131,25 +162,96 @@ def test_outcome_diagnostics_are_sanitized(setup_report, caplog, monkeypatch, ch path.write_text('{"devices": []}') elif change == "write_failed": monkeypatch.setattr(device_info, "write_inventory", lambda *args: False) - with caplog.at_level(logging.INFO, logger=device_info.__name__): + with caplog.at_level(logging.INFO, logger=API_LOGGER): _request(ctx, params) - assert f"did=123 outcome={outcome} updated=" in caplog.text + assert f"did=123 outcome={outcome} updated=" in _outcome_log(caplog) assert params["sn"][0] not in caplog.text assert params["signature"][0] not in caplog.text -@pytest.mark.parametrize("prefix", ["", "/.roborock.com"]) -def test_real_http_form_preserves_base64_signature(tmp_path, prefix): +def test_v2_header_signed_upload_updates_metadata(setup_v2_report): + ctx, path, original, params, headers = setup_v2_report + route, response = _request(ctx, params, headers=headers) + assert route == "device_info" + assert response == catchall.build(ctx, {}, params, "/devices/123/info") + device = json.loads(path.read_text())["devices"][0] + assert (device["sn"], device["featureSet"], device["newFeatureSet"]) == ("TESTSERIAL", "123456789", "0000000AbCD") + assert {key: device[key] for key in original["devices"][0]} == original["devices"][0] + + +@pytest.mark.parametrize("change,outcome", [ + ("tampered", "invalid_signature"), ("other_key", "invalid_signature"), ("sha256", "invalid_signature"), + ("bad_base64", "invalid_signature"), ("nonce", "invalid_signature"), ("timestamp", "invalid_signature"), + ("short_signature", "invalid_signature"), ("long_signature", "invalid_signature"), + ("missing_v", "malformed_fields"), ("missing_n", "malformed_fields"), ("missing_t", "malformed_fields"), + ("missing_s", "malformed_fields"), ("version", "malformed_fields"), ("duplicate", "malformed_fields"), + ("wrong_did", "did_mismatch"), ("unsafe_value", "unsupported_values"), ("unknown_key", "missing_key"), +]) +def test_unverifiable_v2_upload_acknowledged_without_writes(setup_v2_report, signing_key, caplog, change, outcome): + ctx, path, _, params, headers = setup_v2_report + before = path.read_bytes() + if change == "tampered": params["sn"] = ["ALTERED"] + if change == "other_key": headers["s"] = _sign_v2(rsa.generate_private_key(public_exponent=65537, key_size=2048), params, headers) + if change == "sha256": headers["s"] = _sign_v2(signing_key, params, headers, hashes.SHA256()) + if change == "bad_base64": headers["s"] = "!!!!" + # key.verify rejects a signature whose length differs from the key size. + if change == "short_signature": headers["s"] = base64.b64encode(base64.b64decode(headers["s"])[:-1]).decode() + if change == "long_signature": headers["s"] = base64.b64encode(base64.b64decode(headers["s"]) + b"\0").decode() + if change == "nonce": headers["n"] = "q7Xk2Q" + if change == "timestamp": headers["t"] = "1767225601" + if change.startswith("missing_"): del headers[change.removeprefix("missing_")] + if change == "version": headers["v"] = "v1" + if change == "duplicate": params["did"].append("456") + if change == "wrong_did": params["did"] = ["456"] + if change == "unsafe_value": params["sn"] = ["TEST SERIAL"] + if change == "unknown_key": ctx.device_public_key = lambda did: None + with caplog.at_level(logging.INFO, logger=API_LOGGER): + route, response = _request(ctx, params, headers=headers) + assert route == "device_info" and response["code"] == 200 + assert path.read_bytes() == before + assert f"did=123 outcome={outcome} updated=0" in _outcome_log(caplog) + + +def test_v1_form_ignores_v2_headers(setup_report): + ctx, path, _, params = setup_report + headers = {**V2_HEADERS, "s": base64.b64encode(b"\0" * 256).decode()} + _request(ctx, params, headers=headers) + assert json.loads(path.read_text())["devices"][0]["sn"] == "TESTSERIAL" + + +def test_query_cannot_supply_route_headers(): + query = {"__header_s": ["forged"], "__host": ["example.com"]} + assert http_helpers.with_route_headers(query, {}) == {"__host": ["example.com"]} + assert http_helpers.with_route_headers(query, {"s": " real "})["__header_s"] == ["real"] + + +_TEST_FIELDS = {"did": "123", "featureset": "123456789", "newfeatureset": "0000000AbCD", + "pid": "roborock.vacuum.a87", "sn": "TESTSERIAL"} + + +def _release_supervisor(tmp_path, key): from conftest import write_release_config - from fastapi.testclient import TestClient from roborock_local_server.config import load_config, resolve_paths from roborock_local_server.server import ReleaseSupervisor config_file = write_release_config(tmp_path) config = load_config(config_file) paths = resolve_paths(config_file, config) - fields = {"did": "123", "featureset": "123456789", "newfeatureset": "0000000AbCD", - "pid": "roborock.vacuum.a87", "sn": "TESTSERIAL"} + for path, payload in ( + (paths.inventory_path, {"devices": [{"did": "123", "duid": "cloud-a"}]}), + (paths.device_key_state_path, + {"devices": {"123": {"modulus_hex": format(key.public_key().public_numbers().n, "x")}}}), + ): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload)) + return ReleaseSupervisor(config=config, paths=paths), paths + + +@pytest.mark.parametrize("prefix", ["", "/.roborock.com"]) +def test_real_http_form_preserves_base64_signature(tmp_path, prefix): + from fastapi.testclient import TestClient + + fields = _TEST_FIELDS canonical = "&".join(f"{name}={value}" for name, value in fields.items()).encode() # Select a synthetic key whose signature exercises both URL-escaped chars. for _ in range(100): @@ -159,14 +261,7 @@ def test_real_http_form_preserves_base64_signature(tmp_path, prefix): break else: pytest.fail("Could not produce representative synthetic signature") - for path, payload in ( - (paths.inventory_path, {"devices": [{"did": "123", "duid": "cloud-a"}]}), - (paths.device_key_state_path, - {"devices": {"123": {"modulus_hex": format(key.public_key().public_numbers().n, "x")}}}), - ): - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(payload)) - supervisor = ReleaseSupervisor(config=config, paths=paths) + supervisor, paths = _release_supervisor(tmp_path, key) body = urlencode({**fields, "signature": signature}) assert "%2B" in body and "%2F" in body with TestClient(supervisor.app) as client: @@ -178,3 +273,20 @@ def test_real_http_form_preserves_base64_signature(tmp_path, prefix): assert inventory["devices"][0]["sn"] == fields["sn"] entries = [json.loads(line) for line in paths.http_jsonl_path.read_text().splitlines()] assert entries[-1]["route"] == "device_info" + + +def test_real_http_multipart_v2_upload(tmp_path, signing_key): + from fastapi.testclient import TestClient + + supervisor, paths = _release_supervisor(tmp_path, signing_key) + params = {name: [value] for name, value in _TEST_FIELDS.items()} + headers = {**V2_HEADERS, "s": _sign_v2(signing_key, params, V2_HEADERS)} + boundary = "deviceinfotestboundary" + body = "".join(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n' + for name, value in _TEST_FIELDS.items()) + f"--{boundary}--\r\n" + with TestClient(supervisor.app) as client: + response = client.post("/devices/123/info", content=body, + headers={"content-type": f"multipart/form-data; boundary={boundary}", **headers}) + assert response.status_code == 200 + assert json.loads(paths.inventory_path.read_text())["devices"][0]["sn"] == "TESTSERIAL" + assert "Device info did=123 outcome=stored updated=1" in (paths.runtime_dir / "api_server.log").read_text()