diff --git a/src/roborock_local_server/admin_settings.py b/src/roborock_local_server/admin_settings.py new file mode 100644 index 00000000..15a8d6a1 --- /dev/null +++ b/src/roborock_local_server/admin_settings.py @@ -0,0 +1,136 @@ +"""Admin settings that can be changed at runtime from the admin dashboard. + +The config file provides the default value of each setting. When an admin +changes a setting in the dashboard, the new value is stored in a small JSON +file in the state directory instead of being written back into the config +file. This keeps the config file read-only for the server, so it can be +generated by tools such as the Home Assistant add-on or a NixOS module. + +Each stored value remembers the config value it overrode. While the config +file keeps that value, the stored value is used, also across restarts. When the +store is opened with a different config value, the config file wins and the +stored value is discarded. Changing a setting in the config file therefore +replaces an earlier dashboard change, but only if the new config value differs +from the old one. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import tempfile +import threading +from typing import Mapping + +RUNTIME_ADMIN_SETTINGS = ("protocol_auth_enabled", "new_connections_enabled") + + +class AdminSettingsStore: + """Stores dashboard overrides of boolean admin settings.""" + + def __init__(self, path: Path, config_values: Mapping[str, bool]) -> None: + self._path = path + self._lock = threading.Lock() + loaded = self._load() + self._overrides = { + name: entry + for name, entry in loaded.items() + if config_values.get(name) == entry["config_value"] + } + if self._overrides != loaded: + self._save(self._overrides) + + @property + def path(self) -> Path: + return self._path + + def _load(self) -> dict[str, dict[str, bool]]: + try: + raw = self._path.read_text(encoding="utf-8") + except FileNotFoundError: + return {} + try: + parsed = json.loads(raw) + except json.JSONDecodeError as exc: + raise ValueError( + f"Admin settings file {self._path} is not valid JSON. " + "Fix or delete it to fall back to the values from the config file." + ) from exc + if not isinstance(parsed, dict): + raise ValueError(f"Admin settings file {self._path} must contain a JSON object.") + overrides: dict[str, dict[str, bool]] = {} + for name, entry in parsed.items(): + if name not in RUNTIME_ADMIN_SETTINGS: + continue + if ( + not isinstance(entry, dict) + or not isinstance(entry.get("value"), bool) + or not isinstance(entry.get("config_value"), bool) + ): + raise ValueError( + f"Admin settings file {self._path} has an invalid entry for {name}. " + "Fix or delete it to fall back to the values from the config file." + ) + overrides[name] = {"value": entry["value"], "config_value": entry["config_value"]} + return overrides + + def effective(self, name: str, config_value: bool) -> bool: + """Return the stored value, unless the config value changed since it was stored.""" + self._check_name(name) + with self._lock: + entry = self._overrides.get(name) + if entry is None or entry["config_value"] != config_value: + return config_value + return entry["value"] + + def set(self, name: str, value: bool, config_value: bool) -> None: + """Store a dashboard change and write the file atomically.""" + self._check_name(name) + with self._lock: + updated = dict(self._overrides) + updated[name] = {"value": bool(value), "config_value": bool(config_value)} + self._save(updated) + + @staticmethod + def _check_name(name: str) -> None: + if name not in RUNTIME_ADMIN_SETTINGS: + raise KeyError(f"{name} is not a runtime admin setting") + + def _save(self, overrides: dict[str, dict[str, bool]]) -> None: + """Write the overrides and keep the in-memory copy equal to the file. + + The in-memory copy is updated as soon as the file has been replaced, + before the directory is synced. If the sync fails, the error is still + raised, but the next write starts from what is actually on disk. + """ + self._write(overrides) + self._overrides = overrides + self._sync_directory() + + def _write(self, overrides: dict[str, dict[str, bool]]) -> None: + self._path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=self._path.parent, + prefix=f".{self._path.name}.", + suffix=".tmp", + ) + temporary = Path(temporary_name) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + json.dump(overrides, handle, indent=2, sort_keys=True) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, self._path) + except BaseException: + temporary.unlink(missing_ok=True) + raise + + def _sync_directory(self) -> None: + """Flush the rename to disk, so that a power failure cannot undo it.""" + descriptor = os.open(self._path.parent, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py index 157e3bea..77dd15e8 100644 --- a/src/roborock_local_server/server.py +++ b/src/roborock_local_server/server.py @@ -23,6 +23,7 @@ import uvicorn from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware +from .admin_settings import AdminSettingsStore from .certs import CertificateManager from .bundled_backend.shared.constants import DEFAULT_PRODUCT_SCHEMA, region_country from .bundled_backend.shared.data_helpers import utcnow_iso @@ -384,6 +385,13 @@ def __init__( self._stop_event = asyncio.Event() self.certificate_manager = CertificateManager(config=config, paths=paths) + self.admin_settings = AdminSettingsStore( + paths.state_dir / "admin_settings.json", + config_values={ + "protocol_auth_enabled": config.admin.protocol_auth_enabled, + "new_connections_enabled": config.admin.new_connections_enabled, + }, + ) self.session_manager = AdminSessionManager( secret=config.admin.session_secret, ttl_seconds=config.admin.session_ttl_seconds, @@ -596,10 +604,10 @@ def cookie_secure(self, request: Request) -> bool: return request.url.scheme == "https" def protocol_auth_enabled(self) -> bool: - return bool(self.config.admin.protocol_auth_enabled) + return self.admin_settings.effective("protocol_auth_enabled", self.config.admin.protocol_auth_enabled) def new_connections_enabled(self) -> bool: - return bool(self.config.admin.new_connections_enabled) + return self.admin_settings.effective("new_connections_enabled", self.config.admin.new_connections_enabled) def _protocol_login_email(self) -> str: return str(self.config.admin.protocol_login_email or "").strip() @@ -1613,58 +1621,20 @@ def _auth_payload(self) -> dict[str, Any]: "pending_device_mqtt_recovery": self._pending_device_mqtt_recovery_payload(), } - def _rewrite_admin_bool_setting(self, *, key: str, value: bool) -> None: - config_path = self.paths.config_file - lines = config_path.read_text(encoding="utf-8").splitlines() - rendered_value = "true" if value else "false" - output: list[str] = [] - in_admin_section = False - admin_section_found = False - updated = False - - for line in lines: - stripped = line.strip() - is_section = stripped.startswith("[") and stripped.endswith("]") - if is_section and in_admin_section and not updated: - output.append(f"{key} = {rendered_value}") - updated = True - if stripped == "[admin]": - admin_section_found = True - in_admin_section = True - elif is_section: - in_admin_section = False - if in_admin_section: - is_comment = stripped.startswith(("#", ";")) - if not is_comment and "=" in line: - existing_key, _existing_value = line.split("=", 1) - if existing_key.strip() == key: - indent = line[: len(line) - len(line.lstrip())] - output.append(f"{indent}{key} = {rendered_value}") - updated = True - continue - output.append(line) - - if admin_section_found and in_admin_section and not updated: - output.append(f"{key} = {rendered_value}") - updated = True - - if not admin_section_found: - if output and output[-1].strip(): - output.append("") - output.extend(["[admin]", f"{key} = {rendered_value}"]) - - config_path.write_text("\n".join(output) + "\n", encoding="utf-8") - def set_protocol_auth_enabled(self, enabled: bool) -> dict[str, Any]: - normalized_enabled = bool(enabled) - self._rewrite_admin_bool_setting(key="protocol_auth_enabled", value=normalized_enabled) - self.config = load_config(self.paths.config_file) + self.admin_settings.set( + "protocol_auth_enabled", + bool(enabled), + config_value=self.config.admin.protocol_auth_enabled, + ) return self._auth_payload() def set_new_connections_enabled(self, enabled: bool) -> dict[str, Any]: - normalized_enabled = bool(enabled) - self._rewrite_admin_bool_setting(key="new_connections_enabled", value=normalized_enabled) - self.config = load_config(self.paths.config_file) + self.admin_settings.set( + "new_connections_enabled", + bool(enabled), + config_value=self.config.admin.new_connections_enabled, + ) return self._auth_payload() def remove_protocol_session(self, *, hawk_id: str, hawk_session: str) -> bool: diff --git a/tests/test_admin_api.py b/tests/test_admin_api.py index c300ba7f..4b5426e5 100644 --- a/tests/test_admin_api.py +++ b/tests/test_admin_api.py @@ -1,8 +1,10 @@ import json +import os from dataclasses import replace from datetime import datetime, timedelta from pathlib import Path +import pytest from fastapi.testclient import TestClient from roborock.data import HomeData @@ -334,7 +336,7 @@ def test_admin_auth_endpoints_toggle_new_connections_and_manage_sessions(tmp_pat toggled = client.post("/admin/api/auth", json={"new_connections_enabled": False}) assert toggled.status_code == 200 assert toggled.json()["new_connections_enabled"] is False - assert 'new_connections_enabled = false' in paths.config_file.read_text(encoding="utf-8") + assert 'new_connections_enabled = true' in paths.config_file.read_text(encoding="utf-8") blocked_login = client.post( "/api/v5/auth/email/login/code", @@ -383,50 +385,50 @@ def test_admin_auth_update_rejects_invalid_payload_types(tmp_path: Path) -> None assert missing_toggle.json()["error"] == "new_connections_enabled or protocol_auth_enabled is required" -def test_set_protocol_auth_enabled_rewrites_only_exact_admin_key(tmp_path: Path) -> None: +def test_admin_toggles_persist_across_restart_without_rewriting_config(tmp_path: Path) -> None: config_file = write_release_config(tmp_path) original = config_file.read_text(encoding="utf-8") - modified = original.replace( - "protocol_auth_enabled = true", - "# protocol_auth_enabled = true\nprotocol_auth_enabled_backup = true", - ) - config_file.write_text(modified, encoding="utf-8") - config = load_config(config_file) paths = resolve_paths(config_file, config) - supervisor = ReleaseSupervisor(config=config, paths=paths) - payload = supervisor.set_protocol_auth_enabled(False) + supervisor = ReleaseSupervisor(config=config, paths=paths) + supervisor.set_protocol_auth_enabled(False) + payload = supervisor.set_new_connections_enabled(False) - rendered = config_file.read_text(encoding="utf-8") assert payload["protocol_auth_enabled"] is False - assert "# protocol_auth_enabled = true" in rendered - assert "protocol_auth_enabled_backup = true" in rendered - assert "protocol_auth_enabled = false" in rendered - assert rendered.count("protocol_auth_enabled = false") == 1 + assert payload["new_connections_enabled"] is False + assert config_file.read_text(encoding="utf-8") == original + restarted = ReleaseSupervisor(config=load_config(config_file), paths=paths) + assert restarted.protocol_auth_enabled() is False + assert restarted.new_connections_enabled() is False -def test_set_new_connections_enabled_rewrites_only_exact_admin_key(tmp_path: Path) -> None: - config_file = write_release_config(tmp_path) - original = config_file.read_text(encoding="utf-8") - modified = original.replace( - "new_connections_enabled = true", - "# new_connections_enabled = true\nnew_connections_enabled_backup = true", - ) - config_file.write_text(modified, encoding="utf-8") +def test_config_change_after_dashboard_toggle_takes_precedence(tmp_path: Path) -> None: + config_file = write_release_config(tmp_path, new_connections_enabled=True) config = load_config(config_file) paths = resolve_paths(config_file, config) - supervisor = ReleaseSupervisor(config=config, paths=paths) + ReleaseSupervisor(config=config, paths=paths).set_new_connections_enabled(False) - payload = supervisor.set_new_connections_enabled(False) + config_file.write_text( + config_file.read_text(encoding="utf-8").replace( + "new_connections_enabled = true", + "new_connections_enabled = false", + ), + encoding="utf-8", + ) + lowered = ReleaseSupervisor(config=load_config(config_file), paths=paths) + assert lowered.new_connections_enabled() is False - rendered = config_file.read_text(encoding="utf-8") - assert payload["new_connections_enabled"] is False - assert "# new_connections_enabled = true" in rendered - assert "new_connections_enabled_backup = true" in rendered - assert "new_connections_enabled = false" in rendered - assert rendered.count("new_connections_enabled = false") == 1 + config_file.write_text( + config_file.read_text(encoding="utf-8").replace( + "new_connections_enabled = false", + "new_connections_enabled = true", + ), + encoding="utf-8", + ) + raised = ReleaseSupervisor(config=load_config(config_file), paths=paths) + assert raised.new_connections_enabled() is True def test_admin_onboarding_endpoints_require_auth_and_manage_session(tmp_path: Path) -> None: @@ -1723,3 +1725,44 @@ def test_last_known_route_names_each_room_of_the_robots_room_table(tmp_path: Pat {"segment": 19, "iot_id": "4", "tag": 14, "name": "Kitchen"}, {"segment": 18, "iot_id": "999", "tag": 1, "name": None}, ] + + +@pytest.mark.skipif( + os.name != "posix" or os.geteuid() == 0, + reason="needs POSIX file permissions, which root ignores", +) +def test_admin_toggles_work_with_a_read_only_config(tmp_path: Path) -> None: + """The shipped compose.yaml mounts config.toml read-only. + + Both the file and its directory are made read-only, so that neither an + in-place write nor a replacement of the config file can succeed. The data + directory stays writable, as in the container. + """ + config_file = write_release_config(tmp_path) + config = load_config(config_file) + paths = resolve_paths(config_file, config) + paths.state_dir.mkdir(parents=True, exist_ok=True) + original = config_file.read_bytes() + config_file.chmod(0o444) + tmp_path.chmod(0o555) + try: + client = TestClient(ReleaseSupervisor(config=config, paths=paths).app) + assert client.post("/admin/api/login", json={"password": "correct horse battery staple"}).status_code == 200 + + for toggle in ("new_connections_enabled", "protocol_auth_enabled"): + response = client.post("/admin/api/auth", json={toggle: False}) + assert response.status_code == 200, response.text + assert response.json()[toggle] is False + + assert config_file.read_bytes() == original + assert sorted(json.loads((paths.state_dir / "admin_settings.json").read_text(encoding="utf-8"))) == [ + "new_connections_enabled", + "protocol_auth_enabled", + ] + + restarted = ReleaseSupervisor(config=load_config(config_file), paths=paths) + assert restarted.new_connections_enabled() is False + assert restarted.protocol_auth_enabled() is False + finally: + tmp_path.chmod(0o755) + config_file.chmod(0o644) diff --git a/tests/test_admin_settings.py b/tests/test_admin_settings.py new file mode 100644 index 00000000..0c1d56aa --- /dev/null +++ b/tests/test_admin_settings.py @@ -0,0 +1,106 @@ +import json +import os +from pathlib import Path + +import pytest + +from roborock_local_server.admin_settings import AdminSettingsStore + +CONFIG_DEFAULTS = {"protocol_auth_enabled": True, "new_connections_enabled": True} + + +def test_without_stored_value_the_config_value_is_used(tmp_path: Path) -> None: + store = AdminSettingsStore(tmp_path / "admin_settings.json", CONFIG_DEFAULTS) + assert store.effective("protocol_auth_enabled", True) is True + assert store.effective("new_connections_enabled", False) is False + assert not store.path.exists() + + +def test_stored_value_applies_only_while_config_value_is_unchanged(tmp_path: Path) -> None: + path = tmp_path / "state" / "admin_settings.json" + AdminSettingsStore(path, CONFIG_DEFAULTS).set("new_connections_enabled", False, config_value=True) + + reloaded = AdminSettingsStore(path, CONFIG_DEFAULTS) + assert reloaded.effective("new_connections_enabled", True) is False + assert reloaded.effective("new_connections_enabled", False) is False + assert reloaded.effective("protocol_auth_enabled", True) is True + assert json.loads(path.read_text(encoding="utf-8")) == { + "new_connections_enabled": {"config_value": True, "value": False}, + } + assert [entry.name for entry in path.parent.iterdir()] == ["admin_settings.json"] + + +def test_unknown_setting_names_are_rejected(tmp_path: Path) -> None: + store = AdminSettingsStore(tmp_path / "admin_settings.json", CONFIG_DEFAULTS) + with pytest.raises(KeyError): + store.set("session_ttl_seconds", True, config_value=False) + + +@pytest.mark.parametrize( + "content", + [ + "{not json", + "[]", + '{"protocol_auth_enabled": {"value": "false", "config_value": true}}', + '{"protocol_auth_enabled": {"value": false}}', + ], +) +def test_invalid_file_fails_loudly_instead_of_reopening_access(tmp_path: Path, content: str) -> None: + path = tmp_path / "admin_settings.json" + path.write_text(content, encoding="utf-8") + with pytest.raises(ValueError, match="admin_settings.json"): + AdminSettingsStore(path, CONFIG_DEFAULTS) + + +def test_stale_value_is_discarded_when_config_changes(tmp_path: Path) -> None: + path = tmp_path / "admin_settings.json" + AdminSettingsStore(path, CONFIG_DEFAULTS).set("new_connections_enabled", False, config_value=True) + + changed = {**CONFIG_DEFAULTS, "new_connections_enabled": False} + assert AdminSettingsStore(path, changed).effective("new_connections_enabled", False) is False + assert json.loads(path.read_text(encoding="utf-8")) == {} + + assert AdminSettingsStore(path, CONFIG_DEFAULTS).effective("new_connections_enabled", True) is True + + +def test_rename_is_flushed_to_disk(tmp_path: Path, monkeypatch) -> None: + events: list[str] = [] + real_replace = os.replace + real_fsync = os.fsync + + def replace(source, destination): + events.append("replace") + real_replace(source, destination) + + def fsync(descriptor): + events.append("fsync") + real_fsync(descriptor) + + monkeypatch.setattr(os, "replace", replace) + monkeypatch.setattr(os, "fsync", fsync) + + AdminSettingsStore(tmp_path / "admin_settings.json", CONFIG_DEFAULTS).set( + "new_connections_enabled", False, config_value=True + ) + + assert events == ["fsync", "replace", "fsync"] + + +def test_failed_directory_sync_keeps_memory_and_file_in_step(tmp_path: Path, monkeypatch) -> None: + path = tmp_path / "admin_settings.json" + store = AdminSettingsStore(path, CONFIG_DEFAULTS) + + def failing_sync() -> None: + raise OSError(5, "directory fsync failed") + + monkeypatch.setattr(store, "_sync_directory", failing_sync) + with pytest.raises(OSError): + store.set("new_connections_enabled", False, config_value=True) + assert store.effective("new_connections_enabled", True) is False + + monkeypatch.undo() + store.set("protocol_auth_enabled", False, config_value=True) + assert json.loads(path.read_text(encoding="utf-8")) == { + "new_connections_enabled": {"config_value": True, "value": False}, + "protocol_auth_enabled": {"config_value": True, "value": False}, + } diff --git a/tests/test_ha_addon.py b/tests/test_ha_addon.py index 8cdbdd43..355a759f 100644 --- a/tests/test_ha_addon.py +++ b/tests/test_ha_addon.py @@ -7,6 +7,7 @@ import pytest import yaml +from roborock_local_server.admin_settings import AdminSettingsStore from roborock_local_server.config import load_config from roborock_local_server.ha_addon import write_config_from_home_assistant_options @@ -615,3 +616,40 @@ def replace(source, target): write_config_from_home_assistant_options(options_path=options_path, config_path=tmp_path / "config.toml") assert replacements == [password_path] assert len(password_path.read_text()) >= 32 + + +def test_dashboard_toggles_survive_home_assistant_config_regeneration(tmp_path: Path) -> None: + options_path = tmp_path / "options.json" + config_path = tmp_path / "config.toml" + _write_options( + options_path, + { + "stack_fqdn": "api-roborock.example.com", + "tls_mode": "provided", + "cert_file": "/ssl/fullchain.pem", + "key_file": "/ssl/privkey.pem", + "admin_password": "super-secret-password", + "protocol_login_email": "user@example.com", + "protocol_login_pin": "123456", + }, + ) + settings_path = tmp_path / "state" / "admin_settings.json" + + def start() -> AdminSettingsStore: + write_config_from_home_assistant_options(options_path=options_path, config_path=config_path) + admin = load_config(config_path).admin + return AdminSettingsStore( + settings_path, + config_values={ + "protocol_auth_enabled": admin.protocol_auth_enabled, + "new_connections_enabled": admin.new_connections_enabled, + }, + ) + + first = start() + first.set("protocol_auth_enabled", False, config_value=True) + first.set("new_connections_enabled", False, config_value=True) + + restarted = start() + assert restarted.effective("protocol_auth_enabled", True) is False + assert restarted.effective("new_connections_enabled", True) is False