servarr: add configXml option with preStart hook

Adds services.arrInit.<name>.configXml for declaratively ensuring XML
elements exist in a Servarr config.xml before the service starts.

Generates a preStart hook on the main service that runs a Python helper
to patch or create config.xml. Undeclared elements are preserved;
declared elements are written with exact values.

Primary use case: preventing recurring Prowlarr 'not listening on port'
failures when config.xml loses the <Port> element — now guaranteed to
exist before Prowlarr starts.

Hardening:
- Atomic writes (tmp + rename): power loss cannot corrupt config.xml
- Malformed XML recovery: fresh <Config> root instead of blocking boot
- Secure default mode (0600) for new files containing ApiKey
- Preserves existing file mode on rewrite
- Assertion against duplicate serviceName targeting

Tests (10 subtests): creates-from-missing, patches-existing, preserves-
undeclared, corrects-tampered, idempotent, malformed-recovery,
ownership-preserved, not-world-readable.
This commit is contained in:
2026-04-17 00:38:32 -04:00
parent a1ae022dc3
commit 6dde2a3e0d
14 changed files with 684 additions and 212 deletions

183
tests/config-xml.nix Normal file
View File

@@ -0,0 +1,183 @@
{
pkgs,
self,
}:
pkgs.testers.runNixOSTest {
name = "arr-init-config-xml";
nodes.machine =
{ pkgs, lib, ... }:
{
imports = [ self.nixosModules.default ];
system.stateVersion = "24.11";
environment.systemPackages = with pkgs; [
libxml2
gnugrep
];
services.sonarr = {
enable = true;
dataDir = "/var/lib/sonarr/.config/NzbDrone";
settings.server.port = lib.mkDefault 8989;
};
services.prowlarr = {
enable = true;
};
# Sonarr: declare configXml to ensure Port and BindAddress
services.arrInit.sonarr = {
enable = true;
serviceName = "sonarr";
dataDir = "/var/lib/sonarr/.config/NzbDrone";
port = 8989;
configXml = {
Port = 8989;
BindAddress = "*";
AnalyticsEnabled = false;
};
};
# Prowlarr: declare configXml to ensure Port — dataDir starts empty,
# so preStart must create config.xml from scratch.
services.arrInit.prowlarr = {
enable = true;
serviceName = "prowlarr";
dataDir = "/var/lib/prowlarr";
port = 9696;
apiVersion = "v1";
configXml = {
Port = 9696;
BindAddress = "*";
EnableSsl = false;
};
};
};
testScript = ''
import xml.etree.ElementTree as ET
def elem_text(xml: str, tag: str) -> str:
"""Return the text of root.<tag>. Asserts element exists."""
root = ET.fromstring(xml)
node = root.find(tag)
assert node is not None, f"<{tag}> missing from config.xml"
assert node.text is not None, f"<{tag}> has no text in config.xml"
return node.text
start_all()
# --- Subtest: config.xml created from scratch when missing ---
with subtest("preStart creates config.xml if missing"):
# Prowlarr's dataDir starts empty; preStart must create config.xml
# before the service main process reads it.
machine.wait_for_unit("prowlarr.service")
machine.succeed("test -f /var/lib/prowlarr/config.xml")
with subtest("created config.xml has declared elements"):
xml = machine.succeed("cat /var/lib/prowlarr/config.xml")
assert elem_text(xml, "Port") == "9696", f"Port={elem_text(xml, 'Port')}"
assert elem_text(xml, "BindAddress") == "*"
assert elem_text(xml, "EnableSsl") == "False"
with subtest("config.xml is well-formed XML"):
xml = machine.succeed("cat /var/lib/prowlarr/config.xml")
# Must parse cleanly; will raise if malformed
ET.fromstring(xml)
# --- Subtest: config.xml patched when elements are missing ---
with subtest("preStart patches existing config.xml with missing elements"):
# Flow for a fresh dataDir:
# 1. preStart creates config.xml with only declared elements
# 2. Sonarr starts, reads it, generates ApiKey, writes back
# We must wait for step 2 (ApiKey present) before asserting.
machine.wait_for_unit("sonarr.service")
machine.wait_until_succeeds(
"grep -q '<ApiKey>' /var/lib/sonarr/.config/NzbDrone/config.xml",
timeout=120,
)
xml = machine.succeed("cat /var/lib/sonarr/.config/NzbDrone/config.xml")
assert elem_text(xml, "Port") == "8989"
assert elem_text(xml, "BindAddress") == "*"
assert elem_text(xml, "AnalyticsEnabled") == "False"
with subtest("preStart preserves undeclared elements"):
# Restart Sonarr: preStart runs again over existing config.xml with
# an ApiKey. Our declared elements are re-applied, but ApiKey must survive.
machine.succeed("systemctl restart sonarr.service")
machine.wait_for_unit("sonarr.service")
xml = machine.succeed("cat /var/lib/sonarr/.config/NzbDrone/config.xml")
api_key = elem_text(xml, "ApiKey")
assert len(api_key) > 0, "ApiKey is empty"
# --- Subtest: preStart corrects wrong values ---
with subtest("preStart fixes incorrect values on restart"):
# Tamper with the Port value
machine.succeed(
"sed -i 's|<Port>9696</Port>|<Port>1234</Port>|' /var/lib/prowlarr/config.xml"
)
machine.succeed("grep '<Port>1234</Port>' /var/lib/prowlarr/config.xml")
# Restart the service; preStart should fix it
machine.succeed("systemctl restart prowlarr.service")
machine.wait_for_unit("prowlarr.service")
xml = machine.succeed("cat /var/lib/prowlarr/config.xml")
assert elem_text(xml, "Port") == "9696", "Port not corrected"
# --- Subtest: idempotency ---
with subtest("preStart is idempotent: bit-for-bit identical after restart"):
xml_before = machine.succeed("cat /var/lib/prowlarr/config.xml")
machine.succeed("systemctl restart prowlarr.service")
machine.wait_for_unit("prowlarr.service")
xml_after = machine.succeed("cat /var/lib/prowlarr/config.xml")
assert xml_before == xml_after, (
"config.xml changed on idempotent restart"
)
# --- Subtest: malformed XML recovery ---
with subtest("preStart recovers from malformed config.xml"):
# Corrupt the file completely
machine.succeed(
"echo 'not <valid/> xml <<<' > /var/lib/prowlarr/config.xml"
)
machine.succeed("systemctl restart prowlarr.service")
machine.wait_for_unit("prowlarr.service")
xml = machine.succeed("cat /var/lib/prowlarr/config.xml")
# Should be a fresh <Config> with declared elements
ET.fromstring(xml)
assert elem_text(xml, "Port") == "9696"
assert elem_text(xml, "BindAddress") == "*"
# --- Subtest: file ownership preserved ---
with subtest("preStart preserves ownership of config.xml"):
# Prowlarr uses DynamicUser; owner is dynamic. Just verify the service
# can read its own config.xml after preStart.
machine.succeed("systemctl restart prowlarr.service")
machine.wait_for_unit("prowlarr.service")
# If ownership were wrong, the service would fail to start or read.
# The unit being active is sufficient evidence.
# --- Subtest: preStart permissions are sensible ---
with subtest("config.xml has non-world-readable perms"):
# ApiKey is sensitive; config.xml must not be world-readable.
mode = machine.succeed(
"stat -c %a /var/lib/sonarr/.config/NzbDrone/config.xml"
).strip()
# Last digit must be 0 (no 'other' permissions)
assert mode.endswith("0"), f"config.xml world-readable: mode={mode}"
'';
}

