Coverage for src/homeassistant_repl/config.py: 96%
192 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"""Persistent configuration: named servers and plugins, read from
2`~/.config/ha-repl/` with a repo's own `.ha-repl/` directory layered over it.
4 ~/.config/ha-repl/config.toml servers, and defaults for the flags
5 ~/.config/ha-repl/plugins/*.py run at the start of every session
6 <repo>/.ha-repl/ the same layout, merged over the above
8A repo directory arrives with a clone, and can run code (a plugin, a
9`token_command`) and choose where a session connects - so it's ignored until
10approved with `ha-repl trust`, and again whenever anything in it changes.
11See docs/configuration.md and docs/plugins.md, and docs/developer/design/rfcs/0001 for why it's
12this shape.
13"""
15from __future__ import annotations
17import hashlib
18import json
19import os
20import shlex
21import subprocess # nosec B404 - token_command is the user's own, see Server.resolve_token
22import tomllib
23from dataclasses import dataclass, field
24from pathlib import Path
25from typing import Any
27from .client import HaReplError, _dotenv, resolve_token, resolve_url
29REPO_DIR = ".ha-repl"
31# Where a server's token comes from - exactly one per server.
32_TOKEN_KEYS = ("token", "token_command", "token_env")
33_SETTINGS: dict[str, type | tuple[type, ...]] = {
34 "default": str,
35 "session": str,
36 "ttl": (int, float),
37 "auto_await": bool,
38}
41@dataclass(frozen=True)
42class Server:
43 """One `[servers.NAME]` entry."""
45 name: str
46 url: str
47 token: str | None = None
48 token_command: str | None = None
49 token_env: str | None = None
51 @property
52 def token_source(self) -> str | None:
53 """Which key supplies the token - never the token itself."""
54 return next((key for key in _TOKEN_KEYS if getattr(self, key)), None)
56 def resolve_token(self) -> str:
57 if self.token:
58 return self.token
59 if self.token_env:
60 token = os.environ.get(self.token_env)
61 if not token:
62 raise HaReplError(
63 f"Server {self.name!r}: environment variable "
64 f"{self.token_env} is not set"
65 )
66 return token
67 if self.token_command:
68 return self._run_token_command(self.token_command)
69 raise HaReplError(
70 f"Server {self.name!r} has no token: "
71 f"give it one of {', '.join(_TOKEN_KEYS)}"
72 )
74 def _run_token_command(self, command: str) -> str:
75 # No shell, and stderr left attached to the terminal: a secrets
76 # manager's own prompt or error message is shown as it is, and
77 # nothing the command prints can end up in one of our messages.
78 try:
79 result = subprocess.run( # nosec B603
80 shlex.split(command), stdout=subprocess.PIPE, text=True, check=False
81 )
82 except (OSError, ValueError) as err:
83 raise HaReplError(
84 f"Server {self.name!r}: token_command could not be run: {err}"
85 ) from err
86 token = result.stdout.strip()
87 if result.returncode != 0 or not token:
88 raise HaReplError(
89 f"Server {self.name!r}: token_command gave no token "
90 f"(exit status {result.returncode})"
91 )
92 return token
95@dataclass
96class Config:
97 """The home and repo configuration, merged."""
99 default: str | None = None
100 session: str | None = None
101 ttl: float | None = None
102 auto_await: bool | None = None
103 servers: dict[str, Server] = field(default_factory=dict)
104 # Plugins in the order they run: home first, then the repo's.
105 plugins: list[Path] = field(default_factory=list)
106 # Things worth telling the user, for the caller to report its own way.
107 warnings: list[str] = field(default_factory=list)
110@dataclass(frozen=True)
111class Connection:
112 """Where to connect, and as what."""
114 url: str # the websocket endpoint
115 token: str
116 name: str | None = None # the configured server's name, if chosen by name
119def home_dir() -> Path:
120 """`~/.config/ha-repl` on every platform, macOS included - as git, gh
121 and uv do, and where dotfiles managers expect it."""
122 base = os.environ.get("XDG_CONFIG_HOME")
123 return (Path(base) if base else Path.home() / ".config") / "ha-repl"
126def _state_dir() -> Path:
127 base = os.environ.get("XDG_STATE_HOME")
128 return (Path(base) if base else Path.home() / ".local" / "state") / "ha-repl"
131def find_repo_dir(start: Path | None = None) -> Path | None:
132 """The nearest `.ha-repl/` walking up from the working directory, not
133 looking beyond the root of the git repository it's in."""
134 here = (start or Path.cwd()).resolve()
135 for directory in (here, *here.parents): 135 ↛ 141line 135 didn't jump to line 141 because the loop on line 135 didn't complete
136 candidate = directory / REPO_DIR
137 if candidate.is_dir():
138 return candidate
139 if (directory / ".git").exists():
140 return None
141 return None
144def display_path(path: Path) -> str:
145 """A path as it's shown to the user: `~` for the home directory."""
146 try:
147 return f"~/{path.relative_to(Path.home()).as_posix()}"
148 except ValueError:
149 return str(path)
152def _files(directory: Path) -> list[Path]:
153 return sorted(path for path in directory.rglob("*") if path.is_file())
156def _fingerprint(directory: Path) -> str:
157 """A hash of every file in a directory, by name and content."""
158 digest = hashlib.sha256()
159 for path in _files(directory):
160 digest.update(path.relative_to(directory).as_posix().encode())
161 digest.update(b"\0")
162 digest.update(hashlib.sha256(path.read_bytes()).digest())
163 return digest.hexdigest()
166def _trust_file() -> Path:
167 return _state_dir() / "trusted.json"
170def _trusted() -> dict[str, str]:
171 try:
172 stored = json.loads(_trust_file().read_text(encoding="utf-8"))
173 except OSError, ValueError:
174 return {}
175 return stored if isinstance(stored, dict) else {}
178def trust(directory: Path) -> list[Path]:
179 """Approve a repo directory as it stands now. Returns the files covered."""
180 directory = directory.resolve()
181 stored = _trusted()
182 stored[str(directory)] = _fingerprint(directory)
183 path = _trust_file()
184 path.parent.mkdir(parents=True, exist_ok=True)
185 path.write_text(json.dumps(stored, indent=2, sort_keys=True), encoding="utf-8")
186 return _files(directory)
189def _untrusted_reason(directory: Path) -> str | None:
190 """None if this repo directory has been approved as it stands."""
191 approved = _trusted().get(str(directory.resolve()))
192 if approved is None:
193 return "ignoring"
194 if approved != _fingerprint(directory):
195 return "changed since it was trusted, ignoring"
196 return None
199def _read(path: Path, warnings: list[str]) -> dict[str, Any]:
200 """One config.toml, checked - {} if there isn't one."""
201 if not path.is_file():
202 return {}
203 try:
204 with path.open("rb") as fp:
205 data = tomllib.load(fp)
206 except (OSError, tomllib.TOMLDecodeError) as err:
207 raise HaReplError(f"{display_path(path)}: {err}") from err
209 for key, kind in _SETTINGS.items():
210 # bool is an int as far as isinstance() goes, but not as a ttl
211 if key in data and (
212 not isinstance(data[key], kind)
213 or (kind is not bool and isinstance(data[key], bool))
214 ):
215 raise HaReplError(f"{display_path(path)}: `{key}` has the wrong type")
216 servers = data.get("servers", {})
217 if not isinstance(servers, dict):
218 raise HaReplError(f"{display_path(path)}: `servers` must be a table")
219 holds_token = False
220 for name, entry in servers.items():
221 where = f"{display_path(path)}: server {name!r}"
222 if not isinstance(entry, dict): 222 ↛ 223line 222 didn't jump to line 223 because the condition on line 222 was never true
223 raise HaReplError(f"{where} must be a table")
224 for key in ("url", *_TOKEN_KEYS):
225 if key in entry and not (isinstance(entry[key], str) and entry[key]):
226 raise HaReplError(f"{where}: `{key}` must be a string")
227 if "://" in name: 227 ↛ 228line 227 didn't jump to line 228 because the condition on line 227 was never true
228 raise HaReplError(f"{where}: a name can't contain `://`")
229 if len([key for key in _TOKEN_KEYS if key in entry]) > 1:
230 raise HaReplError(f"{where}: give only one of {', '.join(_TOKEN_KEYS)}")
231 holds_token = holds_token or "token" in entry
232 if holds_token and os.name != "nt" and path.stat().st_mode & 0o077:
233 warnings.append(
234 f"{display_path(path)} holds a token and is readable by other "
235 f"users - `chmod 600` it"
236 )
237 return data
240def _merge(base: dict[str, Any], over: dict[str, Any]) -> dict[str, Any]:
241 """Top-level keys are replaced; `servers` is merged by name, then key
242 by key - except that a token given one way replaces one given another."""
243 merged = {**base, **over}
244 servers = {name: dict(entry) for name, entry in base.get("servers", {}).items()}
245 for name, entry in over.get("servers", {}).items():
246 current = servers.get(name, {})
247 if any(key in entry for key in _TOKEN_KEYS):
248 current = {k: v for k, v in current.items() if k not in _TOKEN_KEYS}
249 servers[name] = {**current, **entry}
250 merged["servers"] = servers
251 return merged
254def _plugin_files(directory: Path) -> list[Path]:
255 return sorted((directory / "plugins").glob("*.py"), key=lambda path: path.name)
258def load_config(cwd: Path | None = None) -> Config:
259 """Read the home configuration and, if it has been trusted, the repo's."""
260 config = Config()
261 directories = [home_dir()]
262 repo = find_repo_dir(cwd)
263 if repo is not None:
264 reason = _untrusted_reason(repo)
265 if reason is None:
266 directories.append(repo)
267 else:
268 config.warnings.append(
269 f"{reason} {display_path(repo)} - run `ha-repl trust` to allow it"
270 )
272 data: dict[str, Any] = {}
273 for directory in directories:
274 data = _merge(data, _read(directory / "config.toml", config.warnings))
275 config.plugins += _plugin_files(directory)
277 config.default = data.get("default")
278 config.session = data.get("session")
279 config.ttl = data.get("ttl")
280 config.auto_await = data.get("auto_await")
281 for name, entry in data["servers"].items():
282 if "url" not in entry:
283 raise HaReplError(f"Server {name!r} has no `url`")
284 config.servers[name] = Server(
285 name, entry["url"], *(entry.get(key) for key in _TOKEN_KEYS)
286 )
287 return config
290def resolve_connection(
291 server: str | None, token: str | None, config: Config
292) -> Connection:
293 """Decide where to connect. `server` is a configured name or a URL; left
294 out, it's $HASS_SERVER, then a `.env` file's, then the configured
295 `default`, then http://homeassistant.local:8123.
297 A server chosen by name brings its own token, which only an explicit
298 `token` overrides - $HASS_TOKEN is never paired with a server out of a
299 config file, since a token from one place sent to an address from
300 another is the mistake named servers are there to prevent.
301 """
302 if not server and os.environ.get("SUPERVISOR_TOKEN"):
303 # Inside a Home Assistant add-on: via the supervisor, as ever.
304 return Connection(resolve_url(None), resolve_token(token))
305 target = server or os.environ.get("HASS_SERVER") or _dotenv().get("HASS_SERVER")
306 if not target and config.default:
307 if config.default not in config.servers:
308 raise HaReplError(
309 f"`default = {config.default!r}` in config.toml names no "
310 f"configured server{_known(config)}"
311 )
312 target = config.default
313 if not target or "://" in target:
314 return Connection(resolve_url(target), resolve_token(token))
315 entry = config.servers.get(target)
316 if entry is None:
317 raise HaReplError(f"No server named {target!r}{_known(config)}")
318 return Connection(resolve_url(entry.url), token or entry.resolve_token(), target)
321def _known(config: Config) -> str:
322 if not config.servers: 322 ↛ 323line 322 didn't jump to line 323 because the condition on line 322 was never true
323 return f" - none are configured in {display_path(home_dir() / 'config.toml')}"
324 return f" - configured: {', '.join(sorted(config.servers))}"