diff --git a/modules/ha_addon.py b/modules/ha_addon.py index 2e04056b..9349fc5f 100644 --- a/modules/ha_addon.py +++ b/modules/ha_addon.py @@ -38,13 +38,13 @@ import json import os import shutil import sys -import tempfile from collections.abc import Callable, Mapping from dataclasses import dataclass from pathlib import Path from typing import Any, Literal -from modules.ini_writer import update_ini_values +from modules.ini_writer import update_ini_values, write_text_atomic +from modules.managed_keys import MANAGED_KEYS_ENV, MANAGED_KEYS_FILENAME CONFIG_DIR = Path("/config") DATA_DIR = Path("/data") @@ -53,8 +53,6 @@ REPO_ROOT = Path("/app") CONFIG_FILENAME = "config.ini" EXAMPLE_FILENAME = "config.ini.example" OPTIONS_FILENAME = "options.json" -MANAGED_KEYS_FILENAME = "ha_managed_keys.json" -MANAGED_KEYS_ENV = "MESHCORE_HA_MANAGED_KEYS" # Fixed paths, relative to the base directory each INI_MAP row names. DB_PATH = "databases/meshcore_bot.db" @@ -67,8 +65,6 @@ VIEWER_PORT = 8080 _CONNECTION_TYPES = ("serial", "tcp", "ble") _LOG_LEVELS = ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL") -_TRUE = frozenset({"1", "true", "yes", "on"}) -_FALSE = frozenset({"0", "false", "no", "off"}) def as_str(value: object) -> str: @@ -79,12 +75,11 @@ def as_bool(value: object) -> str: """Render a boolean the way ``config.ini`` spells it.""" if isinstance(value, bool): return "true" if value else "false" - text = as_str(value).lower() - if text in _TRUE: - return "true" - if text in _FALSE: - return "false" - raise ValueError(f"expected a boolean, got {value!r}") + try: + state = configparser.ConfigParser.BOOLEAN_STATES[as_str(value).lower()] + except KeyError: + raise ValueError(f"expected a boolean, got {value!r}") from None + return "true" if state else "false" def as_int(value: object) -> str: @@ -202,11 +197,11 @@ def _assignments( ) -> list[tuple[IniMap, str]]: """Fixed rows first, then options the user set. Later rows win on a shared key.""" rows = [row for row in INI_MAP if row.option is None] - for row in INI_MAP: - if row.option is None or row.option not in options: - continue - if _is_set(options[row.option]): - rows.append(row) + rows += [ + row + for row in INI_MAP + if row.option is not None and _is_set(options.get(row.option)) + ] rendered: list[tuple[IniMap, str]] = [] for row in rows: @@ -281,27 +276,12 @@ def _load_options(path: Path) -> dict[str, Any]: return loaded -def _atomic_write(path: Path, text: str) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.") - try: - with os.fdopen(fd, "w", encoding="utf-8") as handle: - handle.write(text) - os.replace(tmp_name, path) - except BaseException: - try: - os.unlink(tmp_name) - except OSError: - pass - raise - - def _managed_pairs(assignments: list[tuple[IniMap, str]]) -> list[tuple[str, str]]: return sorted({(row.section, row.key) for row, _value in assignments}) def _write_managed_keys(path: Path, assignments: list[tuple[IniMap, str]]) -> None: - _atomic_write(path, json.dumps(_managed_pairs(assignments), indent=2) + "\n") + write_text_atomic(path, json.dumps(_managed_pairs(assignments), indent=2) + "\n") def _local_config_path(config_dir: Path) -> Path: diff --git a/modules/ini_writer.py b/modules/ini_writer.py index a978d91d..cb0163eb 100644 --- a/modules/ini_writer.py +++ b/modules/ini_writer.py @@ -23,6 +23,7 @@ import shutil import tempfile import threading from datetime import datetime +from pathlib import Path # A section header line: ``[Section]`` (optionally indented / trailing space). _SECTION_RE = re.compile(r"^\s*\[(?P[^\]]+)\]\s*$") @@ -67,6 +68,27 @@ def _separator_for(sep: str, new_value: str) -> str: return sep +def write_text_atomic(path: str | Path, text: str) -> None: + """Write ``text`` to ``path`` via a same-directory temp file and replace. + + The temp file lives in the target's directory so ``os.replace`` stays on + one filesystem. It is removed if the write or replace fails. + """ + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + fd, tmp_name = tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.") + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(text) + os.replace(tmp_name, target) + except BaseException: + try: + os.unlink(tmp_name) + except OSError: + pass + raise + + class IniValueError(ValueError): """A section/key/value would corrupt the INI file if written verbatim.""" @@ -344,19 +366,7 @@ def _update_ini_values_locked( # Take the backup *before* replacing the file. backup_path = backup_config(config_path, backup_dir=backup_dir) - # Atomic write: temp file in the same directory, then os.replace. - directory = os.path.dirname(os.path.abspath(config_path)) - fd, tmp_path = tempfile.mkstemp(dir=directory, prefix=".ini_tmp_") - try: - with os.fdopen(fd, "w", encoding="utf-8") as tmp: - tmp.writelines(out) - os.replace(tmp_path, config_path) - except BaseException: - try: - os.remove(tmp_path) - except OSError: - pass - raise + write_text_atomic(config_path, "".join(out)) return { "backup_path": backup_path, diff --git a/modules/managed_keys.py b/modules/managed_keys.py index 2be84fbe..f692dbb8 100644 --- a/modules/managed_keys.py +++ b/modules/managed_keys.py @@ -1,8 +1,8 @@ """Home Assistant managed config.ini keys. The add-on writes a JSON list of ``[section, key]`` pairs and exports the file -path in :data:`modules.ha_addon.MANAGED_KEYS_ENV`. The web viewer reads that -file so it can show those settings as read-only and refuse to save over them. +path in :data:`MANAGED_KEYS_ENV`. The web viewer reads that file so it can show +those settings as read-only and refuse to save over them. A missing variable or a missing file yields an empty set and is not logged. A file that cannot be read, or that is not a JSON list of ``[section, key]`` @@ -19,14 +19,16 @@ import configparser import json import logging import os -from collections.abc import Iterable, Mapping +from collections.abc import Iterable from pathlib import Path -from modules.ha_addon import MANAGED_KEYS_ENV from modules.ini_writer import IniValueError, _normalize_key, _normalize_section logger = logging.getLogger("MeshCoreBot") +MANAGED_KEYS_FILENAME = "ha_managed_keys.json" +MANAGED_KEYS_ENV = "MESHCORE_HA_MANAGED_KEYS" + class ManagedKeyError(IniValueError): """A save would change or delete a key Home Assistant owns. @@ -81,18 +83,15 @@ def load_managed_keys() -> frozenset[tuple[str, str]]: def is_managed( section: str, key: str, - managed: frozenset[tuple[str, str]] | None = None, + managed: frozenset[tuple[str, str]], ) -> bool: """True when ``(section, key)`` is in the managed set.""" - pairs = load_managed_keys() if managed is None else managed - if not pairs: - return False - return normalize_managed_pair(section, key) in pairs + return normalize_managed_pair(section, key) in managed def guard_managed_writes( - updates: Mapping[str, Mapping[str, str]] | None, - deletes: Mapping[str, Iterable[str]] | None, + updates: dict[str, dict[str, str]] | None, + deletes: dict[str, list[str] | set[str]] | None, config: configparser.ConfigParser | None = None, ) -> tuple[dict[str, dict[str, str]], dict[str, list[str] | set[str]] | None]: """Drop unchanged managed keys and reject real changes. @@ -107,13 +106,7 @@ def guard_managed_writes( """ managed = load_managed_keys() if not managed: - concrete_deletes: dict[str, list[str] | set[str]] = { - section: list(keys) for section, keys in (deletes or {}).items() - } - return ( - {section: dict(values) for section, values in (updates or {}).items()}, - concrete_deletes or None, - ) + return updates or {}, deletes or None conflicts: list[tuple[str, str]] = [] filtered: dict[str, dict[str, str]] = {} diff --git a/modules/settings_schema.py b/modules/settings_schema.py index 6ea88820..5832bdd2 100644 --- a/modules/settings_schema.py +++ b/modules/settings_schema.py @@ -511,11 +511,9 @@ def _assemble_entry( description: str, category: str, enabled_default: bool, + managed: frozenset[tuple[str, str]], source: str = "base", - managed: Optional[frozenset[tuple[str, str]]] = None, ) -> dict: - if managed is None: - managed = load_managed_keys() schema = list(getattr(cls, "settings_schema", []) or []) fields: list[dict] = [] for field in schema: @@ -595,7 +593,7 @@ def _read_repeating_blocks( config: configparser.ConfigParser, cls: type, section: str, - managed: Optional[frozenset[tuple[str, str]]] = None, + managed: frozenset[tuple[str, str]], ) -> list[dict]: """Build the repeating structured-block editors a plugin declares. @@ -631,16 +629,15 @@ def _read_repeating_blocks( enabled = str(sub.get(enabled_field, "true")).strip().lower() in _TRUE values = {k: v for k, v in sub.items() if k != enabled_field} block: dict = {"index": idx, "enabled": enabled, "values": values} - if managed: - owned = [ - subkey - for subkey in list(values) + schema_keys - if is_managed(section, f"{bid}{idx}_{subkey}", managed) - ] - if owned: - block["managed_keys"] = sorted(set(owned)) - if is_managed(section, f"{bid}{idx}_{enabled_field}", managed): - block["enabled_managed"] = True + owned = [ + subkey + for subkey in list(values) + schema_keys + if is_managed(section, f"{bid}{idx}_{subkey}", managed) + ] + if owned: + block["managed_keys"] = sorted(set(owned)) + if is_managed(section, f"{bid}{idx}_{enabled_field}", managed): + block["enabled_managed"] = True blocks.append(block) result.append({ "id": bid, @@ -657,8 +654,8 @@ def _read_repeating_blocks( def read_section_items( config: configparser.ConfigParser, section: str, - prefix: str = "", - managed: Optional[frozenset[tuple[str, str]]] = None, + prefix: str, + managed: frozenset[tuple[str, str]], ) -> list[dict]: """Return a section's key/value pairs as ``[{"key", "value"}, ...]`` (raw). @@ -679,7 +676,7 @@ def read_section_items( item: dict[str, Any] = {"key": key[len(prefix):], "value": raw} else: item = {"key": key, "value": raw} - if managed and is_managed(section, key, managed): + if is_managed(section, key, managed): item["managed"] = True items.append(item) return items @@ -688,7 +685,7 @@ def read_section_items( def _read_dynamic_sections( config: configparser.ConfigParser, cls: type, - managed: Optional[frozenset[tuple[str, str]]] = None, + managed: frozenset[tuple[str, str]], ) -> list[dict]: """Build the dynamic key/value section editors a plugin declares. diff --git a/modules/web_viewer/app.py b/modules/web_viewer/app.py index 87b08a57..c25f9d50 100644 --- a/modules/web_viewer/app.py +++ b/modules/web_viewer/app.py @@ -925,10 +925,6 @@ class BotDataViewer(DashboardSnapshotMixin, LiveStreamMixin, SocketClientsMixin, error_message='Something went wrong on our end. The error has been logged.', ), 500) - @self.app.errorhandler(ManagedKeyError) - def managed_key_rejected(exc: ManagedKeyError): - return _managed_key_response(exc) - # Authentication middleware (BUG-001). # Fail closed when a password is configured: only the public allowlist # below is reachable without authenticated_admin. Everything else @@ -1019,15 +1015,13 @@ class BotDataViewer(DashboardSnapshotMixin, LiveStreamMixin, SocketClientsMixin, if not self._auth_enforced(): return # Legacy open mode, or Home Assistant already authenticated path = _normalize_request_path(request.path) - if path.startswith('/static/'): + if path.startswith('/static/') or path == '/api/stream_data': return if not self.web_viewer_password: # Ingress is on with no password: there is no login to succeed, # so direct access fails closed instead of falling back to open # mode. The bot's ingest endpoint uses X-Stream-Token, not the # admin session. - if path == '/api/stream_data': - return return _direct_access_disabled(path) if path in _EXEMPT_PATHS: return diff --git a/modules/web_viewer/templates/plugins.html b/modules/web_viewer/templates/plugins.html index 0ad74552..cc20a5c3 100644 --- a/modules/web_viewer/templates/plugins.html +++ b/modules/web_viewer/templates/plugins.html @@ -253,6 +253,8 @@ {% block extra_js %}