fix(ha_addon): close review gaps in ingress, backups, and exit status

- mypy is clean again (the CI typecheck job was red on new lines).
- The overlay's config backup goes to /data/backups/local, so it no longer overwrites the base config backup taken in the same second.
- One ha_ingress_enabled() helper; a malformed ha_ingress value counts as off instead of disabling the whole web viewer.
- An exception that escapes the bot (e.g. a BLE adapter error) now exits 1 too.
- The web manifest's icon paths are relative, so they resolve with or without a path prefix.
- The root-relative URL scan also catches .href/.src/.action assignments, EventSource, Worker, Audio, Image and io().
This commit is contained in:
agessaman committed 2026-11-09 20:38:11 -08:00
1 parent 966fa1726a
commit 2575e86a03
13 files changed
+174 -55

No files matched your search

+4 -1
View File
@@ -303,8 +303,11 @@ def main():
# Cleanup already handled in run_bot's finally block
print("\nShutdown complete.")
except Exception as e:
# Cleanup already handled in run_bot's finally block
# Cleanup already handled in run_bot's finally block. A failure that
# escapes asyncio.run (e.g. BleakError from the BLE adapter) must exit
# non-zero so launchd and the Supervisor watchdog restart the bot.
print(f"Error: {e}")
sys.exit(1)
else:
if not started:
# A startup connection failure must exit non-zero: launchd
+11 -5
View File
@@ -59,6 +59,7 @@ 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"
LOCAL_DIR = "local"
LOCAL_BACKUP_DIR = "local"
# The viewer binds this port. config.yaml's ingress_port and published port
# use the same number; tests keep the three in step.
@@ -251,7 +252,9 @@ def _prepare_directories(config_dir: Path, data_dir: Path) -> Path:
config_dir.mkdir(parents=True, exist_ok=True)
data_dir.mkdir(parents=True, exist_ok=True)
backup_dir = data_dir / "backups"
backup_dir.mkdir(parents=True, exist_ok=True)
# Both files are named config.ini and backups are timestamped to the second,
# so the overlay needs its own directory to keep its backup separate.
(backup_dir / LOCAL_BACKUP_DIR).mkdir(parents=True, exist_ok=True)
# The database's parent and the user-visible local directory.
for directory in (data_dir / Path(DB_PATH).parent, config_dir / LOCAL_DIR):
directory.mkdir(parents=True, exist_ok=True)
@@ -308,13 +311,13 @@ def _local_config_path(config_dir: Path) -> Path:
def _overlay_deletes(
overlay_path: Path,
assignments: list[tuple[IniMap, str]],
) -> dict[str, list[str]]:
) -> dict[str, list[str] | set[str]]:
"""Managed keys the local overlay defines, shaped for ``update_ini_values``."""
parser = _read_config(overlay_path)
deletes: dict[str, list[str]] = {}
deletes: dict[str, list[str] | set[str]] = {}
for section, key in _managed_pairs(assignments):
if parser.has_option(section, key):
deletes.setdefault(section, []).append(key)
deletes[section] = [*deletes.get(section, []), key]
return deletes
@@ -348,7 +351,10 @@ def run(
deletes = _overlay_deletes(overlay_path, assignments)
if deletes:
update_ini_values(
str(overlay_path), {}, deletes=deletes, backup_dir=str(backup_dir)
str(overlay_path),
{},
deletes=deletes,
backup_dir=str(backup_dir / LOCAL_BACKUP_DIR),
)
removed = ", ".join(
f"[{section}] {key}" for section, keys in deletes.items() for key in keys
+11 -12
View File
@@ -95,7 +95,7 @@ def guard_managed_writes(
updates: Mapping[str, Mapping[str, str]] | None,
deletes: Mapping[str, Iterable[str]] | None,
config: configparser.ConfigParser | None = None,
) -> tuple[Mapping[str, Mapping[str, str]], Mapping[str, Iterable[str]] | None]:
) -> tuple[dict[str, dict[str, str]], dict[str, list[str] | set[str]] | None]:
"""Drop unchanged managed keys and reject real changes.
Rewriting a managed key with the value already stored is not a change (the
@@ -103,20 +103,19 @@ def guard_managed_writes(
any delete of a managed key raises :class:`ManagedKeyError` and nothing
should be written.
When no keys are managed, ``updates`` and ``deletes`` are returned unchanged.
When no keys are managed, ``updates`` and ``deletes`` are returned as
equivalent concrete dicts.
"""
managed = load_managed_keys()
if not managed:
return updates or {}, deletes
return _guard_against(managed, updates, deletes, config)
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,
)
def _guard_against(
managed: frozenset[tuple[str, str]],
updates: Mapping[str, Mapping[str, str]] | None,
deletes: Mapping[str, Iterable[str]] | None,
config: configparser.ConfigParser | None,
) -> tuple[dict[str, dict[str, str]], dict[str, list[str]] | None]:
conflicts: list[tuple[str, str]] = []
filtered: dict[str, dict[str, str]] = {}
for section, values in (updates or {}).items():
@@ -132,7 +131,7 @@ def _guard_against(
if kept:
filtered[section] = kept
filtered_deletes: dict[str, list[str]] = {}
filtered_deletes: dict[str, list[str] | set[str]] = {}
for section, keys in (deletes or {}).items():
kept_keys: list[str] = []
for key in keys:
+1 -1
View File
@@ -676,7 +676,7 @@ def read_section_items(
if prefix:
if not key.lower().startswith(pl):
continue
item = {"key": key[len(prefix):], "value": raw}
item: dict[str, Any] = {"key": key[len(prefix):], "value": raw}
else:
item = {"key": key, "value": raw}
if managed and is_managed(section, key, managed):
+7 -5
View File
@@ -198,7 +198,12 @@ from modules.web_viewer.feeds import ( # noqa: F401 _read_limited_requests_res
_read_limited_requests_response,
_validate_feed_interval,
)
from modules.web_viewer.ha_ingress import HaIngressMiddleware, ingress_prefix, socketio_cors_allowed
from modules.web_viewer.ha_ingress import (
HaIngressMiddleware,
ha_ingress_enabled,
ingress_prefix,
socketio_cors_allowed,
)
from modules.web_viewer.integration import normalized_web_viewer_password
from modules.web_viewer.live_stream import ( # noqa: F401 _ANSI_ESCAPE_RE re-exported
_ANSI_ESCAPE_RE,
@@ -355,10 +360,7 @@ class BotDataViewer(DashboardSnapshotMixin, LiveStreamMixin, SocketClientsMixin,
# Optional password authentication for web viewer (BUG-001)
self.web_viewer_password = normalized_web_viewer_password(self.config)
try:
self.ha_ingress = self.config.getboolean("Web_Viewer", "ha_ingress", fallback=False)
except (configparser.Error, ValueError, TypeError):
self.ha_ingress = False
self.ha_ingress = ha_ingress_enabled(self.config)
if self.web_viewer_password:
self.logger.info("Web viewer authentication enabled")
else:
+9
View File
@@ -8,6 +8,7 @@ an ingress panel, so a request that passes these checks is already authenticated
from __future__ import annotations
import configparser
import re
from collections.abc import Mapping
@@ -27,6 +28,14 @@ _BROWSER_ORIGIN = re.compile(
)
def ha_ingress_enabled(config: configparser.ConfigParser) -> bool:
"""True when ``[Web_Viewer] ha_ingress`` is set; malformed values are off."""
try:
return config.getboolean("Web_Viewer", "ha_ingress", fallback=False)
except (configparser.Error, ValueError, TypeError):
return False
def normalize_ingress_path(value: object) -> str | None:
"""Return a safe SCRIPT_NAME, or None when the header is not a path.
+2 -1
View File
@@ -21,6 +21,7 @@ from ..db_retention import (
retention_delete_settings,
)
from ..utils import resolve_path
from .ha_ingress import ha_ingress_enabled
def normalized_web_viewer_password(config) -> str:
@@ -871,7 +872,7 @@ class WebViewerIntegration:
# Only warn when the web viewer is configured to run at startup.
# Home Assistant ingress does not publish that port; the Supervisor
# is the only client and has already authenticated the user.
ha_ingress = self.bot.config.getboolean("Web_Viewer", "ha_ingress", fallback=False)
ha_ingress = ha_ingress_enabled(self.bot.config)
if self.enabled and self.host == "0.0.0.0" and not ha_ingress:
if not normalized_web_viewer_password(self.bot.config):
self.logger.error(
+1
View File
@@ -27,6 +27,7 @@ class SocketClientsMixin:
config: Any
connected_clients: Any
db_path: Any
is_ha_ingress_request: Any
logger: Any
max_clients: Any
socketio: Any
@@ -1 +1 @@
{"name":"","short_name":"","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}
{"name":"","short_name":"","icons":[{"src":"android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}
+21
View File
@@ -485,6 +485,27 @@ def test_overlay_without_managed_keys_is_ignored(layout: dict[str, Path]) -> Non
assert sorted(path.name for path in (layout["data_dir"] / "backups").iterdir()) == backups
def test_base_and_overlay_backups_do_not_collide(
layout: dict[str, Path],
blocked_exec: list[tuple[str, list[str]]],
) -> None:
overlay = layout["config_dir"] / "local" / "config.ini"
overlay.parent.mkdir(parents=True, exist_ok=True)
overlay.write_text("[Bot]\nbot_name = Override\n", encoding="utf-8")
_options(layout["data_dir"], {"bot_name": "HA Radio"})
run(**layout)
base_backups = list((layout["data_dir"] / "backups").glob("config.ini.bak.*"))
overlay_backups = list(
(layout["data_dir"] / "backups" / "local").glob("config.ini.bak.*")
)
assert len(base_backups) == 1
assert len(overlay_backups) == 1
assert "bot_name = MeshCoreBot" in base_backups[0].read_text(encoding="utf-8")
assert "bot_name = Override" in overlay_backups[0].read_text(encoding="utf-8")
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"
+30 -3
View File
@@ -121,14 +121,17 @@ class _RecordingLogger:
class _FakeBot:
"""Stands in for MeshCoreBot so main() can run without a radio or config."""
def __init__(self, started: bool):
def __init__(self, started: bool, start_error: Exception | None = None):
self.logger = _RecordingLogger()
self.connected = False
self._shutdown_event = None
self._started = started
self._start_error = start_error
self.stop_calls = 0
async def start(self) -> bool:
if self._start_error is not None:
raise self._start_error
return self._started
async def stop(self) -> None:
@@ -136,9 +139,13 @@ class _FakeBot:
def _run_main_with_fake_bot(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, *, started: bool
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
*,
started: bool,
start_error: Exception | None = None,
) -> _FakeBot:
fake = _FakeBot(started)
fake = _FakeBot(started, start_error)
import modules.core
monkeypatch.setattr(modules.core, "MeshCoreBot", lambda config_file: fake)
@@ -175,6 +182,26 @@ class TestStartupExitStatus:
assert fake.stop_calls == 1
def test_start_exception_exits_1(
self,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
fake = _run_main_with_fake_bot(
monkeypatch,
tmp_path,
started=False,
start_error=RuntimeError("BLE adapter unavailable"),
)
with pytest.raises(SystemExit) as exc:
main()
assert exc.value.code == 1
assert fake.stop_calls == 1 # cleanup ran before the exit
assert "Error: BLE adapter unavailable" in capsys.readouterr().out
class TestReportConfigIssues:
"""Startup config findings must reach the configured log file, not just stderr:
+62 -26
View File
@@ -17,6 +17,7 @@ import pytest
from modules.web_viewer.app import BotDataViewer
from modules.web_viewer.ha_ingress import (
HA_INGRESS_PROXY_IP,
ha_ingress_enabled,
ingress_prefix,
is_browser_origin,
normalize_ingress_path,
@@ -55,8 +56,10 @@ _SAFE_CALL = re.compile(
_REQUEST_PATH_CMP = re.compile(r"request\.path\s*[=!]=\s*$")
_ATTR = re.compile(r"(?:href|src|action)\s*=\s*$", re.IGNORECASE)
_SINK = re.compile(
r"(?:\.href|\.src|location(?:\.href)?\s*=|window\.open\s*\(|EventSource\s*\(|"
r"\bimport\s*\(|new\s+URL\s*\(|history\.(?:pushState|replaceState)\s*\(|\bpath\s*:)\s*$"
r"(?:\.(?:href|src|action)\s*=?|location(?:\.href)?\s*=|window\.open\s*\(|"
r"new\s+(?:EventSource|Worker|Audio|Image)\s*\(|\bEventSource\s*\(|"
r"\bimport\s*\(|new\s+URL\s*\(|history\.(?:pushState|replaceState)\s*\(|"
r"\bio\s*\(|\bpath\s*:)\s*$"
)
@@ -336,6 +339,13 @@ class TestIngressMiddlewareAndAuth:
assert callable(ingress_viewer.socketio.server.eio.cors_allowed_origins)
@pytest.mark.parametrize("value", ["maybe", "", "2"])
def test_malformed_ha_ingress_value_is_treated_as_off(value: str) -> None:
cfg = configparser.ConfigParser()
cfg["Web_Viewer"] = {"ha_ingress": value}
assert ha_ingress_enabled(cfg) is False
def _viewer_sources():
root = Path(__file__).resolve().parent.parent / "modules" / "web_viewer"
files = list((root / "templates").rglob("*.html"))
@@ -351,6 +361,36 @@ def _line_at(text: str, index: int) -> str:
return text[start:end]
def _scan_source(rel: str, text: str, used: dict[tuple[str, str, str], bool]) -> list[str]:
"""Return root-relative URL literals in ``text`` that bypass appUrl/fetch."""
violations = []
for match in _LITERAL.finditer(text):
literal = match.group("path")
if not (literal == "/" or _URL_PATH.fullmatch(literal)):
continue
before = text[: match.start()].rstrip()
line = _line_at(text, match.start())
if _SAFE_CALL.search(before) or _REQUEST_PATH_CMP.search(before):
continue
navigates = bool(_ATTR.search(before) or _SINK.search(before))
# A quoted "/" is a character test (appUrl, path slicing), not a URL.
if literal == "/" and not navigates:
continue
allow = next(
(entry for entry in _ALLOWLIST if entry[0] == rel and entry[1] in line),
None,
)
if allow is not None:
used[allow] = True
continue
# /api/... strings ride the fetch wrapper unless a sink resolves them
# itself. /api-explorer is a page, so the slash after "api" matters.
if literal.startswith("/api/") and not navigates:
continue
violations.append(f"{rel}:{text[:match.start()].count(chr(10)) + 1}: {line.strip()}")
return violations
def test_root_relative_urls_go_through_url_for_app_url_or_fetch():
"""New root-relative URLs have to use url_for, appUrl, or the fetch wrapper.
@@ -364,31 +404,27 @@ def test_root_relative_urls_go_through_url_for_app_url_or_fetch():
for path in _viewer_sources():
text = path.read_text(encoding="utf-8")
rel = str(path.relative_to(Path(__file__).resolve().parent.parent / "modules" / "web_viewer"))
for match in _LITERAL.finditer(text):
literal = match.group("path")
if not (literal == "/" or _URL_PATH.fullmatch(literal)):
continue
before = text[: match.start()].rstrip()
line = _line_at(text, match.start())
if _SAFE_CALL.search(before) or _REQUEST_PATH_CMP.search(before):
continue
navigates = bool(_ATTR.search(before) or _SINK.search(before))
# A quoted "/" is a character test (appUrl, path slicing), not a URL.
if literal == "/" and not navigates:
continue
allow = next(
(entry for entry in _ALLOWLIST if entry[0] == rel and entry[1] in line),
None,
)
if allow is not None:
used[allow] = True
continue
# /api/... strings ride the fetch wrapper unless a sink resolves them
# itself. /api-explorer is a page, so the slash after "api" matters.
if literal.startswith("/api/") and not navigates:
continue
violations.append(f"{rel}:{text[:match.start()].count(chr(10)) + 1}: {line.strip()}")
violations.extend(_scan_source(rel, text, used))
stale = [entry[1] for entry, hit in used.items() if not hit]
assert stale == [], f"allowlist entries matched nothing: {stale}"
assert violations == [], "root-relative URL bypasses url_for/appUrl/fetch:\n" + "\n".join(violations)
@pytest.mark.parametrize(
"snippet",
[
"a.href = '/api/export';\n",
"img.src = '/api/image';\n",
"form.action = '/api/save';\n",
"const source = new EventSource('/api/stream');\n",
"const worker = new Worker('/api/worker.js');\n",
"const audio = new Audio('/api/sound.mp3');\n",
"const image = new Image('/api/picture.png');\n",
"const socket = io('/api/socket');\n",
],
)
def test_sink_patterns_flag_root_relative_urls(snippet: str) -> None:
"""Each self-resolving sink must flag a root-relative literal, not exempt it."""
used = dict.fromkeys(_ALLOWLIST, False)
assert _scan_source("templates/synthetic.html", snippet, used) != []
+14
View File
@@ -542,6 +542,20 @@ 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()