Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions src/roborock_local_server/admin_settings.py
Original file line number Diff line number Diff line change
@@ -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)
70 changes: 20 additions & 50 deletions src/roborock_local_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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:
Expand Down
105 changes: 74 additions & 31 deletions tests/test_admin_api.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Loading