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/docs/installation.md b/docs/installation.md index b9331973..74af9d33 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -1,9 +1,10 @@ # Installation -Start here for a first-time setup. The project supports two installation methods: +Start here for a first-time setup. The project supports three installation methods: - Docker Compose on your own Linux host or VM - the Home Assistant add-on from this repository +- the NixOS module from this repository After the stack is running, continue with [Onboarding](onboarding.md) to pair a vacuum. @@ -143,6 +144,10 @@ If your model already has certificate notes on the tested-vacuums page, follow t Use [Home Assistant](home_assistant.md) as the installation guide if you want to run the stack as a Home Assistant add-on instead of Docker Compose. +## Method 3: NixOS + +Use [NixOS](nixos.md) as the installation guide if you want to run the stack as a NixOS service. + ## After The Stack Starts 1. Open the admin dashboard at `https://api-roborock.example.com:555/admin` by default, or `https://api-roborock.example.com:YOUR_HTTPS_PORT/admin` if you chose a custom HTTPS port. diff --git a/docs/nixos.md b/docs/nixos.md new file mode 100644 index 00000000..85804afa --- /dev/null +++ b/docs/nixos.md @@ -0,0 +1,159 @@ +# NixOS + +The repository is a Nix flake. It provides a package and a NixOS module that runs the server as a hardened systemd service. Read [Installation](installation.md) first. The requirements for DNS, the stack hostname and the choice of certificate apply here in the same way. + +## What The Module Does + +- It runs `roborock-local-server serve` as a systemd service with a dynamic, unprivileged user. +- It keeps all state in `/var/lib/roborock-local-server`. +- It writes the non-secret settings to `config.toml` in the Nix store. +- It passes secrets to the service as systemd credentials, so they never reach the Nix store. +- It starts the embedded Mosquitto broker and, if enabled, the coturn TURN relay, from the Nix store. +- It can serve a certificate from `security.acme` and restarts the service when the certificate is renewed. + +The module supports certificates that are provided by the host. The server's own Cloudflare certificate management (`tls.mode = "cloudflare_acme"`) is not available with the module. Use `security.acme` with the Cloudflare DNS provider instead, as shown below. + +## Create The Secrets + +The server needs three secrets. Create them with the package, for example in a temporary shell: + +```bash +nix shell github:Python-roborock/local_roborock_server +roborock-local-server hash-password # admin password hash +roborock-local-server hash-password # enter the 6-digit protocol login PIN +roborock-local-server generate-secret # admin session secret +``` + +Store each value in its own file and make the files readable by root only. A secret manager such as sops-nix or agenix works well for this. Any file path on the host is fine, because systemd reads the files as root when the service starts. + +The protocol login PIN is the 6-digit code that Home Assistant or the Roborock app enter together with the protocol login email. See [Credential Names](installation.md#credential-names). + +## Configure The Module + +Add the flake to your system flake and import the module: + +```nix +{ + inputs.roborock-local-server.url = "github:Python-roborock/local_roborock_server"; + + outputs = { nixpkgs, roborock-local-server, ... }: { + nixosConfigurations.myhost = nixpkgs.lib.nixosSystem { + modules = [ + roborock-local-server.nixosModules.default + ./configuration.nix + ]; + }; + }; +} +``` + +Then configure the service: + +```nix +{ + services.roborock-local-server = { + enable = true; + openFirewall = true; + + adminPasswordHashFile = "/run/secrets/roborock/admin-password-hash"; + sessionSecretFile = "/run/secrets/roborock/session-secret"; + protocolLoginPinHashFile = "/run/secrets/roborock/protocol-login-pin-hash"; + + useACMEHost = "example.com"; + + settings = { + network = { + stack_fqdn = "api-roborock.example.com"; + region = "eu"; + timezone = "Europe/Berlin"; + }; + admin.protocol_login_email = "you@example.com"; + }; + }; +} +``` + +`settings` accepts the settings from `config.example.toml` in the repository, with these exceptions: + +- Secrets are not allowed, because the Nix store is readable by every user. The module refuses to build if a secret is set in `settings`. Use the options that end in `File` instead. +- `storage.data_dir` is fixed to the state directory of the service. +- `tls.mode` only supports `provided`. See the certificate sections below. +- `network.localkey` and `network.mqtt_password` have no `File` option. Leave them unset, and the server generates them on the first start and keeps them in its state directory. + +The default ports are `555` for HTTPS and `8881` for MQTT TLS. Change them with `settings.network.https_port` and `settings.network.mqtt_tls_port`. `openFirewall` opens the ports that the server listens on. + +## Certificates From security.acme + +`useACMEHost` names a certificate from `security.acme.certs`. The certificate has to cover the stack hostname. If you use the camera, it also has to cover the camera hostname. See [Camera](camera.md). + +Vacuums differ in which certificate authorities they trust. NixOS defaults to Let's Encrypt with an EC key, which is not the combination that the server requests by itself. Check [Tested Vacuums](tested_vacuums.md) and set the certificate authority and key type to a combination that is known to work for your model. This example requests an RSA certificate from ZeroSSL through Cloudflare DNS: + +```nix +{ + security.acme = { + acceptTerms = true; + certs."example.com" = { + domain = "example.com"; + extraDomainNames = [ "*.example.com" ]; + email = "you@example.com"; + server = "https://acme.zerossl.com/v2/DV90"; + keyType = "rsa2048"; + dnsProvider = "cloudflare"; + environmentFile = "/run/secrets/roborock/acme-environment"; + }; + }; +} +``` + +The environment file holds the Cloudflare token and the External Account Binding credentials that ZeroSSL and Actalis require. You get the credentials from the dashboard of the certificate authority. + +```bash +CLOUDFLARE_DNS_API_TOKEN=... +LEGO_EAB=true +LEGO_EAB_KID=... +LEGO_EAB_HMAC=... +``` + +The service waits for the certificate before it starts. On the very first start, NixOS may serve a temporary self-signed certificate until the real one has been issued. The service is restarted as soon as the real certificate is available, and after every renewal. + +## Certificates From Files + +If you manage certificates in another way, point the module to the files instead of using `useACMEHost`: + +```nix +{ + services.roborock-local-server = { + certificateFile = "/var/lib/certificates/fullchain.pem"; + certificateKeyFile = "/var/lib/certificates/key.pem"; + }; +} +``` + +Restart the service after the files change, for example from the renewal hook of your certificate tool. + +## Reverse Proxy + +If a reverse proxy terminates TLS, set `settings.network.listener_mode = "external_tls"` and follow [Reverse Proxy](reverse_proxy.md). No certificate is needed in this mode. `openFirewall` does not open the HTTPS and MQTT ports in this mode, because the server then speaks plain HTTP and MQTT, which only the proxy should reach. The TURN ports are still opened if the server runs the TURN relay. + +## Camera TURN Relay + +To let the server run the TURN relay for the camera preview, set `settings.turn.mode = "provided"` together with the other `turn` settings from [Camera](camera.md), and put the TURN password in a file that `turnPasswordFile` points to. With `openFirewall`, the module also opens the TURN port and the UDP relay ports `49160` to `49179`. + +To use a TURN server that runs elsewhere, for example `services.coturn`, set `settings.turn.mode = "external"`. Make sure that the username, password and realm match the configuration of that server. + +## Dashboard Settings + +Turning protocol auth or new connections on or off in the admin dashboard is stored in the state directory. The values in `settings.admin` are the defaults. A dashboard change stays in effect across restarts until the corresponding value in `settings.admin` changes. + +## Backups + +Back up `/var/lib/private/roborock-local-server`, which is where systemd keeps the state of a service with a dynamic user. It holds device keys, credentials, the imported cloud data and the logs. Treat the backup like a secret. + +## Troubleshooting + +```bash +systemctl status roborock-local-server +journalctl -u roborock-local-server -f +``` + +The service is marked as running even if the optional TURN relay could not start. Check the log for warnings about the relay in that case. diff --git a/flake.lock b/flake.lock new file mode 100644 index 00000000..1c9a0949 --- /dev/null +++ b/flake.lock @@ -0,0 +1,99 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1795761588, + "narHash": "sha256-lyvlcjA/bJySrgwKiEoIYFNkDJM6aOck6/9gGRm9He4=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "78cc855faf4382e44b781c23bf9f456b924ef0e2", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "pyproject-build-systems": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ], + "pyproject-nix": [ + "pyproject-nix" + ], + "uv2nix": [ + "uv2nix" + ] + }, + "locked": { + "lastModified": 1794012432, + "narHash": "sha256-zBKFTg7tEGApNt+CEKI5+WNNomD5MZqYNBr+r6/Bmdg=", + "owner": "pyproject-nix", + "repo": "build-system-pkgs", + "rev": "bdbc5f8dd2ad6136bb2ccecb14f6ec343965b194", + "type": "github" + }, + "original": { + "owner": "pyproject-nix", + "repo": "build-system-pkgs", + "type": "github" + } + }, + "pyproject-nix": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1793820880, + "narHash": "sha256-NUMabnvaL/0Ah9WM9pBMXEp+dQjMSYjezZ/fNjXouLQ=", + "owner": "pyproject-nix", + "repo": "pyproject.nix", + "rev": "d43f0e74444c1f266c640fc49ce6ce6fb69d33c3", + "type": "github" + }, + "original": { + "owner": "pyproject-nix", + "repo": "pyproject.nix", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs", + "pyproject-build-systems": "pyproject-build-systems", + "pyproject-nix": "pyproject-nix", + "uv2nix": "uv2nix" + } + }, + "uv2nix": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ], + "pyproject-nix": [ + "pyproject-nix" + ] + }, + "locked": { + "lastModified": 1793272761, + "narHash": "sha256-3CE1CEwprYlHRlRVkXDkhqec0jjF9Cti7tdk8vVDsCM=", + "owner": "pyproject-nix", + "repo": "uv2nix", + "rev": "c361746c7d630d98b972378290547c8d35542a7a", + "type": "github" + }, + "original": { + "owner": "pyproject-nix", + "repo": "uv2nix", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 00000000..4fab0b1b --- /dev/null +++ b/flake.nix @@ -0,0 +1,99 @@ +{ + description = "Private local server for Roborock vacuums"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + + pyproject-nix = { + url = "github:pyproject-nix/pyproject.nix"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + + uv2nix = { + url = "github:pyproject-nix/uv2nix"; + inputs.pyproject-nix.follows = "pyproject-nix"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + + pyproject-build-systems = { + url = "github:pyproject-nix/build-system-pkgs"; + inputs.pyproject-nix.follows = "pyproject-nix"; + inputs.uv2nix.follows = "uv2nix"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + }; + + outputs = + { + self, + nixpkgs, + pyproject-nix, + uv2nix, + pyproject-build-systems, + }: + let + inherit (nixpkgs) lib; + + systems = [ + "x86_64-linux" + "aarch64-linux" + ]; + + forAllSystems = function: lib.genAttrs systems (system: function nixpkgs.legacyPackages.${system}); + + # The Python dependencies are taken from uv.lock, so the package uses + # exactly the versions that the project is tested with. The source only + # contains the files that are needed to build the package, so that changes + # to the documentation, the tests or the Nix files do not rebuild it. + workspace = uv2nix.lib.workspace.loadWorkspace { + workspaceRoot = lib.fileset.toSource { + root = ./.; + fileset = lib.fileset.unions [ + ./pyproject.toml + ./uv.lock + ./README.md + ./LICENSE + ./src + ]; + }; + }; + in + { + packages = forAllSystems (pkgs: { + roborock-local-server = pkgs.callPackage ./nix/package.nix { + inherit workspace pyproject-nix pyproject-build-systems; + }; + default = self.packages.${pkgs.stdenv.hostPlatform.system}.roborock-local-server; + }); + + nixosModules = { + roborock-local-server = import ./nix/module.nix self; + default = self.nixosModules.roborock-local-server; + }; + + checks = forAllSystems (pkgs: { + package = self.packages.${pkgs.stdenv.hostPlatform.system}.default; + nixos = pkgs.testers.runNixOSTest (import ./nix/test.nix self); + }); + + devShells = forAllSystems (pkgs: { + default = pkgs.mkShell { + packages = [ + pkgs.python312 + pkgs.uv + pkgs.mosquitto + pkgs.coturn + pkgs.openssl + pkgs.nixfmt + ]; + env = { + # Let uv manage the virtual environment with the Python from Nix. + UV_PYTHON = lib.getExe pkgs.python312; + UV_PYTHON_DOWNLOADS = "never"; + }; + }; + }); + + formatter = forAllSystems (pkgs: pkgs.nixfmt-tree); + }; +} diff --git a/mitm_redirect.py b/mitm_redirect.py index dec623c5..88696131 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, + # 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: @@ -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/mkdocs.yml b/mkdocs.yml index cf26ac8d..4ba9331c 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -51,6 +51,7 @@ nav: - Getting Started: - Installation: installation.md - Home Assistant: home_assistant.md + - NixOS: nixos.md - Cloudflare Setup: cloudflare_setup.md - Onboarding: onboarding.md - Updating: updating.md diff --git a/nix/module.nix b/nix/module.nix new file mode 100644 index 00000000..e83afcfc --- /dev/null +++ b/nix/module.nix @@ -0,0 +1,448 @@ +# NixOS module for the local Roborock server. +# +# The non-secret settings are written to config.toml in the Nix store. Secrets +# never enter the store. They are passed to the service as systemd credentials +# and referenced from config.toml with the "_file" variants of their keys. +self: + +{ + config, + lib, + pkgs, + ... +}: + +let + cfg = config.services.roborock-local-server; + + settingsFormat = pkgs.formats.toml { }; + + serviceName = "roborock-local-server"; + stateDirectory = "/var/lib/${serviceName}"; + credentialsDirectory = "/run/credentials/${serviceName}.service"; + + # Secrets that are passed as systemd credentials, keyed by credential name. + # Each entry lists the source file on the host and the config key that + # receives the path of the credential. + credentials = lib.filterAttrs (_: credential: credential.source != null) { + admin_password_hash = { + source = cfg.adminPasswordHashFile; + section = "admin"; + key = "password_hash_file"; + }; + admin_session_secret = { + source = cfg.sessionSecretFile; + section = "admin"; + key = "session_secret_file"; + }; + protocol_login_pin_hash = { + source = cfg.protocolLoginPinHashFile; + section = "admin"; + key = "protocol_login_pin_hash_file"; + }; + turn_password = { + source = cfg.turnPasswordFile; + section = "turn"; + key = "password_file"; + }; + tls_certificate = { + source = certificateSource; + section = "tls"; + key = "cert_file"; + }; + tls_key = { + source = keySource; + section = "tls"; + key = "key_file"; + }; + }; + + acmeDirectory = config.security.acme.certs.${cfg.useACMEHost}.directory; + + certificateSource = + if cfg.useACMEHost != null then "${acmeDirectory}/fullchain.pem" else cfg.certificateFile; + + keySource = if cfg.useACMEHost != null then "${acmeDirectory}/key.pem" else cfg.certificateKeyFile; + + credentialSettings = lib.foldlAttrs ( + settings: name: credential: + lib.recursiveUpdate settings { + ${credential.section}.${credential.key} = "${credentialsDirectory}/${name}"; + } + ) { } credentials; + + # Options that are null are left out, so that the server applies its own + # defaults for them. + configFile = settingsFormat.generate "roborock-local-server.toml" ( + lib.filterAttrsRecursive (_: value: value != null) ( + lib.recursiveUpdate cfg.settings credentialSettings + ) + ); + + # Inline secrets would end up in the world-readable Nix store. + inlineSecretKeys = [ + "admin.password_hash" + "admin.session_secret" + "admin.protocol_login_pin_hash" + "turn.password" + "network.localkey" + "network.mqtt_password" + "tls.acme_eab_kid" + "tls.acme_eab_hmac_key" + ]; + + inlineSecretsInSettings = lib.filter ( + path: lib.hasAttrByPath (lib.splitString "." path) cfg.settings + ) inlineSecretKeys; + + network = cfg.settings.network; + turn = cfg.settings.turn; + terminatesTls = network.listener_mode == "local_tls"; + providesTurn = turn.mode == "provided"; + + broker = cfg.settings.broker; + runsEmbeddedBroker = broker.mode == "embedded"; + + # Every port that the server or one of the programs it starts listens on. + listenerPorts = [ + network.https_port + network.mqtt_tls_port + ] + ++ lib.optional providesTurn turn.port + # The server uses port 18830 for the embedded broker when none is set. + ++ lib.optional runsEmbeddedBroker (if broker.port != null then broker.port else 18830); + + needsPrivilegedPorts = lib.any (port: port < 1024) listenerPorts; + + # The TURN relay started by the server uses this fixed range of UDP ports. + turnRelayPorts = { + from = 49160; + to = 49179; + }; + + # The server rejects port 0, which lib.types.port would allow. + serverPort = lib.types.ints.between 1 65535; + + absolutePathOption = + description: example: + lib.mkOption { + type = lib.types.nullOr (lib.types.strMatching "/.*"); + default = null; + inherit example; + description = '' + Absolute path to a file that contains the ${description}. + + The file is read by systemd when the service starts and is passed to the + server as a credential, so it can be owned by root and be readable only + by root. The path is a string on purpose, so that the file is not copied + into the Nix store. Restart the service after the file changes. + ''; + }; +in +{ + options.services.roborock-local-server = { + enable = lib.mkEnableOption "the local Roborock server"; + + package = lib.mkOption { + type = lib.types.package; + default = self.packages.${pkgs.stdenv.hostPlatform.system}.default; + defaultText = lib.literalExpression "roborock-local-server.packages.\${system}.default"; + description = "The roborock-local-server package to use."; + }; + + openFirewall = lib.mkOption { + type = lib.types.bool; + default = false; + description = '' + Whether to open the HTTPS and MQTT TLS ports in the firewall. When the + server runs the TURN relay itself, the TURN port and the relay port range + are opened as well. + + The HTTPS and MQTT ports are not opened when a reverse proxy terminates + TLS, because the server then speaks plain HTTP and MQTT, which should only + be reachable by the proxy. + ''; + }; + + adminPasswordHashFile = absolutePathOption "admin password hash, as printed by `roborock-local-server hash-password`" "/run/secrets/roborock/admin-password-hash"; + + sessionSecretFile = absolutePathOption "admin session secret of at least 24 characters, for example from `roborock-local-server generate-secret`" "/run/secrets/roborock/session-secret"; + + protocolLoginPinHashFile = absolutePathOption "hash of the 6-digit protocol login PIN, as printed by `roborock-local-server hash-password`" "/run/secrets/roborock/protocol-login-pin-hash"; + + turnPasswordFile = absolutePathOption "TURN password, which is required unless `settings.turn.mode` is `disabled`" "/run/secrets/roborock/turn-password"; + + certificateFile = absolutePathOption "TLS certificate chain in PEM format" "/var/lib/certificates/fullchain.pem"; + + certificateKeyFile = absolutePathOption "TLS private key in PEM format" "/var/lib/certificates/key.pem"; + + useACMEHost = lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = null; + example = "example.com"; + description = '' + Name of a certificate from {option}`security.acme.certs` to serve. The + service is restarted whenever the certificate is renewed. + + The certificate must cover the stack hostname and any other names the + vacuums use. Not every vacuum trusts every certificate authority, so set + {option}`security.acme.certs..server` and + {option}`security.acme.certs..keyType` to a combination that is + known to work with your vacuum. + ''; + }; + + settings = lib.mkOption { + description = '' + Settings written to config.toml. See config.example.toml in the source + repository for all available settings. + + Do not put secrets here, because the file is stored in the Nix store. + Use the options ending in `File` instead. + ''; + default = { }; + type = lib.types.submodule { + freeformType = settingsFormat.type; + + options = { + network = { + stack_fqdn = lib.mkOption { + type = lib.types.str; + example = "api-roborock.example.com"; + description = '' + The hostname of the server. It must start with `api-`. The server + checks the hostname when it starts. + ''; + }; + + listener_mode = lib.mkOption { + type = lib.types.enum [ + "local_tls" + "external_tls" + ]; + default = "local_tls"; + description = '' + Whether the server terminates TLS itself, or a reverse proxy in front + of it does. + ''; + }; + + https_port = lib.mkOption { + type = serverPort; + default = 555; + description = "Port of the HTTPS listener."; + }; + + mqtt_tls_port = lib.mkOption { + type = serverPort; + default = 8881; + description = "Port of the MQTT TLS listener."; + }; + }; + + storage.data_dir = lib.mkOption { + type = lib.types.str; + default = stateDirectory; + readOnly = true; + description = "Directory that holds all state of the server."; + }; + + tls.mode = lib.mkOption { + type = lib.types.enum [ "provided" ]; + default = "provided"; + description = '' + How the server gets its certificate. Only certificates provided by the + host are supported, either from files or from {option}`security.acme`. + ''; + }; + + admin.protocol_login_email = lib.mkOption { + type = lib.types.strMatching ".+@.+"; + example = "you@example.com"; + description = '' + Email address that Home Assistant and the Roborock app use to log in to + the server. + ''; + }; + + broker = { + mode = lib.mkOption { + type = lib.types.enum [ + "embedded" + "external" + ]; + default = "embedded"; + description = '' + Whether the server runs its own Mosquitto broker, or connects to an + existing one at `broker.host` and `broker.port`. + ''; + }; + + port = lib.mkOption { + type = lib.types.nullOr serverPort; + default = null; + description = '' + Port of the MQTT broker. When it is not set, the server uses 18830 for + the embedded broker and 1883 for an external one. + ''; + }; + }; + + turn = { + mode = lib.mkOption { + type = lib.types.enum [ + "disabled" + "provided" + "external" + ]; + default = "disabled"; + description = '' + Whether to run a TURN relay for the camera preview inside the server, + to advertise an external TURN server, or to do neither. + ''; + }; + + port = lib.mkOption { + type = serverPort; + default = 3478; + description = "UDP port of the TURN server."; + }; + }; + }; + }; + }; + }; + + config = lib.mkIf cfg.enable { + assertions = [ + { + assertion = !(cfg.settings.turn ? enabled); + message = '' + services.roborock-local-server.settings.turn.enabled is an old form of the + TURN settings. Use settings.turn.mode instead. + ''; + } + { + assertion = inlineSecretsInSettings == [ ]; + message = '' + services.roborock-local-server.settings must not contain secrets, because + they would be stored in the world-readable Nix store. Found: + ${lib.concatStringsSep ", " inlineSecretsInSettings}. Use the options + ending in File instead. + ''; + } + { + assertion = + cfg.adminPasswordHashFile != null + && cfg.sessionSecretFile != null + && cfg.protocolLoginPinHashFile != null; + message = '' + services.roborock-local-server requires adminPasswordHashFile, + sessionSecretFile and protocolLoginPinHashFile. + ''; + } + { + assertion = turn.mode == "disabled" || cfg.turnPasswordFile != null; + message = "services.roborock-local-server.turnPasswordFile is required when turn.mode is not disabled."; + } + { + assertion = + cfg.useACMEHost == null || (cfg.certificateFile == null && cfg.certificateKeyFile == null); + message = "services.roborock-local-server.useACMEHost cannot be combined with certificateFile or certificateKeyFile."; + } + { + assertion = + !terminatesTls + || cfg.useACMEHost != null + || (cfg.certificateFile != null && cfg.certificateKeyFile != null); + message = '' + services.roborock-local-server needs a certificate. Set useACMEHost, or both + certificateFile and certificateKeyFile. + ''; + } + ]; + + security.acme.certs = lib.mkIf (cfg.useACMEHost != null) { + ${cfg.useACMEHost}.reloadServices = [ "${serviceName}.service" ]; + }; + + # Behind a reverse proxy, the HTTPS and MQTT listeners speak plain text and + # stay closed. The TURN relay is reached directly by the vacuums, so it is + # opened in both cases. + networking.firewall = lib.mkIf cfg.openFirewall { + allowedTCPPorts = lib.optionals terminatesTls [ + network.https_port + network.mqtt_tls_port + ]; + allowedUDPPorts = lib.optional providesTurn turn.port; + allowedUDPPortRanges = lib.optional providesTurn turnRelayPorts; + }; + + systemd.services.${serviceName} = { + description = "Local Roborock server"; + documentation = [ "https://github.com/Python-roborock/local_roborock_server" ]; + + wantedBy = [ "multi-user.target" ]; + wants = [ + "network-online.target" + ] + ++ lib.optional (cfg.useACMEHost != null) "acme-${cfg.useACMEHost}.service"; + after = [ + "network-online.target" + ] + ++ lib.optional (cfg.useACMEHost != null) "acme-${cfg.useACMEHost}.service"; + + # Restart the server when its settings change. + restartTriggers = [ configFile ]; + + serviceConfig = { + ExecStart = "${lib.getExe cfg.package} serve --config ${configFile}"; + Restart = "on-failure"; + RestartSec = 5; + + # Credentials are copies that systemd takes when the service starts. The + # server reloads certificate files that change, but it never sees a new + # version of a credential, and it cannot reload its settings. So there is + # no ExecReload, and systemd restarts the service instead, for example + # after a certificate renewal. Every start reads the credentials again. + LoadCredential = lib.mapAttrsToList (name: credential: "${name}:${credential.source}") credentials; + + DynamicUser = true; + StateDirectory = serviceName; + StateDirectoryMode = "0700"; + WorkingDirectory = stateDirectory; + UMask = "0077"; + + AmbientCapabilities = lib.optional needsPrivilegedPorts "CAP_NET_BIND_SERVICE"; + # An empty string clears the bounding set. An empty list would leave + # out the setting and keep the default set of systemd. + CapabilityBoundingSet = if needsPrivilegedPorts then [ "CAP_NET_BIND_SERVICE" ] else [ "" ]; + + NoNewPrivileges = true; + PrivateTmp = true; + PrivateDevices = true; + ProtectSystem = "strict"; + ProtectHome = true; + ProtectClock = true; + ProtectHostname = true; + ProtectKernelLogs = true; + ProtectKernelModules = true; + ProtectKernelTunables = true; + ProtectControlGroups = true; + ProtectProc = "invisible"; + RestrictAddressFamilies = [ + "AF_INET" + "AF_INET6" + "AF_UNIX" + ] + # The TURN relay lists the network interfaces through netlink. + ++ lib.optional providesTurn "AF_NETLINK"; + RestrictNamespaces = true; + RestrictRealtime = true; + RestrictSUIDSGID = true; + LockPersonality = true; + RemoveIPC = true; + }; + }; + }; +} diff --git a/nix/package.nix b/nix/package.nix new file mode 100644 index 00000000..694c3ec8 --- /dev/null +++ b/nix/package.nix @@ -0,0 +1,108 @@ +# Builds the server from the uv.lock of this repository. +# +# The Python environment is assembled by uv2nix, which installs the locked +# wheels from PyPI. The resulting program is wrapped so that it finds the +# external tools it starts at runtime: Mosquitto for the embedded MQTT broker, +# coturn for the optional TURN relay, and OpenSSL and curl for certificate work. +# The server looks for acme.sh at a fixed path of the container image, which is +# replaced with acme.sh from Nix. +{ + lib, + callPackage, + stdenvNoCC, + makeWrapper, + python312, + mosquitto, + coturn, + openssl, + curl, + acme-sh, + workspace, + pyproject-nix, + pyproject-build-systems, +}: + +let + pythonSet = (callPackage pyproject-nix.build.packages { python = python312; }).overrideScope ( + lib.composeManyExtensions [ + pyproject-build-systems.overlays.wheel + (workspace.mkPyprojectOverlay { sourcePreference = "wheel"; }) + (final: prev: { + roborock-local-server = prev.roborock-local-server.overrideAttrs (old: { + postPatch = (old.postPatch or "") + '' + substituteInPlace src/roborock_local_server/certs.py \ + --replace-fail '"/opt/acme.sh/acme.sh"' '"${lib.getExe acme-sh}"' + ''; + }); + }) + ] + ); + + venv = pythonSet.mkVirtualEnv "roborock-local-server-env" workspace.deps.default; + + application = pythonSet.roborock-local-server; +in +stdenvNoCC.mkDerivation { + pname = "roborock-local-server"; + inherit (application) version; + + dontUnpack = true; + + nativeBuildInputs = [ makeWrapper ]; + + installPhase = '' + runHook preInstall + + makeWrapper ${venv}/bin/roborock-local-server $out/bin/roborock-local-server \ + --prefix PATH : ${ + lib.makeBinPath [ + mosquitto + coturn + openssl + curl + ] + } + + runHook postInstall + ''; + + doInstallCheck = true; + + installCheckPhase = '' + runHook preInstallCheck + + $out/bin/roborock-local-server --help > /dev/null + + # Check that acme.sh is found. The native extensions come from prebuilt + # wheels, so use each of them once to make sure that their shared libraries + # load. + ${venv}/bin/python -c ' + from roborock_local_server.certs import ACME_SH_PATH + assert ACME_SH_PATH.is_file(), ACME_SH_PATH + + import gmpy2 + from Crypto.Cipher import AES + from cryptography.hazmat.primitives.asymmetric import rsa + from PIL import Image + + assert gmpy2.mpz(2) ** 64 == 18446744073709551616 + AES.new(bytes(16), AES.MODE_ECB).encrypt(bytes(16)) + rsa.generate_private_key(public_exponent=65537, key_size=2048) + Image.new("RGB", (1, 1)).tobytes() + ' + + runHook postInstallCheck + ''; + + passthru = { + inherit venv pythonSet; + }; + + meta = { + description = "Private local server for Roborock vacuums"; + homepage = "https://github.com/Python-roborock/local_roborock_server"; + license = lib.licenses.mit; + mainProgram = "roborock-local-server"; + platforms = lib.platforms.linux; + }; +} diff --git a/nix/test.nix b/nix/test.nix new file mode 100644 index 00000000..38442492 --- /dev/null +++ b/nix/test.nix @@ -0,0 +1,210 @@ +# Integration test of the NixOS module. +# +# The "server" machine terminates TLS itself with a self-signed certificate. +# The "proxied" machine is configured for a reverse proxy that terminates TLS, +# so its HTTPS and MQTT ports must stay closed. It listens on unprivileged +# ports, except for the embedded MQTT broker, which is moved to a privileged +# port to check that the service may still bind it. Both run the embedded MQTT +# broker and the TURN relay. A client machine checks which ports are reachable +# through the firewall and allocates TURN relays on both servers. The test also +# checks that dashboard changes survive a restart and that no secret ends up in +# the generated config file. +self: + +{ lib, pkgs, ... }: + +let + serverFqdn = "api-roborock.test"; + proxiedFqdn = "api-proxied.test"; + adminPassword = "correct horse battery staple"; + protocolLoginPin = "123456"; + turnPassword = "turn-test-password"; + + # Every machine resolves the stack hostnames to the matching server. + hosts = + { nodes, ... }: + { + networking.hosts = { + ${nodes.server.networking.primaryIPAddress} = [ serverFqdn ]; + ${nodes.proxied.networking.primaryIPAddress} = [ proxiedFqdn ]; + }; + }; + + # A self-signed certificate is enough to test the TLS listeners. It is only + # used inside the test, so it may live in the Nix store. + certificate = + pkgs.runCommand "roborock-test-certificate" { nativeBuildInputs = [ pkgs.openssl ]; } + '' + mkdir $out + openssl req -x509 -newkey rsa:2048 -nodes -days 3650 \ + -subj "/CN=${serverFqdn}" -addext "subjectAltName=DNS:${serverFqdn}" \ + -keyout $out/key.pem -out $out/fullchain.pem + ''; + + serverMachine = + { + stackFqdn, + listenerMode, + httpsPort, + mqttTlsPort, + brokerPort, + }: + { config, ... }: + { + imports = [ + self.nixosModules.default + hosts + ]; + + services.roborock-local-server = { + enable = true; + openFirewall = true; + adminPasswordHashFile = "/run/roborock-secrets/admin-password-hash"; + sessionSecretFile = "/run/roborock-secrets/session-secret"; + protocolLoginPinHashFile = "/run/roborock-secrets/protocol-login-pin-hash"; + turnPasswordFile = "/run/roborock-secrets/turn-password"; + settings = { + network = { + stack_fqdn = stackFqdn; + listener_mode = listenerMode; + https_port = httpsPort; + mqtt_tls_port = mqttTlsPort; + }; + broker.port = brokerPort; + admin.protocol_login_email = "user@example.com"; + turn = { + mode = "provided"; + host = stackFqdn; + }; + }; + } + // lib.optionalAttrs (listenerMode == "local_tls") { + certificateFile = "${certificate}/fullchain.pem"; + certificateKeyFile = "${certificate}/key.pem"; + }; + + # Secrets are created at runtime, as a secret manager would do. The test + # passwords themselves are part of this script, but the generated + # hashes and the session secret only exist at runtime, so the test can + # check that none of them reach the generated config file. + systemd.services.roborock-test-secrets = { + wantedBy = [ "roborock-local-server.service" ]; + before = [ "roborock-local-server.service" ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + }; + script = + let + server = lib.getExe config.services.roborock-local-server.package; + in + '' + install -d -m 0700 /run/roborock-secrets + cd /run/roborock-secrets + umask 0077 + ${server} hash-password --password '${adminPassword}' > admin-password-hash + ${server} hash-password --password '${protocolLoginPin}' > protocol-login-pin-hash + ${server} generate-secret > session-secret + echo '${turnPassword}' > turn-password + ''; + }; + }; +in +{ + name = "roborock-local-server"; + + nodes = { + server = serverMachine { + stackFqdn = serverFqdn; + listenerMode = "local_tls"; + httpsPort = 555; + mqttTlsPort = 8881; + brokerPort = 18830; + }; + + proxied = serverMachine { + stackFqdn = proxiedFqdn; + listenerMode = "external_tls"; + httpsPort = 8555; + mqttTlsPort = 8881; + brokerPort = 188; + }; + + client = { + imports = [ hosts ]; + environment.systemPackages = [ + pkgs.openssl + pkgs.coturn + ]; + }; + }; + + testScript = '' + import json + + start_all() + + for machine, https_port in [(server, 555), (proxied, 8555)]: + machine.wait_for_unit("roborock-local-server.service") + machine.wait_for_open_port(https_port) + machine.wait_for_open_port(8881) + machine.wait_until_succeeds("ss --listening --udp --numeric | grep -q ':3478 '") + + with subtest("The embedded MQTT broker runs as a child of the service"): + server.succeed("systemctl status roborock-local-server.service | grep -q mosquitto") + + with subtest("The service runs unprivileged and keeps its state in the state directory"): + user = server.succeed("systemctl show -P User roborock-local-server.service").strip() + assert user == "roborock-local-server", user + capabilities = server.succeed("systemctl show -P CapabilityBoundingSet roborock-local-server.service").strip() + assert capabilities == "cap_net_bind_service", capabilities + server.succeed("test -d /var/lib/private/roborock-local-server/state") + + with subtest("No secret is written to the generated config file"): + command = server.succeed("systemctl show -P ExecStart roborock-local-server.service") + config_file = next(word for word in command.split() if word.endswith(".toml")) + config = server.succeed(f"cat {config_file}") + for name in ["admin-password-hash", "protocol-login-pin-hash", "session-secret", "turn-password"]: + secret = server.succeed(f"cat /run/roborock-secrets/{name}").strip() + assert secret not in config, f"{name} found in {config_file}" + + with subtest("The TLS listeners are reachable through the firewall"): + client.wait_until_succeeds("curl --silent --insecure --fail https://${serverFqdn}:555/admin") + client.succeed("openssl s_client -connect ${serverFqdn}:8881 -servername ${serverFqdn} < /dev/null") + + with subtest("An embedded broker on a privileged port can start"): + proxied.wait_for_open_port(188) + proxied.succeed("systemctl status roborock-local-server.service | grep -q mosquitto") + + with subtest("Behind a reverse proxy, the plain listeners stay closed"): + proxied.succeed("curl --silent --fail http://localhost:8555/admin") + client.fail("curl --silent --connect-timeout 3 http://${proxiedFqdn}:8555/admin") + client.fail("timeout 5 bash -c '< /dev/tcp/${proxiedFqdn}/8881'") + + with subtest("A client can allocate a relay on both TURN servers"): + for fqdn in ["${serverFqdn}", "${proxiedFqdn}"]: + client.succeed( + f"timeout 30 turnutils_uclient -n 1 -m 1 -y -u roborock -w '${turnPassword}' {fqdn}" + ) + + def admin(method, path, body=None): + data = f"--data '{json.dumps(body)}' --header 'Content-Type: application/json'" if body else "" + output = server.succeed( + f"curl --silent --insecure --fail --cookie-jar /tmp/cookies --cookie /tmp/cookies " + f"--request {method} {data} https://localhost:555{path}" + ) + return json.loads(output) + + with subtest("Dashboard toggles survive a restart"): + admin("POST", "/admin/api/login", {"password": "${adminPassword}"}) + changed = admin("POST", "/admin/api/auth", {"new_connections_enabled": False}) + assert changed["new_connections_enabled"] is False, changed + + server.systemctl("restart roborock-local-server.service") + server.wait_for_open_port(555) + + admin("POST", "/admin/api/login", {"password": "${adminPassword}"}) + current = admin("GET", "/admin/api/auth") + assert current["new_connections_enabled"] is False, current + ''; +} 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/config.py b/src/roborock_local_server/config.py index 6fb12c5e..ae9c588b 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, "")).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/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_config.py b/tests/test_config.py index ba569588..bd720ffc 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -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" 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 diff --git a/tests/test_mitm_redirect.py b/tests/test_mitm_redirect.py index 73056e3e..8a705ff7 100644 --- a/tests/test_mitm_redirect.py +++ b/tests/test_mitm_redirect.py @@ -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"