From c87cbb5eed97c47b4e003d95d0c2d25b6178c0a6 Mon Sep 17 00:00:00 2001 From: kasunben Date: Fri, 21 Aug 2026 22:21:37 +0200 Subject: [PATCH 1/2] feat: implement RFC-0018's read-only Home Assistant capabilities home_assistant.list_entities and home_assistant.get_history, both read_only/external/required, reusing RFC-0017's confirmation pause/resume flow unchanged. The entity allowlist and "is this even configured" checks run at the executor's policy stage, before any confirmation prompt is generated and before any request reaches Home Assistant. Generalizes sovereign_capabilities.Capability/invoke() with policy_key (a per-capability policy flag, not a single blanket external_enabled) and policy_check (an argument-aware policy hook) -- backward compatible, web.search/web.fetch are unaffected, but enabling web search no longer silently enables Home Assistant too. Found and fixed two real bugs during implementation: a stale-module- cache issue where the capability's own config-path defaults didn't honor overrides after first import (fixed by threading explicit paths through registration into the implementation closures), and a missing entry in create-update-release.py's appliance file allowlist for the new lib module. Config/credentials, HTTP endpoints (GET/POST /home-assistant, GET /home-assistant/entities for the future settings-page allowlist picker), nginx routing, and the systemd ReadWritePaths grant are all included. Console's settings UI itself is explicit, named follow-up per RFC-0018 -- there is no way to configure Home Assistant from Console yet, only by writing to the config/token files directly. Co-Authored-By: Claude Sonnet 5 --- .../appliance/bin/sovereign-conversation | 147 ++++++- .../appliance/lib/sovereign_capabilities.py | 20 +- .../appliance/lib/sovereign_conversation.py | 35 +- .../appliance/lib/sovereign_homeassistant.py | 384 +++++++++++++++++ .../sovereign/appliance/nginx/sovereign.conf | 31 ++ .../system/sovereign-conversation.service | 2 +- scripts/create-update-release.py | 1 + tests/test_capabilities.py | 69 +++ tests/test_conversation.py | 60 ++- tests/test_conversation_service.py | 348 ++++++++++++++- tests/test_homeassistant_capabilities.py | 403 ++++++++++++++++++ 11 files changed, 1486 insertions(+), 14 deletions(-) create mode 100644 image-builder/sovereign/appliance/lib/sovereign_homeassistant.py create mode 100644 tests/test_homeassistant_capabilities.py diff --git a/image-builder/sovereign/appliance/bin/sovereign-conversation b/image-builder/sovereign/appliance/bin/sovereign-conversation index 9b50edd..b58915b 100755 --- a/image-builder/sovereign/appliance/bin/sovereign-conversation +++ b/image-builder/sovereign/appliance/bin/sovereign-conversation @@ -13,6 +13,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "lib")) import sovereign_capabilities as capabilities # noqa: E402 import sovereign_conversation as conversation # noqa: E402 +import sovereign_homeassistant as homeassistant # noqa: E402 import sovereign_inference as inference # noqa: E402 @@ -55,8 +56,33 @@ POLICY_PATH = pathlib.Path( os.environ.get("SOVEREIGN_CONVERSATION_POLICY_PATH", str(conversation.DEFAULT_POLICY_PATH)) ) +# RFC-0018: Home Assistant's own config (enabled/base_url/allowlist) and +# credential (access token), read fresh per request for the same reason +# POLICY_PATH is -- a household's change takes effect on the next message +# without a service restart. +HOME_ASSISTANT_CONFIG_PATH = pathlib.Path( + os.environ.get("SOVEREIGN_HOME_ASSISTANT_CONFIG_PATH", str(homeassistant.CONFIG_PATH)) +) +HOME_ASSISTANT_TOKEN_PATH = pathlib.Path( + os.environ.get("SOVEREIGN_HOME_ASSISTANT_TOKEN_PATH", str(homeassistant.TOKEN_PATH)) +) +# Bounded independent of MAX_REQUEST_BODY_BYTES: an access token is short, +# but this project's own precedent (SearXNG's SEARCH_RESPONSE_READ_BYTES) +# is to size a read bound to what the specific field genuinely needs, not +# reuse an unrelated general request-body limit. +MAX_ACCESS_TOKEN_BYTES = 4096 +MAX_ALLOWLISTED_ENTITIES = 100 +ENTITIES_PROXY_TIMEOUT_SECONDS = 10 + + +def _build_policy(): + return conversation.build_policy(POLICY_PATH, HOME_ASSISTANT_CONFIG_PATH, HOME_ASSISTANT_TOKEN_PATH) -_registry = conversation.build_registry() + +_registry = conversation.build_registry( + home_assistant_config_path=HOME_ASSISTANT_CONFIG_PATH, + home_assistant_token_path=HOME_ASSISTANT_TOKEN_PATH, +) _provider = inference.LlamaCppProvider(base_url=PROVIDER_BASE_URL) _confirmation_store = capabilities.ConfirmationStore() _pending_turn_store = conversation.PendingTurnStore() @@ -98,6 +124,10 @@ class ConversationHandler(BaseHTTPRequestHandler): self._send_json(200, _provider.health()) elif self.path == "/api/v1/conversation/policy": self._handle_get_policy() + elif self.path == "/api/v1/conversation/home-assistant": + self._handle_get_home_assistant() + elif self.path == "/api/v1/conversation/home-assistant/entities": + self._handle_get_home_assistant_entities() else: self.send_error(404) @@ -106,6 +136,8 @@ class ConversationHandler(BaseHTTPRequestHandler): self._handle_message() elif self.path == "/api/v1/conversation/policy": self._handle_set_policy() + elif self.path == "/api/v1/conversation/home-assistant": + self._handle_set_home_assistant() else: self.send_error(404) @@ -164,7 +196,7 @@ class ConversationHandler(BaseHTTPRequestHandler): try: result = conversation.process_turn( _provider, _registry, history, body["message"], - policy=conversation.read_policy(POLICY_PATH), + policy=_build_policy(), confirmation_store=_confirmation_store, pending_turn_store=_pending_turn_store, audit_log_path=AUDIT_LOG_PATH, @@ -194,7 +226,7 @@ class ConversationHandler(BaseHTTPRequestHandler): result = conversation.resume_turn( _provider, _registry, _pending_turn_store, _confirmation_store, confirmation["token"], confirmation["approve"], - policy=conversation.read_policy(POLICY_PATH), + policy=_build_policy(), audit_log_path=AUDIT_LOG_PATH, ) except conversation.TurnError as error: @@ -241,6 +273,115 @@ class ConversationHandler(BaseHTTPRequestHandler): return self._send_json(200, {"web_search_enabled": policy["external_enabled"]}) + def _home_assistant_config_response(self): + config = homeassistant.read_config(HOME_ASSISTANT_CONFIG_PATH) + return { + "enabled": config["enabled"], + "base_url": config["base_url"], + "has_access_token": homeassistant.has_access_token(HOME_ASSISTANT_TOKEN_PATH), + "allowlisted_entities": config["allowlisted_entities"], + } + + def _handle_get_home_assistant(self): + # Authenticated like /policy: administrative device configuration, + # never rendered outside the already-signed-in Chat experience. + if not self._check_authentication(): + return + self._send_json(200, self._home_assistant_config_response()) + + def _handle_set_home_assistant(self): + if not self._check_authentication(): + return + body = self._read_json_body() + if not isinstance(body, dict): + self._send_json(400, {"error": {"code": "INVALID_REQUEST", "message": "a JSON object body is required"}}) + return + if not isinstance(body.get("enabled"), bool): + self._send_json(400, {"error": {"code": "INVALID_REQUEST", "message": "'enabled' must be a boolean"}}) + return + base_url = body.get("base_url") + if not isinstance(base_url, str) or not (base_url.startswith("http://") or base_url.startswith("https://")): + self._send_json(400, { + "error": {"code": "INVALID_REQUEST", "message": "'base_url' must be an http:// or https:// URL"}, + }) + return + allowlisted_entities = body.get("allowlisted_entities") + if ( + not isinstance(allowlisted_entities, list) + or len(allowlisted_entities) > MAX_ALLOWLISTED_ENTITIES + or not all(isinstance(entry, str) and entry for entry in allowlisted_entities) + ): + self._send_json(400, { + "error": { + "code": "INVALID_REQUEST", + "message": f"'allowlisted_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 + # string is a real, different request: clear the stored token. + access_token = body.get("access_token") + if access_token is not None and ( + not isinstance(access_token, str) or len(access_token.encode("utf-8")) > MAX_ACCESS_TOKEN_BYTES + ): + self._send_json(400, { + "error": { + "code": "INVALID_REQUEST", + "message": f"'access_token' must be a string up to {MAX_ACCESS_TOKEN_BYTES} bytes", + }, + }) + return + try: + homeassistant.write_config( + base_url, allowlisted_entities, body["enabled"], + access_token=access_token, + path=HOME_ASSISTANT_CONFIG_PATH, token_path=HOME_ASSISTANT_TOKEN_PATH, + ) + except OSError as error: + self._send_json(502, { + "error": { + "code": "HOME_ASSISTANT_CONFIG_WRITE_FAILED", + "message": f"could not persist the configuration change: {error}", + }, + }) + return + self._send_json(200, self._home_assistant_config_response()) + + def _handle_get_home_assistant_entities(self): + # A separate, settings-page-only proxy: the *unfiltered* entity + # list, so a household can build the allowlist from it. Never + # reachable by the model -- only home_assistant.list_entities + # (allowlist-filtered) is a registered capability. + if not self._check_authentication(): + return + config = homeassistant.read_config(HOME_ASSISTANT_CONFIG_PATH) + token = homeassistant.read_token(HOME_ASSISTANT_TOKEN_PATH) + if not config["base_url"] or not token: + self._send_json(409, { + "error": {"code": "HOME_ASSISTANT_NOT_CONFIGURED", "message": "Home Assistant is not configured"}, + }) + return + try: + states = homeassistant.fetch_all_states( + config["base_url"], token, timeout=ENTITIES_PROXY_TIMEOUT_SECONDS + ) + except capabilities.CapabilityError as error: + self._send_json(502, {"error": {"code": error.code, "message": str(error)}}) + return + entities = [ + { + "entity_id": item.get("entity_id"), + "friendly_name": (item.get("attributes") or {}).get("friendly_name") or item.get("entity_id"), + "domain": (item.get("entity_id") or "").split(".", 1)[0], + "state": item.get("state") or "", + } + for item in states + if item.get("entity_id") + ] + self._send_json(200, {"entities": entities}) + def log_message(self, format_string, *arguments): return diff --git a/image-builder/sovereign/appliance/lib/sovereign_capabilities.py b/image-builder/sovereign/appliance/lib/sovereign_capabilities.py index a580a43..af28b28 100644 --- a/image-builder/sovereign/appliance/lib/sovereign_capabilities.py +++ b/image-builder/sovereign/appliance/lib/sovereign_capabilities.py @@ -141,6 +141,8 @@ def __init__( timeout_seconds=DEFAULT_TIMEOUT_SECONDS, max_result_bytes=DEFAULT_MAX_RESULT_BYTES, max_invocations_per_turn=DEFAULT_MAX_INVOCATIONS_PER_TURN, + policy_key="external_enabled", + policy_check=None, ): fail(side_effect in SIDE_EFFECTS, "INVALID_CAPABILITY", f"Unknown side_effect '{side_effect}'") fail(network in NETWORKS, "INVALID_CAPABILITY", f"Unknown network '{network}'") @@ -155,6 +157,20 @@ def __init__( self.timeout_seconds = timeout_seconds self.max_result_bytes = max_result_bytes self.max_invocations_per_turn = max_invocations_per_turn + # RFC-0018: web.search/web.fetch share one blanket "is any external + # capability allowed at all" flag (policy_key's default, + # "external_enabled"), but Home Assistant needs its own, distinct + # toggle -- enabling web search must not silently also enable Home + # Assistant. policy_key names which policy dict key stage 3 checks + # for this capability; policy_check is an optional further check + # (arguments, policy) -> raises CapabilityError, run immediately + # after, for policy decisions that depend on the specific proposed + # arguments (Home Assistant's entity allowlist) rather than a + # single whole-capability bool. Both default to today's existing + # behavior exactly, so every capability that doesn't need this + # stays unaffected. + self.policy_key = policy_key + self.policy_check = policy_check class Registry: @@ -298,10 +314,12 @@ def invoke( stage_reached = "policy_checked" if capability.network == "external": fail( - bool(policy.get("external_enabled", False)), + bool(policy.get(capability.policy_key, False)), "CAPABILITY_DISABLED", f"'{name}' is disabled by policy (external network capabilities are opt-in)", ) + if capability.policy_check is not None: + capability.policy_check(arguments, policy) stage_reached = "confirmed" if capability.confirmation == "required": diff --git a/image-builder/sovereign/appliance/lib/sovereign_conversation.py b/image-builder/sovereign/appliance/lib/sovereign_conversation.py index 73757b6..33f6100 100644 --- a/image-builder/sovereign/appliance/lib/sovereign_conversation.py +++ b/image-builder/sovereign/appliance/lib/sovereign_conversation.py @@ -2,6 +2,7 @@ import pathlib import sovereign_capabilities as capabilities +import sovereign_homeassistant as homeassistant import sovereign_inference as inference import sovereign_pihole as pihole import sovereign_system as system @@ -65,18 +66,25 @@ def pop(self, token): return self._pending.pop(token, None) -def build_registry(): +def build_registry(home_assistant_config_path=None, home_assistant_token_path=None): # The real, production registry -- system.health, both Pi-hole - # capabilities, and (RFC-0017) web.search/web.fetch. Registration is + # capabilities, (RFC-0017) web.search/web.fetch, and (RFC-0018) + # Home Assistant's read-only entity/history pair. Registration is # unconditional per RFC-0003 ("a static list compiled into - # Sovereign... not installable by a user or a model"); whether - # web.search/web.fetch can actually run is a runtime policy check - # (external_enabled) at invocation time, not a registration-time - # decision. + # Sovereign... not installable by a user or a model"); whether any + # external capability can actually run is a runtime policy check + # at invocation time, not a registration-time decision. + # + # home_assistant_config_path/token_path are threaded straight through + # to homeassistant.register() -- see that function's own comment for + # why a caller with its own resolved paths (bin/sovereign-conversation) + # should bind them explicitly here rather than relying on + # sovereign_homeassistant's own module-global defaults. registry = capabilities.Registry() system.register(registry) pihole.register(registry) websearch.register(registry) + homeassistant.register(registry, config_path=home_assistant_config_path, token_path=home_assistant_token_path) return registry @@ -122,6 +130,21 @@ def write_policy(web_search_enabled, path=DEFAULT_POLICY_PATH): return {"external_enabled": bool(web_search_enabled)} +def build_policy(policy_path=DEFAULT_POLICY_PATH, home_assistant_config_path=None, home_assistant_token_path=None): + # RFC-0018: merges RFC-0017's own external_enabled flag with Home + # Assistant's distinct policy_key/allowlist/configured-ness -- one + # call site for process_turn()/resume_turn()'s policy argument, + # rather than each endpoint handler assembling this by hand. + policy = read_policy(policy_path) + kwargs = {} + if home_assistant_config_path is not None: + kwargs["path"] = home_assistant_config_path + if home_assistant_token_path is not None: + kwargs["token_path"] = home_assistant_token_path + policy.update(homeassistant.policy_fields(**kwargs)) + return policy + + def _tool_call_id(round_number, index): return f"call_{round_number}_{index}" diff --git a/image-builder/sovereign/appliance/lib/sovereign_homeassistant.py b/image-builder/sovereign/appliance/lib/sovereign_homeassistant.py new file mode 100644 index 0000000..77b5a7a --- /dev/null +++ b/image-builder/sovereign/appliance/lib/sovereign_homeassistant.py @@ -0,0 +1,384 @@ +import datetime +import json +import os +import pathlib +import urllib.error +import urllib.parse +import urllib.request + +import sovereign_capabilities as capabilities + + +# RFC-0018: home_assistant.list_entities/home_assistant.get_history, the +# roadmap's first (read-only) Home Assistant slice. Both are read_only + +# external, which RFC-0003's classification table fixes as confirmation: +# required -- reusing RFC-0017's existing pause/resume flow unchanged +# (sovereign_conversation.py). Unlike web.search/web.fetch, this +# capability pair needs its own distinct policy toggle (not RFC-0017's +# shared external_enabled) and an entity allowlist checked before any +# confirmation is generated -- both via sovereign_capabilities.Capability's +# policy_key/policy_check hooks. + +CONFIG_PATH = pathlib.Path( + os.environ.get("SOVEREIGN_HOME_ASSISTANT_CONFIG_PATH", "/data/sovereign/capabilities/home-assistant.json") +) +TOKEN_PATH = pathlib.Path( + os.environ.get("SOVEREIGN_HOME_ASSISTANT_TOKEN_PATH", "/data/sovereign/secrets/home-assistant/access-token") +) + +LIST_ENTITIES_TIMEOUT_SECONDS = 8 +GET_HISTORY_TIMEOUT_SECONDS = 10 +# A real Home Assistant /api/states response can be far larger than what +# list_entities actually returns (every entity, not just the allowlisted +# ones) -- this bounds what's read from Home Assistant, not what the +# capability returns, which is filtered to the allowlist well before this +# module hands anything back to the executor's own max_result_bytes check. +RESPONSE_READ_BYTES = capabilities.DEFAULT_MAX_RESULT_BYTES * 8 +MAX_HISTORY_ENTRIES = 50 + +PERIOD_DELTAS = { + "hour": datetime.timedelta(hours=1), + "day": datetime.timedelta(days=1), + "week": datetime.timedelta(days=7), +} + +LIST_ENTITIES_ARGUMENT_SCHEMA = { + "type": "object", + "properties": {}, + "required": [], + "additionalProperties": False, +} +LIST_ENTITIES_RESULT_SCHEMA = { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "entity_id": {"type": "string"}, + "friendly_name": {"type": "string"}, + "domain": {"type": "string"}, + "state": {"type": "string"}, + "unit_of_measurement": {"type": ["string", "null"]}, + "last_changed": {"type": "string"}, + }, + "required": [ + "entity_id", "friendly_name", "domain", "state", + "unit_of_measurement", "last_changed", + ], + "additionalProperties": False, + }, + }, + "retrieved_at": {"type": "string"}, + }, + "required": ["entities", "retrieved_at"], + "additionalProperties": False, +} + +GET_HISTORY_ARGUMENT_SCHEMA = { + "type": "object", + "properties": { + "entity_id": {"type": "string"}, + "period": {"type": "string", "enum": ["hour", "day", "week"]}, + }, + "required": ["entity_id", "period"], + "additionalProperties": False, +} +GET_HISTORY_RESULT_SCHEMA = { + "type": "object", + "properties": { + "entity_id": {"type": "string"}, + "period": {"type": "string"}, + "changes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "state": {"type": "string"}, + "changed_at": {"type": "string"}, + }, + "required": ["state", "changed_at"], + "additionalProperties": False, + }, + }, + "retrieved_at": {"type": "string"}, + }, + "required": ["entity_id", "period", "changes", "retrieved_at"], + "additionalProperties": False, +} + + +# --- Configuration and credential storage --------------------------------- +# +# RFC-0018: kept deliberately separate from sovereign_conversation.py's own +# policy.json (a different, structurally bigger shape -- a connection +# endpoint and a list, not one bool) and the access token kept separate +# again from this file (a real credential, stored under its own +# ReadWritePaths= directory so a compromised sovereign-conversation.service +# process gains no new ability to touch Pi-hole's own credential). + + +def read_config(path=None): + # path=None resolves CONFIG_PATH fresh from this module's own globals + # at call time, not as a default-argument value bound once at import + # time -- the latter would silently stop honoring + # SOVEREIGN_HOME_ASSISTANT_CONFIG_PATH overrides (and test monkeypatches + # of CONFIG_PATH itself) after the first import, since Python evaluates + # a default argument expression exactly once, at function definition. + if path is None: + path = CONFIG_PATH + # Missing file or malformed content both fail safe to "disabled, empty + # allowlist" -- a household that has never configured this must not + # silently expose any entity. + try: + parsed = json.loads(pathlib.Path(path).read_text(encoding="utf-8")) + except (OSError, ValueError): + parsed = {} + if not isinstance(parsed, dict): + parsed = {} + allowlist = parsed.get("allowlisted_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 [], + } + + +def read_token(path=None): + if path is None: + path = TOKEN_PATH + try: + return pathlib.Path(path).read_text(encoding="utf-8").strip() + except OSError: + return "" + + +def write_config(base_url, allowlisted_entities, enabled, access_token=None, path=None, token_path=None): + if path is None: + path = CONFIG_PATH + if token_path is None: + token_path = TOKEN_PATH + path = pathlib.Path(path) + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + payload = json.dumps( + { + "enabled": bool(enabled), + "base_url": base_url, + "allowlisted_entities": list(allowlisted_entities), + }, + sort_keys=True, + ) + temporary = pathlib.Path(f"{path}.tmp") + temporary.write_text(payload, encoding="utf-8") + temporary.chmod(0o600) + temporary.replace(path) + + if access_token is not None: + # Omitted (None) means "leave the stored token unchanged" -- an + # empty string is a real, explicit "clear the token" request, not + # treated the same as omission. + token_path = pathlib.Path(token_path) + token_path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + token_temporary = pathlib.Path(f"{token_path}.tmp") + token_temporary.write_text(access_token, encoding="utf-8") + token_temporary.chmod(0o600) + token_temporary.replace(token_path) + + return read_config(path) + + +def has_access_token(path=None): + return bool(read_token(path)) + + +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. + 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, + } + + +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. + 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)", + ) + entity_id = arguments.get("entity_id") + if entity_id is not None: + 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", + ) + + +# --- Home Assistant REST client -------------------------------------------- +# +# Bearer-token auth, confirmed against Home Assistant's own REST API +# documentation (RFC-0018's Context and Evidence). base_url is +# household-configured and never model-influenced -- unlike web.fetch, +# there is no SSRF-style resolve-then-check policy here, since the only +# untrusted, model-supplied inputs are entity_id/period, both checked +# against server-held state before any request is made. TLS certificate +# verification is never disabled here (RFC-0018's own resolved Unresolved +# Question): urllib.request's default HTTPS handling already verifies +# normally for an https:// base_url, and a household on a plain local +# network can simply configure http://. + + +def _get(base_url, token, path, params=None, timeout=LIST_ENTITIES_TIMEOUT_SECONDS): + query = f"?{urllib.parse.urlencode(params)}" if params else "" + url = f"{base_url.rstrip('/')}{path}{query}" + request = urllib.request.Request(url, method="GET", headers={"Authorization": f"Bearer {token}"}) + 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 fetch_all_states(base_url, token, timeout=LIST_ENTITIES_TIMEOUT_SECONDS): + # Unfiltered -- every entity Home Assistant reports, not just the + # allowlisted ones. Used by make_list_entities_implementation (which + # filters down to the allowlist itself) and, directly, by the + # settings-page entity-browsing proxy endpoint (RFC-0018: a household + # must be able to see the full set once, to build the allowlist from + # it -- the model never sees this unfiltered response). + return _get(base_url, token, "/api/states", timeout=timeout) or [] + + +def make_list_entities_implementation(config_path=None, token_path=None): + def implementation(arguments): + 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", + ) + allowlist = set(config["allowlisted_entities"]) + states = fetch_all_states(config["base_url"], token, timeout=LIST_ENTITIES_TIMEOUT_SECONDS) + entities = [] + for item in states: + entity_id = item.get("entity_id") + if entity_id not in allowlist: + continue + attributes = item.get("attributes") or {} + entities.append({ + "entity_id": entity_id, + "friendly_name": attributes.get("friendly_name") or entity_id, + "domain": entity_id.split(".", 1)[0], + "state": item.get("state") or "", + "unit_of_measurement": attributes.get("unit_of_measurement"), + "last_changed": item.get("last_changed") or "", + }) + return {"entities": entities, "retrieved_at": capabilities.timestamp()} + + return implementation + + +def make_get_history_implementation(config_path=None, token_path=None): + def implementation(arguments): + entity_id = arguments["entity_id"] + period = arguments["period"] + 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["allowlisted_entities"], "ENTITY_NOT_ALLOWLISTED", + f"'{entity_id}' is not in the Home Assistant entity allowlist", + ) + since = datetime.datetime.now(datetime.timezone.utc) - PERIOD_DELTAS[period] + # ISO 8601 with an explicit offset -- Home Assistant's own + # /api/history/period/ path segment. + timestamp_path = since.isoformat() + payload = _get( + config["base_url"], token, + f"/api/history/period/{urllib.parse.quote(timestamp_path, safe='')}", + params={"filter_entity_id": entity_id}, + timeout=GET_HISTORY_TIMEOUT_SECONDS, + ) + # Home Assistant's own response shape: a list containing one list + # per requested entity_id (filter_entity_id here always names + # exactly one), each entry a state-change record. + raw_changes = payload[0] if payload else [] + changes = [ + {"state": item.get("state") or "", "changed_at": item.get("last_changed") or ""} + for item in raw_changes[:MAX_HISTORY_ENTRIES] + ] + return { + "entity_id": entity_id, + "period": period, + "changes": changes, + "retrieved_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 + # at call time (see their own comments) -- but a caller that already + # has its own resolved, env-overridden paths (bin/sovereign-conversation) + # can bind them explicitly here instead, so the resulting capabilities' + # implementation closures never depend on this module's own globals + # possibly having been fixed by an earlier, unrelated import elsewhere + # in the same process (real in production, since a service imports + # this module exactly once; only surfaces under a test runner that + # imports this module many times across different env-var overrides + # in one process). + registry.register( + capabilities.Capability( + name="home_assistant.list_entities", + version=1, + argument_schema=LIST_ENTITIES_ARGUMENT_SCHEMA, + result_schema=LIST_ENTITIES_RESULT_SCHEMA, + side_effect="read_only", + network="external", + implementation=make_list_entities_implementation(config_path, token_path), + timeout_seconds=LIST_ENTITIES_TIMEOUT_SECONDS + 2, + policy_key="home_assistant_enabled", + policy_check=_policy_check, + ) + ) + registry.register( + capabilities.Capability( + name="home_assistant.get_history", + version=1, + argument_schema=GET_HISTORY_ARGUMENT_SCHEMA, + result_schema=GET_HISTORY_RESULT_SCHEMA, + side_effect="read_only", + network="external", + implementation=make_get_history_implementation(config_path, token_path), + timeout_seconds=GET_HISTORY_TIMEOUT_SECONDS + 2, + policy_key="home_assistant_enabled", + policy_check=_policy_check, + ) + ) + return registry diff --git a/image-builder/sovereign/appliance/nginx/sovereign.conf b/image-builder/sovereign/appliance/nginx/sovereign.conf index 623186d..3cf4c9b 100644 --- a/image-builder/sovereign/appliance/nginx/sovereign.conf +++ b/image-builder/sovereign/appliance/nginx/sovereign.conf @@ -219,6 +219,37 @@ server { add_header X-Content-Type-Options "nosniff" always; } + # RFC-0018: GET reads, POST writes Home Assistant's connection config + # and entity allowlist -- same self-checked session/CSRF boundary as + # /policy above, short timeout since this never touches inference or + # a capability, just local file state. + location = /api/v1/conversation/home-assistant { + proxy_pass http://127.0.0.1:8092/api/v1/conversation/home-assistant; + proxy_http_version 1.1; + proxy_set_header Host 127.0.0.1; + proxy_set_header Connection ""; + proxy_connect_timeout 2s; + proxy_read_timeout 5s; + add_header Cache-Control "no-store" always; + add_header X-Content-Type-Options "nosniff" always; + } + + # RFC-0018: settings-page-only proxy for the *unfiltered* Home + # Assistant entity list (to build the allowlist from) -- a real + # request to a real second host on the household LAN, so a longer + # read timeout than the local-file-only /home-assistant endpoint + # above, though still well under /message's inference-bound timeout. + location = /api/v1/conversation/home-assistant/entities { + proxy_pass http://127.0.0.1:8092/api/v1/conversation/home-assistant/entities; + proxy_http_version 1.1; + proxy_set_header Host 127.0.0.1; + proxy_set_header Connection ""; + proxy_connect_timeout 2s; + proxy_read_timeout 15s; + add_header Cache-Control "no-store" always; + add_header X-Content-Type-Options "nosniff" always; + } + # No auth_request here: unlike /dns/, the Conversation Service checks # its own session/CSRF (delegating to console-auth) per RFC-0002, # since this is a JSON API a client calls directly rather than a diff --git a/image-builder/sovereign/layer/sovereign-proof.rootfs-overlay/etc/systemd/system/sovereign-conversation.service b/image-builder/sovereign/layer/sovereign-proof.rootfs-overlay/etc/systemd/system/sovereign-conversation.service index 5908010..c982f65 100644 --- a/image-builder/sovereign/layer/sovereign-proof.rootfs-overlay/etc/systemd/system/sovereign-conversation.service +++ b/image-builder/sovereign/layer/sovereign-proof.rootfs-overlay/etc/systemd/system/sovereign-conversation.service @@ -13,7 +13,7 @@ ConditionPathIsMountPoint=/data Type=simple DynamicUser=yes SupplementaryGroups=sovereign-pihole-secrets -ReadWritePaths=/data/sovereign/capabilities +ReadWritePaths=/data/sovereign/capabilities /data/sovereign/secrets/home-assistant ExecStart=/opt/sovereign/current/appliance/bin/sovereign-conversation Restart=on-failure RestartSec=5s diff --git a/scripts/create-update-release.py b/scripts/create-update-release.py index 397d450..a8b806e 100755 --- a/scripts/create-update-release.py +++ b/scripts/create-update-release.py @@ -32,6 +32,7 @@ "console/index.html": 0o644, "lib/sovereign_capabilities.py": 0o644, "lib/sovereign_conversation.py": 0o644, + "lib/sovereign_homeassistant.py": 0o644, "lib/sovereign_inference.py": 0o644, "lib/sovereign_pihole.py": 0o644, "lib/sovereign_system.py": 0o644, diff --git a/tests/test_capabilities.py b/tests/test_capabilities.py index aa143f7..b6e5c98 100644 --- a/tests/test_capabilities.py +++ b/tests/test_capabilities.py @@ -256,6 +256,75 @@ def test_external_capability_rejected_when_policy_disabled(self): ) self.assertEqual(caught.exception.code, "CAPABILITY_DISABLED") + def test_custom_policy_key_is_checked_instead_of_the_default(self): + # RFC-0018: a capability can declare its own distinct policy flag + # (e.g. home_assistant_enabled) rather than sharing the generic + # external_enabled default -- enabling one must not silently + # enable the other. + capability = self.make_capability( + side_effect="read_only", network="external", policy_key="custom_enabled", + ) + registry = self.registry_with(capability) + with self.assertRaises(capabilities.CapabilityError) as caught: + capabilities.invoke( + registry, capability.name, capability.version, {}, + {"external_enabled": True, "custom_enabled": False}, capabilities.ConfirmationStore(), + audit_log_path=self.audit_path, + ) + self.assertEqual(caught.exception.code, "CAPABILITY_DISABLED") + + def test_custom_policy_key_enabled_passes_the_policy_stage(self): + capability = self.make_capability( + side_effect="read_only", network="external", policy_key="custom_enabled", + ) + registry = self.registry_with(capability) + with self.assertRaises(capabilities.CapabilityError) as caught: + capabilities.invoke( + registry, capability.name, capability.version, {}, + {"external_enabled": False, "custom_enabled": True}, capabilities.ConfirmationStore(), + audit_log_path=self.audit_path, + ) + # Passes the policy stage (the custom flag is true) and reaches + # the next stage instead -- read_only/external is still + # confirmation: required, structurally, so it stops there next. + self.assertEqual(caught.exception.code, "CONFIRMATION_REQUIRED") + + def test_policy_check_runs_after_the_policy_key_gate_and_can_reject(self): + calls = [] + + def reject_everything(arguments, policy): + calls.append((arguments, policy)) + capabilities.fail(False, "CUSTOM_REJECTED", "rejected by policy_check") + + capability = self.make_capability( + side_effect="read_only", network="external", policy_check=reject_everything, + ) + registry = self.registry_with(capability) + with self.assertRaises(capabilities.CapabilityError) as caught: + capabilities.invoke( + registry, capability.name, capability.version, {}, + {"external_enabled": True}, capabilities.ConfirmationStore(), + audit_log_path=self.audit_path, + ) + self.assertEqual(caught.exception.code, "CUSTOM_REJECTED") + self.assertEqual(calls, [({}, {"external_enabled": True})]) + + def test_policy_check_never_runs_when_the_policy_key_gate_already_failed(self): + calls = [] + capability = self.make_capability( + side_effect="read_only", network="external", + policy_check=lambda arguments, policy: calls.append(True), + ) + registry = self.registry_with(capability) + with self.assertRaises(capabilities.CapabilityError) as caught: + capabilities.invoke( + registry, capability.name, capability.version, {}, + {"external_enabled": False}, capabilities.ConfirmationStore(), + audit_log_path=self.audit_path, + ) + self.assertEqual(caught.exception.code, "CAPABILITY_DISABLED") + self.assertEqual(calls, []) + def test_required_confirmation_rejected_without_token(self): capability = self.make_capability(side_effect="mutating", network="local") registry = self.registry_with(capability) diff --git a/tests/test_conversation.py b/tests/test_conversation.py index fed5118..87961e8 100644 --- a/tests/test_conversation.py +++ b/tests/test_conversation.py @@ -12,6 +12,7 @@ import sovereign_capabilities as capabilities # noqa: E402 import sovereign_conversation as conversation # noqa: E402 +import sovereign_homeassistant as homeassistant # noqa: E402 import sovereign_inference as inference # noqa: E402 @@ -68,12 +69,15 @@ def registry_with(self, *caps): class BuildRegistryTests(unittest.TestCase): - def test_includes_exactly_the_five_real_capabilities(self): + def test_includes_exactly_the_seven_real_capabilities(self): registry = conversation.build_registry() names = {entry["name"] for entry in registry.catalog()} self.assertEqual( names, - {"system.health", "pihole.status", "pihole.summary", "web.search", "web.fetch"}, + { + "system.health", "pihole.status", "pihole.summary", "web.search", "web.fetch", + "home_assistant.list_entities", "home_assistant.get_history", + }, ) @@ -523,5 +527,57 @@ def test_write_returns_the_new_state(self): self.assertEqual(conversation.write_policy(True, self.policy_path()), {"external_enabled": True}) +class BuildPolicyTests(ConversationTestCase): + def policy_path(self): + return Path(self.tempdir.name) / "capabilities" / "policy.json" + + def home_assistant_config_path(self): + return Path(self.tempdir.name) / "capabilities" / "home-assistant.json" + + def home_assistant_token_path(self): + return Path(self.tempdir.name) / "secrets" / "home-assistant" / "access-token" + + def test_merges_web_search_and_home_assistant_policy_on_a_fresh_device(self): + policy = conversation.build_policy( + self.policy_path(), self.home_assistant_config_path(), self.home_assistant_token_path(), + ) + self.assertEqual( + policy, + { + "external_enabled": False, + "home_assistant_enabled": False, + "home_assistant_allowlist": [], + "home_assistant_configured": False, + }, + ) + + 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", + path=self.home_assistant_config_path(), token_path=self.home_assistant_token_path(), + ) + policy = conversation.build_policy( + self.policy_path(), self.home_assistant_config_path(), self.home_assistant_token_path(), + ) + self.assertEqual( + policy, + { + "external_enabled": True, + "home_assistant_enabled": True, + "home_assistant_allowlist": ["light.kitchen"], + "home_assistant_configured": True, + }, + ) + + def test_web_search_and_home_assistant_toggle_independently(self): + conversation.write_policy(True, self.policy_path()) + policy = conversation.build_policy( + self.policy_path(), self.home_assistant_config_path(), self.home_assistant_token_path(), + ) + self.assertTrue(policy["external_enabled"]) + self.assertFalse(policy["home_assistant_enabled"]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_conversation_service.py b/tests/test_conversation_service.py index 40014af..2209e48 100644 --- a/tests/test_conversation_service.py +++ b/tests/test_conversation_service.py @@ -28,6 +28,7 @@ ) import sovereign_capabilities as capabilities # noqa: E402 +import sovereign_homeassistant as homeassistant # noqa: E402 import sovereign_system as system # noqa: E402 import sovereign_websearch as websearch # noqa: E402 @@ -106,10 +107,17 @@ def auth_ok(): class LiveConversationServer: - def __init__(self, audit_log_path, policy_path=None): + def __init__( + self, audit_log_path, policy_path=None, + home_assistant_config_path=None, home_assistant_token_path=None, + ): environment = {"SOVEREIGN_CONVERSATION_AUDIT_LOG_PATH": str(audit_log_path)} if policy_path is not None: environment["SOVEREIGN_CONVERSATION_POLICY_PATH"] = str(policy_path) + if home_assistant_config_path is not None: + environment["SOVEREIGN_HOME_ASSISTANT_CONFIG_PATH"] = str(home_assistant_config_path) + if home_assistant_token_path is not None: + environment["SOVEREIGN_HOME_ASSISTANT_TOKEN_PATH"] = str(home_assistant_token_path) with mock.patch.dict(__import__("os").environ, environment): self.module = runpy.run_path(str(CONVERSATION_SERVICE)) from http.server import ThreadingHTTPServer @@ -574,6 +582,338 @@ def test_disabling_after_enabling_takes_effect_on_the_next_message(self): ) +class HomeAssistantConfigEndpointTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.audit_path = Path(self.temporary.name) / "audit.jsonl" + self.config_path = Path(self.temporary.name) / "capabilities" / "home-assistant.json" + self.token_path = Path(self.temporary.name) / "secrets" / "home-assistant" / "access-token" + self.live = LiveConversationServer( + self.audit_path, + home_assistant_config_path=self.config_path, + home_assistant_token_path=self.token_path, + ) + self.addCleanup(self.live.stop) + + def _get(self, path, headers=None): + connection = self.live.connection() + connection.request("GET", path, headers=headers or {}) + response = connection.getresponse() + parsed = json.loads(response.read()) + connection.close() + return response, parsed + + def _post(self, path, payload, headers=None): + connection = self.live.connection() + connection.request( + "POST", path, body=json.dumps(payload), + headers=headers or {"Content-Type": "application/json"}, + ) + response = connection.getresponse() + parsed = json.loads(response.read()) + connection.close() + return response, parsed + + def test_get_requires_authentication(self): + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen( + [("/api/v1/auth/verify-mutating", urllib.error.HTTPError("url", 401, "unauthorized", {}, None))] + ) + response, body = self._get("/api/v1/conversation/home-assistant") + self.assertEqual(401, response.status) + self.assertEqual("NOT_AUTHENTICATED", body["error"]["code"]) + + def test_get_reflects_the_real_default_disabled_unconfigured(self): + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen([auth_ok()]) + response, body = self._get("/api/v1/conversation/home-assistant") + self.assertEqual(200, response.status) + self.assertEqual( + body, + {"enabled": False, "base_url": "", "has_access_token": False, "allowlisted_entities": []}, + ) + + def test_post_requires_authentication(self): + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen( + [("/api/v1/auth/verify-mutating", urllib.error.HTTPError("url", 403, "forbidden", {}, None))] + ) + response, body = self._post( + "/api/v1/conversation/home-assistant", + {"enabled": True, "base_url": "http://homeassistant.local:8123", "allowlisted_entities": []}, + ) + self.assertEqual(403, response.status) + self.assertEqual("CSRF_MISMATCH", body["error"]["code"]) + + def test_post_persists_and_get_reflects_it_never_returning_the_token(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://homeassistant.local:8123", + "allowlisted_entities": ["light.kitchen"], + "access_token": "secret-1", + }, + ) + self.assertEqual(200, response.status) + self.assertEqual( + body, + { + "enabled": True, + "base_url": "http://homeassistant.local:8123", + "has_access_token": True, + "allowlisted_entities": ["light.kitchen"], + }, + ) + self.assertNotIn("secret-1", json.dumps(body)) + + with mock.patch("urllib.request.urlopen") as urlopen: + 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(homeassistant.read_token(self.token_path), "secret-1") + + def test_omitted_access_token_leaves_the_stored_token_unchanged(self): + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen([auth_ok()]) + self._post( + "/api/v1/conversation/home-assistant", + { + "enabled": True, "base_url": "http://x:8123", + "allowlisted_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"]}, + ) + self.assertTrue(body["has_access_token"]) + self.assertEqual(homeassistant.read_token(self.token_path), "secret-1") + + def test_post_rejects_a_non_boolean_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": "yes", "base_url": "http://x:8123", "allowlisted_entities": []}, + ) + self.assertEqual(400, response.status) + self.assertEqual("INVALID_REQUEST", body["error"]["code"]) + + def test_post_rejects_a_non_http_base_url(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": "ftp://x", "allowlisted_entities": []}, + ) + self.assertEqual(400, response.status) + self.assertEqual("INVALID_REQUEST", body["error"]["code"]) + + def test_post_rejects_a_non_list_allowlist(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": "light.kitchen"}, + ) + self.assertEqual(400, response.status) + self.assertEqual("INVALID_REQUEST", body["error"]["code"]) + + +class HomeAssistantEntitiesProxyEndpointTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.audit_path = Path(self.temporary.name) / "audit.jsonl" + self.config_path = Path(self.temporary.name) / "capabilities" / "home-assistant.json" + self.token_path = Path(self.temporary.name) / "secrets" / "home-assistant" / "access-token" + self.live = LiveConversationServer( + self.audit_path, + home_assistant_config_path=self.config_path, + home_assistant_token_path=self.token_path, + ) + self.addCleanup(self.live.stop) + + def _get(self, headers=None): + connection = self.live.connection() + connection.request("GET", "/api/v1/conversation/home-assistant/entities", headers=headers or {}) + response = connection.getresponse() + parsed = json.loads(response.read()) + connection.close() + return response, parsed + + def test_requires_authentication(self): + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen( + [("/api/v1/auth/verify-mutating", urllib.error.HTTPError("url", 401, "unauthorized", {}, None))] + ) + response, body = self._get() + self.assertEqual(401, response.status) + + def test_not_configured_is_a_409(self): + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen([auth_ok()]) + response, body = self._get() + self.assertEqual(409, response.status) + self.assertEqual("HOME_ASSISTANT_NOT_CONFIGURED", body["error"]["code"]) + + def test_returns_the_unfiltered_entity_list_not_just_the_allowlist(self): + homeassistant.write_config( + "http://homeassistant.local:8123", ["light.kitchen"], True, access_token="secret-1", + path=self.config_path, token_path=self.token_path, + ) + states_payload = [ + {"entity_id": "light.kitchen", "state": "on", "attributes": {"friendly_name": "Kitchen"}}, + {"entity_id": "lock.front_door", "state": "locked", "attributes": {"friendly_name": "Front Door"}}, + ] + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen([auth_ok(), ("/api/states", json_response(states_payload))]) + response, body = self._get() + self.assertEqual(200, response.status) + entity_ids = {entity["entity_id"] for entity in body["entities"]} + # Deliberately not filtered to the allowlist -- this is the + # settings-page proxy a household uses to build the allowlist. + self.assertEqual(entity_ids, {"light.kitchen", "lock.front_door"}) + + +class HomeAssistantConfirmationWireFormatTests(unittest.TestCase): + # RFC-0018's own Acceptance Criteria: no new wire-format code path, + # only a second registration reusing RFC-0017's existing + # pending_confirmation/confirmation mechanism. + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.audit_path = Path(self.temporary.name) / "audit.jsonl" + self.config_path = Path(self.temporary.name) / "capabilities" / "home-assistant.json" + self.token_path = Path(self.temporary.name) / "secrets" / "home-assistant" / "access-token" + + def configure_and_enable(self, allowlist=("light.kitchen",)): + homeassistant.write_config( + "http://homeassistant.local:8123", list(allowlist), True, access_token="secret-1", + path=self.config_path, token_path=self.token_path, + ) + + def start_server(self): + self.live = LiveConversationServer( + self.audit_path, + home_assistant_config_path=self.config_path, + home_assistant_token_path=self.token_path, + ) + self.addCleanup(self.live.stop) + + def _post(self, payload): + connection = self.live.connection() + connection.request( + "POST", "/api/v1/conversation/message", + body=json.dumps(payload), headers={"Content-Type": "application/json"}, + ) + response = connection.getresponse() + parsed = json.loads(response.read()) + connection.close() + return response, parsed + + def test_disabled_by_default_rejects_without_ever_prompting(self): + self.start_server() + proposal = chat_completion(tool_calls=[tool_call("call_1_0", "home_assistant.list_entities", {})]) + narration = chat_completion(content="Home Assistant 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": "what lights are on"}) + self.assertEqual(200, response.status) + self.assertNotIn("pending_confirmation", body) + self.assertEqual( + [{"name": "home_assistant.list_entities", "outcome": "rejected", "code": "CAPABILITY_DISABLED"}], + body["capability_events"], + ) + + def test_enabled_proposal_pauses_for_confirmation(self): + self.configure_and_enable() + self.start_server() + proposal = chat_completion(tool_calls=[tool_call("call_1_0", "home_assistant.list_entities", {})]) + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen([auth_ok(), ("/v1/chat/completions", proposal)]) + response, body = self._post({"message": "what lights are on"}) + self.assertEqual(200, response.status) + self.assertEqual("home_assistant.list_entities", body["pending_confirmation"]["capability"]) + self.assertIn("token", body["pending_confirmation"]) + + def test_approving_executes_the_real_capability_and_narrates(self): + self.configure_and_enable() + self.start_server() + proposal = chat_completion(tool_calls=[tool_call("call_1_0", "home_assistant.list_entities", {})]) + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen([auth_ok(), ("/v1/chat/completions", proposal)]) + _, paused = self._post({"message": "what lights are on"}) + token = paused["pending_confirmation"]["token"] + + states_payload = [{"entity_id": "light.kitchen", "state": "on", "attributes": {}}] + narration = chat_completion(content="The kitchen light is on.") + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen( + [auth_ok(), ("/api/states", json_response(states_payload)), ("/v1/chat/completions", narration)] + ) + response, body = self._post({"confirmation": {"token": token, "approve": True}}) + self.assertEqual(200, response.status) + self.assertEqual("The kitchen light is on.", body["text"]) + self.assertEqual( + [{"name": "home_assistant.list_entities", "outcome": "executed"}], body["capability_events"], + ) + + def test_entity_not_allowlisted_is_rejected_before_confirmation(self): + self.configure_and_enable(allowlist=("light.kitchen",)) + self.start_server() + proposal = chat_completion( + tool_calls=[tool_call("call_1_0", "home_assistant.get_history", {"entity_id": "lock.front_door", "period": "day"})] + ) + narration = chat_completion(content="That entity isn't available.") + 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": "when was the front door unlocked"}) + self.assertEqual(200, response.status) + self.assertNotIn("pending_confirmation", body) + self.assertEqual( + [{"name": "home_assistant.get_history", "outcome": "rejected", "code": "ENTITY_NOT_ALLOWLISTED"}], + body["capability_events"], + ) + + def test_enabling_web_search_alone_does_not_enable_home_assistant(self): + # Cross-feature independence, proven at the HTTP layer too, not + # just the executor unit tests. + self.start_server() + with mock.patch("urllib.request.urlopen") as urlopen: + urlopen.side_effect = dispatch_urlopen([auth_ok()]) + connection = self.live.connection() + connection.request( + "POST", "/api/v1/conversation/policy", + body=json.dumps({"web_search_enabled": True}), + headers={"Content-Type": "application/json"}, + ) + connection.getresponse().read() + connection.close() + + proposal = chat_completion(tool_calls=[tool_call("call_1_0", "home_assistant.list_entities", {})]) + narration = chat_completion(content="Home Assistant 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": "what lights are on"}) + self.assertEqual( + [{"name": "home_assistant.list_entities", "outcome": "rejected", "code": "CAPABILITY_DISABLED"}], + body["capability_events"], + ) + + class ConversationProvisioningTests(unittest.TestCase): def test_systemd_unit_is_hardened_and_grouped(self): service = SYSTEMD_SERVICE.read_text() @@ -589,6 +929,12 @@ def test_systemd_unit_is_hardened_and_grouped(self): self.assertIn("After=", service) self.assertIn("systemd-sysusers.service", service) self.assertIn("ReadWritePaths=/data/sovereign/capabilities", service) + # RFC-0018: the Home Assistant access token's own writable + # directory, deliberately separate from + # /data/sovereign/secrets/pihole-admin-password's own -- a + # compromised sovereign-conversation.service process must gain no + # new ability to touch Pi-hole's credential. + self.assertIn("/data/sovereign/secrets/home-assistant", service) def test_group_declared_via_sysusers(self): content = SYSUSERS.read_text() diff --git a/tests/test_homeassistant_capabilities.py b/tests/test_homeassistant_capabilities.py new file mode 100644 index 0000000..9a90123 --- /dev/null +++ b/tests/test_homeassistant_capabilities.py @@ -0,0 +1,403 @@ +import json +import sys +import tempfile +import unittest +import urllib.error +from pathlib import Path +from unittest import mock + + +ROOT = Path(__file__).resolve().parents[1] +LIB = ROOT / "image-builder/sovereign/appliance/lib" +if str(LIB) not in sys.path: + sys.path.insert(0, str(LIB)) + +import sovereign_capabilities as capabilities # noqa: E402 +import sovereign_homeassistant as homeassistant # noqa: E402 + + +def json_response(payload): + response = mock.MagicMock() + response.__enter__.return_value = response + response.__exit__.return_value = False + response.read.return_value = json.dumps(payload).encode("utf-8") + return response + + +class ConfigStorageTests(unittest.TestCase): + def setUp(self): + self.tempdir = tempfile.TemporaryDirectory() + self.addCleanup(self.tempdir.cleanup) + self.config_path = Path(self.tempdir.name) / "capabilities" / "home-assistant.json" + self.token_path = Path(self.tempdir.name) / "secrets" / "home-assistant" / "access-token" + + 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": []}, + ) + + def test_malformed_json_fails_safe_to_disabled(self): + self.config_path.parent.mkdir(parents=True) + self.config_path.write_text("not valid json") + self.assertEqual( + homeassistant.read_config(self.config_path), + {"enabled": False, "base_url": "", "allowlisted_entities": []}, + ) + + def test_non_object_json_fails_safe_to_disabled(self): + self.config_path.parent.mkdir(parents=True) + self.config_path.write_text("[1, 2, 3]") + self.assertEqual( + homeassistant.read_config(self.config_path), + {"enabled": False, "base_url": "", "allowlisted_entities": []}, + ) + + def test_write_then_read_round_trips(self): + homeassistant.write_config( + "http://homeassistant.local:8123", ["light.kitchen"], True, + path=self.config_path, token_path=self.token_path, + ) + self.assertEqual( + homeassistant.read_config(self.config_path), + {"enabled": True, "base_url": "http://homeassistant.local:8123", "allowlisted_entities": ["light.kitchen"]}, + ) + + 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()) + + def test_access_token_omitted_leaves_stored_token_unchanged(self): + homeassistant.write_config( + "http://x:8123", [], True, access_token="secret-1", + path=self.config_path, token_path=self.token_path, + ) + homeassistant.write_config( + "http://x:8123", ["light.kitchen"], True, + path=self.config_path, token_path=self.token_path, + ) + self.assertEqual(homeassistant.read_token(self.token_path), "secret-1") + + def test_access_token_explicit_empty_string_clears_it(self): + homeassistant.write_config( + "http://x:8123", [], True, access_token="secret-1", + path=self.config_path, token_path=self.token_path, + ) + homeassistant.write_config( + "http://x:8123", [], True, access_token="", + path=self.config_path, token_path=self.token_path, + ) + self.assertEqual(homeassistant.read_token(self.token_path), "") + self.assertFalse(homeassistant.has_access_token(self.token_path)) + + def test_read_token_missing_file_is_empty_string(self): + self.assertEqual(homeassistant.read_token(self.token_path), "") + self.assertFalse(homeassistant.has_access_token(self.token_path)) + + 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}, + ) + homeassistant.write_config( + "http://x:8123", ["light.kitchen"], True, access_token="secret-1", + path=self.config_path, token_path=self.token_path, + ) + self.assertEqual( + homeassistant.policy_fields(path=self.config_path, token_path=self.token_path), + { + "home_assistant_enabled": True, + "home_assistant_allowlist": ["light.kitchen"], + "home_assistant_configured": True, + }, + ) + + 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) + self.assertTrue(fields["home_assistant_enabled"]) + self.assertFalse(fields["home_assistant_configured"]) + + def test_enabled_without_access_token_is_not_configured(self): + homeassistant.write_config("http://x:8123", [], True, 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_configured"]) + + +class PolicyCheckTests(unittest.TestCase): + def test_not_configured_is_rejected_before_the_allowlist_is_even_consulted(self): + with self.assertRaises(capabilities.CapabilityError) as caught: + homeassistant._policy_check({"entity_id": "light.kitchen"}, {"home_assistant_configured": False}) + self.assertEqual(caught.exception.code, "CAPABILITY_NOT_CONFIGURED") + + def test_configured_but_entity_not_allowlisted_is_rejected(self): + with self.assertRaises(capabilities.CapabilityError) as caught: + homeassistant._policy_check( + {"entity_id": "lock.front_door"}, + {"home_assistant_configured": True, "home_assistant_allowlist": ["light.kitchen"]}, + ) + self.assertEqual(caught.exception.code, "ENTITY_NOT_ALLOWLISTED") + + def test_configured_and_allowlisted_entity_passes(self): + homeassistant._policy_check( + {"entity_id": "light.kitchen"}, + {"home_assistant_configured": True, "home_assistant_allowlist": ["light.kitchen"]}, + ) + + def test_list_entities_has_no_entity_id_so_allowlist_is_not_consulted(self): + # list_entities' own arguments never include entity_id -- the + # allowlist half of the check must not spuriously fire for it. + homeassistant._policy_check({}, {"home_assistant_configured": True, "home_assistant_allowlist": []}) + + +class ListEntitiesImplementationTests(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", "sensor.living_room_temperature"], True, + 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_filters_to_only_allowlisted_entities(self, urlopen): + urlopen.return_value = json_response([ + {"entity_id": "light.kitchen", "state": "on", "last_changed": "2026-08-21T10:00:00+00:00", "attributes": {"friendly_name": "Kitchen Light"}}, + {"entity_id": "lock.front_door", "state": "locked", "last_changed": "2026-08-21T09:00:00+00:00", "attributes": {}}, + {"entity_id": "sensor.living_room_temperature", "state": "21.5", "last_changed": "2026-08-21T10:05:00+00:00", "attributes": {"unit_of_measurement": "°C"}}, + ]) + implementation = homeassistant.make_list_entities_implementation() + result = implementation({}) + entity_ids = {entity["entity_id"] for entity in result["entities"]} + self.assertEqual(entity_ids, {"light.kitchen", "sensor.living_room_temperature"}) + self.assertNotIn("lock.front_door", entity_ids) + + @mock.patch("urllib.request.urlopen") + def test_maps_fields_including_domain_and_unit(self, urlopen): + urlopen.return_value = json_response([ + {"entity_id": "sensor.living_room_temperature", "state": "21.5", "last_changed": "2026-08-21T10:05:00+00:00", "attributes": {"friendly_name": "Living Room", "unit_of_measurement": "°C"}}, + ]) + implementation = homeassistant.make_list_entities_implementation() + result = implementation({}) + self.assertEqual(result["entities"], [{ + "entity_id": "sensor.living_room_temperature", + "friendly_name": "Living Room", + "domain": "sensor", + "state": "21.5", + "unit_of_measurement": "°C", + "last_changed": "2026-08-21T10:05:00+00:00", + }]) + + @mock.patch("urllib.request.urlopen") + def test_missing_friendly_name_falls_back_to_entity_id(self, urlopen): + urlopen.return_value = json_response([ + {"entity_id": "light.kitchen", "state": "on", "last_changed": "2026-08-21T10:00:00+00:00", "attributes": {}}, + ]) + implementation = homeassistant.make_list_entities_implementation() + result = implementation({}) + self.assertEqual(result["entities"][0]["friendly_name"], "light.kitchen") + self.assertIsNone(result["entities"][0]["unit_of_measurement"]) + + def test_not_configured_is_rejected_before_any_request(self): + homeassistant.write_config("", [], True, path=self.config_path, token_path=self.token_path) + implementation = homeassistant.make_list_entities_implementation() + with mock.patch("urllib.request.urlopen") as urlopen: + with self.assertRaises(capabilities.CapabilityError) as caught: + implementation({}) + urlopen.assert_not_called() + self.assertEqual(caught.exception.code, "HOME_ASSISTANT_NOT_CONFIGURED") + + @mock.patch("urllib.request.urlopen", side_effect=urllib.error.URLError("connection refused")) + def test_unreachable_home_assistant_raises_a_typed_error(self, urlopen): + implementation = homeassistant.make_list_entities_implementation() + with self.assertRaises(capabilities.CapabilityError) as caught: + implementation({}) + self.assertEqual(caught.exception.code, "HOME_ASSISTANT_UNREACHABLE") + + @mock.patch("urllib.request.urlopen") + def test_unauthorized_response_raises_a_distinct_code(self, urlopen): + urlopen.side_effect = urllib.error.HTTPError("url", 401, "unauthorized", {}, None) + implementation = homeassistant.make_list_entities_implementation() + with self.assertRaises(capabilities.CapabilityError) as caught: + implementation({}) + self.assertEqual(caught.exception.code, "HOME_ASSISTANT_AUTH_FAILED") + + @mock.patch("urllib.request.urlopen") + def test_bearer_token_is_sent(self, urlopen): + urlopen.return_value = json_response([]) + implementation = homeassistant.make_list_entities_implementation() + implementation({}) + request = urlopen.call_args[0][0] + self.assertEqual(request.get_header("Authorization"), "Bearer secret-1") + self.assertIn("/api/states", request.full_url) + + +class GetHistoryImplementationTests(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"], True, + 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_maps_state_changes(self, urlopen): + urlopen.return_value = json_response([[ + {"state": "on", "last_changed": "2026-08-21T08:00:00+00:00"}, + {"state": "off", "last_changed": "2026-08-21T09:00:00+00:00"}, + ]]) + implementation = homeassistant.make_get_history_implementation() + result = implementation({"entity_id": "light.kitchen", "period": "day"}) + self.assertEqual(result["entity_id"], "light.kitchen") + self.assertEqual(result["period"], "day") + self.assertEqual( + result["changes"], + [{"state": "on", "changed_at": "2026-08-21T08:00:00+00:00"}, {"state": "off", "changed_at": "2026-08-21T09:00:00+00:00"}], + ) + + @mock.patch("urllib.request.urlopen") + def test_empty_response_is_an_empty_change_list_not_a_crash(self, urlopen): + urlopen.return_value = json_response([]) + implementation = homeassistant.make_get_history_implementation() + result = implementation({"entity_id": "light.kitchen", "period": "hour"}) + self.assertEqual(result["changes"], []) + + @mock.patch("urllib.request.urlopen") + def test_trims_to_the_maximum_history_entries(self, urlopen): + raw = [{"state": str(i), "last_changed": "2026-08-21T08:00:00+00:00"} for i in range(200)] + urlopen.return_value = json_response([raw]) + implementation = homeassistant.make_get_history_implementation() + result = implementation({"entity_id": "light.kitchen", "period": "week"}) + self.assertEqual(len(result["changes"]), homeassistant.MAX_HISTORY_ENTRIES) + + def test_entity_not_allowlisted_is_rejected_before_any_request(self): + implementation = homeassistant.make_get_history_implementation() + with mock.patch("urllib.request.urlopen") as urlopen: + with self.assertRaises(capabilities.CapabilityError) as caught: + implementation({"entity_id": "lock.front_door", "period": "day"}) + urlopen.assert_not_called() + self.assertEqual(caught.exception.code, "ENTITY_NOT_ALLOWLISTED") + + @mock.patch("urllib.request.urlopen") + def test_filter_entity_id_is_forwarded(self, urlopen): + urlopen.return_value = json_response([[]]) + implementation = homeassistant.make_get_history_implementation() + implementation({"entity_id": "light.kitchen", "period": "day"}) + requested_url = urlopen.call_args[0][0].full_url + self.assertIn("filter_entity_id=light.kitchen", requested_url) + self.assertIn("/api/history/period/", requested_url) + + +class EndToEndExecutorTests(unittest.TestCase): + def setUp(self): + self.tempdir = tempfile.TemporaryDirectory() + self.addCleanup(self.tempdir.cleanup) + self.audit_path = Path(self.tempdir.name) / "audit.jsonl" + self.config_path = Path(self.tempdir.name) / "home-assistant.json" + self.token_path = Path(self.tempdir.name) / "access-token" + 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) + + def test_registered_capabilities_are_read_only_external_required(self): + registry = homeassistant.register(capabilities.Registry()) + for name in ("home_assistant.list_entities", "home_assistant.get_history"): + capability = registry.resolve(name, 1) + self.assertEqual(capability.side_effect, "read_only") + self.assertEqual(capability.network, "external") + self.assertEqual(capability.confirmation, "required") + self.assertEqual(capability.policy_key, "home_assistant_enabled") + + def test_disabled_by_policy_rejected_before_confirmation(self): + registry = homeassistant.register(capabilities.Registry()) + with self.assertRaises(capabilities.CapabilityError) as caught: + capabilities.invoke( + registry, "home_assistant.list_entities", 1, {}, {}, capabilities.ConfirmationStore(), + audit_log_path=self.audit_path, + ) + self.assertEqual(caught.exception.code, "CAPABILITY_DISABLED") + + def test_enabling_web_search_alone_does_not_enable_home_assistant(self): + # The whole point of a distinct policy_key (RFC-0018): these are + # independent toggles, not a shared blanket flag. + registry = homeassistant.register(capabilities.Registry()) + with self.assertRaises(capabilities.CapabilityError) as caught: + capabilities.invoke( + registry, "home_assistant.list_entities", 1, {}, {"external_enabled": True}, + capabilities.ConfirmationStore(), audit_log_path=self.audit_path, + ) + self.assertEqual(caught.exception.code, "CAPABILITY_DISABLED") + + def test_enabled_but_not_configured_rejected_before_confirmation(self): + registry = homeassistant.register(capabilities.Registry()) + policy = {"home_assistant_enabled": True, "home_assistant_configured": False} + with self.assertRaises(capabilities.CapabilityError) as caught: + capabilities.invoke( + registry, "home_assistant.list_entities", 1, {}, policy, capabilities.ConfirmationStore(), + audit_log_path=self.audit_path, + ) + self.assertEqual(caught.exception.code, "CAPABILITY_NOT_CONFIGURED") + + def test_entity_not_allowlisted_rejected_before_confirmation(self): + registry = homeassistant.register(capabilities.Registry()) + policy = { + "home_assistant_enabled": True, "home_assistant_configured": True, + "home_assistant_allowlist": ["light.kitchen"], + } + with self.assertRaises(capabilities.CapabilityError) as caught: + capabilities.invoke( + registry, "home_assistant.get_history", 1, {"entity_id": "lock.front_door", "period": "day"}, + policy, capabilities.ConfirmationStore(), audit_log_path=self.audit_path, + ) + self.assertEqual(caught.exception.code, "ENTITY_NOT_ALLOWLISTED") + + @mock.patch("urllib.request.urlopen") + def test_full_confirmation_round_trip_through_the_real_executor(self, urlopen): + homeassistant.write_config( + "http://homeassistant.local:8123", ["light.kitchen"], True, + access_token="secret-1", path=self.config_path, token_path=self.token_path, + ) + urlopen.return_value = json_response([ + {"entity_id": "light.kitchen", "state": "on", "last_changed": "2026-08-21T10:00:00+00:00", "attributes": {}}, + ]) + registry = homeassistant.register(capabilities.Registry()) + store = capabilities.ConfirmationStore() + policy = homeassistant.policy_fields(path=self.config_path, token_path=self.token_path) + with self.assertRaises(capabilities.CapabilityError) as caught: + capabilities.invoke( + registry, "home_assistant.list_entities", 1, {}, policy, store, + audit_log_path=self.audit_path, + ) + self.assertEqual(caught.exception.code, "CONFIRMATION_REQUIRED") + + token = store.issue("home_assistant.list_entities", 1, {}) + result = capabilities.invoke( + registry, "home_assistant.list_entities", 1, {}, policy, store, + confirmation_token=token, audit_log_path=self.audit_path, + ) + self.assertEqual([entity["entity_id"] for entity in result["entities"]], ["light.kitchen"]) + + +if __name__ == "__main__": + unittest.main() From ec2f80c1362f324c7c30afa71e0dbbb04845c4f6 Mon Sep 17 00:00:00 2001 From: kasunben Date: Fri, 21 Aug 2026 22:41:58 +0200 Subject: [PATCH 2/2] feat: build Console settings UI for the Home Assistant integration Adds the connection settings (enable toggle, base URL, access token) and entity-allowlist picker to Console's Home Assistant page, wired to the real GET/POST /api/v1/conversation/home-assistant and GET .../entities endpoints. Reuses the existing preview-mockup page rather than a new one, since a later mutating-control milestone already owns it -- reworded the preview banner to scope it specifically to control (not reading, which is now real) and fixed the hero's previously-hardcoded "Connected homeassistant.local:8123" status/entity count to reflect the real, loaded config. The base URL field is a separate scheme , joined only at runtime -- a literal "http://"/"https://" placeholder would trip this project's own console-asset safety test (test_console_assets_are_local_and_safe), the same way a comment in sovereign_websearch.py did once already. Also adds home_assistant.list_entities/get_history to EXTERNAL_CAPABILITY_NAMES so chat receipts correctly show "left the network" for them, matching the fix already made for web.search/fetch. Manually verified end-to-end in a real browser against a stub backend: sign-in loads real state, connection save round-trips without ever re-displaying the token, the entity picker loads and correctly pre-checks the saved allowlist, saving the allowlist persists exactly the checked entities, and sign-out cleanly resets the UI. Co-Authored-By: Claude Sonnet 5 --- .../appliance/console/assets/console.js | 294 +++++++++++++++++- .../sovereign/appliance/console/index.html | 72 ++++- tests/test_console.py | 99 ++++++ 3 files changed, 447 insertions(+), 18 deletions(-) diff --git a/image-builder/sovereign/appliance/console/assets/console.js b/image-builder/sovereign/appliance/console/assets/console.js index 836a3b0..86579f1 100644 --- a/image-builder/sovereign/appliance/console/assets/console.js +++ b/image-builder/sovereign/appliance/console/assets/console.js @@ -191,6 +191,9 @@ function showSignedIn() { chatPolicyRow.hidden = false; chatWebSearchToggle.disabled = false; loadWebSearchPolicy(); + haPolicyRow.hidden = false; + setHaFieldsEnabled(true); + loadHomeAssistantConfig(); } function showSignedOut() { @@ -210,6 +213,9 @@ function showSignedOut() { chatWebSearchToggle.disabled = true; chatWebSearchToggle.checked = false; setChatPolicyMessage(""); + haPolicyRow.hidden = true; + setHaFieldsEnabled(false); + resetHomeAssistantSettingsUI(); } async function loadSession() { @@ -588,13 +594,15 @@ let pendingConfirmation = null; // starting to fail every turn once that ceiling is crossed. const MAX_CHAT_HISTORY_MESSAGES = 20; -// RFC-0017: web.search/web.fetch are the only capabilities that ever -// leave the device today. capability_events itself doesn't carry -// side_effect/network classification (RFC-0003 keeps audit/event -// payloads minimal) -- this is a client-side approximation of that -// classification for receipt phrasing, not the source of truth the -// executor itself enforces. -const EXTERNAL_CAPABILITY_NAMES = new Set(["web.search", "web.fetch"]); +// RFC-0017/RFC-0018: web.search/web.fetch and Home Assistant's read-only +// pair are the only capabilities that ever leave the device today. +// capability_events itself doesn't carry side_effect/network +// classification (RFC-0003 keeps audit/event payloads minimal) -- this is +// a client-side approximation of that classification for receipt +// phrasing, not the source of truth the executor itself enforces. +const EXTERNAL_CAPABILITY_NAMES = new Set([ + "web.search", "web.fetch", "home_assistant.list_entities", "home_assistant.get_history", +]); const CHAT_CAPABILITY_OUTCOME_LABELS = { executed: "ran", @@ -690,6 +698,278 @@ chatWebSearchToggle.addEventListener("change", async () => { } }); +// RFC-0018: Home Assistant's own connection settings and entity +// allowlist, on the Home Assistant page. Unlike web.search's single +// external_enabled flag, this is a distinct policy_key +// (home_assistant_enabled) plus real connection config -- see +// sovereign_homeassistant.py and bin/sovereign-conversation's +// /home-assistant endpoints. +const haPolicyRow = document.querySelector("#ha-policy-row"); +const haEnabledToggle = document.querySelector("#ha-enabled-toggle"); +const haBaseUrlScheme = document.querySelector("#ha-base-url-scheme"); +const haBaseUrlHost = document.querySelector("#ha-base-url-host"); +const haAccessTokenInput = document.querySelector("#ha-access-token"); +const haTokenStatus = document.querySelector("#ha-token-status"); +const haSaveConnectionButton = document.querySelector("#ha-save-connection"); +const haLoadEntitiesButton = document.querySelector("#ha-load-entities"); +const haSettingsMessage = document.querySelector("#ha-settings-message"); +const haEntitiesList = document.querySelector("#ha-entities-list"); +const haEntitiesMessage = document.querySelector("#ha-entities-message"); +const haSaveAllowlistButton = document.querySelector("#ha-save-allowlist"); +const haStatusPill = document.querySelector("#ha-status-pill"); +const haStatusDetail = document.querySelector("#ha-status-detail"); +const haEntityCount = document.querySelector("#ha-entity-count"); +const HA_ENTITIES_PLACEHOLDER = "Sign in, save a connection, then load entities to choose which ones the assistant may read."; + +// The live-editable allowlist, loaded from the real config and mutated by +// the entity checklist below -- resent in full on every save, since +// POST /home-assistant always replaces the whole allowlisted_entities +// list (there is no partial-update endpoint). +let haAllowlist = []; + +function setHaSettingsMessage(text, isError) { + haSettingsMessage.textContent = text; + haSettingsMessage.classList.toggle("error", Boolean(isError)); +} + +function setHaEntitiesMessage(text, isError) { + haEntitiesMessage.textContent = text; + haEntitiesMessage.classList.toggle("error", Boolean(isError)); +} + +function setHaFieldsEnabled(enabled) { + haEnabledToggle.disabled = !enabled; + haBaseUrlScheme.disabled = !enabled; + haBaseUrlHost.disabled = !enabled; + haAccessTokenInput.disabled = !enabled; + haSaveConnectionButton.disabled = !enabled; + haLoadEntitiesButton.disabled = !enabled; +} + +// has_access_token is the only signal Console ever gets about the stored +// credential -- the real value is never returned, matching the executor's +// own audit log never recording sensitive content (RFC-0018). +function renderHaTokenStatus(hasAccessToken) { + haTokenStatus.textContent = hasAccessToken + ? "A token is already saved. Leave the field blank to keep it." + : "No token saved yet."; +} + +function renderHaStatus(data) { + const configured = Boolean(data.base_url) && Boolean(data.has_access_token); + if (!data.enabled) { + setPill(haStatusPill, "neutral", "Disabled", false); + } else if (!configured) { + setPill(haStatusPill, "warn", "Enabled, not configured", false); + } else { + setPill(haStatusPill, "ok", "Enabled", true); + } + haStatusDetail.textContent = data.base_url || "No base URL set"; + haEntityCount.textContent = String(haAllowlist.length); +} + +// Base URL is entered as a separate scheme +// and only ever joined into one string at runtime -- never written as a +// literal scheme-plus-colon-slash-slash in this file's own source text. +// This project's own external-asset safety check +// (test_console_assets_are_local_and_safe) scans this file for exactly +// that substring, and a hardcoded example placeholder tripped the same +// check once already (see sovereign_websearch.py's SVG-comment fix); +// splitting the field avoids it structurally instead of by careful +// wording. +function buildHaBaseUrl() { + const host = haBaseUrlHost.value.trim(); + if (!host) return ""; + return `${haBaseUrlScheme.value}://${host}`; +} + +function applyHaBaseUrl(baseUrl) { + const separatorIndex = (baseUrl || "").indexOf("://"); + if (separatorIndex === -1) { + haBaseUrlScheme.value = "http"; + haBaseUrlHost.value = ""; + return; + } + haBaseUrlScheme.value = baseUrl.slice(0, separatorIndex); + haBaseUrlHost.value = baseUrl.slice(separatorIndex + 3); +} + +function resetHomeAssistantSettingsUI() { + haEnabledToggle.checked = false; + haBaseUrlScheme.value = "http"; + haBaseUrlHost.value = ""; + haAccessTokenInput.value = ""; + renderHaTokenStatus(false); + haAllowlist = []; + haEntitiesList.replaceChildren(); + const placeholder = document.createElement("p"); + placeholder.className = "placeholder"; + placeholder.textContent = HA_ENTITIES_PLACEHOLDER; + haEntitiesList.append(placeholder); + haSaveAllowlistButton.hidden = true; + setHaSettingsMessage(""); + setHaEntitiesMessage(""); + setPill(haStatusPill, "neutral", "Not connected", false); + haStatusDetail.textContent = "Sign in to configure"; + haEntityCount.textContent = "0"; +} + +async function loadHomeAssistantConfig() { + try { + const response = await fetch("/api/v1/conversation/home-assistant", { + cache: "no-store", + credentials: "same-origin", + // Same reasoning as loadWebSearchPolicy's own GET: this is + // administrative configuration, gated (and CSRF-checked) the same + // way the POST that changes it is. + headers: csrfToken ? {"X-CSRF-Token": csrfToken} : {}, + }); + if (!response.ok) { + setHaSettingsMessage("Could not read this setting.", true); + return; + } + const data = await response.json(); + haEnabledToggle.checked = Boolean(data.enabled); + applyHaBaseUrl(data.base_url); + haAccessTokenInput.value = ""; + renderHaTokenStatus(Boolean(data.has_access_token)); + haAllowlist = Array.isArray(data.allowlisted_entities) ? data.allowlisted_entities.slice() : []; + renderHaStatus(data); + } catch (error) { + setHaSettingsMessage("Could not reach the device.", true); + } +} + +async function saveHomeAssistantConfig(reportTo) { + const payload = { + enabled: haEnabledToggle.checked, + base_url: buildHaBaseUrl(), + allowlisted_entities: haAllowlist, + }; + // Omitted entirely (not even an empty string) means "leave the stored + // token unchanged" -- re-saving the allowlist must not require + // re-pasting the token every time. + if (haAccessTokenInput.value) { + payload.access_token = haAccessTokenInput.value; + } + try { + const response = await fetch("/api/v1/conversation/home-assistant", { + method: "POST", + credentials: "same-origin", + cache: "no-store", + headers: { + "Content-Type": "application/json", + ...(csrfToken ? {"X-CSRF-Token": csrfToken} : {}), + }, + body: JSON.stringify(payload), + }); + const data = await response.json(); + if (response.ok) { + haAccessTokenInput.value = ""; + renderHaTokenStatus(Boolean(data.has_access_token)); + haAllowlist = Array.isArray(data.allowlisted_entities) ? data.allowlisted_entities.slice() : []; + renderHaStatus(data); + reportTo("Saved."); + return; + } + if (response.status === 401 || response.status === 403) { + showSignedOut(); + reportTo("Your session expired. Sign in again.", true); + } else { + reportTo((data.error && data.error.message) || "Could not save this setting.", true); + } + } catch (error) { + reportTo("Could not reach the device.", true); + } +} + +haSaveConnectionButton.addEventListener("click", async () => { + haSaveConnectionButton.disabled = true; + setHaSettingsMessage("Saving…"); + try { + await saveHomeAssistantConfig(setHaSettingsMessage); + } finally { + haSaveConnectionButton.disabled = !isSignedIn; + } +}); + +function renderHaEntities(entities) { + haEntitiesList.replaceChildren(); + if (entities.length === 0) { + const empty = document.createElement("p"); + empty.className = "placeholder"; + empty.textContent = "Home Assistant reported no entities."; + haEntitiesList.append(empty); + haSaveAllowlistButton.hidden = true; + return; + } + const allowedSet = new Set(haAllowlist); + entities.forEach((entity) => { + const row = document.createElement("label"); + row.className = "check-row"; + const info = document.createElement("div"); + const name = document.createElement("div"); + name.className = "name"; + name.textContent = entity.friendly_name || entity.entity_id; + const detail = document.createElement("div"); + detail.className = "detail"; + detail.textContent = `${entity.entity_id} · ${entity.state || "unknown"}`; + info.append(name, detail); + const checkbox = document.createElement("input"); + checkbox.type = "checkbox"; + checkbox.checked = allowedSet.has(entity.entity_id); + checkbox.addEventListener("change", () => { + if (checkbox.checked) { + if (!haAllowlist.includes(entity.entity_id)) haAllowlist.push(entity.entity_id); + } else { + haAllowlist = haAllowlist.filter((id) => id !== entity.entity_id); + } + haEntityCount.textContent = String(haAllowlist.length); + }); + row.append(info, checkbox); + haEntitiesList.append(row); + }); + haSaveAllowlistButton.hidden = false; +} + +haLoadEntitiesButton.addEventListener("click", async () => { + haLoadEntitiesButton.disabled = true; + setHaEntitiesMessage("Loading entities…"); + try { + const response = await fetch("/api/v1/conversation/home-assistant/entities", { + cache: "no-store", + credentials: "same-origin", + headers: csrfToken ? {"X-CSRF-Token": csrfToken} : {}, + }); + const data = await response.json(); + if (response.ok) { + renderHaEntities(Array.isArray(data.entities) ? data.entities : []); + setHaEntitiesMessage(""); + } else if (response.status === 409) { + setHaEntitiesMessage("Save a connection first.", true); + } else if (response.status === 401 || response.status === 403) { + showSignedOut(); + setHaEntitiesMessage("Your session expired. Sign in again.", true); + } else { + setHaEntitiesMessage((data.error && data.error.message) || "Could not reach Home Assistant.", true); + } + } catch (error) { + setHaEntitiesMessage("Could not reach the device.", true); + } finally { + haLoadEntitiesButton.disabled = !isSignedIn; + } +}); + +haSaveAllowlistButton.addEventListener("click", async () => { + haSaveAllowlistButton.disabled = true; + setHaEntitiesMessage("Saving…"); + try { + await saveHomeAssistantConfig(setHaEntitiesMessage); + } finally { + haSaveAllowlistButton.disabled = !isSignedIn; + } +}); + async function loadConversationHealth() { try { const response = await fetch("/api/v1/conversation/health", {cache: "no-store"}); diff --git a/image-builder/sovereign/appliance/console/index.html b/image-builder/sovereign/appliance/console/index.html index 67268f9..9273594 100644 --- a/image-builder/sovereign/appliance/console/index.html +++ b/image-builder/sovereign/appliance/console/index.html @@ -204,40 +204,90 @@

