From cbfbb4dab7267d4a362c50c7e331732db873ff8a Mon Sep 17 00:00:00 2001 From: Aidan Timson Date: Sun, 8 Nov 2026 12:15:43 +0000 Subject: [PATCH] Require admin for System Bridge host actions and raise on failure (#190128) --- .../components/system_bridge/services.py | 106 ++++++++++---- .../components/system_bridge/strings.json | 3 + .../components/system_bridge/test_services.py | 136 +++++++++++++++++- 3 files changed, 218 insertions(+), 27 deletions(-) diff --git a/homeassistant/components/system_bridge/services.py b/homeassistant/components/system_bridge/services.py index 9db0f24aa86b..4b449dedf620 100644 --- a/homeassistant/components/system_bridge/services.py +++ b/homeassistant/components/system_bridge/services.py @@ -1,17 +1,28 @@ """Service registration for System Bridge integration.""" +from collections.abc import Awaitable from dataclasses import asdict import logging from typing import Any import probatio +from systembridgeconnector.const import EventType +from systembridgeconnector.exceptions import ConnectionClosedException from systembridgeconnector.models.keyboard_key import KeyboardKey from systembridgeconnector.models.keyboard_text import KeyboardText from systembridgeconnector.models.modules.processes import Process from systembridgeconnector.models.open_path import OpenPath from systembridgeconnector.models.open_url import OpenUrl +from systembridgeconnector.models.response import Response -from homeassistant.const import CONF_COMMAND, CONF_ID, CONF_NAME, CONF_PATH, CONF_URL +from homeassistant.const import ( + CONF_COMMAND, + CONF_HOST, + CONF_ID, + CONF_NAME, + CONF_PATH, + CONF_URL, +) from homeassistant.core import ( HomeAssistant, ServiceCall, @@ -19,7 +30,7 @@ from homeassistant.core import ( SupportsResponse, callback, ) -from homeassistant.exceptions import ServiceValidationError +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN @@ -71,7 +82,8 @@ def async_setup_services(hass: HomeAssistant) -> None: supports_response=SupportsResponse.ONLY, ) - hass.services.async_register( + service.async_register_admin_service( + hass, DOMAIN, "open_path", handle_open_path, @@ -84,7 +96,8 @@ def async_setup_services(hass: HomeAssistant) -> None: supports_response=SupportsResponse.OPTIONAL, ) - hass.services.async_register( + service.async_register_admin_service( + hass, DOMAIN, "power_command", handle_power_command, @@ -97,7 +110,8 @@ def async_setup_services(hass: HomeAssistant) -> None: supports_response=SupportsResponse.OPTIONAL, ) - hass.services.async_register( + service.async_register_admin_service( + hass, DOMAIN, "open_url", handle_open_url, @@ -110,7 +124,8 @@ def async_setup_services(hass: HomeAssistant) -> None: supports_response=SupportsResponse.OPTIONAL, ) - hass.services.async_register( + service.async_register_admin_service( + hass, DOMAIN, "send_keypress", handle_send_keypress, @@ -126,7 +141,8 @@ def async_setup_services(hass: HomeAssistant) -> None: }, ) - hass.services.async_register( + service.async_register_admin_service( + hass, DOMAIN, "send_text", handle_send_text, @@ -193,50 +209,92 @@ async def handle_get_processes_by_name( } +async def _async_send_command( + coordinator: SystemBridgeDataUpdateCoordinator, + action: str, + command: Awaitable[Response], +) -> ServiceResponse: + """Send a command to the bridge, raising on a closed connection or an error.""" + try: + response = await command + except (ConnectionClosedException, ConnectionResetError) as e: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="connection_failed", + translation_placeholders={ + "title": coordinator.config_entry.title, + "host": coordinator.config_entry.data[CONF_HOST], + }, + ) from e + if response.type == EventType.ERROR: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="action_failed", + translation_placeholders={ + "action": action, + "error": response.message or "", + }, + ) + return asdict(response) + + async def handle_open_path(service_call: ServiceCall) -> ServiceResponse: """Handle the open path service call.""" _LOGGER.debug("Open path: %s", service_call.data) coordinator = _get_coordinator(service_call.hass, service_call.data[CONF_BRIDGE]) - response = await coordinator.websocket_client.open_path( - OpenPath(path=service_call.data[CONF_PATH]) + return await _async_send_command( + coordinator, + service_call.service, + coordinator.websocket_client.open_path( + OpenPath(path=service_call.data[CONF_PATH]) + ), ) - return asdict(response) async def handle_power_command(service_call: ServiceCall) -> ServiceResponse: """Handle the power command service call.""" _LOGGER.debug("Power command: %s", service_call.data) coordinator = _get_coordinator(service_call.hass, service_call.data[CONF_BRIDGE]) - response = await getattr( - coordinator.websocket_client, - POWER_COMMAND_MAP[service_call.data[CONF_COMMAND]], - )() - return asdict(response) + return await _async_send_command( + coordinator, + service_call.service, + getattr( + coordinator.websocket_client, + POWER_COMMAND_MAP[service_call.data[CONF_COMMAND]], + )(), + ) async def handle_open_url(service_call: ServiceCall) -> ServiceResponse: """Handle the open url service call.""" _LOGGER.debug("Open URL: %s", service_call.data) coordinator = _get_coordinator(service_call.hass, service_call.data[CONF_BRIDGE]) - response = await coordinator.websocket_client.open_url( - OpenUrl(url=service_call.data[CONF_URL]) + return await _async_send_command( + coordinator, + service_call.service, + coordinator.websocket_client.open_url(OpenUrl(url=service_call.data[CONF_URL])), ) - return asdict(response) async def handle_send_keypress(service_call: ServiceCall) -> ServiceResponse: """Handle the send_keypress service call.""" coordinator = _get_coordinator(service_call.hass, service_call.data[CONF_BRIDGE]) - response = await coordinator.websocket_client.keyboard_keypress( - KeyboardKey(key=service_call.data[CONF_KEY]) + return await _async_send_command( + coordinator, + service_call.service, + coordinator.websocket_client.keyboard_keypress( + KeyboardKey(key=service_call.data[CONF_KEY]) + ), ) - return asdict(response) async def handle_send_text(service_call: ServiceCall) -> ServiceResponse: """Handle the send_text service call.""" coordinator = _get_coordinator(service_call.hass, service_call.data[CONF_BRIDGE]) - response = await coordinator.websocket_client.keyboard_text( - KeyboardText(text=service_call.data[CONF_TEXT]) + return await _async_send_command( + coordinator, + service_call.service, + coordinator.websocket_client.keyboard_text( + KeyboardText(text=service_call.data[CONF_TEXT]) + ), ) - return asdict(response) diff --git a/homeassistant/components/system_bridge/strings.json b/homeassistant/components/system_bridge/strings.json index 83cdffb95c66..16fef37e016c 100644 --- a/homeassistant/components/system_bridge/strings.json +++ b/homeassistant/components/system_bridge/strings.json @@ -324,6 +324,9 @@ } }, "exceptions": { + "action_failed": { + "message": "Failed to run {action}: {error}" + }, "audio_control_failed": { "message": "Failed to control audio device {name}: {error}" }, diff --git a/tests/components/system_bridge/test_services.py b/tests/components/system_bridge/test_services.py index 826a865264fb..f012d021d3e6 100644 --- a/tests/components/system_bridge/test_services.py +++ b/tests/components/system_bridge/test_services.py @@ -3,12 +3,15 @@ from typing import Any import pytest -from pytest_homeassistant.common import AsyncMock, MockConfigEntry +from pytest_homeassistant.common import AsyncMock, MockConfigEntry, MockUser from syrupy.assertion import SnapshotAssertion +from systembridgeconnector.const import EventType +from systembridgeconnector.exceptions import ConnectionClosedException from systembridgeconnector.models.keyboard_key import KeyboardKey from systembridgeconnector.models.keyboard_text import KeyboardText from systembridgeconnector.models.open_path import OpenPath from systembridgeconnector.models.open_url import OpenUrl +from systembridgeconnector.models.response import Response from homeassistant.components.system_bridge.const import DOMAIN from homeassistant.components.system_bridge.services import ( @@ -18,10 +21,11 @@ from homeassistant.components.system_bridge.services import ( ) from homeassistant.config_entries import ConfigEntryState from homeassistant.const import CONF_COMMAND, CONF_ID, CONF_NAME, CONF_PATH, CONF_URL -from homeassistant.core import HomeAssistant +from homeassistant.core import Context, HomeAssistant +from homeassistant.exceptions import HomeAssistantError, Unauthorized from homeassistant.helpers import device_registry as dr -from . import FIXTURE_UUID +from . import FIXTURE_REQUEST_ID, FIXTURE_UUID @pytest.mark.parametrize( @@ -133,6 +137,132 @@ async def test_power_command_without_response( assert resp is None +@pytest.mark.parametrize( + ("service", "service_data", "call_method"), + [ + ("open_path", {CONF_PATH: "/home/user/documents"}, "open_path"), + ("open_url", {CONF_URL: "https://example.com"}, "open_url"), + ("power_command", {CONF_COMMAND: "shutdown"}, "power_shutdown"), + ("send_keypress", {CONF_KEY: "backspace"}, "keyboard_keypress"), + ("send_text", {CONF_TEXT: "Hello world"}, "keyboard_text"), + ], +) +@pytest.mark.usefixtures("mock_version") +async def test_service_error_response( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_websocket_client: AsyncMock, + device_registry: dr.DeviceRegistry, + service: str, + service_data: dict[str, Any], + call_method: str, +) -> None: + """Test an error from the bridge raises instead of returning a payload.""" + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + device_entry = device_registry.async_get_device_by_identifier( + (DOMAIN, FIXTURE_UUID), mock_config_entry.entry_id + ) + assert device_entry + + getattr(mock_websocket_client, call_method).return_value = Response( + id=FIXTURE_REQUEST_ID, + type=EventType.ERROR, + message="Something went wrong", + data={}, + ) + + with pytest.raises( + HomeAssistantError, match=f"Failed to run {service}: Something went wrong" + ): + await hass.services.async_call( + DOMAIN, + service, + {CONF_BRIDGE: device_entry.id, **service_data}, + blocking=True, + return_response=True, + ) + + +@pytest.mark.usefixtures("mock_version") +@pytest.mark.parametrize( + "side_effect", + [ + pytest.param( + ConnectionClosedException("Connection is closed"), id="connection_closed" + ), + pytest.param(ConnectionResetError("Connection reset"), id="connection_reset"), + ], +) +async def test_service_connection_closed( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_websocket_client: AsyncMock, + device_registry: dr.DeviceRegistry, + side_effect: Exception, +) -> None: + """Test a closed or reset connection raises a connection error.""" + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + device_entry = device_registry.async_get_device_by_identifier( + (DOMAIN, FIXTURE_UUID), mock_config_entry.entry_id + ) + assert device_entry + + mock_websocket_client.power_shutdown.side_effect = side_effect + + with pytest.raises(HomeAssistantError, match="A connection error occurred"): + await hass.services.async_call( + DOMAIN, + "power_command", + {CONF_BRIDGE: device_entry.id, CONF_COMMAND: "shutdown"}, + blocking=True, + ) + + +@pytest.mark.parametrize( + ("service", "service_data"), + [ + ("open_path", {CONF_PATH: "/home/user/documents"}), + ("open_url", {CONF_URL: "https://example.com"}), + ("power_command", {CONF_COMMAND: "shutdown"}), + ("send_keypress", {CONF_KEY: "backspace"}), + ("send_text", {CONF_TEXT: "Hello world"}), + ], +) +@pytest.mark.usefixtures("mock_version", "mock_websocket_client") +async def test_admin_services_require_admin( + hass: HomeAssistant, + hass_read_only_user: MockUser, + mock_config_entry: MockConfigEntry, + device_registry: dr.DeviceRegistry, + service: str, + service_data: dict[str, Any], +) -> None: + """Test actions that control the host need an admin user.""" + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + device_entry = device_registry.async_get_device_by_identifier( + (DOMAIN, FIXTURE_UUID), mock_config_entry.entry_id + ) + assert device_entry + + with pytest.raises(Unauthorized): + await hass.services.async_call( + DOMAIN, + service, + {CONF_BRIDGE: device_entry.id, **service_data}, + blocking=True, + context=Context(user_id=hass_read_only_user.id), + ) + + @pytest.mark.parametrize( ("service", "service_data"), [