From d1d06a41c8e85f0b44526fc106229fb4a62e1fd2 Mon Sep 17 00:00:00 2001 From: Mateusz Mazelanik Date: Sun, 29 Nov 2026 00:06:53 +0100 Subject: [PATCH 1/3] feat(config): read secrets from files with a _file suffix Every secret that the config holds inline can now be read from a separate file: admin.password_hash, admin.session_secret, admin.protocol_login_pin_hash, turn.password, network.localkey and network.mqtt_password. This keeps secrets out of config files that are generated by tools or stored in world-readable places, and works with Docker secrets, systemd credentials and similar mechanisms. Inline values keep working unchanged. --- config.example.toml | 5 +++ src/roborock_local_server/config.py | 43 +++++++++++++++--- tests/test_config.py | 68 +++++++++++++++++++++++++++++ 3 files changed, 110 insertions(+), 6 deletions(-) diff --git a/config.example.toml b/config.example.toml index 90b27005..f88d08bd 100644 --- a/config.example.toml +++ b/config.example.toml @@ -49,6 +49,11 @@ renew_check_seconds = 43200 acme_server = "zerossl" [admin] +# Every secret in this file can also be read from a separate file by adding +# "_file" to its name, for example password_hash_file = "/run/secrets/admin_password_hash". +# This works for admin.password_hash, admin.session_secret, admin.protocol_login_pin_hash, +# turn.password, network.localkey and network.mqtt_password. A relative path is +# resolved against the directory of this file. Set either the value or the file, not both. password_hash = "pbkdf2_sha256$600000$replace_me$replace_me" session_secret = "replace-with-at-least-24-random-characters" session_ttl_seconds = 86400 diff --git a/src/roborock_local_server/config.py b/src/roborock_local_server/config.py index 6fb12c5e..6c68f017 100644 --- a/src/roborock_local_server/config.py +++ b/src/roborock_local_server/config.py @@ -268,8 +268,33 @@ def _matter_key_proxy_enabled(from_file: bool) -> bool: return from_file +def _secret_value(section: dict[str, object], key: str, field_name: str, config_root: Path) -> str: + """Return a secret given either inline as ``key`` or by path as ``key_file``. + + A relative file path is resolved against the directory of the config file. + Setting both forms is an error, because it is unclear which one should win. + """ + inline = str(section.get(key, "") or "").strip() + file_value = str(section.get(f"{key}_file", "") or "").strip() + if not file_value: + return inline + if inline: + raise ValueError(f"{field_name} and {field_name}_file cannot both be set") + secret_path = Path(file_value) + if not secret_path.is_absolute(): + secret_path = config_root / secret_path + try: + secret = secret_path.read_text(encoding="utf-8").strip() + except OSError as exc: + raise ValueError(f"{field_name}_file could not be read: {secret_path} ({exc.strerror})") from exc + if not secret: + raise ValueError(f"{field_name}_file is empty: {secret_path}") + return secret + + def load_config(path: str | Path) -> AppConfig: config_path = Path(path).resolve() + config_root = config_path.parent parsed = tomllib.loads(config_path.read_text(encoding="utf-8")) network = _get_section(parsed, "network") @@ -319,10 +344,10 @@ def load_config(path: str | Path) -> AppConfig: mqtt_tls_port, ), region=str(network.get("region", "us")).strip().lower() or "us", - localkey=str(network.get("localkey", "")).strip(), + localkey=_secret_value(network, "localkey", "network.localkey", config_root), duid=str(network.get("duid", "")).strip(), mqtt_username=str(network.get("mqtt_username", "")).strip(), - mqtt_password=str(network.get("mqtt_password", "")).strip(), + mqtt_password=_secret_value(network, "mqtt_password", "network.mqtt_password", config_root), mqtt_client_id=str(network.get("mqtt_client_id", "")).strip(), trusted_proxies=_as_trusted_proxies( network.get("trusted_proxies"), @@ -369,14 +394,20 @@ def load_config(path: str | Path) -> AppConfig: ), matter=MatterConfig(key_proxy=_matter_key_proxy_enabled(_as_bool(matter.get("key_proxy"), False))), admin=AdminConfig( - password_hash=_require_non_empty(admin.get("password_hash"), "admin.password_hash"), - session_secret=_require_non_empty(admin.get("session_secret"), "admin.session_secret"), + password_hash=_require_non_empty( + _secret_value(admin, "password_hash", "admin.password_hash", config_root), + "admin.password_hash", + ), + session_secret=_require_non_empty( + _secret_value(admin, "session_secret", "admin.session_secret", config_root), + "admin.session_secret", + ), session_ttl_seconds=_as_int(admin.get("session_ttl_seconds"), "admin.session_ttl_seconds", 86400), protocol_auth_enabled=_as_bool(admin.get("protocol_auth_enabled"), True), new_connections_enabled=_as_bool(admin.get("new_connections_enabled"), True), protocol_login_email=_require_non_empty(admin.get("protocol_login_email"), "admin.protocol_login_email"), protocol_login_pin_hash=_require_non_empty( - admin.get("protocol_login_pin_hash"), + _secret_value(admin, "protocol_login_pin_hash", "admin.protocol_login_pin_hash", config_root), "admin.protocol_login_pin_hash", ), ), @@ -385,7 +416,7 @@ def load_config(path: str | Path) -> AppConfig: host=str(turn.get("host", "")).strip(), port=_as_port(turn.get("port"), "turn.port", 3478), username=str(turn.get("username", "") or ("roborock" if turn_mode == "provided" else "")).strip(), - password=str(turn.get("password", "")).strip(), + password=_secret_value(turn, "password", "turn.password", config_root), realm=str(turn.get("realm", "") or turn.get("host", "")).strip(), ttl=_as_int(turn.get("ttl"), "turn.ttl", 86400), ), diff --git a/tests/test_config.py b/tests/test_config.py index ba569588..e0273716 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -557,3 +557,71 @@ def test_load_config_rejects_invalid_trusted_proxy(tmp_path: Path) -> None: with pytest.raises(ValueError, match="network.trusted_proxies entry 'traefik'"): load_config(config_file) + + +def _move_inline_secret_to_file(config_path: Path, key: str, file_name: str) -> str: + """Replace an inline ``key = "..."`` line with ``key_file`` and return the moved value.""" + lines = config_path.read_text(encoding="utf-8").splitlines() + for index, line in enumerate(lines): + name, separator, value = line.partition("=") + if separator and name.strip() == key: + secret = value.strip().strip('"') + lines[index] = f'{key}_file = "{file_name}"' + break + else: + raise AssertionError(f"{key} not found in {config_path}") + config_path.write_text("\n".join(lines) + "\n", encoding="utf-8") + return secret + + +@pytest.mark.parametrize("key", ["password_hash", "session_secret", "protocol_login_pin_hash"]) +def test_admin_secrets_can_be_read_from_files(tmp_path, key): + path = write_release_config(tmp_path) + secret = _move_inline_secret_to_file(path, key, f"secrets/{key}") + (tmp_path / "secrets").mkdir() + (tmp_path / "secrets" / key).write_text(f"{secret}\n", encoding="utf-8") + + assert getattr(load_config(path).admin, key) == secret + + +def test_network_and_turn_secrets_can_be_read_from_absolute_files(tmp_path): + path = write_release_config(tmp_path) + secrets_dir = tmp_path / "elsewhere" + secrets_dir.mkdir() + for name, value in (("localkey", "abcdefghijklmnop"), ("mqtt_password", "mqtt-secret"), ("turn", "turn-secret")): + (secrets_dir / name).write_text(value, encoding="utf-8") + base = path.read_text(encoding="utf-8").replace( + "[network]\n", + f'[network]\nlocalkey_file = "{secrets_dir / "localkey"}"\n' + f'mqtt_password_file = "{secrets_dir / "mqtt_password"}"\n', + ) + path.write_text( + base + f'\n[turn]\nmode="external"\nhost="relay.example"\nusername="relay"\npassword_file="{secrets_dir / "turn"}"\n', + encoding="utf-8", + ) + + config = load_config(path) + assert config.network.localkey == "abcdefghijklmnop" + assert config.network.mqtt_password == "mqtt-secret" + assert config.turn.password == "turn-secret" + + +def test_secret_file_rejects_inline_value_alongside(tmp_path): + path = write_release_config(tmp_path) + (tmp_path / "session_secret").write_text("x" * 32, encoding="utf-8") + path.write_text( + path.read_text(encoding="utf-8").replace("[admin]\n", '[admin]\nsession_secret_file = "session_secret"\n'), + encoding="utf-8", + ) + with pytest.raises(ValueError, match="admin.session_secret and admin.session_secret_file cannot both be set"): + load_config(path) + + +def test_secret_file_reports_missing_and_empty_files(tmp_path): + path = write_release_config(tmp_path) + _move_inline_secret_to_file(path, "session_secret", "session_secret") + with pytest.raises(ValueError, match="admin.session_secret_file could not be read"): + load_config(path) + (tmp_path / "session_secret").write_text("\n", encoding="utf-8") + with pytest.raises(ValueError, match="admin.session_secret_file is empty"): + load_config(path) From 3bceef08779fa7f4de5357040447e3091e74543b Mon Sep 17 00:00:00 2001 From: Mateusz Mazelanik Date: Sun, 29 Nov 2026 00:12:12 +0100 Subject: [PATCH 2/3] fix(config): honour session_secret_file in the MITM launcher The MITM launcher reads admin.session_secret to enable protocol session sync. It now also reads admin.session_secret_file and reports a file that cannot be read. Inline secrets that are not strings, such as a numeric MQTT password, keep their previous value. --- mitm_redirect.py | 18 ++++++++++++++++-- src/roborock_local_server/config.py | 2 +- tests/test_config.py | 6 ++++++ tests/test_mitm_redirect.py | 25 +++++++++++++++++++++++++ 4 files changed, 48 insertions(+), 3 deletions(-) diff --git a/mitm_redirect.py b/mitm_redirect.py index dec623c5..af3ac6d6 100644 --- a/mitm_redirect.py +++ b/mitm_redirect.py @@ -16,6 +16,7 @@ import os import re import ssl +import sys import tomllib from urllib.parse import urlsplit from urllib.error import HTTPError @@ -341,7 +342,21 @@ def _load_local_sync_secret() -> str: admin = parsed.get("admin") if not isinstance(admin, dict): return "" - return str(admin.get("session_secret") or "").strip() + secret_file = str(admin.get("session_secret_file") or "").strip() + if not secret_file: + return str(admin.get("session_secret") or "").strip() + # A relative path is resolved against the directory of the config file, + # in the same way as the server does it. + secret_path = os.path.join(os.path.dirname(config_path), secret_file) + try: + with open(secret_path, encoding="utf-8") as handle: + return handle.read().strip() + except OSError as exc: + print( + f"[SYNC] could not read admin.session_secret_file {secret_path}: {exc.strerror}", + file=sys.stderr, + ) + return "" def load(loader) -> None: @@ -662,7 +677,6 @@ def _rewrite_value(text: str) -> str: if __name__ == "__main__": import argparse import subprocess - import sys parser = argparse.ArgumentParser( description="Launch mitmweb with Roborock traffic interception.", diff --git a/src/roborock_local_server/config.py b/src/roborock_local_server/config.py index 6c68f017..ae9c588b 100644 --- a/src/roborock_local_server/config.py +++ b/src/roborock_local_server/config.py @@ -274,7 +274,7 @@ def _secret_value(section: dict[str, object], key: str, field_name: str, config_ A relative file path is resolved against the directory of the config file. Setting both forms is an error, because it is unclear which one should win. """ - inline = str(section.get(key, "") or "").strip() + inline = str(section.get(key, "")).strip() file_value = str(section.get(f"{key}_file", "") or "").strip() if not file_value: return inline diff --git a/tests/test_config.py b/tests/test_config.py index e0273716..bd720ffc 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -625,3 +625,9 @@ def test_secret_file_reports_missing_and_empty_files(tmp_path): (tmp_path / "session_secret").write_text("\n", encoding="utf-8") with pytest.raises(ValueError, match="admin.session_secret_file is empty"): load_config(path) + + +def test_inline_numeric_secret_keeps_its_value(tmp_path): + path = write_release_config(tmp_path) + path.write_text(path.read_text(encoding="utf-8").replace("[network]\n", "[network]\nmqtt_password = 0\n")) + assert load_config(path).network.mqtt_password == "0" diff --git a/tests/test_mitm_redirect.py b/tests/test_mitm_redirect.py index 73056e3e..2919dc41 100644 --- a/tests/test_mitm_redirect.py +++ b/tests/test_mitm_redirect.py @@ -276,3 +276,28 @@ def test_host_only_local_api_still_defaults_to_555(monkeypatch) -> None: assert (host, port) == ("api-rr.example.com", 555) assert env_authority == "api-rr.example.com:555" + + +def test_local_sync_secret_is_read_from_session_secret_file(monkeypatch, tmp_path) -> None: + mitm_redirect = _load_mitm_redirect(monkeypatch) + monkeypatch.setattr(mitm_redirect, "SCRIPT_DIR", str(tmp_path)) + (tmp_path / "secrets").mkdir() + (tmp_path / "secrets" / "session_secret").write_text("file-secret\n", encoding="utf-8") + (tmp_path / "config.toml").write_text( + '[admin]\nsession_secret_file = "secrets/session_secret"\n', + encoding="utf-8", + ) + + assert mitm_redirect._load_local_sync_secret() == "file-secret" + + +def test_unreadable_session_secret_file_is_reported(monkeypatch, tmp_path, capsys) -> None: + mitm_redirect = _load_mitm_redirect(monkeypatch) + monkeypatch.setattr(mitm_redirect, "SCRIPT_DIR", str(tmp_path)) + (tmp_path / "config.toml").write_text( + '[admin]\nsession_secret_file = "missing"\n', + encoding="utf-8", + ) + + assert mitm_redirect._load_local_sync_secret() == "" + assert "could not read admin.session_secret_file" in capsys.readouterr().err From 4fdcc08ebba096a4939e78c216a433037f489cd5 Mon Sep 17 00:00:00 2001 From: Mateusz Mazelanik Date: Sun, 29 Nov 2026 00:15:42 +0100 Subject: [PATCH 3/3] fix(mitm): resolve session_secret_file against the real config location --- mitm_redirect.py | 4 ++-- tests/test_mitm_redirect.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/mitm_redirect.py b/mitm_redirect.py index af3ac6d6..88696131 100644 --- a/mitm_redirect.py +++ b/mitm_redirect.py @@ -346,8 +346,8 @@ def _load_local_sync_secret() -> str: if not secret_file: return str(admin.get("session_secret") or "").strip() # A relative path is resolved against the directory of the config file, - # in the same way as the server does it. - secret_path = os.path.join(os.path.dirname(config_path), secret_file) + # after following symbolic links, in the same way as the server does it. + secret_path = os.path.join(os.path.dirname(os.path.realpath(config_path)), secret_file) try: with open(secret_path, encoding="utf-8") as handle: return handle.read().strip() diff --git a/tests/test_mitm_redirect.py b/tests/test_mitm_redirect.py index 2919dc41..8a705ff7 100644 --- a/tests/test_mitm_redirect.py +++ b/tests/test_mitm_redirect.py @@ -301,3 +301,18 @@ def test_unreadable_session_secret_file_is_reported(monkeypatch, tmp_path, capsy assert mitm_redirect._load_local_sync_secret() == "" assert "could not read admin.session_secret_file" in capsys.readouterr().err + + +def test_session_secret_file_is_relative_to_the_symlinked_config_target(monkeypatch, tmp_path) -> None: + mitm_redirect = _load_mitm_redirect(monkeypatch) + script_dir = tmp_path / "script" + config_dir = tmp_path / "config" + script_dir.mkdir() + config_dir.mkdir() + (config_dir / "session_secret").write_text("target-secret\n", encoding="utf-8") + (script_dir / "session_secret").write_text("wrong-secret\n", encoding="utf-8") + (config_dir / "config.toml").write_text('[admin]\nsession_secret_file = "session_secret"\n', encoding="utf-8") + (script_dir / "config.toml").symlink_to(config_dir / "config.toml") + monkeypatch.setattr(mitm_redirect, "SCRIPT_DIR", str(script_dir)) + + assert mitm_redirect._load_local_sync_secret() == "target-secret"