From 357c131d487109def6825e4dbe636cd433277bfc Mon Sep 17 00:00:00 2001 From: Tim Laing <11019084+timlaing@users.noreply.github.com> Date: Sun, 25 Oct 2026 10:57:57 +0000 Subject: [PATCH] Add diagnostics to the iCloud integration (#188279) --- homeassistant/components/icloud/account.py | 11 ++ .../components/icloud/diagnostics.py | 87 +++++++++ tests/components/icloud/const.py | 10 + .../icloud/snapshots/test_diagnostics.ambr | 106 +++++++++++ tests/components/icloud/test_diagnostics.py | 171 ++++++++++++++++++ 5 files changed, 385 insertions(+) create mode 100644 homeassistant/components/icloud/diagnostics.py create mode 100644 tests/components/icloud/snapshots/test_diagnostics.ambr create mode 100644 tests/components/icloud/test_diagnostics.py diff --git a/homeassistant/components/icloud/account.py b/homeassistant/components/icloud/account.py index 19edcb743e22..7f27ee18521f 100644 --- a/homeassistant/components/icloud/account.py +++ b/homeassistant/components/icloud/account.py @@ -1070,6 +1070,17 @@ class IcloudDevice: """Return whether the device supports lost mode.""" return self._device.lost_mode_available + @property + def raw_status(self) -> dict[str, Any]: + """Return the raw device data reported by Apple.""" + # update() stores the fetch interval in the status dict, which is + # account state rather than device data. + return { + key: value + for key, value in self._status.items() + if key != ATTR_ACCOUNT_FETCH_INTERVAL + } + @property def extra_state_attributes(self) -> dict[str, Any]: """Return the attributes.""" diff --git a/homeassistant/components/icloud/diagnostics.py b/homeassistant/components/icloud/diagnostics.py new file mode 100644 index 000000000000..0d292dc1244f --- /dev/null +++ b/homeassistant/components/icloud/diagnostics.py @@ -0,0 +1,87 @@ +"""Diagnostics support for iCloud.""" + +from typing import Any + +from homeassistant.components.diagnostics import async_redact_data +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.core import HomeAssistant +from homeassistant.helpers.device_registry import AnyDeviceEntry + +from .account import IcloudConfigEntry, IcloudDevice +from .const import ( + DEVICE_ID, + DEVICE_LOCATION_LATITUDE, + DEVICE_LOCATION_LONGITUDE, + DEVICE_PERSON_ID, + DOMAIN, +) + +TO_REDACT = { + CONF_PASSWORD, + CONF_USERNAME, + DEVICE_ID, + DEVICE_PERSON_ID, + DEVICE_LOCATION_LATITUDE, + DEVICE_LOCATION_LONGITUDE, + "family_members", + "owner_fullname", + # Lost mode contact number and message. + "ownerNbr", + "text", +} + + +async def async_get_config_entry_diagnostics( + hass: HomeAssistant, entry: IcloudConfigEntry +) -> dict[str, Any]: + """Return diagnostics for a config entry.""" + account = entry.runtime_data + + data: dict[str, Any] = { + "entry": { + "title": entry.title, + "data": entry.data, + }, + "account": _account_diagnostics(entry), + "devices": [device.raw_status for device in account.devices.values()], + } + return async_redact_data(data, TO_REDACT) + + +async def async_get_device_diagnostics( + hass: HomeAssistant, entry: IcloudConfigEntry, device: AnyDeviceEntry +) -> dict[str, Any]: + """Return diagnostics for a device.""" + icloud_device = _get_icloud_device(entry, device) + if icloud_device is None: + # The account device carries the calendars and to-do lists of the + # account, and devices iCloud no longer reports have no data at all. + return async_redact_data({"account": _account_diagnostics(entry)}, TO_REDACT) + + return async_redact_data(icloud_device.raw_status, TO_REDACT) + + +def _account_diagnostics(entry: IcloudConfigEntry) -> dict[str, Any]: + """Return the account information.""" + account = entry.runtime_data + return { + "username": account.username, + "owner_fullname": account.owner_fullname, + "family_members": list(account.family_members_fullname.values()), + "fetch_interval": account.fetch_interval, + "device_count": len(account.devices), + } + + +def _get_icloud_device( + entry: IcloudConfigEntry, device: AnyDeviceEntry +) -> IcloudDevice | None: + """Return the iCloud device linked to a device registry entry, if any.""" + identifier = next( + (identifier for domain, identifier in device.identifiers if domain == DOMAIN), + None, + ) + if identifier is None: + return None + + return entry.runtime_data.devices.get(identifier) diff --git a/tests/components/icloud/const.py b/tests/components/icloud/const.py index aeba6b6346d7..d473b342f17a 100644 --- a/tests/components/icloud/const.py +++ b/tests/components/icloud/const.py @@ -57,6 +57,8 @@ TRUSTED_DEVICES = [ ] FEATURES = { + "MSG": True, + "SND": True, "WIP": True, "LOC": True, "LCK": True, @@ -71,6 +73,8 @@ LOCATION = { "altitude": 5.0, "floorLevel": 2, "positionType": "GPS", + "isOld": False, + "isInaccurate": False, "timeStamp": LOCATION_TIMESTAMP_MS, } @@ -87,6 +91,12 @@ DEVICE = { "features": FEATURES, "lostModeCapable": True, "lowPowerMode": False, + "activationLocked": False, + "isLocating": False, + "locationEnabled": True, + "wipeInProgress": False, + "remoteWipe": None, + "remoteLock": None, "lockedTimestamp": None, "lostTimestamp": "", "wipedTimestamp": None, diff --git a/tests/components/icloud/snapshots/test_diagnostics.ambr b/tests/components/icloud/snapshots/test_diagnostics.ambr new file mode 100644 index 000000000000..6ccdb3926e43 --- /dev/null +++ b/tests/components/icloud/snapshots/test_diagnostics.ambr @@ -0,0 +1,106 @@ +# serializer version: 1 +# name: test_config_entry_diagnostics + dict({ + 'account': dict({ + 'device_count': 1, + 'family_members': '**REDACTED**', + 'fetch_interval': 15, + 'owner_fullname': '**REDACTED**', + 'username': '**REDACTED**', + }), + 'devices': list([ + dict({ + 'activationLocked': False, + 'batteryLevel': 0.8, + 'batteryStatus': 'NotCharging', + 'deviceClass': 'iPhone', + 'deviceDisplayName': 'iPhone', + 'deviceStatus': '200', + 'features': dict({ + 'LCK': True, + 'LOC': True, + 'MSG': True, + 'SND': True, + 'WIP': True, + }), + 'id': '**REDACTED**', + 'isLocating': False, + 'location': dict({ + 'altitude': 5.0, + 'floorLevel': 2, + 'horizontalAccuracy': 10, + 'isInaccurate': False, + 'isOld': False, + 'latitude': '**REDACTED**', + 'longitude': '**REDACTED**', + 'positionType': 'GPS', + 'timeStamp': 1700000000000, + }), + 'locationEnabled': True, + 'lockedTimestamp': None, + 'lostModeCapable': True, + 'lostTimestamp': '', + 'lowPowerMode': False, + 'name': 'iPhone', + 'prsId': None, + 'rawDeviceModel': 'iPhone14,2', + 'remoteLock': None, + 'remoteWipe': None, + 'wipeInProgress': False, + 'wipedTimestamp': None, + }), + ]), + 'entry': dict({ + 'data': dict({ + 'gps_accuracy_threshold': 500, + 'max_interval': 15, + 'password': '**REDACTED**', + 'username': '**REDACTED**', + 'with_family': False, + }), + 'title': 'Test iCloud Account', + }), + }) +# --- +# name: test_device_diagnostics + dict({ + 'activationLocked': False, + 'batteryLevel': 0.8, + 'batteryStatus': 'NotCharging', + 'deviceClass': 'iPhone', + 'deviceDisplayName': 'iPhone', + 'deviceStatus': '200', + 'features': dict({ + 'LCK': True, + 'LOC': True, + 'MSG': True, + 'SND': True, + 'WIP': True, + }), + 'id': '**REDACTED**', + 'isLocating': False, + 'location': dict({ + 'altitude': 5.0, + 'floorLevel': 2, + 'horizontalAccuracy': 10, + 'isInaccurate': False, + 'isOld': False, + 'latitude': '**REDACTED**', + 'longitude': '**REDACTED**', + 'positionType': 'GPS', + 'timeStamp': 1700000000000, + }), + 'locationEnabled': True, + 'lockedTimestamp': None, + 'lostModeCapable': True, + 'lostTimestamp': '', + 'lowPowerMode': False, + 'name': 'iPhone', + 'prsId': None, + 'rawDeviceModel': 'iPhone14,2', + 'remoteLock': None, + 'remoteWipe': None, + 'wipeInProgress': False, + 'wipedTimestamp': None, + }) +# --- diff --git a/tests/components/icloud/test_diagnostics.py b/tests/components/icloud/test_diagnostics.py new file mode 100644 index 000000000000..6d6197d89dfb --- /dev/null +++ b/tests/components/icloud/test_diagnostics.py @@ -0,0 +1,171 @@ +"""Tests for the iCloud diagnostics platform.""" + +from collections.abc import Awaitable, Callable + +import pytest +from pytest_homeassistant.common import MockConfigEntry +from pytest_homeassistant.components.diagnostics import ( + get_diagnostics_for_config_entry, + get_diagnostics_for_device, +) +from pytest_homeassistant.typing import ClientSessionGenerator, MagicMock +from syrupy.assertion import SnapshotAssertion + +from homeassistant.components.diagnostics import REDACTED +from homeassistant.components.icloud.const import DOMAIN +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import device_registry as dr + +from .const import DEVICE, LOCATION + + +async def test_config_entry_diagnostics( + hass: HomeAssistant, + icloud_service: MagicMock, + devices_config_entry: MockConfigEntry, + setup_entry: Callable[[Platform], Awaitable[None]], + hass_client: ClientSessionGenerator, + snapshot: SnapshotAssertion, +) -> None: + """Test config entry diagnostics.""" + icloud_service.devices.add({**DEVICE, "location": LOCATION}) + + await setup_entry(Platform.SENSOR) + + assert ( + await get_diagnostics_for_config_entry(hass, hass_client, devices_config_entry) + == snapshot + ) + + +async def test_device_diagnostics( + hass: HomeAssistant, + icloud_service: MagicMock, + devices_config_entry: MockConfigEntry, + device_registry: dr.DeviceRegistry, + setup_entry: Callable[[Platform], Awaitable[None]], + hass_client: ClientSessionGenerator, + snapshot: SnapshotAssertion, +) -> None: + """Test device diagnostics.""" + icloud_service.devices.add({**DEVICE, "location": LOCATION}) + + await setup_entry(Platform.SENSOR) + + device = device_registry.async_get_device_by_identifier( + (DOMAIN, DEVICE["id"]), devices_config_entry.entry_id + ) + assert device is not None + + assert ( + await get_diagnostics_for_device( + hass, hass_client, devices_config_entry, device + ) + == snapshot + ) + + +async def test_diagnostics_redacts_sensitive_data( + hass: HomeAssistant, + icloud_service: MagicMock, + devices_config_entry: MockConfigEntry, + device_registry: dr.DeviceRegistry, + setup_entry: Callable[[Platform], Awaitable[None]], + hass_client: ClientSessionGenerator, +) -> None: + """Diagnostics redact credentials, identity and location data.""" + icloud_service.devices.add( + { + **DEVICE, + "name": "iPhone de John", + "prsId": "johntravolta", + "location": LOCATION, + "lostDevice": {"text": "Call me", "ownerNbr": "+15551234567"}, + } + ) + + await setup_entry(Platform.SENSOR) + + entry_diagnostics = await get_diagnostics_for_config_entry( + hass, hass_client, devices_config_entry + ) + + assert entry_diagnostics["entry"]["data"]["username"] == REDACTED + assert entry_diagnostics["entry"]["data"]["password"] == REDACTED + assert entry_diagnostics["account"]["username"] == REDACTED + assert entry_diagnostics["account"]["owner_fullname"] == REDACTED + assert entry_diagnostics["account"]["family_members"] == REDACTED + + device_diagnostics = entry_diagnostics["devices"][0] + assert device_diagnostics["id"] == REDACTED + assert device_diagnostics["name"] == "iPhone de John" + assert device_diagnostics["prsId"] == REDACTED + assert device_diagnostics["location"]["latitude"] == REDACTED + assert device_diagnostics["location"]["longitude"] == REDACTED + assert device_diagnostics["lostDevice"]["ownerNbr"] == REDACTED + assert device_diagnostics["lostDevice"]["text"] == REDACTED + + device = device_registry.async_get_device_by_identifier( + (DOMAIN, DEVICE["id"]), devices_config_entry.entry_id + ) + assert device is not None + + device_only_diagnostics = await get_diagnostics_for_device( + hass, hass_client, devices_config_entry, device + ) + assert device_only_diagnostics["name"] == "iPhone de John" + assert device_only_diagnostics["location"]["latitude"] == REDACTED + + +@pytest.mark.parametrize( + ("identifiers", "entry_type"), + [ + pytest.param( + {(DOMAIN, "test_account_id_account")}, + dr.DeviceEntryType.SERVICE, + id="account_device", + ), + pytest.param( + {(DOMAIN, "missing_device")}, None, id="device_no_longer_reported" + ), + pytest.param( + {("other_domain", "foreign_device")}, + None, + id="device_without_icloud_identifier", + ), + ], +) +async def test_device_diagnostics_without_device_data( + hass: HomeAssistant, + icloud_service: MagicMock, + devices_config_entry: MockConfigEntry, + device_registry: dr.DeviceRegistry, + setup_entry: Callable[[Platform], Awaitable[None]], + hass_client: ClientSessionGenerator, + identifiers: set[tuple[str, str]], + entry_type: dr.DeviceEntryType | None, +) -> None: + """Test diagnostics for devices that have no device data of their own.""" + icloud_service.devices.add({**DEVICE, "location": LOCATION}) + + await setup_entry(Platform.SENSOR) + + device = device_registry.async_get_or_create( + config_entry_id=devices_config_entry.entry_id, + identifiers=identifiers, + name=devices_config_entry.title, + entry_type=entry_type, + ) + + assert await get_diagnostics_for_device( + hass, hass_client, devices_config_entry, device + ) == { + "account": { + "device_count": 1, + "family_members": REDACTED, + "fetch_interval": 15, + "owner_fullname": REDACTED, + "username": REDACTED, + } + }