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
5 changes: 5 additions & 0 deletions config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 16 additions & 2 deletions mitm_redirect.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import os
import re
import ssl
import sys
import tomllib
from urllib.parse import urlsplit
from urllib.error import HTTPError
Expand Down Expand Up @@ -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,
# 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()
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:
Expand Down Expand Up @@ -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.",
Expand Down
43 changes: 37 additions & 6 deletions src/roborock_local_server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, "")).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")
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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",
),
),
Expand All @@ -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),
),
Expand Down
74 changes: 74 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -557,3 +557,77 @@ 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)


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"
40 changes: 40 additions & 0 deletions tests/test_mitm_redirect.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,3 +276,43 @@ 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


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"