mirror of
https://github.com/agessaman/meshcore-bot.git
synced 2026-11-22 20:27:58 +00:00
refactor(ha_addon): simplify the add-on and managed-key code
- managed_keys owns the env var and file name, so the shared module no longer imports the add-on entrypoint; is_managed takes the loaded set instead of re-reading the file. - One write_text_atomic() in ini_writer, used by update_ini_values and the add-on. - as_bool uses configparser's BOOLEAN_STATES. - Drop the app-level ManagedKeyError handler (every writer already handles it) and fold require_auth's early returns. - Tests read config.yaml with PyYAML (added to the test extra) instead of a hand-written parser, and share setup helpers.
This commit is contained in:
1 parent
01f45732a8
commit
fc8a7a3751
11 files changed
+170
-285
No files matched your search
+13
-33
@@ -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:
|
||||
|
||||
+23
-13
@@ -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<name>[^\]]+)\]\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,
|
||||
|
||||
+11
-18
@@ -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]] = {}
|
||||
|
||||
+15
-18
@@ -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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -253,6 +253,8 @@
|
||||
|
||||
{% block extra_js %}
|
||||
<script nonce="{{ g.csp_nonce }}">
|
||||
const MANAGED_NOTE = 'Managed by Home Assistant';
|
||||
|
||||
class PluginsManager {
|
||||
constructor() {
|
||||
this.loadingEl = document.getElementById('plugins-loading');
|
||||
@@ -362,7 +364,7 @@ class PluginsManager {
|
||||
managedNote = document.createElement('span');
|
||||
managedNote.className = 'text-muted small';
|
||||
managedNote.id = toggleId + '-managed';
|
||||
managedNote.textContent = 'Managed by Home Assistant';
|
||||
managedNote.textContent = MANAGED_NOTE;
|
||||
toggle.setAttribute('aria-describedby', managedNote.id);
|
||||
}
|
||||
// The title area is a real button so the card opens from the keyboard;
|
||||
@@ -666,7 +668,7 @@ class PluginsManager {
|
||||
function applyManagedState(wrapper, input, field) {
|
||||
if (!field || !field.managed) return;
|
||||
input.disabled = true;
|
||||
wrapper.appendChild(helpText('Managed by Home Assistant'));
|
||||
wrapper.appendChild(helpText(MANAGED_NOTE));
|
||||
}
|
||||
|
||||
// `plugin` ({kind, name}) is only needed by template fields, for their preview.
|
||||
@@ -1143,10 +1145,10 @@ function buildDynamicEditor(ds) {
|
||||
ki.disabled = true;
|
||||
vi.disabled = true;
|
||||
rm.disabled = true;
|
||||
rm.title = 'Managed by Home Assistant';
|
||||
rm.title = MANAGED_NOTE;
|
||||
const noteCol = document.createElement('div');
|
||||
noteCol.className = 'col-12';
|
||||
noteCol.appendChild(helpText('Managed by Home Assistant'));
|
||||
noteCol.appendChild(helpText(MANAGED_NOTE));
|
||||
row.appendChild(noteCol);
|
||||
}
|
||||
rowsContainer.appendChild(row);
|
||||
@@ -1239,7 +1241,7 @@ function buildRepeatingBlockEditor(rb) {
|
||||
sw.checked = (block ? block.enabled !== false : true);
|
||||
if (enabledManaged) {
|
||||
sw.disabled = true;
|
||||
sw.title = 'Managed by Home Assistant';
|
||||
sw.title = MANAGED_NOTE;
|
||||
}
|
||||
swWrap.appendChild(sw);
|
||||
const title = document.createElement('span');
|
||||
@@ -1250,11 +1252,11 @@ function buildRepeatingBlockEditor(rb) {
|
||||
rm.innerHTML = '<i class="fas fa-trash" aria-hidden="true"></i>';
|
||||
if (managedKeys.size || enabledManaged) {
|
||||
rm.disabled = true;
|
||||
rm.title = 'Managed by Home Assistant';
|
||||
rm.title = MANAGED_NOTE;
|
||||
}
|
||||
rm.addEventListener('click', () => { card.remove(); renumber(); });
|
||||
header.append(swWrap, title, rm);
|
||||
if (enabledManaged) header.appendChild(helpText('Managed by Home Assistant'));
|
||||
if (enabledManaged) header.appendChild(helpText(MANAGED_NOTE));
|
||||
card.appendChild(header);
|
||||
|
||||
const body = document.createElement('div');
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@ dependencies = [
|
||||
profanity = ["better-profanity>=0.7.0", "unidecode>=1.3.0"]
|
||||
geo = ["pycountry>=23.12.0", "us>=2.0.0"]
|
||||
lang = ["langdetect>=1.0.9"]
|
||||
test = ["pytest>=7.0", "pytest-asyncio>=0.21", "pytest-mock>=3.10", "pytest-cov>=4.0", "pytest-timeout>=2.1.0", "types-requests>=2.31"]
|
||||
test = ["pytest>=7.0", "pytest-asyncio>=0.21", "pytest-mock>=3.10", "pytest-cov>=4.0", "pytest-timeout>=2.1.0", "types-requests>=2.31", "pyyaml>=6.0"]
|
||||
docs = ["mkdocs-material>=9.0.0", "mkdocs-exclude>=1.0.0"]
|
||||
|
||||
[project.scripts]
|
||||
|
||||
+38
-121
@@ -11,12 +11,11 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from modules.config_schema import is_known_config_key, load_documented_keys_from_example
|
||||
from modules.ha_addon import (
|
||||
INI_MAP,
|
||||
MANAGED_KEYS_ENV,
|
||||
MANAGED_KEYS_FILENAME,
|
||||
VIEWER_PORT,
|
||||
as_bool,
|
||||
as_connection_type,
|
||||
@@ -25,6 +24,7 @@ from modules.ha_addon import (
|
||||
main,
|
||||
run,
|
||||
)
|
||||
from modules.managed_keys import MANAGED_KEYS_ENV, MANAGED_KEYS_FILENAME
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ADDON = ROOT / "homeassistant" / "meshcore_bot"
|
||||
@@ -67,22 +67,20 @@ SAMPLE_OPTIONS = {
|
||||
"web_viewer_password": "s3cret",
|
||||
}
|
||||
|
||||
FIXED_PAIRS = {(row.section, row.key) for row in INI_MAP if row.option is None}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def blocked_exec(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, list[str]]]:
|
||||
"""Stop run() from replacing the test process, and restore the env var."""
|
||||
"""Stop run() from replacing the test process, and isolate the env var."""
|
||||
calls: list[tuple[str, list[str]]] = []
|
||||
|
||||
def fake(file: str, args: list[str]) -> None:
|
||||
calls.append((file, list(args)))
|
||||
|
||||
monkeypatch.setattr(os, "execvp", fake)
|
||||
previous = os.environ.get(MANAGED_KEYS_ENV)
|
||||
yield calls
|
||||
if previous is None:
|
||||
os.environ.pop(MANAGED_KEYS_ENV, None)
|
||||
else:
|
||||
os.environ[MANAGED_KEYS_ENV] = previous
|
||||
monkeypatch.delenv(MANAGED_KEYS_ENV, raising=False)
|
||||
return calls
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -114,6 +112,22 @@ def _managed(data_dir: Path) -> set[tuple[str, str]]:
|
||||
return {tuple(pair) for pair in payload}
|
||||
|
||||
|
||||
def _backup_names(data_dir: Path) -> list[str]:
|
||||
return sorted(path.name for path in (data_dir / "backups").iterdir())
|
||||
|
||||
|
||||
def _assert_rerun_writes_nothing(
|
||||
layout: dict[str, Path],
|
||||
config_path: Path,
|
||||
data_dir: Path,
|
||||
) -> None:
|
||||
written = config_path.read_bytes()
|
||||
backups = _backup_names(data_dir)
|
||||
run(**layout)
|
||||
assert config_path.read_bytes() == written
|
||||
assert _backup_names(data_dir) == backups
|
||||
|
||||
|
||||
def _project_version() -> str:
|
||||
text = (ROOT / "pyproject.toml").read_text(encoding="utf-8")
|
||||
try:
|
||||
@@ -125,85 +139,13 @@ def _project_version() -> str:
|
||||
return tomllib.loads(text)["project"]["version"]
|
||||
|
||||
|
||||
def _unquote(text: str) -> str:
|
||||
if len(text) >= 2 and text[0] == text[-1] and text[0] in {'"', "'"}:
|
||||
return text[1:-1]
|
||||
return text
|
||||
|
||||
|
||||
def _scalar(text: str) -> Any:
|
||||
text = text.strip()
|
||||
if text in {"null", "~", ""}:
|
||||
return None
|
||||
if text == "true":
|
||||
return True
|
||||
if text == "false":
|
||||
return False
|
||||
if len(text) >= 2 and text[0] == text[-1] and text[0] in {'"', "'"}:
|
||||
return text[1:-1]
|
||||
if re.fullmatch(r"-?\d+", text):
|
||||
return int(text)
|
||||
return text
|
||||
|
||||
|
||||
def _parse_block(lines: list[tuple[int, str]], index: int, indent: int) -> tuple[Any, int]:
|
||||
if index < len(lines) and lines[index][1].startswith("- "):
|
||||
return _parse_list(lines, index, indent)
|
||||
return _parse_map(lines, index, indent)
|
||||
|
||||
|
||||
def _parse_map(lines: list[tuple[int, str]], index: int, indent: int) -> tuple[dict[str, Any], int]:
|
||||
result: dict[str, Any] = {}
|
||||
while index < len(lines):
|
||||
level, text = lines[index]
|
||||
if level < indent:
|
||||
break
|
||||
if level != indent or text.startswith("- "):
|
||||
raise ValueError(f"unexpected YAML at {text!r}")
|
||||
key, sep, rest = text.partition(":")
|
||||
if not sep:
|
||||
raise ValueError(f"expected key: value, got {text!r}")
|
||||
key = _unquote(key.strip())
|
||||
rest = rest.strip()
|
||||
index += 1
|
||||
if rest == "" and index < len(lines) and lines[index][0] > level:
|
||||
child, index = _parse_block(lines, index, lines[index][0])
|
||||
result[key] = child
|
||||
else:
|
||||
result[key] = _scalar(rest)
|
||||
return result, index
|
||||
|
||||
|
||||
def _parse_list(lines: list[tuple[int, str]], index: int, indent: int) -> tuple[list[Any], int]:
|
||||
result: list[Any] = []
|
||||
while index < len(lines):
|
||||
level, text = lines[index]
|
||||
if level < indent or not text.startswith("- "):
|
||||
break
|
||||
item = text[2:].strip()
|
||||
index += 1
|
||||
if item == "" and index < len(lines) and lines[index][0] > level:
|
||||
child, index = _parse_block(lines, index, lines[index][0])
|
||||
result.append(child)
|
||||
else:
|
||||
result.append(_scalar(item))
|
||||
return result, index
|
||||
|
||||
|
||||
def load_yaml(path: Path) -> dict[str, Any]:
|
||||
"""Parse the small YAML subset the add-on files use. No PyYAML in this repo."""
|
||||
lines: list[tuple[int, str]] = []
|
||||
for raw in path.read_text(encoding="utf-8").splitlines():
|
||||
stripped = raw.strip()
|
||||
if not stripped or stripped.startswith("#") or stripped in {"---", "..."}:
|
||||
continue
|
||||
lines.append((len(raw) - len(raw.lstrip(" ")), stripped))
|
||||
value, index = _parse_block(lines, 0, 0)
|
||||
if index != len(lines):
|
||||
raise ValueError(f"{path} was not fully parsed near {lines[index]!r}")
|
||||
if not isinstance(value, dict):
|
||||
"""Parse one of the add-on's YAML files."""
|
||||
with path.open(encoding="utf-8") as handle:
|
||||
loaded = yaml.safe_load(handle)
|
||||
if not isinstance(loaded, dict):
|
||||
raise ValueError(f"{path} is not a mapping")
|
||||
return value
|
||||
return loaded
|
||||
|
||||
|
||||
def test_schema_and_mapping_agree_both_ways() -> None:
|
||||
@@ -237,20 +179,6 @@ def test_option_rows_target_the_config_keys() -> None:
|
||||
}
|
||||
|
||||
|
||||
def test_fixed_rows_are_constants() -> None:
|
||||
fixed = {(row.section, row.key): row for row in INI_MAP if row.option is None}
|
||||
assert fixed["Bot", "db_path"].constant == "databases/meshcore_bot.db"
|
||||
assert fixed["Bot", "db_path"].base == "data"
|
||||
assert fixed["Bot", "local_dir_path"].constant == "local"
|
||||
assert fixed["Bot", "local_dir_path"].base == "config"
|
||||
assert fixed["Logging", "log_file"].constant == ""
|
||||
assert fixed["Web_Viewer", "enabled"].constant is True
|
||||
assert fixed["Web_Viewer", "host"].constant == "0.0.0.0"
|
||||
assert fixed["Web_Viewer", "port"].constant == VIEWER_PORT
|
||||
assert fixed["Web_Viewer", "ha_ingress"].constant is True
|
||||
assert fixed["Web_Viewer", "auto_start"].constant is True
|
||||
|
||||
|
||||
def test_every_mapped_key_is_known() -> None:
|
||||
example = load_documented_keys_from_example(ROOT / "config.ini.example")
|
||||
missing = [
|
||||
@@ -356,7 +284,7 @@ def test_first_start_seeds_and_applies_fixed_settings(
|
||||
assert len(backups) == 1
|
||||
assert "db_path = meshcore_bot.db" in backups[0].read_text(encoding="utf-8")
|
||||
assert list(layout["config_dir"].glob("*.bak.*")) == []
|
||||
assert _managed(data) == {(row.section, row.key) for row in INI_MAP if row.option is None}
|
||||
assert _managed(data) == FIXED_PAIRS
|
||||
assert os.environ[MANAGED_KEYS_ENV] == str(data / MANAGED_KEYS_FILENAME)
|
||||
assert blocked_exec == [
|
||||
(
|
||||
@@ -411,13 +339,10 @@ def test_set_options_override(layout: dict[str, Path]) -> None:
|
||||
|
||||
def test_restart_writes_nothing_when_unchanged(layout: dict[str, Path]) -> None:
|
||||
run(**layout)
|
||||
config_path = layout["config_dir"] / "config.ini"
|
||||
written = config_path.read_bytes()
|
||||
backups = sorted(path.name for path in (layout["data_dir"] / "backups").iterdir())
|
||||
assert backups
|
||||
run(**layout)
|
||||
assert config_path.read_bytes() == written
|
||||
assert sorted(path.name for path in (layout["data_dir"] / "backups").iterdir()) == backups
|
||||
assert _backup_names(layout["data_dir"])
|
||||
_assert_rerun_writes_nothing(
|
||||
layout, layout["config_dir"] / "config.ini", layout["data_dir"]
|
||||
)
|
||||
|
||||
|
||||
def test_percent_in_password_survives_configparser(layout: dict[str, Path]) -> None:
|
||||
@@ -432,11 +357,7 @@ def test_percent_in_password_survives_configparser(layout: dict[str, Path]) -> N
|
||||
plain.read(config_path, encoding="utf-8")
|
||||
assert plain.get("Web_Viewer", "web_viewer_password") == "abc%xyz"
|
||||
|
||||
written = config_path.read_bytes()
|
||||
backups = sorted(path.name for path in (layout["data_dir"] / "backups").iterdir())
|
||||
run(**layout)
|
||||
assert config_path.read_bytes() == written
|
||||
assert sorted(path.name for path in (layout["data_dir"] / "backups").iterdir()) == backups
|
||||
_assert_rerun_writes_nothing(layout, config_path, layout["data_dir"])
|
||||
|
||||
|
||||
def test_overlay_managed_keys_are_deleted(
|
||||
@@ -509,8 +430,9 @@ def test_base_and_overlay_backups_do_not_collide(
|
||||
def test_real_example_with_sample_options(tmp_path: Path, blocked_exec: list[tuple[str, list[str]]]) -> None:
|
||||
config_dir = tmp_path / "config"
|
||||
data_dir = tmp_path / "data"
|
||||
run_kwargs = {"config_dir": config_dir, "data_dir": data_dir, "repo_root": ROOT}
|
||||
_options(data_dir, SAMPLE_OPTIONS)
|
||||
run(config_dir=config_dir, data_dir=data_dir, repo_root=ROOT)
|
||||
run(**run_kwargs)
|
||||
config_path = config_dir / "config.ini"
|
||||
text = config_path.read_text(encoding="utf-8")
|
||||
assert "# Connection type: serial, ble, or tcp" in text
|
||||
@@ -534,8 +456,7 @@ def test_real_example_with_sample_options(tmp_path: Path, blocked_exec: list[tup
|
||||
assert cfg.get("Bot", "db_path") == str(data_dir / "databases" / "meshcore_bot.db")
|
||||
assert cfg.get("Bot", "local_dir_path") == str(config_dir / "local")
|
||||
owned = _managed(data_dir)
|
||||
fixed = {(row.section, row.key) for row in INI_MAP if row.option is None}
|
||||
assert owned == fixed | {
|
||||
assert owned == FIXED_PAIRS | {
|
||||
("Connection", "connection_type"),
|
||||
("Connection", "hostname"),
|
||||
("Connection", "tcp_port"),
|
||||
@@ -549,11 +470,7 @@ def test_real_example_with_sample_options(tmp_path: Path, blocked_exec: list[tup
|
||||
assert args[-2:] == ["--config", str(config_path)]
|
||||
assert args[1] == str(ROOT / "meshcore_bot.py")
|
||||
|
||||
written = config_path.read_bytes()
|
||||
backup_names = sorted(path.name for path in (data_dir / "backups").iterdir())
|
||||
run(config_dir=config_dir, data_dir=data_dir, repo_root=ROOT)
|
||||
assert config_path.read_bytes() == written
|
||||
assert sorted(path.name for path in (data_dir / "backups").iterdir()) == backup_names
|
||||
_assert_rerun_writes_nothing(run_kwargs, config_path, data_dir)
|
||||
|
||||
|
||||
def test_bad_options_json_does_not_write(layout: dict[str, Path]) -> None:
|
||||
|
||||
+57
-52
@@ -5,14 +5,15 @@ from __future__ import annotations
|
||||
import configparser
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from modules.ha_addon import MANAGED_KEYS_ENV
|
||||
from modules.ini_writer import IniValueError
|
||||
from modules.managed_keys import (
|
||||
MANAGED_KEYS_ENV,
|
||||
ManagedKeyError,
|
||||
guard_managed_writes,
|
||||
is_managed,
|
||||
@@ -40,6 +41,25 @@ def _point(monkeypatch: pytest.MonkeyPatch, path: Path) -> None:
|
||||
monkeypatch.setenv(MANAGED_KEYS_ENV, str(path))
|
||||
|
||||
|
||||
def _managed_file(tmp_path: Path, pairs: list[tuple[str, str]]) -> Path:
|
||||
path = tmp_path / "managed.json"
|
||||
path.write_text(json.dumps(pairs), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_store(tmp_path: Path) -> Callable[[str], ConfigIniStore]:
|
||||
"""Build an INI-backed store over a fresh ``config.ini`` with ``text``."""
|
||||
def _make(text: str) -> ConfigIniStore:
|
||||
config_path = tmp_path / "config.ini"
|
||||
config_path.write_text(text, encoding="utf-8")
|
||||
config = configparser.ConfigParser()
|
||||
config.read(config_path, encoding="utf-8")
|
||||
return ConfigIniStore(config, str(config_path))
|
||||
|
||||
return _make
|
||||
|
||||
|
||||
def test_missing_env_is_empty(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None:
|
||||
monkeypatch.delenv(MANAGED_KEYS_ENV, raising=False)
|
||||
with _watch(caplog):
|
||||
@@ -139,9 +159,7 @@ def _config(text: str) -> configparser.ConfigParser:
|
||||
def test_guard_drops_unchanged_managed_key_and_keeps_the_rest(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
path = tmp_path / "managed.json"
|
||||
path.write_text(json.dumps([["Bot", "DB_Path"]]), encoding="utf-8")
|
||||
_point(monkeypatch, path)
|
||||
_point(monkeypatch, _managed_file(tmp_path, [("Bot", "DB_Path")]))
|
||||
config = _config("[Bot]\ndb_path = /data/db\n")
|
||||
updates, deletes = guard_managed_writes(
|
||||
{"Bot": {"DB_Path": "/data/db", "bot_name": "Zed"}},
|
||||
@@ -153,9 +171,10 @@ def test_guard_drops_unchanged_managed_key_and_keeps_the_rest(
|
||||
|
||||
|
||||
def test_guard_rejects_a_changed_managed_key(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
path = tmp_path / "managed.json"
|
||||
path.write_text(json.dumps([["Bot", "db_path"], ["Connection", "hostname"]]), encoding="utf-8")
|
||||
_point(monkeypatch, path)
|
||||
_point(
|
||||
monkeypatch,
|
||||
_managed_file(tmp_path, [("Bot", "db_path"), ("Connection", "hostname")]),
|
||||
)
|
||||
config = _config("[Bot]\ndb_path = /data/db\n")
|
||||
with pytest.raises(ManagedKeyError, match=r"Managed by Home Assistant: \[bot\] db_path") as caught:
|
||||
guard_managed_writes(
|
||||
@@ -168,20 +187,17 @@ def test_guard_rejects_a_changed_managed_key(monkeypatch: pytest.MonkeyPatch, tm
|
||||
|
||||
|
||||
def test_store_refuses_managed_write_and_leaves_disk_and_memory(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path: Path,
|
||||
make_store: Callable[[str], ConfigIniStore],
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.ini"
|
||||
config_path.write_text("[Bot]\ndb_path = /data/db\nbot_name = A\n", encoding="utf-8")
|
||||
managed = tmp_path / "managed.json"
|
||||
managed.write_text(json.dumps([["Bot", "db_path"]]), encoding="utf-8")
|
||||
_point(monkeypatch, managed)
|
||||
config = configparser.ConfigParser()
|
||||
config.read(config_path, encoding="utf-8")
|
||||
store = ConfigIniStore(config, str(config_path))
|
||||
store = make_store("[Bot]\ndb_path = /data/db\nbot_name = A\n")
|
||||
config_path = Path(store.config_path)
|
||||
_point(monkeypatch, _managed_file(tmp_path, [("Bot", "db_path")]))
|
||||
with pytest.raises(ManagedKeyError):
|
||||
store.write_values("Bot", {"db_path": "/other", "bot_name": "B"})
|
||||
assert config.get("Bot", "db_path") == "/data/db"
|
||||
assert config.get("Bot", "bot_name") == "A"
|
||||
assert store.config.get("Bot", "db_path") == "/data/db"
|
||||
assert store.config.get("Bot", "bot_name") == "A"
|
||||
text = config_path.read_text(encoding="utf-8")
|
||||
assert "db_path = /data/db" in text
|
||||
assert "bot_name = B" not in text
|
||||
@@ -194,57 +210,46 @@ def test_store_refuses_managed_write_and_leaves_disk_and_memory(
|
||||
def test_store_refuses_managed_write_across_section_case(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path: Path,
|
||||
make_store: Callable[[str], ConfigIniStore],
|
||||
managed_section: str,
|
||||
write_section: str,
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.ini"
|
||||
original = "[Web_Viewer]\nport = 8080\n"
|
||||
config_path.write_text(original, encoding="utf-8")
|
||||
managed = tmp_path / "managed.json"
|
||||
managed.write_text(json.dumps([[managed_section, "port"]]), encoding="utf-8")
|
||||
_point(monkeypatch, managed)
|
||||
config = configparser.ConfigParser()
|
||||
config.read(config_path, encoding="utf-8")
|
||||
store = ConfigIniStore(config, str(config_path))
|
||||
store = make_store("[Web_Viewer]\nport = 8080\n")
|
||||
config_path = Path(store.config_path)
|
||||
original = config_path.read_text(encoding="utf-8")
|
||||
_point(monkeypatch, _managed_file(tmp_path, [(managed_section, "port")]))
|
||||
with pytest.raises(ManagedKeyError):
|
||||
store.write_values(write_section, {"port": "9"})
|
||||
assert config.get("Web_Viewer", "port") == "8080"
|
||||
assert store.config.get("Web_Viewer", "port") == "8080"
|
||||
assert config_path.read_text(encoding="utf-8") == original
|
||||
|
||||
|
||||
def test_store_allows_unchanged_managed_write_with_different_section_case(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path: Path,
|
||||
make_store: Callable[[str], ConfigIniStore],
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.ini"
|
||||
original = "[Web_Viewer]\nport = 8080\n"
|
||||
config_path.write_text(original, encoding="utf-8")
|
||||
managed = tmp_path / "managed.json"
|
||||
managed.write_text(json.dumps([["web_viewer", "port"]]), encoding="utf-8")
|
||||
_point(monkeypatch, managed)
|
||||
config = configparser.ConfigParser()
|
||||
config.read(config_path, encoding="utf-8")
|
||||
store = ConfigIniStore(config, str(config_path))
|
||||
store = make_store("[Web_Viewer]\nport = 8080\n")
|
||||
config_path = Path(store.config_path)
|
||||
original = config_path.read_text(encoding="utf-8")
|
||||
_point(monkeypatch, _managed_file(tmp_path, [("web_viewer", "port")]))
|
||||
store.write_values("web_viewer", {"port": "8080"})
|
||||
assert config.get("Web_Viewer", "port") == "8080"
|
||||
assert not config.has_section("web_viewer")
|
||||
assert store.config.get("Web_Viewer", "port") == "8080"
|
||||
assert not store.config.has_section("web_viewer")
|
||||
assert config_path.read_text(encoding="utf-8") == original
|
||||
|
||||
|
||||
def test_store_writes_unmanaged_keys_and_leaves_an_unchanged_managed_line(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path: Path,
|
||||
make_store: Callable[[str], ConfigIniStore],
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.ini"
|
||||
original = "[Bot]\ndb_path = /data/db\nbot_name = A\n"
|
||||
config_path.write_text(original, encoding="utf-8")
|
||||
managed = tmp_path / "managed.json"
|
||||
managed.write_text(json.dumps([["Bot", "db_path"]]), encoding="utf-8")
|
||||
_point(monkeypatch, managed)
|
||||
config = configparser.ConfigParser()
|
||||
config.read(config_path, encoding="utf-8")
|
||||
store = ConfigIniStore(config, str(config_path))
|
||||
store = make_store("[Bot]\ndb_path = /data/db\nbot_name = A\n")
|
||||
config_path = Path(store.config_path)
|
||||
_point(monkeypatch, _managed_file(tmp_path, [("Bot", "db_path")]))
|
||||
store.write_values("Bot", {"db_path": "/data/db", "bot_name": "B"})
|
||||
assert config.get("Bot", "bot_name") == "B"
|
||||
assert config.get("Bot", "db_path") == "/data/db"
|
||||
assert store.config.get("Bot", "bot_name") == "B"
|
||||
assert store.config.get("Bot", "db_path") == "/data/db"
|
||||
text = config_path.read_text(encoding="utf-8")
|
||||
assert "db_path = /data/db" in text
|
||||
assert "bot_name = B" in text
|
||||
@@ -14,8 +14,8 @@ from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from modules.ha_addon import MANAGED_KEYS_ENV
|
||||
from modules.ini_writer import backup_config, update_ini_values
|
||||
from modules.managed_keys import MANAGED_KEYS_ENV
|
||||
from modules.settings_schema import (
|
||||
_assemble_entry,
|
||||
build_plugin_settings_view,
|
||||
@@ -438,6 +438,7 @@ class TestBuildViewPasswordRedaction:
|
||||
description="",
|
||||
category="general",
|
||||
enabled_default=True,
|
||||
managed=frozenset(),
|
||||
)
|
||||
return next(f for f in entry["fields"] if f["key"] == "api_password")
|
||||
|
||||
|
||||
@@ -542,20 +542,6 @@ class TestWebViewerIntegrationValidation:
|
||||
WebViewerIntegration(bot)
|
||||
bot.logger.error.assert_not_called()
|
||||
|
||||
def test_malformed_ha_ingress_value_is_treated_as_off(self):
|
||||
from modules.web_viewer.integration import WebViewerIntegration
|
||||
bot = _make_bot()
|
||||
bot.config.set("Web_Viewer", "enabled", "true")
|
||||
bot.config.set("Web_Viewer", "host", "0.0.0.0")
|
||||
bot.config.set("Web_Viewer", "web_viewer_password", "")
|
||||
bot.config.set("Web_Viewer", "ha_ingress", "maybe")
|
||||
with patch.object(WebViewerIntegration, "start_viewer"):
|
||||
with patch("modules.web_viewer.integration.BotIntegration._init_http_session"), \
|
||||
patch("modules.web_viewer.integration.BotIntegration._init_packet_stream_table"), \
|
||||
patch("modules.web_viewer.integration.BotIntegration._start_drain_thread"):
|
||||
WebViewerIntegration(bot) # must not raise from getboolean
|
||||
bot.logger.error.assert_called()
|
||||
|
||||
def test_zero_host_without_password_does_not_log_when_disabled(self):
|
||||
from modules.web_viewer.integration import WebViewerIntegration
|
||||
bot = _make_bot()
|
||||
|
||||
Reference in new issue
Block a user