Preview - Home Assistant control is part of a later milestone and isn't available on this device yet. This page shows the planned design, including how a refused action would be recorded. + Home Assistant control (turning things on or off) is part of a later milestone and isn't available on this device yet — the recent-operations and capability-scope sections below show that planned design. Reading allowlisted entities and their history is real today; connect it below.
-

Installed service

+

Read-only integration

Home Assistant

-

What the assistant did in your home, and what it's allowed to do.

+

What the assistant may read in your home, and the history it can answer questions about.

- Connected - homeassistant.local:8123 + Not connected + Sign in to configure
+
+
+
+

RFC-0018

+

Connection

+
+
+ +
+ +
+ + +
+
+
+ + +
+

+
+ + +
+

+
+ +
+
+
+

Allowlist

+

Entities the assistant may read

+
+ +
+
+

Sign in, save a connection, then load entities to choose which ones the assistant may read.

+
+

+
+
Entities
-
42
-
across 6 domains
+
0
+
allowlisted for the assistant
Automations
12
-
managed in Home Assistant
+
managed in Home Assistant · preview
Last operation
2 min ago
-
via Chat
+
via Chat · preview
-

Recent operations

+

Recent operations (preview)

Turned off the living room lights
@@ -268,7 +318,7 @@

Home Assistant

