From 7ff90ca49db53e245442ca3e8f3ee7b40bb6156f Mon Sep 17 00:00:00 2001 From: Maciej Bieniek Date: Wed, 2 Jul 2025 13:06:27 +0200 Subject: [PATCH] Open repair issue when outbound WebSocket is enabled for Shelly non-sleeping RPC device (#147901) --- homeassistant/components/shelly/__init__.py | 9 +- homeassistant/components/shelly/const.py | 3 + homeassistant/components/shelly/repairs.py | 91 +++++++++++++++++++- homeassistant/components/shelly/strings.json | 14 +++ tests/components/shelly/test_repairs.py | 82 ++++++++++++++++++ 5 files changed, 194 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/shelly/__init__.py b/homeassistant/components/shelly/__init__.py index 75fedf9b16d..0467b93a7c8 100644 --- a/homeassistant/components/shelly/__init__.py +++ b/homeassistant/components/shelly/__init__.py @@ -56,7 +56,10 @@ from .coordinator import ( ShellyRpcCoordinator, ShellyRpcPollingCoordinator, ) -from .repairs import async_manage_ble_scanner_firmware_unsupported_issue +from .repairs import ( + async_manage_ble_scanner_firmware_unsupported_issue, + async_manage_outbound_websocket_incorrectly_enabled_issue, +) from .utils import ( async_create_issue_unsupported_firmware, get_coap_context, @@ -327,6 +330,10 @@ async def _async_setup_rpc_entry(hass: HomeAssistant, entry: ShellyConfigEntry) hass, entry, ) + async_manage_outbound_websocket_incorrectly_enabled_issue( + hass, + entry, + ) elif ( sleep_period is None or device_entry is None diff --git a/homeassistant/components/shelly/const.py b/homeassistant/components/shelly/const.py index 7462766e2d4..60fc5b03d13 100644 --- a/homeassistant/components/shelly/const.py +++ b/homeassistant/components/shelly/const.py @@ -237,6 +237,9 @@ NOT_CALIBRATED_ISSUE_ID = "not_calibrated_{unique}" FIRMWARE_UNSUPPORTED_ISSUE_ID = "firmware_unsupported_{unique}" BLE_SCANNER_FIRMWARE_UNSUPPORTED_ISSUE_ID = "ble_scanner_firmware_unsupported_{unique}" +OUTBOUND_WEBSOCKET_INCORRECTLY_ENABLED_ISSUE_ID = ( + "outbound_websocket_incorrectly_enabled_{unique}" +) GAS_VALVE_OPEN_STATES = ("opening", "opened") diff --git a/homeassistant/components/shelly/repairs.py b/homeassistant/components/shelly/repairs.py index c39f619fc6c..e1b15f04417 100644 --- a/homeassistant/components/shelly/repairs.py +++ b/homeassistant/components/shelly/repairs.py @@ -11,7 +11,7 @@ from awesomeversion import AwesomeVersion import voluptuous as vol from homeassistant import data_entry_flow -from homeassistant.components.repairs import RepairsFlow +from homeassistant.components.repairs import ConfirmRepairFlow, RepairsFlow from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import issue_registry as ir @@ -20,9 +20,11 @@ from .const import ( BLE_SCANNER_MIN_FIRMWARE, CONF_BLE_SCANNER_MODE, DOMAIN, + OUTBOUND_WEBSOCKET_INCORRECTLY_ENABLED_ISSUE_ID, BLEScannerMode, ) from .coordinator import ShellyConfigEntry +from .utils import get_rpc_ws_url @callback @@ -65,7 +67,46 @@ def async_manage_ble_scanner_firmware_unsupported_issue( ir.async_delete_issue(hass, DOMAIN, issue_id) -class BleScannerFirmwareUpdateFlow(RepairsFlow): +@callback +def async_manage_outbound_websocket_incorrectly_enabled_issue( + hass: HomeAssistant, + entry: ShellyConfigEntry, +) -> None: + """Manage the Outbound WebSocket incorrectly enabled issue.""" + issue_id = OUTBOUND_WEBSOCKET_INCORRECTLY_ENABLED_ISSUE_ID.format( + unique=entry.unique_id + ) + + if TYPE_CHECKING: + assert entry.runtime_data.rpc is not None + + device = entry.runtime_data.rpc.device + + if ( + (ws_config := device.config.get("ws")) + and ws_config["enable"] + and ws_config["server"] == get_rpc_ws_url(hass) + ): + ir.async_create_issue( + hass, + DOMAIN, + issue_id, + is_fixable=True, + is_persistent=True, + severity=ir.IssueSeverity.WARNING, + translation_key="outbound_websocket_incorrectly_enabled", + translation_placeholders={ + "device_name": device.name, + "ip_address": device.ip_address, + }, + data={"entry_id": entry.entry_id}, + ) + return + + ir.async_delete_issue(hass, DOMAIN, issue_id) + + +class ShellyRpcRepairsFlow(RepairsFlow): """Handler for an issue fixing flow.""" def __init__(self, device: RpcDevice) -> None: @@ -83,7 +124,7 @@ class BleScannerFirmwareUpdateFlow(RepairsFlow): ) -> data_entry_flow.FlowResult: """Handle the confirm step of a fix flow.""" if user_input is not None: - return await self.async_step_update_firmware() + return await self._async_step_confirm() issue_registry = ir.async_get(self.hass) description_placeholders = None @@ -96,6 +137,18 @@ class BleScannerFirmwareUpdateFlow(RepairsFlow): description_placeholders=description_placeholders, ) + async def _async_step_confirm(self) -> data_entry_flow.FlowResult: + """Handle the confirm step of a fix flow.""" + raise NotImplementedError + + +class BleScannerFirmwareUpdateFlow(ShellyRpcRepairsFlow): + """Handler for BLE Scanner Firmware Update flow.""" + + async def _async_step_confirm(self) -> data_entry_flow.FlowResult: + """Handle the confirm step of a fix flow.""" + return await self.async_step_update_firmware() + async def async_step_update_firmware( self, user_input: dict[str, str] | None = None ) -> data_entry_flow.FlowResult: @@ -110,6 +163,29 @@ class BleScannerFirmwareUpdateFlow(RepairsFlow): return self.async_create_entry(title="", data={}) +class DisableOutboundWebSocketFlow(ShellyRpcRepairsFlow): + """Handler for Disable Outbound WebSocket flow.""" + + async def _async_step_confirm(self) -> data_entry_flow.FlowResult: + """Handle the confirm step of a fix flow.""" + return await self.async_step_disable_outbound_websocket() + + async def async_step_disable_outbound_websocket( + self, user_input: dict[str, str] | None = None + ) -> data_entry_flow.FlowResult: + """Handle the confirm step of a fix flow.""" + try: + result = await self._device.ws_setconfig( + False, self._device.config["ws"]["server"] + ) + if result["restart_required"]: + await self._device.trigger_reboot() + except (DeviceConnectionError, RpcCallError): + return self.async_abort(reason="cannot_connect") + + return self.async_create_entry(title="", data={}) + + async def async_create_fix_flow( hass: HomeAssistant, issue_id: str, data: dict[str, str] | None ) -> RepairsFlow: @@ -124,4 +200,11 @@ async def async_create_fix_flow( assert entry is not None device = entry.runtime_data.rpc.device - return BleScannerFirmwareUpdateFlow(device) + + if "ble_scanner_firmware_unsupported" in issue_id: + return BleScannerFirmwareUpdateFlow(device) + + if "outbound_websocket_incorrectly_enabled" in issue_id: + return DisableOutboundWebSocketFlow(device) + + return ConfirmRepairFlow() diff --git a/homeassistant/components/shelly/strings.json b/homeassistant/components/shelly/strings.json index 28f3a993462..c1d520a59f1 100644 --- a/homeassistant/components/shelly/strings.json +++ b/homeassistant/components/shelly/strings.json @@ -288,6 +288,20 @@ "unsupported_firmware": { "title": "Unsupported firmware for device {device_name}", "description": "Your Shelly device {device_name} with IP address {ip_address} is running an unsupported firmware. Please update the firmware.\n\nIf the device does not offer an update, check internet connectivity (gateway, DNS, time) and restart the device." + }, + "outbound_websocket_incorrectly_enabled": { + "title": "Outbound WebSocket is enabled for {device_name}", + "fix_flow": { + "step": { + "confirm": { + "title": "Outbound WebSocket is enabled for {device_name}", + "description": "Your Shelly device {device_name} with IP address {ip_address} is a non-sleeping device and Outbound WebSocket should be disabled in its configuration.\n\nSelect **Submit** button to disable Outbound WebSocket." + } + }, + "abort": { + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]" + } + } } } } diff --git a/tests/components/shelly/test_repairs.py b/tests/components/shelly/test_repairs.py index f68d2f82f1b..8dfd59c49ba 100644 --- a/tests/components/shelly/test_repairs.py +++ b/tests/components/shelly/test_repairs.py @@ -9,6 +9,7 @@ from homeassistant.components.shelly.const import ( BLE_SCANNER_FIRMWARE_UNSUPPORTED_ISSUE_ID, CONF_BLE_SCANNER_MODE, DOMAIN, + OUTBOUND_WEBSOCKET_INCORRECTLY_ENABLED_ISSUE_ID, BLEScannerMode, ) from homeassistant.core import HomeAssistant @@ -129,3 +130,84 @@ async def test_unsupported_firmware_issue_exc( assert issue_registry.async_get_issue(DOMAIN, issue_id) assert len(issue_registry.issues) == 1 + + +async def test_outbound_websocket_incorrectly_enabled_issue( + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + mock_rpc_device: Mock, + issue_registry: ir.IssueRegistry, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Test repair issues handling for the outbound WebSocket incorrectly enabled.""" + ws_url = "ws://10.10.10.10:8123/api/shelly/ws" + monkeypatch.setitem( + mock_rpc_device.config, "ws", {"enable": True, "server": ws_url} + ) + + issue_id = OUTBOUND_WEBSOCKET_INCORRECTLY_ENABLED_ISSUE_ID.format(unique=MOCK_MAC) + assert await async_setup_component(hass, "repairs", {}) + await hass.async_block_till_done() + await init_integration(hass, 2) + + assert issue_registry.async_get_issue(DOMAIN, issue_id) + assert len(issue_registry.issues) == 1 + + await async_process_repairs_platforms(hass) + client = await hass_client() + result = await start_repair_fix_flow(client, DOMAIN, issue_id) + + flow_id = result["flow_id"] + assert result["step_id"] == "confirm" + + result = await process_repair_fix_flow(client, flow_id) + assert result["type"] == "create_entry" + assert mock_rpc_device.ws_setconfig.call_count == 1 + assert mock_rpc_device.ws_setconfig.call_args[0] == (False, ws_url) + assert mock_rpc_device.trigger_reboot.call_count == 1 + + # Assert the issue is no longer present + assert not issue_registry.async_get_issue(DOMAIN, issue_id) + assert len(issue_registry.issues) == 0 + + +@pytest.mark.parametrize( + "exception", [DeviceConnectionError, RpcCallError(999, "Unknown error")] +) +async def test_outbound_websocket_incorrectly_enabled_issue_exc( + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + mock_rpc_device: Mock, + issue_registry: ir.IssueRegistry, + monkeypatch: pytest.MonkeyPatch, + exception: Exception, +) -> None: + """Test repair issues handling when ws_setconfig ends with an exception.""" + ws_url = "ws://10.10.10.10:8123/api/shelly/ws" + monkeypatch.setitem( + mock_rpc_device.config, "ws", {"enable": True, "server": ws_url} + ) + + issue_id = OUTBOUND_WEBSOCKET_INCORRECTLY_ENABLED_ISSUE_ID.format(unique=MOCK_MAC) + assert await async_setup_component(hass, "repairs", {}) + await hass.async_block_till_done() + await init_integration(hass, 2) + + assert issue_registry.async_get_issue(DOMAIN, issue_id) + assert len(issue_registry.issues) == 1 + + await async_process_repairs_platforms(hass) + client = await hass_client() + result = await start_repair_fix_flow(client, DOMAIN, issue_id) + + flow_id = result["flow_id"] + assert result["step_id"] == "confirm" + + mock_rpc_device.ws_setconfig.side_effect = exception + result = await process_repair_fix_flow(client, flow_id) + assert result["type"] == "abort" + assert result["reason"] == "cannot_connect" + assert mock_rpc_device.ws_setconfig.call_count == 1 + + assert issue_registry.async_get_issue(DOMAIN, issue_id) + assert len(issue_registry.issues) == 1