Coverage for custom_components/ha_repl_server/__init__.py: 95%
75 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-17 19:05 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-17 19:05 +0000
1"""Home Assistant REPL: a live Python REPL inside Home Assistant, served over the websocket API.
3Set up from Settings > Devices & services > Add integration, or with `ha_repl_server:` in
4configuration.yaml (imported as a config entry). Executes arbitrary code as admin; never
5enable it on an instance where admin accounts are not fully trusted.
6"""
8from __future__ import annotations
10import logging
11from datetime import datetime
12from importlib import import_module
13from typing import Any
15from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
16from homeassistant.const import Platform
17from homeassistant.core import HomeAssistant, callback
18from homeassistant.helpers import config_validation as cv
19from homeassistant.helpers.event import async_track_point_in_utc_time
20from homeassistant.helpers.typing import ConfigType
21from homeassistant.requirements import RequirementsNotFound, async_process_requirements
22from homeassistant.util import dt as dt_util
24from . import websocket_api
25from .const import (
26 CAPABILITIES,
27 DEFAULT_COMPLETE_BUDGET_MS,
28 DEFAULT_COMPLETE_LIMIT,
29 DOMAIN,
30 SQL_REQUIREMENTS,
31)
32from .objtree import ObjTree
33from .session import SessionManager
35_LOGGER = logging.getLogger(__name__)
37CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN)
39# The Stop button, see button.py.
40PLATFORMS = [Platform.BUTTON]
43async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
44 # Commands stay registered for the life of the process (HA has no unregister);
45 # they report an error while no config entry is loaded.
46 websocket_api.async_register(hass)
47 if DOMAIN in config: 47 ↛ 48line 47 didn't jump to line 48 because the condition on line 47 was never true
48 hass.async_create_task(
49 hass.config_entries.flow.async_init(
50 DOMAIN, context={"source": SOURCE_IMPORT}, data={}
51 )
52 )
53 return True
56def _switch_off(hass: HomeAssistant, entry: ConfigEntry, names: list[str]) -> None:
57 """Record in the entry's options that the time limit on each of these
58 has run out: switched off, as if from Configure, with no limit left."""
59 options = dict(entry.options)
60 for name in names:
61 options[f"expose_{name}"] = False
62 options.pop(f"expose_{name}_until", None)
63 _LOGGER.warning("Home Assistant REPL: time limit on `%s` reached", name)
64 hass.config_entries.async_update_entry(entry, options=options)
67def _apply_time_limits(hass: HomeAssistant, entry: ConfigEntry) -> None:
68 """Switch off what ran out of time while this wasn't running, and
69 arrange for the rest to be when their time comes."""
70 now = dt_util.utcnow()
71 limits = {
72 name: until
73 for name in CAPABILITIES
74 if entry.options.get(f"expose_{name}", True)
75 and (
76 until := dt_util.parse_datetime(
77 entry.options.get(f"expose_{name}_until") or ""
78 )
79 )
80 }
81 if expired := [name for name, until in limits.items() if until <= now]:
82 _switch_off(hass, entry, expired)
84 def _expire(name: str) -> Any:
85 @callback
86 def expire(_now: datetime) -> None:
87 _switch_off(hass, entry, [name])
88 # a reload is how any change of options takes effect
89 hass.config_entries.async_schedule_reload(entry.entry_id)
91 return expire
93 for name, until in limits.items():
94 if name not in expired:
95 entry.async_on_unload(
96 async_track_point_in_utc_time(hass, _expire(name), until)
97 )
100async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
101 _apply_time_limits(hass, entry)
102 # In entry.options, not entry.data: editable after setup via Configure
103 # (see config_flow.py's HaReplServerOptionsFlow), not fixed at creation.
104 # Missing (not just False) means an entry from before these existed -
105 # both default on, matching that version's always-on behaviour.
106 bindings: dict[str, Any] = {"obj": ObjTree(hass)}
107 if entry.options.get("expose_hass", True):
108 bindings["hass"] = hass
109 # sql isn't a session binding: the client's own `sql` object fetches
110 # Arrow data through ha_repl_server/sql, which checks this feature.
111 features: set[str] = set()
112 unavailable: dict[str, str] = {}
113 if entry.options.get("expose_sql", True):
114 if (reason := await _load_sql(hass)) is None:
115 features.add("sql")
116 else:
117 unavailable["sql"] = reason
118 _LOGGER.warning(
119 "Home Assistant REPL: sql is unavailable, everything else works: %s",
120 reason,
121 )
123 hass.data[DOMAIN] = SessionManager(
124 bindings,
125 frozenset(features),
126 complete_limit=entry.options.get("complete_limit", DEFAULT_COMPLETE_LIMIT),
127 complete_budget=entry.options.get(
128 "complete_budget_ms", DEFAULT_COMPLETE_BUDGET_MS
129 )
130 / 1000,
131 unavailable=unavailable,
132 )
133 await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
134 _LOGGER.warning(
135 "Home Assistant REPL is enabled: admin users can execute arbitrary Python in this instance"
136 )
137 return True
140async def _load_sql(hass: HomeAssistant) -> str | None:
141 """Install and import what `sql` needs. None if that worked, otherwise
142 why not - for `sql` alone to be switched off."""
143 try:
144 await async_process_requirements(
145 hass, DOMAIN, SQL_REQUIREMENTS, is_built_in=False
146 )
147 # In the executor: an import reads files, which the loop mustn't.
148 await hass.async_add_executor_job(import_module, f"{__package__}.sql")
149 except (RequirementsNotFound, ImportError) as err:
150 return f"{type(err).__name__}: {err}"
151 return None
154async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
155 if not await hass.config_entries.async_unload_platforms(entry, PLATFORMS): 155 ↛ 156line 155 didn't jump to line 156 because the condition on line 155 was never true
156 return False
157 if manager := hass.data.pop(DOMAIN, None): 157 ↛ 159line 157 didn't jump to line 159 because the condition on line 157 was always true
158 manager.cancel(None, "Stopped: Home Assistant REPL unloaded")
159 return True