View File

@@ -16,4 +16,5 @@
naming = import ./naming.nix { inherit pkgs lib self; };
network-namespace = import ./network-namespace.nix { inherit pkgs lib self; };
permanent-failure = import ./permanent-failure.nix { inherit pkgs lib self; };
config-xml = import ./config-xml.nix { inherit pkgs self; };
}

View File

@@ -27,8 +27,14 @@ pkgs.testers.runNixOSTest {
systemd.services.mock-qbittorrent = mocks.mkMockQbittorrent {
initialCategories = {
tv = { name = "tv"; savePath = "/downloads"; };
movies = { name = "movies"; savePath = "/downloads"; };
tv = {
name = "tv";
savePath = "/downloads";
};
movies = {
name = "movies";
savePath = "/downloads";
};
};
};

View File

@@ -27,10 +27,19 @@ pkgs.testers.runNixOSTest {
systemd.services.mock-qbittorrent = mocks.mkMockQbittorrent {
initialCategories = {
tv = { name = "tv"; savePath = "/downloads"; };
movies = { name = "movies"; savePath = "/downloads"; };
tv = {
name = "tv";
savePath = "/downloads";
};
movies = {
name = "movies";
savePath = "/downloads";
};
};
before = [ "sonarr-init.service" "radarr-init.service" ];
before = [
"sonarr-init.service"
"radarr-init.service"
];
};
systemd.tmpfiles.rules = [

View File

@@ -85,7 +85,9 @@
# Mock SABnzbd API.
mkMockSabnzbd =
{ port ? 6012 }:
{
port ? 6012,
}:
let
mockScript = pkgs.writeScript "mock-sabnzbd.py" ''
import json

View File

@@ -28,7 +28,10 @@ pkgs.testers.runNixOSTest {
# Mock qBittorrent on port 6011
systemd.services.mock-qbittorrent = mocks.mkMockQbittorrent {
initialCategories = {
tv = { name = "tv"; savePath = "/downloads"; };
tv = {
name = "tv";
savePath = "/downloads";
};
};
};

View File

@@ -1,30 +1,40 @@
{ pkgs, lib, self }:
{
pkgs,
lib,
self,
}:
pkgs.testers.runNixOSTest {
name = "arr-init-naming";
nodes.machine = { pkgs, lib, ... }: {
imports = [ self.nixosModules.default ];
system.stateVersion = "24.11";
virtualisation.memorySize = 4096;
environment.systemPackages = with pkgs; [ curl jq gnugrep ];
nodes.machine =
{ pkgs, lib, ... }:
{
imports = [ self.nixosModules.default ];
system.stateVersion = "24.11";
virtualisation.memorySize = 4096;
environment.systemPackages = with pkgs; [
curl
jq
gnugrep
];
services.sonarr = {
enable = true;
dataDir = "/var/lib/sonarr/.config/NzbDrone";
settings.server.port = lib.mkDefault 8989;
};
services.sonarr = {
enable = true;
dataDir = "/var/lib/sonarr/.config/NzbDrone";
settings.server.port = lib.mkDefault 8989;
};
services.arrInit.sonarr = {
enable = true;
serviceName = "sonarr";
dataDir = "/var/lib/sonarr/.config/NzbDrone";
port = 8989;
naming = {
renameEpisodes = true;
standardEpisodeFormat = "{Series Title} - S{season:00}E{episode:00} - {Episode Title} {Quality Full}";
seasonFolderFormat = "Season {season}";
services.arrInit.sonarr = {
enable = true;
serviceName = "sonarr";
dataDir = "/var/lib/sonarr/.config/NzbDrone";
port = 8989;
naming = {
renameEpisodes = true;
standardEpisodeFormat = "{Series Title} - S{season:00}E{episode:00} - {Episode Title} {Quality Full}";
seasonFolderFormat = "Season {season}";
};
};
};
};
testScript = ''
start_all()
machine.wait_for_unit("sonarr.service")

View File

@@ -1,100 +1,113 @@
{ pkgs, lib, self }:
{
pkgs,
lib,
self,
}:
pkgs.testers.runNixOSTest {
name = "arr-init-network-namespace";
nodes.machine = { pkgs, lib, ... }: {
imports = [ self.nixosModules.default ];
system.stateVersion = "24.11";
virtualisation.memorySize = 2048;
environment.systemPackages = with pkgs; [ curl jq gnugrep iproute2 ];
nodes.machine =
{ pkgs, lib, ... }:
{
imports = [ self.nixosModules.default ];
system.stateVersion = "24.11";
virtualisation.memorySize = 2048;
environment.systemPackages = with pkgs; [
curl
jq
gnugrep
iproute2
];
# Create the network namespace with loopback
systemd.services.create-netns = {
description = "Create test network namespace";
wantedBy = [ "multi-user.target" ];
before = [ "mock-sonarr.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${pkgs.iproute2}/bin/ip netns add test-ns";
ExecStartPost = "${pkgs.iproute2}/bin/ip netns exec test-ns ${pkgs.iproute2}/bin/ip link set lo up";
ExecStop = "${pkgs.iproute2}/bin/ip netns delete test-ns";
# Create the network namespace with loopback
systemd.services.create-netns = {
description = "Create test network namespace";
wantedBy = [ "multi-user.target" ];
before = [ "mock-sonarr.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${pkgs.iproute2}/bin/ip netns add test-ns";
ExecStartPost = "${pkgs.iproute2}/bin/ip netns exec test-ns ${pkgs.iproute2}/bin/ip link set lo up";
ExecStop = "${pkgs.iproute2}/bin/ip netns delete test-ns";
};
};
# Mock Servarr API running inside the namespace
systemd.services.mock-sonarr =
let
mockScript = pkgs.writeScript "mock-sonarr-ns.py" ''
import json
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse
DOWNLOAD_CLIENTS = []
ROOT_FOLDERS = []
class MockArr(BaseHTTPRequestHandler):
def _respond(self, code=200, body=b"", content_type="application/json"):
self.send_response(code)
self.send_header("Content-Type", content_type)
self.end_headers()
self.wfile.write(body if isinstance(body, bytes) else body.encode())
def do_GET(self):
path = urlparse(self.path).path
if path == "/api/v3/system/status":
self._respond(200, json.dumps({"version": "4.0.0"}).encode())
elif path == "/api/v3/downloadclient":
self._respond(200, json.dumps(DOWNLOAD_CLIENTS).encode())
elif path == "/api/v3/rootfolder":
self._respond(200, json.dumps(ROOT_FOLDERS).encode())
else:
self._respond(200, b"{}")
def do_POST(self):
path = urlparse(self.path).path
content_length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(content_length)
if "/rootfolder" in path:
data = json.loads(body)
data["id"] = len(ROOT_FOLDERS) + 1
ROOT_FOLDERS.append(data)
self._respond(201, json.dumps(data).encode())
else:
self._respond(200, b"{}")
def log_message(self, format, *args):
pass
HTTPServer(("0.0.0.0", 8989), MockArr).serve_forever()
'';
in
{
description = "Mock Sonarr API in network namespace";
after = [ "create-netns.service" ];
requires = [ "create-netns.service" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
ExecStart = "${pkgs.python3}/bin/python3 ${mockScript}";
Type = "simple";
NetworkNamespacePath = "/run/netns/test-ns";
};
};
# Pre-seed config.xml
systemd.tmpfiles.rules = [
"d /var/lib/mock-sonarr 0755 root root -"
"f /var/lib/mock-sonarr/config.xml 0644 root root - <Config><ApiKey>test-api-key-ns</ApiKey></Config>"
"d /media/tv 0755 root root -"
];
services.arrInit.sonarr = {
enable = true;
serviceName = "mock-sonarr";
dataDir = "/var/lib/mock-sonarr";
port = 8989;
networkNamespacePath = "/run/netns/test-ns";
networkNamespaceService = "create-netns";
rootFolders = [ "/media/tv" ];
};
};
# Mock Servarr API running inside the namespace
systemd.services.mock-sonarr = let
mockScript = pkgs.writeScript "mock-sonarr-ns.py" ''
import json
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse
DOWNLOAD_CLIENTS = []
ROOT_FOLDERS = []
class MockArr(BaseHTTPRequestHandler):
def _respond(self, code=200, body=b"", content_type="application/json"):
self.send_response(code)
self.send_header("Content-Type", content_type)
self.end_headers()
self.wfile.write(body if isinstance(body, bytes) else body.encode())
def do_GET(self):
path = urlparse(self.path).path
if path == "/api/v3/system/status":
self._respond(200, json.dumps({"version": "4.0.0"}).encode())
elif path == "/api/v3/downloadclient":
self._respond(200, json.dumps(DOWNLOAD_CLIENTS).encode())
elif path == "/api/v3/rootfolder":
self._respond(200, json.dumps(ROOT_FOLDERS).encode())
else:
self._respond(200, b"{}")
def do_POST(self):
path = urlparse(self.path).path
content_length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(content_length)
if "/rootfolder" in path:
data = json.loads(body)
data["id"] = len(ROOT_FOLDERS) + 1
ROOT_FOLDERS.append(data)
self._respond(201, json.dumps(data).encode())
else:
self._respond(200, b"{}")
def log_message(self, format, *args):
pass
HTTPServer(("0.0.0.0", 8989), MockArr).serve_forever()
'';
in {
description = "Mock Sonarr API in network namespace";
after = [ "create-netns.service" ];
requires = [ "create-netns.service" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
ExecStart = "${pkgs.python3}/bin/python3 ${mockScript}";
Type = "simple";
NetworkNamespacePath = "/run/netns/test-ns";
};
};
# Pre-seed config.xml
systemd.tmpfiles.rules = [
"d /var/lib/mock-sonarr 0755 root root -"
"f /var/lib/mock-sonarr/config.xml 0644 root root - <Config><ApiKey>test-api-key-ns</ApiKey></Config>"
"d /media/tv 0755 root root -"
];
services.arrInit.sonarr = {
enable = true;
serviceName = "mock-sonarr";
dataDir = "/var/lib/mock-sonarr";
port = 8989;
networkNamespacePath = "/run/netns/test-ns";
networkNamespaceService = "create-netns";
rootFolders = [ "/media/tv" ];
};
};
testScript = ''
start_all()
machine.wait_for_unit("create-netns.service")

View File

@@ -1,59 +1,71 @@
{ pkgs, lib, self }:
{
pkgs,
lib,
self,
}:
pkgs.testers.runNixOSTest {
name = "arr-init-permanent-failure";
nodes.machine = { pkgs, lib, ... }: {
imports = [ self.nixosModules.default ];
system.stateVersion = "24.11";
virtualisation.memorySize = 2048;
environment.systemPackages = with pkgs; [ curl jq gnugrep ];
nodes.machine =
{ pkgs, lib, ... }:
{
imports = [ self.nixosModules.default ];
system.stateVersion = "24.11";
virtualisation.memorySize = 2048;
environment.systemPackages = with pkgs; [
curl
jq
gnugrep
];
# Mock that always returns 503
systemd.services.mock-sonarr = let
mockScript = pkgs.writeScript "mock-sonarr-fail.py" ''
from http.server import HTTPServer, BaseHTTPRequestHandler
# Mock that always returns 503
systemd.services.mock-sonarr =
let
mockScript = pkgs.writeScript "mock-sonarr-fail.py" ''
from http.server import HTTPServer, BaseHTTPRequestHandler
class FailMock(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(503)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"Service Unavailable")
class FailMock(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(503)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"Service Unavailable")
def do_POST(self):
self.do_GET()
def do_POST(self):
self.do_GET()
def log_message(self, format, *args):
pass
def log_message(self, format, *args):
pass
HTTPServer(("0.0.0.0", 8989), FailMock).serve_forever()
'';
in {
description = "Mock Sonarr that never becomes ready";
wantedBy = [ "multi-user.target" ];
serviceConfig = {
ExecStart = "${pkgs.python3}/bin/python3 ${mockScript}";
Type = "simple";
HTTPServer(("0.0.0.0", 8989), FailMock).serve_forever()
'';
in
{
description = "Mock Sonarr that never becomes ready";
wantedBy = [ "multi-user.target" ];
serviceConfig = {
ExecStart = "${pkgs.python3}/bin/python3 ${mockScript}";
Type = "simple";
};
};
# Pre-seed config.xml
systemd.tmpfiles.rules = [
"d /var/lib/mock-sonarr 0755 root root -"
"f /var/lib/mock-sonarr/config.xml 0644 root root - <Config><ApiKey>test-api-key-fail</ApiKey></Config>"
];
services.arrInit.sonarr = {
enable = true;
serviceName = "mock-sonarr";
dataDir = "/var/lib/mock-sonarr";
port = 8989;
# Very short timeout so retries happen fast
apiTimeout = 3;
};
# Speed up retries for test
systemd.services.mock-sonarr-init.serviceConfig.RestartSec = lib.mkForce 2;
};
# Pre-seed config.xml
systemd.tmpfiles.rules = [
"d /var/lib/mock-sonarr 0755 root root -"
"f /var/lib/mock-sonarr/config.xml 0644 root root - <Config><ApiKey>test-api-key-fail</ApiKey></Config>"
];
services.arrInit.sonarr = {
enable = true;
serviceName = "mock-sonarr";
dataDir = "/var/lib/mock-sonarr";
port = 8989;
# Very short timeout so retries happen fast
apiTimeout = 3;
};
# Speed up retries for test
systemd.services.mock-sonarr-init.serviceConfig.RestartSec = lib.mkForce 2;
};
testScript = ''
start_all()
machine.wait_for_unit("mock-sonarr.service")