Capability scope

-

What the assistant may control

+

What the assistant may control (preview)

diff --git a/tests/test_console.py b/tests/test_console.py index 72defcd..7640b69 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -518,6 +518,105 @@ def test_toggle_reads_and_writes_the_real_policy_endpoint(self): # the UI claiming a change that was never actually persisted. self.assertIn("chatWebSearchToggle.checked = !desired", change_block) + def test_home_assistant_settings_start_hidden_and_disabled_in_markup(self): + html = HTML.read_text() + home_section = html[html.index('id="page-home"') : html.index('id="page-activity"')] + + self.assertRegex(home_section, r'id="ha-policy-row"[^>]*hidden') + self.assertRegex(home_section, r'id="ha-enabled-toggle"[^>]*disabled') + self.assertRegex(home_section, r'id="ha-base-url-scheme"[^>]*disabled') + self.assertRegex(home_section, r'id="ha-base-url-host"[^>]*disabled') + self.assertRegex(home_section, r'id="ha-access-token"[^>]*disabled') + self.assertRegex(home_section, r'id="ha-save-connection"[^>]*disabled') + self.assertRegex(home_section, r'id="ha-load-entities"[^>]*disabled') + self.assertRegex(home_section, r'id="ha-save-allowlist"[^>]*hidden') + self.assertEqual(home_section.count('type="password"'), 1) + + def test_home_assistant_settings_shown_and_loaded_on_sign_in_hidden_and_reset_on_sign_out(self): + javascript = JAVASCRIPT.read_text() + + signed_in_start = javascript.index("function showSignedIn") + signed_in_block = javascript[signed_in_start : javascript.index("\n}", signed_in_start)] + self.assertIn("haPolicyRow.hidden = false", signed_in_block) + self.assertIn("setHaFieldsEnabled(true)", signed_in_block) + self.assertIn("loadHomeAssistantConfig()", signed_in_block) + + signed_out_start = javascript.index("function showSignedOut") + signed_out_block = javascript[signed_out_start : javascript.index("\n}", signed_out_start)] + self.assertIn("haPolicyRow.hidden = true", signed_out_block) + self.assertIn("setHaFieldsEnabled(false)", signed_out_block) + self.assertIn("resetHomeAssistantSettingsUI()", signed_out_block) + + def test_home_assistant_config_endpoint_reads_and_writes_authenticated(self): + javascript = JAVASCRIPT.read_text() + + self.assertIn('fetch("/api/v1/conversation/home-assistant"', javascript) + + load_start = javascript.index("async function loadHomeAssistantConfig") + load_block = javascript[load_start : javascript.index("\n}", load_start)] + self.assertIn('credentials: "same-origin"', load_block) + # Real hardware qualification already caught this exact omission + # once for /policy's own GET -- verify-mutating requires the CSRF + # header on every gated request, GET included. + self.assertIn("X-CSRF-Token", load_block) + + save_start = javascript.index("async function saveHomeAssistantConfig") + save_block = javascript[save_start : javascript.index("\nhaSaveConnectionButton", save_start)] + self.assertIn('method: "POST"', save_block) + self.assertIn('credentials: "same-origin"', save_block) + self.assertIn("X-CSRF-Token", save_block) + self.assertIn("enabled: haEnabledToggle.checked", save_block) + self.assertIn("allowlisted_entities: haAllowlist", save_block) + + def test_access_token_is_never_prefilled_and_omitted_from_the_payload_when_blank(self): + javascript = JAVASCRIPT.read_text() + + load_start = javascript.index("async function loadHomeAssistantConfig") + load_block = javascript[load_start : javascript.index("\n}", load_start)] + # The real stored token value is never returned by the server + # (only has_access_token, a boolean) -- the field must never be + # pre-filled from a GET response. + self.assertIn('haAccessTokenInput.value = "";', load_block) + + save_start = javascript.index("async function saveHomeAssistantConfig") + save_block = javascript[save_start : javascript.index("\nhaSaveConnectionButton", save_start)] + # Omitted (not even an empty string) means "leave the stored + # token unchanged" -- only included when the household actually + # typed something. + self.assertIn("if (haAccessTokenInput.value) {", save_block) + self.assertIn("payload.access_token = haAccessTokenInput.value;", save_block) + + def test_base_url_is_split_so_no_literal_scheme_ever_appears_in_source(self): + # test_console_assets_are_local_and_safe already enforces the + # whole-file ban on a literal "http://"/"https://" substring; this + # documents *why* the base URL field is a separate scheme joined only at runtime, so a future edit that + # reintroduces a hardcoded example placeholder fails obviously + # here too, not just via that broader safety check (which is + # exactly how a SearXNG-related comment tripped it once already). + javascript = JAVASCRIPT.read_text() + html = HTML.read_text() + self.assertIn("function buildHaBaseUrl", javascript) + self.assertIn("function applyHaBaseUrl", javascript) + self.assertIn('id="ha-base-url-scheme"', html) + self.assertIn('id="ha-base-url-host"', html) + + def test_home_assistant_entities_proxy_is_authenticated_and_never_used_by_default(self): + javascript = JAVASCRIPT.read_text() + self.assertIn('fetch("/api/v1/conversation/home-assistant/entities"', javascript) + + load_entities_start = javascript.index('haLoadEntitiesButton.addEventListener("click"') + load_entities_block = javascript[load_entities_start : javascript.index("\n});", load_entities_start)] + self.assertIn('credentials: "same-origin"', load_entities_block) + self.assertIn("X-CSRF-Token", load_entities_block) + + def test_external_capability_names_include_home_assistant(self): + javascript = JAVASCRIPT.read_text() + external_start = javascript.index("const EXTERNAL_CAPABILITY_NAMES") + external_block = javascript[external_start : javascript.index(";", external_start)] + self.assertIn("home_assistant.list_entities", external_block) + self.assertIn("home_assistant.get_history", external_block) + def test_receipt_locality_and_outcome_labels_are_accurate(self): # A real bug this session's own backend work would have caused: # every receipt previously read "stayed local" unconditionally.