Skip to content

Commit 02b84cf

Browse files
authored
fix: redact private data in device diagnostics (#1026)
* fix: redact private data in device diagnostics Redact JSON documents stored as strings, such as the A01 product info data point, which exposed the serial number, Wi-Fi name, IP and MAC. Also redact ssid and iotName. Decode the A01 product info and voice pack data points, which the device reports as JSON strings and always decoded to None, and add the decoded A01 state to device diagnostics as traits. * refactor: decode JSON strings before redacting diagnostics Decode JSON documents stored as strings and redact the result through the normal dict and list handling, instead of redacting and re-encoding them. JSON strings now appear as structured data in diagnostics. * refactor: decode A01 JSON data point values when they arrive Decode data point values that hold a JSON object or array as a string in decode_rpc_response and in the home data status snapshot, instead of in the SND_STATE, PRODUCT_INFO and SCHEDULE_TASK converters. Query responses, pushes and listeners now all get structured values. * refactor: tidy A01 decoding follow-ups Drop the simulator's JSON string query branch, which decode_rpc_response made unreachable, and keep JSON values in the string form the device sends. Make the redact_device_data return type cover lists, type the schedule converter input as wire data, explain why diagnostics has its own JSON decoder, and run the A01 diagnostics test for both Dyad and Zeo.
1 parent 135b43a commit 02b84cf

12 files changed

Lines changed: 675 additions & 98 deletions

File tree

‎roborock/devices/device.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,10 @@ def diagnostic_data(self) -> dict[str, Any]:
255255
extra: dict[str, Any] = {}
256256
if self.v1_properties:
257257
extra["traits"] = self.v1_properties.as_dict()
258+
elif self.dyad:
259+
extra["traits"] = self.dyad.as_dict()
260+
elif self.zeo:
261+
extra["traits"] = self.zeo.as_dict()
258262
elif self.b01_q10_properties:
259263
extra["traits"] = self.b01_q10_properties.as_dict()
260264
return redact_device_data(

‎roborock/devices/traits/a01/__init__.py‎

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,14 @@
3131
from datetime import UTC, datetime, time
3232
from typing import Any, Generic, TypeVar
3333

34-
from roborock.data import DyadProductInfo, DyadScheduleTask, DyadSndState, HomeDataProduct, RoborockCategory
34+
from roborock.data import (
35+
DyadProductInfo,
36+
DyadScheduleTask,
37+
DyadSndState,
38+
HomeDataProduct,
39+
RoborockBase,
40+
RoborockCategory,
41+
)
3542
from roborock.data.dyad.dyad_code_mappings import (
3643
DyadBrushSpeed,
3744
DyadCleanAssistPower,
@@ -72,7 +79,7 @@
7279
from roborock.devices.traits.common import TraitUpdateListener
7380
from roborock.devices.transport.mqtt_channel import MqttChannel
7481
from roborock.exceptions import RoborockException
75-
from roborock.protocols.a01_protocol import decode_rpc_response
82+
from roborock.protocols.a01_protocol import decode_datapoint_value, decode_rpc_response
7683
from roborock.roborock_message import (
7784
RoborockDyadDataProtocol,
7885
RoborockMessage,
@@ -89,11 +96,13 @@
8996
]
9097

9198

92-
def _decode_dyad_schedule(value: str) -> list[DyadScheduleTask]:
93-
"""Decode the schedule data point, which is a JSON list or an empty string."""
99+
def _decode_dyad_schedule(value: Any) -> list[DyadScheduleTask]:
100+
"""Decode the schedule data point, a list of tasks or an empty string when there are none."""
94101
if not value:
95102
return []
96-
return [DyadScheduleTask.from_dict(task) for task in json.loads(value)]
103+
if not isinstance(value, list):
104+
raise ValueError(f"Unexpected schedule value: {value!r}")
105+
return [DyadScheduleTask.from_dict(task) for task in value]
97106

98107

99108
DYAD_PROTOCOL_ENTRIES: dict[RoborockDyadDataProtocol, Callable] = {
@@ -191,6 +200,17 @@ def convert_zeo_value(protocol_value: RoborockZeoProtocol, value: Any) -> Any:
191200
return None
192201

193202

203+
def _diagnostic_value(value: Any) -> Any:
204+
"""Convert a decoded value to plain data for diagnostics."""
205+
if isinstance(value, RoborockBase):
206+
return value.as_dict()
207+
if isinstance(value, list):
208+
return [_diagnostic_value(item) for item in value]
209+
if isinstance(value, time):
210+
return value.isoformat()
211+
return value
212+
213+
194214
_DYAD_PROTOCOL_VALUES = frozenset(protocol.value for protocol in RoborockDyadDataProtocol)
195215
_ZEO_PROTOCOL_VALUES = frozenset(protocol.value for protocol in RoborockZeoProtocol)
196216

@@ -225,6 +245,10 @@ def values(self) -> dict[_P, Any]:
225245
"""
226246
return dict(self._values)
227247

248+
def as_dict(self) -> dict[str, Any]:
249+
"""Return the latest known state as plain data for diagnostics."""
250+
return {protocol.name: _diagnostic_value(value) for protocol, value in self._values.items()}
251+
228252
@property
229253
def last_message_time(self) -> datetime | None:
230254
"""Time the last message was received from the device.
@@ -459,11 +483,11 @@ async def set_value(self, protocol: RoborockZeoProtocol, value: Any) -> dict[Rob
459483

460484

461485
def _parse_device_status(device_status: dict | None) -> dict[int, Any] | None:
462-
"""Normalize the cloud home data status snapshot to integer datapoint codes."""
486+
"""Normalize the cloud home data status snapshot to integer datapoint codes and decoded values."""
463487
if not device_status:
464488
return None
465489
try:
466-
return {int(code): value for code, value in device_status.items()}
490+
return {int(code): decode_datapoint_value(value) for code, value in device_status.items()}
467491
except (TypeError, ValueError):
468492
_LOGGER.debug("Ignoring malformed device status snapshot: %s", device_status)
469493
return None

‎roborock/diagnostics.py‎

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,12 @@
99
DeviceManager.
1010
"""
1111

12+
import json
1213
import time
1314
from collections import Counter
1415
from collections.abc import Generator, Mapping
1516
from contextlib import contextmanager
16-
from typing import Any, Self, TypeVar, cast
17+
from typing import Any, Self, TypeVar, overload
1718

1819

1920
class Diagnostics:
@@ -106,7 +107,9 @@ def reset(self) -> None:
106107
"ipAddress",
107108
"ipAdress",
108109
"wifiName",
110+
"ssid",
109111
"rawName",
112+
"iotName",
110113
"lat",
111114
"long",
112115
}
@@ -123,13 +126,46 @@ def reset(self) -> None:
123126
REDACTED = "**REDACTED**"
124127

125128

126-
def redact_device_data(data: T, path: str = "") -> T | dict[str, Any]:
127-
"""Redact sensitive data in a dict."""
129+
def _decode_json_string(value: str) -> Any:
130+
"""Decode a JSON object or array stored as a string.
131+
132+
Some devices report structured data this way, such as the A01 product info
133+
data point. Any other string is returned unchanged.
134+
135+
`roborock.protocols.a01_protocol.decode_datapoint_value` does the same for A01
136+
data points. This module cannot import it: `roborock.util` imports this module,
137+
so the import would be circular.
138+
"""
139+
if not value.lstrip().startswith(("{", "[")):
140+
return value
141+
try:
142+
return json.loads(value)
143+
except json.JSONDecodeError:
144+
return value
145+
146+
147+
@overload
148+
def redact_device_data(data: Mapping[str, Any], path: str = "") -> dict[str, Any]: ...
149+
150+
151+
@overload
152+
def redact_device_data(data: T, path: str = "") -> T | dict[str, Any] | list[Any]: ...
153+
154+
155+
def redact_device_data(data: Any, path: str = "") -> Any:
156+
"""Redact sensitive data in a dict or list.
157+
158+
Strings holding a JSON object or array are decoded and redacted, so a string
159+
input can return a dict or a list. Other values are returned unchanged.
160+
"""
161+
if isinstance(data, str):
162+
data = _decode_json_string(data)
163+
128164
if not isinstance(data, (Mapping, list)):
129165
return data
130166

131167
if isinstance(data, list):
132-
return cast(T, [redact_device_data(item, path) for item in data])
168+
return [redact_device_data(item, path) for item in data]
133169

134170
redacted = {**data}
135171

@@ -141,7 +177,7 @@ def redact_device_data(data: T, path: str = "") -> T | dict[str, Any]:
141177
redacted[key] = REDACTED
142178
elif key == DEVICE_UID and isinstance(value, str):
143179
redacted[key] = redact_device_uid(value)
144-
elif isinstance(value, dict):
180+
elif isinstance(value, (dict, str)):
145181
redacted[key] = redact_device_data(value, curr_path)
146182
elif isinstance(value, list):
147183
redacted[key] = [redact_device_data(item, curr_path) for item in value]

‎roborock/protocols/a01_protocol.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,20 @@ def encode_mqtt_payload(
5555
)
5656

5757

58+
def decode_datapoint_value(value: Any) -> Any:
59+
"""Decode a data point value that holds a JSON object or array stored as a string.
60+
61+
Some data points are sent this way, such as the Dyad schedule and product info.
62+
Other values, including strings that are not valid JSON, are returned unchanged.
63+
"""
64+
if not isinstance(value, str) or not value.lstrip().startswith(("{", "[")):
65+
return value
66+
try:
67+
return json.loads(value)
68+
except json.JSONDecodeError:
69+
return value
70+
71+
5872
def decode_rpc_response(message: RoborockMessage) -> dict[int, Any]:
5973
"""Decode a V1 RPC_RESPONSE message."""
6074
if not message.payload:
@@ -73,7 +87,7 @@ def decode_rpc_response(message: RoborockMessage) -> dict[int, Any]:
7387
if not isinstance(datapoints, dict):
7488
raise RoborockException(f"Invalid A01 message format: 'dps' should be a dictionary for {message.payload!r}")
7589
try:
76-
return {int(key): value for key, value in datapoints.items()}
90+
return {int(key): decode_datapoint_value(value) for key, value in datapoints.items()}
7791
except ValueError as err:
7892
raise RoborockException(
7993
f"Invalid A01 message format: 'dps' key should be an integer for {message.payload!r}"

‎roborock/testing/a01_simulator.py‎

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -161,17 +161,8 @@ async def _handle_publish(self, message: RoborockMessage, channel: Any) -> None:
161161

162162
id_query_key = int(RoborockDyadDataProtocol.ID_QUERY)
163163
if query_raw := decoded_dps.get(id_query_key):
164-
query_list: list[Any] = []
165-
if isinstance(query_raw, str):
166-
try:
167-
parsed = json.loads(query_raw)
168-
if isinstance(parsed, list):
169-
query_list = parsed
170-
except (json.JSONDecodeError, TypeError):
171-
pass
172-
elif isinstance(query_raw, list):
173-
query_list = query_raw
174-
164+
# decode_rpc_response already decodes the JSON list of requested data points.
165+
query_list: list[Any] = query_raw if isinstance(query_raw, list) else []
175166
for key_val in query_list:
176167
key_int = int(_extract_int_value(key_val))
177168
if key_int in self.status:
@@ -184,7 +175,8 @@ async def _handle_publish(self, message: RoborockMessage, channel: Any) -> None:
184175
# Direct setters: update internal state for received DPS
185176
for code, val in decoded_dps.items():
186177
if code != id_query_key:
187-
self.status[code] = val
178+
# Keep JSON values in the string form the device sends.
179+
self.status[code] = json.dumps(val) if isinstance(val, (dict, list)) else val
188180
updated_dps[code] = val
189181

190182
if updated_dps:

0 commit comments

Comments
 (0)