From 38f58e15a6dfdce873c49f94dc3b338321bb0aa0 Mon Sep 17 00:00:00 2001 From: kasunben Date: Fri, 21 Aug 2026 23:42:43 +0200 Subject: [PATCH] feat: implement RFC-0019's allowlisted Home Assistant action capability home_assistant.set_entity_state (mutating/external/required) turns an allowlisted light or switch entity on or off. Reads current state first so a proposal matching it is a real, narrated no-op that never contacts Home Assistant's service-call endpoint; a real change is verified against the service call's own response before reporting success, never trusting a 200 status alone. Domain scope (light/switch only) is enforced at three independent points, per RFC-0019's own review finding that a single point isn't enough (Home Assistant's climate domain has real turn_on/turn_off services, so a bypassed check wouldn't fail safely by accident): write_config() rejects a bad domain at the source, a new _control_policy_check re-derives and re-confirms it at the executor's policy stage, and the implementation itself checks a third time immediately before constructing the service-call URL. Adds a second, independent allowlist and policy toggle (controllable_entities/home_assistant_control_enabled), distinct from RFC-0018's read allowlist/toggle, with controllable_entities enforced as a strict subset of allowlisted_entities at write time. Extends the existing POST /api/v1/conversation/home-assistant endpoint (now requiring the two new fields in every write, matching the existing full-replace fields) and fixes Console's existing save-connection flow to round-trip them, since the endpoint's contract changed under it. Console UI for editing control settings itself is not built here, per RFC-0019's own Non-Goals. Reuses RFC-0017's confirmation wire format completely unchanged for this project's first mutating capability -- no new fields, no new halting behavior. Co-Authored-By: Claude Sonnet 5 --- .../appliance/bin/sovereign-conversation | 34 ++ .../appliance/console/assets/console.js | 18 + .../appliance/lib/sovereign_homeassistant.py | 253 +++++++++++- tests/test_conversation.py | 11 +- tests/test_conversation_service.py | 198 ++++++++- tests/test_homeassistant_capabilities.py | 378 +++++++++++++++++- 6 files changed, 870 insertions(+), 22 deletions(-) diff --git a/image-builder/sovereign/appliance/bin/sovereign-conversation b/image-builder/sovereign/appliance/bin/sovereign-conversation index b58915b..7db2c76 100755 --- a/image-builder/sovereign/appliance/bin/sovereign-conversation +++ b/image-builder/sovereign/appliance/bin/sovereign-conversation @@ -280,6 +280,8 @@ class ConversationHandler(BaseHTTPRequestHandler): "base_url": config["base_url"], "has_access_token": homeassistant.has_access_token(HOME_ASSISTANT_TOKEN_PATH), "allowlisted_entities": config["allowlisted_entities"], + "control_enabled": config["control_enabled"], + "controllable_entities": config["controllable_entities"], } def _handle_get_home_assistant(self): @@ -318,6 +320,29 @@ class ConversationHandler(BaseHTTPRequestHandler): }, }) return + # RFC-0019: a second, independent permission dimension -- required + # in every write, same as 'enabled'/'allowlisted_entities' above, + # not optional-with-a-default the way access_token is (that one + # is a credential-specific "leave unchanged" convenience, not the + # pattern for ordinary config fields in this endpoint). + if not isinstance(body.get("control_enabled"), bool): + self._send_json(400, { + "error": {"code": "INVALID_REQUEST", "message": "'control_enabled' must be a boolean"}, + }) + return + controllable_entities = body.get("controllable_entities") + if ( + not isinstance(controllable_entities, list) + or len(controllable_entities) > MAX_ALLOWLISTED_ENTITIES + or not all(isinstance(entry, str) and entry for entry in controllable_entities) + ): + self._send_json(400, { + "error": { + "code": "INVALID_REQUEST", + "message": f"'controllable_entities' must be a list of up to {MAX_ALLOWLISTED_ENTITIES} non-empty strings", + }, + }) + return # None (the field omitted) means "leave the stored token # unchanged" -- re-saving the allowlist must not require # re-pasting the token every time (RFC-0018). An explicit empty @@ -336,9 +361,18 @@ class ConversationHandler(BaseHTTPRequestHandler): try: homeassistant.write_config( base_url, allowlisted_entities, body["enabled"], + control_enabled=body["control_enabled"], controllable_entities=controllable_entities, access_token=access_token, path=HOME_ASSISTANT_CONFIG_PATH, token_path=HOME_ASSISTANT_TOKEN_PATH, ) + except ValueError as error: + # RFC-0019: write_config() itself enforces controllable_entities + # is a subset of allowlisted_entities and light/switch-only -- + # this is that invariant being violated, not a malformed + # request shape, so it's reported distinctly from the + # INVALID_REQUEST checks above even though it's still a 400. + self._send_json(400, {"error": {"code": "INVALID_CONTROL_CONFIGURATION", "message": str(error)}}) + return except OSError as error: self._send_json(502, { "error": { diff --git a/image-builder/sovereign/appliance/console/assets/console.js b/image-builder/sovereign/appliance/console/assets/console.js index 86579f1..d8ac479 100644 --- a/image-builder/sovereign/appliance/console/assets/console.js +++ b/image-builder/sovereign/appliance/console/assets/console.js @@ -727,6 +727,16 @@ const HA_ENTITIES_PLACEHOLDER = "Sign in, save a connection, then load entities // list (there is no partial-update endpoint). let haAllowlist = []; +// RFC-0019: control_enabled/controllable_entities -- loaded and resent +// unchanged on every save the same way haAllowlist is, even though this +// pass builds no UI to edit them yet (that's Console's own follow-up +// per RFC-0019's Non-Goals). Without this, "Save connection" would +// silently wipe out control settings a household configured through +// some other path (a future settings page, or a direct API call), +// since POST /home-assistant always replaces the whole config object. +let haControlEnabled = false; +let haControllableEntities = []; + function setHaSettingsMessage(text, isError) { haSettingsMessage.textContent = text; haSettingsMessage.classList.toggle("error", Boolean(isError)); @@ -801,6 +811,8 @@ function resetHomeAssistantSettingsUI() { haAccessTokenInput.value = ""; renderHaTokenStatus(false); haAllowlist = []; + haControlEnabled = false; + haControllableEntities = []; haEntitiesList.replaceChildren(); const placeholder = document.createElement("p"); placeholder.className = "placeholder"; @@ -834,6 +846,8 @@ async function loadHomeAssistantConfig() { haAccessTokenInput.value = ""; renderHaTokenStatus(Boolean(data.has_access_token)); haAllowlist = Array.isArray(data.allowlisted_entities) ? data.allowlisted_entities.slice() : []; + haControlEnabled = Boolean(data.control_enabled); + haControllableEntities = Array.isArray(data.controllable_entities) ? data.controllable_entities.slice() : []; renderHaStatus(data); } catch (error) { setHaSettingsMessage("Could not reach the device.", true); @@ -845,6 +859,8 @@ async function saveHomeAssistantConfig(reportTo) { enabled: haEnabledToggle.checked, base_url: buildHaBaseUrl(), allowlisted_entities: haAllowlist, + control_enabled: haControlEnabled, + controllable_entities: haControllableEntities, }; // Omitted entirely (not even an empty string) means "leave the stored // token unchanged" -- re-saving the allowlist must not require @@ -868,6 +884,8 @@ async function saveHomeAssistantConfig(reportTo) { haAccessTokenInput.value = ""; renderHaTokenStatus(Boolean(data.has_access_token)); haAllowlist = Array.isArray(data.allowlisted_entities) ? data.allowlisted_entities.slice() : []; + haControlEnabled = Boolean(data.control_enabled); + haControllableEntities = Array.isArray(data.controllable_entities) ? data.controllable_entities.slice() : []; renderHaStatus(data); reportTo("Saved."); return; diff --git a/image-builder/sovereign/appliance/lib/sovereign_homeassistant.py b/image-builder/sovereign/appliance/lib/sovereign_homeassistant.py index 77b5a7a..7d2fb38 100644 --- a/image-builder/sovereign/appliance/lib/sovereign_homeassistant.py +++ b/image-builder/sovereign/appliance/lib/sovereign_homeassistant.py @@ -42,6 +42,21 @@ "week": datetime.timedelta(days=7), } +# RFC-0019: the allowlisted-action slice's entire domain surface. Binary, +# fully reversible, no numeric range or safety implication -- every other +# domain (locks, climate, covers, cameras) is out of scope, enforced +# independently at write_config(), _control_policy_check, and inside +# make_set_entity_state_implementation itself (see that function's own +# comment for why a single enforcement point isn't enough: Home +# Assistant's climate domain has real turn_on/turn_off services, so a +# bypassed check wouldn't fail safely by accident). +CONTROLLABLE_DOMAINS = {"light", "switch"} +SET_ENTITY_STATE_TIMEOUT_SECONDS = 10 + + +def _entity_domain(entity_id): + return entity_id.split(".", 1)[0] if isinstance(entity_id, str) and "." in entity_id else "" + LIST_ENTITIES_ARGUMENT_SCHEMA = { "type": "object", "properties": {}, @@ -108,6 +123,29 @@ "additionalProperties": False, } +SET_ENTITY_STATE_ARGUMENT_SCHEMA = { + "type": "object", + "properties": { + "entity_id": {"type": "string"}, + "state": {"type": "string", "enum": ["on", "off"]}, + }, + "required": ["entity_id", "state"], + "additionalProperties": False, +} +SET_ENTITY_STATE_RESULT_SCHEMA = { + "type": "object", + "properties": { + "entity_id": {"type": "string"}, + "domain": {"type": "string", "enum": ["light", "switch"]}, + "previous_state": {"type": "string"}, + "new_state": {"type": "string"}, + "changed": {"type": "boolean"}, + "applied_at": {"type": "string"}, + }, + "required": ["entity_id", "domain", "previous_state", "new_state", "changed", "applied_at"], + "additionalProperties": False, +} + # --- Configuration and credential storage --------------------------------- # @@ -138,10 +176,18 @@ def read_config(path=None): if not isinstance(parsed, dict): parsed = {} allowlist = parsed.get("allowlisted_entities") + controllable = parsed.get("controllable_entities") return { "enabled": bool(parsed.get("enabled", False)), "base_url": (parsed.get("base_url") or "").strip(), "allowlisted_entities": [entry for entry in allowlist if isinstance(entry, str)] if isinstance(allowlist, list) else [], + # RFC-0019: a second, independent permission dimension -- default + # false/empty matches allowlisted_entities' own fail-safe default, + # and a device with only RFC-0018's three-field config (written + # before this RFC existed) reads these as their safe defaults via + # this same missing-key path, not a schema migration. + "control_enabled": bool(parsed.get("control_enabled", False)), + "controllable_entities": [entry for entry in controllable if isinstance(entry, str)] if isinstance(controllable, list) else [], } @@ -154,11 +200,33 @@ def read_token(path=None): return "" -def write_config(base_url, allowlisted_entities, enabled, access_token=None, path=None, token_path=None): +def write_config( + base_url, allowlisted_entities, enabled, + control_enabled=False, controllable_entities=None, + access_token=None, path=None, token_path=None, +): if path is None: path = CONFIG_PATH if token_path is None: token_path = TOKEN_PATH + controllable_entities = list(controllable_entities or []) + allowlisted_set = set(allowlisted_entities) + # RFC-0019: both invariants enforced here, independent of whichever + # caller submitted the write (raw API call, a future Console picker, + # or a direct write_config() call from a test) -- see that RFC's own + # Domain Scope section for why relying on a UI to simply not offer + # the option isn't enough. + for entity_id in controllable_entities: + fail_if = None + if entity_id not in allowlisted_set: + fail_if = f"'{entity_id}' cannot be controllable without also being allowlisted for reading" + elif _entity_domain(entity_id) not in CONTROLLABLE_DOMAINS: + fail_if = ( + f"'{entity_id}' has domain '{_entity_domain(entity_id)}', which cannot be made " + f"controllable (only {sorted(CONTROLLABLE_DOMAINS)} are supported)" + ) + if fail_if: + raise ValueError(fail_if) path = pathlib.Path(path) path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) payload = json.dumps( @@ -166,6 +234,8 @@ def write_config(base_url, allowlisted_entities, enabled, access_token=None, pat "enabled": bool(enabled), "base_url": base_url, "allowlisted_entities": list(allowlisted_entities), + "control_enabled": bool(control_enabled), + "controllable_entities": controllable_entities, }, sort_keys=True, ) @@ -195,26 +265,32 @@ def has_access_token(path=None): def policy_fields(path=None, token_path=None): # Merged into the turn's policy dict (sovereign_conversation.build_policy) # so the executor's stage-3 policy_key/policy_check can see it -- see - # this module's own _policy_check below. + # this module's own _policy_check/_control_policy_check below. config = read_config(path) configured = bool(config["base_url"]) and has_access_token(token_path) return { "home_assistant_enabled": config["enabled"], "home_assistant_allowlist": config["allowlisted_entities"], "home_assistant_configured": configured, + "home_assistant_control_enabled": config["control_enabled"], + "home_assistant_controllable_entities": config["controllable_entities"], } -def _policy_check(arguments, policy): - # Runs at executor stage 3, before any confirmation is generated - # (RFC-0018): both a "not configured yet" and a "not allowlisted" - # rejection must happen before the model ever discloses a query about - # a specific entity in a confirmation prompt. +def _check_configured(policy): capabilities.fail( bool(policy.get("home_assistant_configured", False)), "CAPABILITY_NOT_CONFIGURED", "Home Assistant is enabled but not yet configured (base URL or access token missing)", ) + + +def _policy_check(arguments, policy): + # Runs at executor stage 3, before any confirmation is generated + # (RFC-0018): both a "not configured yet" and a "not allowlisted" + # rejection must happen before the model ever discloses a query about + # a specific entity in a confirmation prompt. + _check_configured(policy) entity_id = arguments.get("entity_id") if entity_id is not None: allowlist = policy.get("home_assistant_allowlist") or [] @@ -225,6 +301,48 @@ def _policy_check(arguments, policy): ) +def _control_policy_check(arguments, policy): + # RFC-0019: distinct from _policy_check above, not a literal reuse -- + # this checks a different policy field (controllable_entities, not + # allowlist) and raises a different code, so a household reading the + # audit log or a denied-proposal narration can tell "not readable" + # apart from "readable but not controllable." Only the "is Home + # Assistant even configured" prerequisite is genuinely shared. + _check_configured(policy) + entity_id = arguments.get("entity_id") + controllable = policy.get("home_assistant_controllable_entities") or [] + capabilities.fail( + entity_id in controllable, + "ENTITY_NOT_CONTROLLABLE", + f"'{entity_id}' is not in the Home Assistant controllable-entity allowlist", + ) + # Defensive re-check: write_config() already enforces + # controllable_entities is a subset of allowlisted_entities, but a + # mutating, physical-effect capability's authorization path + # re-verifying an invariant that's supposed to already hold -- rather + # than trusting it silently -- is proportionate to what this + # capability can actually do if that invariant is ever wrong. + allowlist = policy.get("home_assistant_allowlist") or [] + capabilities.fail( + entity_id in allowlist, + "ENTITY_NOT_ALLOWLISTED", + f"'{entity_id}' is not in the Home Assistant entity allowlist", + ) + # Independent domain re-check, the second of three independent + # enforcement points (write_config() is the first; the implementation + # itself, immediately before the service call, is the third) -- see + # CONTROLLABLE_DOMAINS' own comment for why a single point isn't + # enough (Home Assistant's climate domain has real turn_on/turn_off + # services, so a bypassed check here wouldn't fail safely by + # accident). + domain = _entity_domain(entity_id) + capabilities.fail( + domain in CONTROLLABLE_DOMAINS, + "ENTITY_DOMAIN_NOT_CONTROLLABLE", + f"'{entity_id}' has domain '{domain}', which this capability does not control", + ) + + # --- Home Assistant REST client -------------------------------------------- # # Bearer-token auth, confirmed against Home Assistant's own REST API @@ -270,6 +388,37 @@ def fetch_all_states(base_url, token, timeout=LIST_ENTITIES_TIMEOUT_SECONDS): return _get(base_url, token, "/api/states", timeout=timeout) or [] +def fetch_state(base_url, token, entity_id, timeout=SET_ENTITY_STATE_TIMEOUT_SECONDS): + # A single entity's current state -- RFC-0019: read before acting, so + # a proposal matching current state is a no-op that never contacts + # Home Assistant's service-call endpoint at all. + return _get(base_url, token, f"/api/states/{urllib.parse.quote(entity_id, safe='')}", timeout=timeout) + + +def _post(base_url, token, path, body, timeout=SET_ENTITY_STATE_TIMEOUT_SECONDS): + url = f"{base_url.rstrip('/')}{path}" + data = json.dumps(body).encode("utf-8") + request = urllib.request.Request( + url, data=data, method="POST", + headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310 + return json.loads(response.read(RESPONSE_READ_BYTES + 1)) + except urllib.error.HTTPError as error: + if error.code == 401: + raise capabilities.CapabilityError( + "HOME_ASSISTANT_AUTH_FAILED", "Home Assistant rejected the stored access token" + ) from error + raise capabilities.CapabilityError( + "HOME_ASSISTANT_REQUEST_FAILED", f"Home Assistant returned HTTP {error.code}" + ) from error + except (urllib.error.URLError, OSError, ValueError) as error: + raise capabilities.CapabilityError( + "HOME_ASSISTANT_UNREACHABLE", "Could not reach Home Assistant" + ) from error + + def make_list_entities_implementation(config_path=None, token_path=None): def implementation(arguments): config = read_config(config_path) @@ -341,6 +490,82 @@ def implementation(arguments): return implementation +def make_set_entity_state_implementation(config_path=None, token_path=None): + # RFC-0019: this project's first mutating capability. Every check + # here that _control_policy_check already performed at stage 3 is + # re-checked here too, at stage 5 -- the same "don't just trust an + # earlier stage" posture make_list_entities_implementation and + # make_get_history_implementation already take toward stage 3's own + # checks, elevated here because a bypassed check has a real physical + # effect, not just an unwanted read. + def implementation(arguments): + entity_id = arguments["entity_id"] + requested_state = arguments["state"] + config = read_config(config_path) + token = read_token(token_path) + capabilities.fail( + bool(config["base_url"]) and bool(token), "HOME_ASSISTANT_NOT_CONFIGURED", + "Home Assistant is not configured", + ) + capabilities.fail( + entity_id in config["controllable_entities"], "ENTITY_NOT_CONTROLLABLE", + f"'{entity_id}' is not in the Home Assistant controllable-entity allowlist", + ) + # Third independent domain check (write_config() is the first, + # _control_policy_check the second) -- see CONTROLLABLE_DOMAINS' + # own comment for why this can't be skipped as redundant: Home + # Assistant's climate domain has real turn_on/turn_off services, + # so a bypassed check here would not fail safely by accident. + domain = _entity_domain(entity_id) + capabilities.fail( + domain in CONTROLLABLE_DOMAINS, "ENTITY_DOMAIN_NOT_CONTROLLABLE", + f"'{entity_id}' has domain '{domain}', which this capability does not control", + ) + + current = fetch_state(config["base_url"], token, entity_id, timeout=SET_ENTITY_STATE_TIMEOUT_SECONDS) + previous_state = (current or {}).get("state") or "" + if previous_state == requested_state: + # Idempotent no-op (RFC-0019): a proposal matching current + # state never reaches Home Assistant's service-call endpoint + # at all -- a real, narratable success, not an error. + return { + "entity_id": entity_id, + "domain": domain, + "previous_state": previous_state, + "new_state": previous_state, + "changed": False, + "applied_at": capabilities.timestamp(), + } + + service = "turn_on" if requested_state == "on" else "turn_off" + changed_states = _post( + config["base_url"], token, f"/api/services/{domain}/{service}", + {"entity_id": entity_id}, timeout=SET_ENTITY_STATE_TIMEOUT_SECONDS, + ) + # Never trust a 200 response alone -- verify the target entity + # actually appears in the changed-states list with the state + # that was requested. Reporting "done" without this would be a + # household trusting a receipt that might not be true. + confirmed = any( + isinstance(item, dict) and item.get("entity_id") == entity_id and item.get("state") == requested_state + for item in (changed_states or []) + ) + capabilities.fail( + confirmed, "HOME_ASSISTANT_ACTION_NOT_CONFIRMED", + f"Home Assistant did not confirm '{entity_id}' changed to '{requested_state}'", + ) + return { + "entity_id": entity_id, + "domain": domain, + "previous_state": previous_state, + "new_state": requested_state, + "changed": True, + "applied_at": capabilities.timestamp(), + } + + return implementation + + def register(registry, config_path=None, token_path=None): # config_path/token_path default to None, which read_config/read_token # resolve fresh from this module's own CONFIG_PATH/TOKEN_PATH globals @@ -381,4 +606,18 @@ def register(registry, config_path=None, token_path=None): policy_check=_policy_check, ) ) + registry.register( + capabilities.Capability( + name="home_assistant.set_entity_state", + version=1, + argument_schema=SET_ENTITY_STATE_ARGUMENT_SCHEMA, + result_schema=SET_ENTITY_STATE_RESULT_SCHEMA, + side_effect="mutating", + network="external", + implementation=make_set_entity_state_implementation(config_path, token_path), + timeout_seconds=SET_ENTITY_STATE_TIMEOUT_SECONDS + 2, + policy_key="home_assistant_control_enabled", + policy_check=_control_policy_check, + ) + ) return registry diff --git a/tests/test_conversation.py b/tests/test_conversation.py index 87961e8..e662568 100644 --- a/tests/test_conversation.py +++ b/tests/test_conversation.py @@ -69,7 +69,7 @@ def registry_with(self, *caps): class BuildRegistryTests(unittest.TestCase): - def test_includes_exactly_the_seven_real_capabilities(self): + def test_includes_exactly_the_eight_real_capabilities(self): registry = conversation.build_registry() names = {entry["name"] for entry in registry.catalog()} self.assertEqual( @@ -77,6 +77,7 @@ def test_includes_exactly_the_seven_real_capabilities(self): { "system.health", "pihole.status", "pihole.summary", "web.search", "web.fetch", "home_assistant.list_entities", "home_assistant.get_history", + "home_assistant.set_entity_state", }, ) @@ -548,13 +549,17 @@ def test_merges_web_search_and_home_assistant_policy_on_a_fresh_device(self): "home_assistant_enabled": False, "home_assistant_allowlist": [], "home_assistant_configured": False, + "home_assistant_control_enabled": False, + "home_assistant_controllable_entities": [], }, ) def test_reflects_both_independently_when_configured(self): conversation.write_policy(True, self.policy_path()) homeassistant.write_config( - "http://homeassistant.local:8123", ["light.kitchen"], True, access_token="secret-1", + "http://homeassistant.local:8123", ["light.kitchen"], True, + control_enabled=True, controllable_entities=["light.kitchen"], + access_token="secret-1", path=self.home_assistant_config_path(), token_path=self.home_assistant_token_path(), ) policy = conversation.build_policy( @@ -567,6 +572,8 @@ def test_reflects_both_independently_when_configured(self): "home_assistant_enabled": True, "home_assistant_allowlist": ["light.kitchen"], "home_assistant_configured": True, + "home_assistant_control_enabled": True, + "home_assistant_controllable_entities": ["light.kitchen"], }, ) diff --git a/tests/test_conversation_service.py b/tests/test_conversation_service.py index 2209e48..62e33fb 100644 --- a/tests/test_conversation_service.py +++ b/tests/test_conversation_service.py @@ -631,7 +631,10 @@ def test_get_reflects_the_real_default_disabled_unconfigured(self): self.assertEqual(200, response.status) self.assertEqual( body, - {"enabled": False, "base_url": "", "has_access_token": False, "allowlisted_entities": []}, + { + "enabled": False, "base_url": "", "has_access_token": False, "allowlisted_entities": [], + "control_enabled": False, "controllable_entities": [], + }, ) def test_post_requires_authentication(self): @@ -641,7 +644,10 @@ def test_post_requires_authentication(self): ) response, body = self._post( "/api/v1/conversation/home-assistant", - {"enabled": True, "base_url": "http://homeassistant.local:8123", "allowlisted_entities": []}, + { + "enabled": True, "base_url": "http://homeassistant.local:8123", + "allowlisted_entities": [], "control_enabled": False, "controllable_entities": [], + }, ) self.assertEqual(403, response.status) self.assertEqual("CSRF_MISMATCH", body["error"]["code"]) @@ -655,6 +661,8 @@ def test_post_persists_and_get_reflects_it_never_returning_the_token(self): "enabled": True, "base_url": "http://homeassistant.local:8123", "allowlisted_entities": ["light.kitchen"], + "control_enabled": True, + "controllable_entities": ["light.kitchen"], "access_token": "secret-1", }, ) @@ -666,6 +674,8 @@ def test_post_persists_and_get_reflects_it_never_returning_the_token(self): "base_url": "http://homeassistant.local:8123", "has_access_token": True, "allowlisted_entities": ["light.kitchen"], + "control_enabled": True, + "controllable_entities": ["light.kitchen"], }, ) self.assertNotIn("secret-1", json.dumps(body)) @@ -674,6 +684,7 @@ def test_post_persists_and_get_reflects_it_never_returning_the_token(self): urlopen.side_effect = dispatch_urlopen([auth_ok()]) response, body = self._get("/api/v1/conversation/home-assistant") self.assertEqual(body["allowlisted_entities"], ["light.kitchen"]) + self.assertEqual(body["controllable_entities"], ["light.kitchen"]) self.assertEqual(homeassistant.read_token(self.token_path), "secret-1") def test_omitted_access_token_leaves_the_stored_token_unchanged(self): @@ -683,14 +694,18 @@ def test_omitted_access_token_leaves_the_stored_token_unchanged(self): "/api/v1/conversation/home-assistant", { "enabled": True, "base_url": "http://x:8123", - "allowlisted_entities": [], "access_token": "secret-1", + "allowlisted_entities": [], "control_enabled": False, "controllable_entities": [], + "access_token": "secret-1", }, ) with mock.patch("urllib.request.urlopen") as urlopen: urlopen.side_effect = dispatch_urlopen([auth_ok()]) response, body = self._post( "/api/v1/conversation/home-assistant", - {"enabled": True, "base_url": "http://x:8123", "allowlisted_entities": ["light.kitchen"]}, + { + "enabled": True, "base_url": "http://x:8123", "allowlisted_entities": ["light.kitchen"], + "control_enabled": False, "controllable_entities": [], + }, ) self.assertTrue(body["has_access_token"]) self.assertEqual(homeassistant.read_token(self.token_path), "secret-1") @@ -700,7 +715,10 @@ def test_post_rejects_a_non_boolean_enabled(self): urlopen.side_effect = dispatch_urlopen([auth_ok()]) response, body = self._post( "/api/v1/conversation/home-assistant", - {"enabled": "yes", "base_url": "http://x:8123", "allowlisted_entities": []}, + { + "enabled": "yes", "base_url": "http://x:8123", "allowlisted_entities": [], + "control_enabled": False, "controllable_entities": [], + }, ) self.assertEqual(400, response.status) self.assertEqual("INVALID_REQUEST", body["error"]["code"]) @@ -710,7 +728,10 @@ def test_post_rejects_a_non_http_base_url(self): urlopen.side_effect = dispatch_urlopen([auth_ok()]) response, body = self._post( "/api/v1/conversation/home-assistant", - {"enabled": True, "base_url": "ftp://x", "allowlisted_entities": []}, + { + "enabled": True, "base_url": "ftp://x", "allowlisted_entities": [], + "control_enabled": False, "controllable_entities": [], + }, ) self.assertEqual(400, response.status) self.assertEqual("INVALID_REQUEST", body["error"]["code"]) @@ -720,11 +741,77 @@ def test_post_rejects_a_non_list_allowlist(self): urlopen.side_effect = dispatch_urlopen([auth_ok()]) response, body = self._post( "/api/v1/conversation/home-assistant", - {"enabled": True, "base_url": "http://x:8123", "allowlisted_entities": "light.kitchen"}, + { + "enabled": True, "base_url": "http://x:8123", "allowlisted_entities": "light.kitchen", + "control_enabled": False, "controllable_entities": [], + }, ) self.assertEqual(400, response.status) self.assertEqual("INVALID_REQUEST", body["error"]["code"]) + def test_post_rejects_a_non_boolean_control_enabled(self): + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen([auth_ok()]) + response, body = self._post( + "/api/v1/conversation/home-assistant", + { + "enabled": True, "base_url": "http://x:8123", "allowlisted_entities": [], + "control_enabled": "yes", "controllable_entities": [], + }, + ) + self.assertEqual(400, response.status) + self.assertEqual("INVALID_REQUEST", body["error"]["code"]) + + def test_post_rejects_a_non_list_controllable_entities(self): + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen([auth_ok()]) + response, body = self._post( + "/api/v1/conversation/home-assistant", + { + "enabled": True, "base_url": "http://x:8123", "allowlisted_entities": [], + "control_enabled": True, "controllable_entities": "light.kitchen", + }, + ) + self.assertEqual(400, response.status) + self.assertEqual("INVALID_REQUEST", body["error"]["code"]) + + def test_post_rejects_a_controllable_entity_not_allowlisted(self): + # RFC-0019: write_config()'s own invariant (controllable is a + # subset of allowlisted) is enforced here, reported distinctly + # from a malformed-request shape. + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen([auth_ok()]) + response, body = self._post( + "/api/v1/conversation/home-assistant", + { + "enabled": True, "base_url": "http://x:8123", "allowlisted_entities": ["light.kitchen"], + "control_enabled": True, "controllable_entities": ["light.hallway"], + }, + ) + self.assertEqual(400, response.status) + self.assertEqual("INVALID_CONTROL_CONFIGURATION", body["error"]["code"]) + + def test_post_rejects_a_non_light_switch_controllable_domain(self): + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen([auth_ok()]) + response, body = self._post( + "/api/v1/conversation/home-assistant", + { + "enabled": True, "base_url": "http://x:8123", "allowlisted_entities": ["lock.front_door"], + "control_enabled": True, "controllable_entities": ["lock.front_door"], + }, + ) + self.assertEqual(400, response.status) + self.assertEqual("INVALID_CONTROL_CONFIGURATION", body["error"]["code"]) + # The whole write must be rejected -- no partial persistence. + self.assertEqual( + homeassistant.read_config(self.config_path), + { + "enabled": False, "base_url": "", "allowlisted_entities": [], + "control_enabled": False, "controllable_entities": [], + }, + ) + class HomeAssistantEntitiesProxyEndpointTests(unittest.TestCase): def setUp(self): @@ -799,6 +886,14 @@ def configure_and_enable(self, allowlist=("light.kitchen",)): path=self.config_path, token_path=self.token_path, ) + def configure_and_enable_control(self, allowlist=("light.kitchen",), controllable=("light.kitchen",)): + homeassistant.write_config( + "http://homeassistant.local:8123", list(allowlist), True, + control_enabled=True, controllable_entities=list(controllable), + access_token="secret-1", + path=self.config_path, token_path=self.token_path, + ) + def start_server(self): self.live = LiveConversationServer( self.audit_path, @@ -913,6 +1008,95 @@ def test_enabling_web_search_alone_does_not_enable_home_assistant(self): body["capability_events"], ) + def test_set_entity_state_disabled_by_default_rejects_without_ever_prompting(self): + # RFC-0019: control has its own default-off toggle, independent + # of read's own. + self.configure_and_enable() + self.start_server() + proposal = chat_completion( + tool_calls=[tool_call("call_1_0", "home_assistant.set_entity_state", {"entity_id": "light.kitchen", "state": "off"})] + ) + narration = chat_completion(content="Home Assistant control is disabled.") + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen( + [auth_ok(), ("/v1/chat/completions", proposal), ("/v1/chat/completions", narration)] + ) + response, body = self._post({"message": "turn off the kitchen light"}) + self.assertEqual(200, response.status) + self.assertNotIn("pending_confirmation", body) + self.assertEqual( + [{"name": "home_assistant.set_entity_state", "outcome": "rejected", "code": "CAPABILITY_DISABLED"}], + body["capability_events"], + ) + + def test_set_entity_state_enabled_pauses_for_confirmation_and_approving_executes(self): + self.configure_and_enable_control() + self.start_server() + proposal = chat_completion( + tool_calls=[tool_call("call_1_0", "home_assistant.set_entity_state", {"entity_id": "light.kitchen", "state": "off"})] + ) + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen([auth_ok(), ("/v1/chat/completions", proposal)]) + response, paused = self._post({"message": "turn off the kitchen light"}) + self.assertEqual(200, response.status) + self.assertEqual("home_assistant.set_entity_state", paused["pending_confirmation"]["capability"]) + self.assertEqual({"entity_id": "light.kitchen", "state": "off"}, paused["pending_confirmation"]["arguments"]) + token = paused["pending_confirmation"]["token"] + + state_response = json_response({"entity_id": "light.kitchen", "state": "on", "attributes": {}}) + service_response = json_response([{"entity_id": "light.kitchen", "state": "off", "attributes": {}}]) + narration = chat_completion(content="Turned off the kitchen light.") + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen( + [auth_ok(), ("/api/states/light.kitchen", state_response), + ("/api/services/light/turn_off", service_response), ("/v1/chat/completions", narration)] + ) + response, body = self._post({"confirmation": {"token": token, "approve": True}}) + self.assertEqual(200, response.status) + self.assertEqual("Turned off the kitchen light.", body["text"]) + self.assertEqual( + [{"name": "home_assistant.set_entity_state", "outcome": "executed"}], body["capability_events"], + ) + + def test_set_entity_state_denying_never_calls_home_assistant(self): + self.configure_and_enable_control() + self.start_server() + proposal = chat_completion( + tool_calls=[tool_call("call_1_0", "home_assistant.set_entity_state", {"entity_id": "light.kitchen", "state": "off"})] + ) + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen([auth_ok(), ("/v1/chat/completions", proposal)]) + _, paused = self._post({"message": "turn off the kitchen light"}) + token = paused["pending_confirmation"]["token"] + + narration = chat_completion(content="Okay, leaving it as is.") + with mock.patch("urllib.request.urlopen") as urlopen: + # No /api/states or /api/services rule registered -- proves + # denial never contacts Home Assistant at all. + urlopen.side_effect = dispatch_urlopen([auth_ok(), ("/v1/chat/completions", narration)]) + response, body = self._post({"confirmation": {"token": token, "approve": False}}) + self.assertEqual(200, response.status) + self.assertEqual( + [{"name": "home_assistant.set_entity_state", "outcome": "denied"}], body["capability_events"], + ) + + def test_enabling_read_alone_does_not_enable_control_at_the_http_layer(self): + self.configure_and_enable() # read-only, control_enabled stays False + self.start_server() + proposal = chat_completion( + tool_calls=[tool_call("call_1_0", "home_assistant.set_entity_state", {"entity_id": "light.kitchen", "state": "off"})] + ) + narration = chat_completion(content="Control is disabled.") + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen( + [auth_ok(), ("/v1/chat/completions", proposal), ("/v1/chat/completions", narration)] + ) + response, body = self._post({"message": "turn off the kitchen light"}) + self.assertEqual( + [{"name": "home_assistant.set_entity_state", "outcome": "rejected", "code": "CAPABILITY_DISABLED"}], + body["capability_events"], + ) + class ConversationProvisioningTests(unittest.TestCase): def test_systemd_unit_is_hardened_and_grouped(self): diff --git a/tests/test_homeassistant_capabilities.py b/tests/test_homeassistant_capabilities.py index 9a90123..3f7959f 100644 --- a/tests/test_homeassistant_capabilities.py +++ b/tests/test_homeassistant_capabilities.py @@ -34,7 +34,10 @@ def setUp(self): def test_missing_file_fails_safe_to_disabled_empty_allowlist(self): self.assertEqual( homeassistant.read_config(self.config_path), - {"enabled": False, "base_url": "", "allowlisted_entities": []}, + { + "enabled": False, "base_url": "", "allowlisted_entities": [], + "control_enabled": False, "controllable_entities": [], + }, ) def test_malformed_json_fails_safe_to_disabled(self): @@ -42,7 +45,10 @@ def test_malformed_json_fails_safe_to_disabled(self): self.config_path.write_text("not valid json") self.assertEqual( homeassistant.read_config(self.config_path), - {"enabled": False, "base_url": "", "allowlisted_entities": []}, + { + "enabled": False, "base_url": "", "allowlisted_entities": [], + "control_enabled": False, "controllable_entities": [], + }, ) def test_non_object_json_fails_safe_to_disabled(self): @@ -50,7 +56,10 @@ def test_non_object_json_fails_safe_to_disabled(self): self.config_path.write_text("[1, 2, 3]") self.assertEqual( homeassistant.read_config(self.config_path), - {"enabled": False, "base_url": "", "allowlisted_entities": []}, + { + "enabled": False, "base_url": "", "allowlisted_entities": [], + "control_enabled": False, "controllable_entities": [], + }, ) def test_write_then_read_round_trips(self): @@ -60,9 +69,71 @@ def test_write_then_read_round_trips(self): ) self.assertEqual( homeassistant.read_config(self.config_path), - {"enabled": True, "base_url": "http://homeassistant.local:8123", "allowlisted_entities": ["light.kitchen"]}, + { + "enabled": True, "base_url": "http://homeassistant.local:8123", + "allowlisted_entities": ["light.kitchen"], + "control_enabled": False, "controllable_entities": [], + }, ) + def test_control_fields_round_trip(self): + homeassistant.write_config( + "http://homeassistant.local:8123", ["light.kitchen", "switch.fan"], True, + control_enabled=True, controllable_entities=["light.kitchen"], + path=self.config_path, token_path=self.token_path, + ) + config = homeassistant.read_config(self.config_path) + self.assertTrue(config["control_enabled"]) + self.assertEqual(config["controllable_entities"], ["light.kitchen"]) + + def test_a_device_with_only_the_rfc_0018_three_field_config_reads_control_defaults_safely(self): + # A config file written before this RFC existed (or hand-crafted + # without the two new fields) must fail safe, not crash. + self.config_path.parent.mkdir(parents=True) + self.config_path.write_text(json.dumps({ + "enabled": True, "base_url": "http://x:8123", "allowlisted_entities": ["light.kitchen"], + })) + config = homeassistant.read_config(self.config_path) + self.assertFalse(config["control_enabled"]) + self.assertEqual(config["controllable_entities"], []) + + def test_write_config_rejects_a_controllable_entity_not_in_the_read_allowlist(self): + with self.assertRaises(ValueError): + homeassistant.write_config( + "http://x:8123", ["light.kitchen"], True, + control_enabled=True, controllable_entities=["light.hallway"], + path=self.config_path, token_path=self.token_path, + ) + # The whole write is rejected -- no partial file left behind. + self.assertFalse(self.config_path.exists()) + + def test_write_config_rejects_a_non_light_switch_domain_even_if_allowlisted(self): + with self.assertRaises(ValueError): + homeassistant.write_config( + "http://x:8123", ["climate.attic"], True, + control_enabled=True, controllable_entities=["climate.attic"], + path=self.config_path, token_path=self.token_path, + ) + self.assertFalse(self.config_path.exists()) + + def test_write_config_rejects_lock_domain_specifically(self): + # RFC-0019's own named example -- locks are explicitly excluded. + with self.assertRaises(ValueError): + homeassistant.write_config( + "http://x:8123", ["lock.front_door"], True, + control_enabled=True, controllable_entities=["lock.front_door"], + path=self.config_path, token_path=self.token_path, + ) + + def test_write_config_accepts_a_valid_light_switch_subset(self): + homeassistant.write_config( + "http://x:8123", ["light.kitchen", "switch.fan", "lock.front_door"], True, + control_enabled=True, controllable_entities=["light.kitchen", "switch.fan"], + path=self.config_path, token_path=self.token_path, + ) + config = homeassistant.read_config(self.config_path) + self.assertEqual(config["controllable_entities"], ["light.kitchen", "switch.fan"]) + def test_write_is_atomic_no_partial_file_left_behind(self): homeassistant.write_config("http://x:8123", [], False, path=self.config_path, token_path=self.token_path) self.assertFalse(Path(f"{self.config_path}.tmp").exists()) @@ -97,10 +168,16 @@ def test_read_token_missing_file_is_empty_string(self): def test_policy_fields_reflects_configured_state(self): self.assertEqual( homeassistant.policy_fields(path=self.config_path, token_path=self.token_path), - {"home_assistant_enabled": False, "home_assistant_allowlist": [], "home_assistant_configured": False}, + { + "home_assistant_enabled": False, "home_assistant_allowlist": [], + "home_assistant_configured": False, "home_assistant_control_enabled": False, + "home_assistant_controllable_entities": [], + }, ) homeassistant.write_config( - "http://x:8123", ["light.kitchen"], True, access_token="secret-1", + "http://x:8123", ["light.kitchen"], True, + control_enabled=True, controllable_entities=["light.kitchen"], + access_token="secret-1", path=self.config_path, token_path=self.token_path, ) self.assertEqual( @@ -109,9 +186,23 @@ def test_policy_fields_reflects_configured_state(self): "home_assistant_enabled": True, "home_assistant_allowlist": ["light.kitchen"], "home_assistant_configured": True, + "home_assistant_control_enabled": True, + "home_assistant_controllable_entities": ["light.kitchen"], }, ) + def test_control_enabled_independent_of_read_enabled(self): + # RFC-0019's own central point: enabling read must not silently + # enable control, and vice versa. + homeassistant.write_config( + "http://x:8123", ["light.kitchen"], True, + control_enabled=False, access_token="secret-1", + path=self.config_path, token_path=self.token_path, + ) + fields = homeassistant.policy_fields(path=self.config_path, token_path=self.token_path) + self.assertTrue(fields["home_assistant_enabled"]) + self.assertFalse(fields["home_assistant_control_enabled"]) + def test_enabled_without_base_url_is_not_configured(self): homeassistant.write_config("", [], True, access_token="secret-1", path=self.config_path, token_path=self.token_path) fields = homeassistant.policy_fields(path=self.config_path, token_path=self.token_path) @@ -151,6 +242,76 @@ def test_list_entities_has_no_entity_id_so_allowlist_is_not_consulted(self): homeassistant._policy_check({}, {"home_assistant_configured": True, "home_assistant_allowlist": []}) +class ControlPolicyCheckTests(unittest.TestCase): + # RFC-0019: _control_policy_check is a distinct function from + # _policy_check above -- it checks a different policy field + # (controllable_entities) and raises a different code + # (ENTITY_NOT_CONTROLLABLE), plus two checks _policy_check doesn't + # have at all (the defensive allowlist re-check, and the domain + # re-check). + CONFIGURED = { + "home_assistant_configured": True, + "home_assistant_allowlist": ["light.kitchen"], + "home_assistant_controllable_entities": ["light.kitchen"], + } + + def test_not_configured_is_rejected_before_anything_else(self): + with self.assertRaises(capabilities.CapabilityError) as caught: + homeassistant._control_policy_check( + {"entity_id": "light.kitchen", "state": "on"}, {"home_assistant_configured": False}, + ) + self.assertEqual(caught.exception.code, "CAPABILITY_NOT_CONFIGURED") + + def test_entity_not_in_controllable_entities_is_rejected(self): + policy = dict(self.CONFIGURED, home_assistant_controllable_entities=[]) + with self.assertRaises(capabilities.CapabilityError) as caught: + homeassistant._control_policy_check({"entity_id": "light.kitchen", "state": "on"}, policy) + self.assertEqual(caught.exception.code, "ENTITY_NOT_CONTROLLABLE") + + def test_entity_controllable_but_not_readable_is_rejected(self): + # The defensive re-check: write_config() is supposed to guarantee + # controllable subset-of-allowlisted, but this policy_check must + # not simply trust that invariant silently. + policy = dict(self.CONFIGURED, home_assistant_allowlist=[]) + with self.assertRaises(capabilities.CapabilityError) as caught: + homeassistant._control_policy_check({"entity_id": "light.kitchen", "state": "on"}, policy) + self.assertEqual(caught.exception.code, "ENTITY_NOT_ALLOWLISTED") + + def test_non_light_switch_domain_is_rejected_even_if_present_in_both_lists(self): + # Simulates a policy dict that bypassed write_config() entirely + # (e.g. hand-edited config, or a future bug) -- the domain + # re-check must catch it independently. + policy = { + "home_assistant_configured": True, + "home_assistant_allowlist": ["climate.attic"], + "home_assistant_controllable_entities": ["climate.attic"], + } + with self.assertRaises(capabilities.CapabilityError) as caught: + homeassistant._control_policy_check({"entity_id": "climate.attic", "state": "on"}, policy) + self.assertEqual(caught.exception.code, "ENTITY_DOMAIN_NOT_CONTROLLABLE") + + def test_lock_domain_specifically_is_rejected(self): + policy = { + "home_assistant_configured": True, + "home_assistant_allowlist": ["lock.front_door"], + "home_assistant_controllable_entities": ["lock.front_door"], + } + with self.assertRaises(capabilities.CapabilityError) as caught: + homeassistant._control_policy_check({"entity_id": "lock.front_door", "state": "on"}, policy) + self.assertEqual(caught.exception.code, "ENTITY_DOMAIN_NOT_CONTROLLABLE") + + def test_configured_controllable_allowlisted_light_passes(self): + homeassistant._control_policy_check({"entity_id": "light.kitchen", "state": "on"}, self.CONFIGURED) + + def test_configured_controllable_allowlisted_switch_passes(self): + policy = { + "home_assistant_configured": True, + "home_assistant_allowlist": ["switch.fan"], + "home_assistant_controllable_entities": ["switch.fan"], + } + homeassistant._control_policy_check({"entity_id": "switch.fan", "state": "off"}, policy) + + class ListEntitiesImplementationTests(unittest.TestCase): def setUp(self): self.tempdir = tempfile.TemporaryDirectory() @@ -306,6 +467,137 @@ def test_filter_entity_id_is_forwarded(self, urlopen): self.assertIn("/api/history/period/", requested_url) +class SetEntityStateImplementationTests(unittest.TestCase): + def setUp(self): + self.tempdir = tempfile.TemporaryDirectory() + self.addCleanup(self.tempdir.cleanup) + self.config_path = Path(self.tempdir.name) / "home-assistant.json" + self.token_path = Path(self.tempdir.name) / "access-token" + homeassistant.write_config( + "http://homeassistant.local:8123", ["light.kitchen", "switch.fan"], True, + control_enabled=True, controllable_entities=["light.kitchen", "switch.fan"], + access_token="secret-1", path=self.config_path, token_path=self.token_path, + ) + self.patched_config_path = mock.patch.object(homeassistant, "CONFIG_PATH", self.config_path) + self.patched_token_path = mock.patch.object(homeassistant, "TOKEN_PATH", self.token_path) + self.patched_config_path.start() + self.patched_token_path.start() + self.addCleanup(self.patched_config_path.stop) + self.addCleanup(self.patched_token_path.stop) + + @mock.patch("urllib.request.urlopen") + def test_matching_current_state_is_a_no_op_no_service_call_made(self, urlopen): + urlopen.return_value = json_response({"entity_id": "light.kitchen", "state": "off", "attributes": {}}) + implementation = homeassistant.make_set_entity_state_implementation() + result = implementation({"entity_id": "light.kitchen", "state": "off"}) + self.assertEqual(result["changed"], False) + self.assertEqual(result["previous_state"], "off") + self.assertEqual(result["new_state"], "off") + self.assertEqual(result["domain"], "light") + # Only the state read happened -- no POST to a service-call endpoint. + self.assertEqual(urlopen.call_count, 1) + self.assertEqual(urlopen.call_args[0][0].get_method(), "GET") + + @mock.patch("urllib.request.urlopen") + def test_differing_state_calls_the_correct_service_and_reports_changed(self, urlopen): + state_response = json_response({"entity_id": "light.kitchen", "state": "on", "attributes": {}}) + service_response = json_response([{"entity_id": "light.kitchen", "state": "off", "attributes": {}}]) + urlopen.side_effect = [state_response, service_response] + implementation = homeassistant.make_set_entity_state_implementation() + result = implementation({"entity_id": "light.kitchen", "state": "off"}) + self.assertTrue(result["changed"]) + self.assertEqual(result["previous_state"], "on") + self.assertEqual(result["new_state"], "off") + service_request = urlopen.call_args_list[1][0][0] + self.assertEqual(service_request.get_method(), "POST") + self.assertIn("/api/services/light/turn_off", service_request.full_url) + self.assertEqual(json.loads(service_request.data), {"entity_id": "light.kitchen"}) + + @mock.patch("urllib.request.urlopen") + def test_turn_on_calls_the_turn_on_service(self, urlopen): + state_response = json_response({"entity_id": "switch.fan", "state": "off", "attributes": {}}) + service_response = json_response([{"entity_id": "switch.fan", "state": "on", "attributes": {}}]) + urlopen.side_effect = [state_response, service_response] + implementation = homeassistant.make_set_entity_state_implementation() + implementation({"entity_id": "switch.fan", "state": "on"}) + service_request = urlopen.call_args_list[1][0][0] + self.assertIn("/api/services/switch/turn_on", service_request.full_url) + + @mock.patch("urllib.request.urlopen") + def test_unconfirmed_service_response_is_a_distinct_failure_not_a_false_success(self, urlopen): + state_response = json_response({"entity_id": "light.kitchen", "state": "on", "attributes": {}}) + # Home Assistant returns 200 but the changed-states list doesn't + # actually confirm the target entity/state -- must not report + # changed: true regardless. + service_response = json_response([]) + urlopen.side_effect = [state_response, service_response] + implementation = homeassistant.make_set_entity_state_implementation() + with self.assertRaises(capabilities.CapabilityError) as caught: + implementation({"entity_id": "light.kitchen", "state": "off"}) + self.assertEqual(caught.exception.code, "HOME_ASSISTANT_ACTION_NOT_CONFIRMED") + + @mock.patch("urllib.request.urlopen") + def test_wrong_entity_in_changed_states_is_not_confirmed(self, urlopen): + state_response = json_response({"entity_id": "light.kitchen", "state": "on", "attributes": {}}) + service_response = json_response([{"entity_id": "light.other", "state": "off", "attributes": {}}]) + urlopen.side_effect = [state_response, service_response] + implementation = homeassistant.make_set_entity_state_implementation() + with self.assertRaises(capabilities.CapabilityError) as caught: + implementation({"entity_id": "light.kitchen", "state": "off"}) + self.assertEqual(caught.exception.code, "HOME_ASSISTANT_ACTION_NOT_CONFIRMED") + + def test_entity_not_controllable_is_rejected_before_any_request(self): + homeassistant.write_config( + "http://homeassistant.local:8123", ["light.kitchen", "light.hallway"], True, + control_enabled=True, controllable_entities=["light.kitchen"], + path=self.config_path, token_path=self.token_path, + ) + implementation = homeassistant.make_set_entity_state_implementation() + with mock.patch("urllib.request.urlopen") as urlopen: + with self.assertRaises(capabilities.CapabilityError) as caught: + implementation({"entity_id": "light.hallway", "state": "off"}) + urlopen.assert_not_called() + self.assertEqual(caught.exception.code, "ENTITY_NOT_CONTROLLABLE") + + def test_not_configured_is_rejected_before_any_request(self): + homeassistant.write_config( + "", [], True, control_enabled=True, path=self.config_path, token_path=self.token_path, + ) + implementation = homeassistant.make_set_entity_state_implementation() + with mock.patch("urllib.request.urlopen") as urlopen: + with self.assertRaises(capabilities.CapabilityError) as caught: + implementation({"entity_id": "light.kitchen", "state": "off"}) + urlopen.assert_not_called() + self.assertEqual(caught.exception.code, "HOME_ASSISTANT_NOT_CONFIGURED") + + def test_domain_bypass_is_rejected_before_any_request(self): + # Adversarial, per RFC-0019's own review finding: even if + # controllable_entities somehow contains a non-light/switch + # entity (bypassing write_config() entirely, e.g. a hand-edited + # config file), the implementation's own independent domain check + # must still refuse it -- Home Assistant's climate domain has + # real turn_on/turn_off services, so this can't be assumed to + # fail safely on its own. + self.config_path.write_text(json.dumps({ + "enabled": True, "base_url": "http://homeassistant.local:8123", + "allowlisted_entities": ["climate.attic"], + "control_enabled": True, "controllable_entities": ["climate.attic"], + })) + implementation = homeassistant.make_set_entity_state_implementation() + with mock.patch("urllib.request.urlopen") as urlopen: + with self.assertRaises(capabilities.CapabilityError) as caught: + implementation({"entity_id": "climate.attic", "state": "on"}) + urlopen.assert_not_called() + self.assertEqual(caught.exception.code, "ENTITY_DOMAIN_NOT_CONTROLLABLE") + + @mock.patch("urllib.request.urlopen", side_effect=urllib.error.URLError("connection refused")) + def test_unreachable_home_assistant_on_state_read_raises_a_typed_error(self, urlopen): + implementation = homeassistant.make_set_entity_state_implementation() + with self.assertRaises(capabilities.CapabilityError) as caught: + implementation({"entity_id": "light.kitchen", "state": "off"}) + self.assertEqual(caught.exception.code, "HOME_ASSISTANT_UNREACHABLE") + + class EndToEndExecutorTests(unittest.TestCase): def setUp(self): self.tempdir = tempfile.TemporaryDirectory() @@ -398,6 +690,80 @@ def test_full_confirmation_round_trip_through_the_real_executor(self, urlopen): ) self.assertEqual([entity["entity_id"] for entity in result["entities"]], ["light.kitchen"]) + def test_set_entity_state_is_mutating_external_required_with_its_own_policy_key(self): + registry = homeassistant.register(capabilities.Registry()) + capability = registry.resolve("home_assistant.set_entity_state", 1) + self.assertEqual(capability.side_effect, "mutating") + self.assertEqual(capability.network, "external") + self.assertEqual(capability.confirmation, "required") + self.assertEqual(capability.policy_key, "home_assistant_control_enabled") + + def test_set_entity_state_disabled_by_its_own_policy_key_rejected_before_confirmation(self): + registry = homeassistant.register(capabilities.Registry()) + with self.assertRaises(capabilities.CapabilityError) as caught: + capabilities.invoke( + registry, "home_assistant.set_entity_state", 1, + {"entity_id": "light.kitchen", "state": "off"}, {}, capabilities.ConfirmationStore(), + audit_log_path=self.audit_path, + ) + self.assertEqual(caught.exception.code, "CAPABILITY_DISABLED") + + def test_enabling_read_alone_does_not_enable_control(self): + # The other half of RFC-0019's central point: home_assistant_enabled + # (read) and home_assistant_control_enabled are independent. + registry = homeassistant.register(capabilities.Registry()) + policy = {"home_assistant_enabled": True, "home_assistant_control_enabled": False} + with self.assertRaises(capabilities.CapabilityError) as caught: + capabilities.invoke( + registry, "home_assistant.set_entity_state", 1, + {"entity_id": "light.kitchen", "state": "off"}, policy, capabilities.ConfirmationStore(), + audit_log_path=self.audit_path, + ) + self.assertEqual(caught.exception.code, "CAPABILITY_DISABLED") + + def test_set_entity_state_entity_not_controllable_rejected_before_confirmation(self): + registry = homeassistant.register(capabilities.Registry()) + policy = { + "home_assistant_control_enabled": True, "home_assistant_configured": True, + "home_assistant_allowlist": ["light.kitchen"], "home_assistant_controllable_entities": [], + } + with self.assertRaises(capabilities.CapabilityError) as caught: + capabilities.invoke( + registry, "home_assistant.set_entity_state", 1, + {"entity_id": "light.kitchen", "state": "off"}, policy, capabilities.ConfirmationStore(), + audit_log_path=self.audit_path, + ) + self.assertEqual(caught.exception.code, "ENTITY_NOT_CONTROLLABLE") + + @mock.patch("urllib.request.urlopen") + def test_set_entity_state_full_confirmation_round_trip_through_the_real_executor(self, urlopen): + homeassistant.write_config( + "http://homeassistant.local:8123", ["light.kitchen"], True, + control_enabled=True, controllable_entities=["light.kitchen"], + access_token="secret-1", path=self.config_path, token_path=self.token_path, + ) + state_response = json_response({"entity_id": "light.kitchen", "state": "on", "attributes": {}}) + service_response = json_response([{"entity_id": "light.kitchen", "state": "off", "attributes": {}}]) + urlopen.side_effect = [state_response, service_response] + registry = homeassistant.register(capabilities.Registry()) + store = capabilities.ConfirmationStore() + policy = homeassistant.policy_fields(path=self.config_path, token_path=self.token_path) + arguments = {"entity_id": "light.kitchen", "state": "off"} + with self.assertRaises(capabilities.CapabilityError) as caught: + capabilities.invoke( + registry, "home_assistant.set_entity_state", 1, arguments, policy, store, + audit_log_path=self.audit_path, + ) + self.assertEqual(caught.exception.code, "CONFIRMATION_REQUIRED") + + token = store.issue("home_assistant.set_entity_state", 1, arguments) + result = capabilities.invoke( + registry, "home_assistant.set_entity_state", 1, arguments, policy, store, + confirmation_token=token, audit_log_path=self.audit_path, + ) + self.assertTrue(result["changed"]) + self.assertEqual(result["new_state"], "off") + if __name__ == "__main__": unittest.main()