Files
nixos-router/tests/loadbalancer.nix
nils 20ec791827 Hand certificates and CA files to HAProxy as credentials
The settings only allow paths in the state directory, which is 0700 root
and which HAProxy (a user of its own) cannot enter. systemd reads the
files and gives the service copies; a path unit restarts it when one
changes. The load balancer test keeps its files in the state directory
now, and verifies the backends' certificate.
2026-11-28 21:23:09 +01:00

325 lines
13 KiB
Nix

# Load balancers: a service on two backends, reachable from outside and inside.
#
# upstream (ISP, and the client from outside) -- router -- client
# |
# hv1, hv2 (HTTPS API)
#
# `api` decrypts TLS on the router (re-encrypting toward the backends) and
# tells them the client in X-Forwarded-For; `raw` passes TLS through. Both
# check /healthz, so a backend that fails it gets no connections.
{ self, pkgs }:
let
common = import ./common.nix;
macs = {
hv1 = "02:00:00:00:00:21";
hv2 = "02:00:00:00:00:22";
};
settings = pkgs.writeText "settings.json" (
builtins.toJSON {
system = {
hostName = "router";
stateVersion = "26.11";
};
router = { };
}
);
# One certificate for everything: the router's (api.lb.test) and the backends'.
cert =
pkgs.runCommand "lb-cert" { nativeBuildInputs = [ pkgs.openssl ]; } ''
mkdir $out
openssl req -x509 -newkey rsa:2048 -nodes -days 3650 -subj /CN=api.lb.test \
-addext subjectAltName=DNS:api.lb.test -keyout $out/key.pem -out $out/cert.pem
cat $out/cert.pem $out/key.pem > $out/both.pem
'';
# What a backend answers: who it is, who connected, and what the router said.
# /healthz fails while /tmp/sick exists.
api = pkgs.writeScript "api.py" ''
#!${pkgs.python3}/bin/python3
import http.server, os, ssl, sys
name = sys.argv[1]
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/healthz" and os.path.exists("/tmp/sick"):
self.send_response(503)
self.end_headers()
return
body = "name=%s peer=%s xff=%s host=%s\n" % (
name, self.client_address[0], self.headers.get("X-Forwarded-For", "-"), self.headers.get("Host", "-"))
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body.encode())
def log_message(self, *args):
pass
server = http.server.ThreadingHTTPServer(("0.0.0.0", 8443), Handler)
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain("${cert}/cert.pem", "${cert}/key.pem")
server.socket = ctx.wrap_socket(server.socket, server_side=True)
server.serve_forever()
'';
backend = name: {
imports = [ ];
virtualisation.vlans = [ 2 ];
networking.useNetworkd = true;
networking.useDHCP = false;
networking.firewall.enable = false;
networking.interfaces.eth1.ipv4.addresses = pkgs.lib.mkForce [ ];
systemd.network.networks."10-lan" = {
matchConfig.Name = "eth1";
linkConfig.MACAddress = macs.${name};
networkConfig.DHCP = "ipv4";
};
systemd.services.api = {
wantedBy = [ "multi-user.target" ];
after = [ "network-online.target" ];
serviceConfig.ExecStart = "${api} ${name}";
};
};
in
pkgs.testers.runNixOSTest {
name = "router-loadbalancer";
defaults.imports = [ common.tools ];
interactive.defaults = common.interactiveDefaults;
nodes = {
upstream =
{ lib, ... }:
{
virtualisation.vlans = [ 1 ];
networking.useNetworkd = true;
networking.useDHCP = false;
networking.firewall.enable = false;
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [ ];
systemd.network.networks."10-wan" = {
matchConfig.Name = "eth1";
address = [ "203.0.113.1/24" ];
};
services.dnsmasq = {
enable = true;
settings = {
interface = "eth1";
bind-interfaces = true;
dhcp-range = "203.0.113.100,203.0.113.100,255.255.255.0,1h";
dhcp-option = [ "option:router,203.0.113.1" ];
};
};
};
router =
{ lib, ... }:
{
imports = [
self.nixosModules.router
self.nixosModules.settings
];
routerSettings.file = settings;
virtualisation.vlans = [
1
2
];
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [ ];
networking.interfaces.eth2.ipv4.addresses = lib.mkForce [ ];
systemd.tmpfiles.rules = [
"d /var/lib/router 0700 root root -"
"d /var/lib/router/lb 0700 root root -"
"C /var/lib/router/lb/both.pem 0600 root root - ${cert}/both.pem"
"C /var/lib/router/lb/ca.pem 0600 root root - ${cert}/cert.pem"
];
router = {
enable = true;
wan.interface = "eth1";
lans.main = {
interface = "eth2";
internet = true;
ipv4.address = "192.168.10.1";
dhcp = {
pool = {
start = "192.168.10.100";
end = "192.168.10.199";
};
reservations = {
hv1 = {
mac = macs.hv1;
address = "192.168.10.21";
};
hv2 = {
mac = macs.hv2;
address = "192.168.10.22";
};
};
};
};
dns.forwarders = [ "203.0.113.1" ];
loadBalancers = {
api = {
listen.port = 8443;
listen.zones = [
"wan"
"main"
];
hosts = [ "api.lb.test" ];
# Files in the router's state directory, as the settings editor requires:
# 0700 root, so HAProxy (its own user) cannot read them itself.
certificate = "/var/lib/router/lb/both.pem";
backends = [
"hv1"
"hv2"
];
backendTls = {
enable = true;
verify = true;
caFile = "/var/lib/router/lb/ca.pem";
};
check.path = "/healthz";
check.interval = "1s";
check.fall = 2;
check.rise = 2;
};
raw = {
listen.port = 9443;
listen.zones = [ "wan" ];
tls = "passthrough";
backends = [
"hv1"
"hv2"
];
backendPort = 8443;
check.path = "/healthz";
check.interval = "1s";
check.fall = 2;
check.rise = 2;
};
};
};
};
client =
{ lib, ... }:
{
virtualisation.vlans = [ 2 ];
networking.useNetworkd = true;
networking.useDHCP = false;
networking.firewall.enable = false;
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [ ];
systemd.network.networks."10-lan" = {
matchConfig.Name = "eth1";
networkConfig.DHCP = "ipv4";
};
};
hv1 = backend "hv1";
hv2 = backend "hv2";
};
testScript = ''
start_all()
upstream.wait_for_unit("dnsmasq.service")
router.wait_for_unit("network-online.target")
router.wait_until_succeeds("ip -4 addr show dev eth1 | grep -q 203.0.113.100")
router.wait_for_unit("kea-dhcp4-server.service")
router.wait_for_unit("haproxy.service")
for n in ["hv1", "hv2"]:
globals()[n].wait_for_unit("api.service")
hv1.wait_until_succeeds("ip -4 addr show dev eth1 | grep -q 192.168.10.21")
hv2.wait_until_succeeds("ip -4 addr show dev eth1 | grep -q 192.168.10.22")
client.wait_until_succeeds("ip -4 addr show dev eth1 | grep -q 192.168.10.1[0-9][0-9]")
outside = "curl -sk --max-time 5 --resolve api.lb.test:8443:203.0.113.100 https://api.lb.test:8443"
inside = "curl -sk --max-time 5 --resolve api.lb.test:8443:192.168.10.1 https://api.lb.test:8443"
def answers(node, cmd, path="/", n=8):
return [node.succeed(f"{cmd}{path}").strip() for _ in range(n)]
def names(lines):
return {l.split()[0] for l in lines}
# Two servers and the backend itself, for each of the two services.
router.wait_until_succeeds("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | grep -c ',UP,' | grep -qx 6", timeout=60)
with subtest("the statistics have the columns the web UI's page reads"):
header = router.succeed("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | head -1")
cols = header.lstrip("# ").strip().split(",")
for c in ["pxname", "svname", "status", "scur", "stot", "lastchg", "check_status", "check_code"]:
assert c in cols, (c, cols)
# (The CSV's own `addr` column is empty: the address is in the servers' state.)
state = router.succeed("echo 'show servers state' | nc -U -N /run/haproxy/haproxy.sock")
head = [l for l in state.splitlines() if l.startswith("#")][0].split()[1:]
for c in ["be_name", "srv_name", "srv_addr", "srv_port"]:
assert c in head, (c, head)
rows = [l.split() for l in state.splitlines() if l and l[0] != "#" and len(l.split()) == len(head)]
got = {(r[head.index("be_name")], r[head.index("srv_name")]): r[head.index("srv_addr")] + ":" + r[head.index("srv_port")] for r in rows}
assert got[("be_api", "hv1")] == "192.168.10.21:8443" and got[("be_api", "hv2")] == "192.168.10.22:8443", got
with subtest("from outside, both backends are used"):
got = answers(upstream, outside)
assert names(got) == {"name=hv1", "name=hv2"}, got
with subtest("the backends see the router, and the client in X-Forwarded-For"):
line = upstream.succeed(f"{outside}/").strip()
assert "peer=192.168.10.1" in line and "xff=203.0.113.1" in line, line
assert "host=api.lb.test:8443" in line, line
with subtest("from inside, through the router's address"):
got = answers(client, inside)
assert names(got) == {"name=hv1", "name=hv2"}, got
# The client's own (pool) address, not the router's.
import re
assert re.search(r"xff=192\.168\.10\.1[0-9][0-9] ", got[0]), got[0]
with subtest("the service's name is published for the LAN"):
assert client.succeed("dig +short @192.168.10.1 api.lb.test").strip() == "192.168.10.1"
with subtest("a name that is not the service's is refused"):
code = upstream.succeed("curl -sk -o /dev/null -w '%{http_code}' --max-time 5 --resolve other.lb.test:8443:203.0.113.100 https://other.lb.test:8443/").strip()
assert code in ("503", "000"), code
with subtest("passthrough: the backend's own certificate and the router as the peer"):
out = upstream.succeed("curl -sk --max-time 5 https://203.0.113.100:9443/").strip()
assert out.startswith("name=hv") and "peer=203.0.113.1" not in out and "peer=192.168.10.1" in out, out
assert names(answers(upstream, "curl -sk --max-time 5 https://203.0.113.100:9443", n=8)) == {"name=hv1", "name=hv2"}
with subtest("the port is closed where the service does not listen"):
client.fail("curl -sk --max-time 3 https://192.168.10.1:9443/")
with subtest("HAProxy only has copies of the files: a changed one restarts it"):
pid = router.succeed("systemctl show -p MainPID --value haproxy.service").strip()
router.succeed("echo >> /var/lib/router/lb/both.pem")
router.wait_until_succeeds(f"test $(systemctl show -p MainPID --value haproxy.service) != {pid}", timeout=60)
router.wait_until_succeeds("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | grep -c ',UP,' | grep -qx 6", timeout=60)
assert names(answers(upstream, outside)) == {"name=hv1", "name=hv2"}
with subtest("a backend that fails its check gets no connections, and returns when it passes"):
hv1.succeed("touch /tmp/sick")
router.wait_until_succeeds("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | grep '^be_api,hv1' | grep -q ',DOWN,'", timeout=60)
got = answers(upstream, outside, n=8)
assert names(got) == {"name=hv2"}, got
assert names(answers(client, inside, n=8)) == {"name=hv2"}
assert names(answers(upstream, "curl -sk --max-time 5 https://203.0.113.100:9443", n=8)) == {"name=hv2"}
hv1.succeed("rm /tmp/sick")
router.wait_until_succeeds("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | grep '^be_api,hv1' | grep -q ',UP,'", timeout=60)
assert names(answers(upstream, outside)) == {"name=hv1", "name=hv2"}
with subtest("a backend that is down is out too"):
hv2.systemctl("stop api.service")
router.wait_until_succeeds("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | grep '^be_api,hv2' | grep -q ',DOWN,'", timeout=60)
assert names(answers(upstream, outside)) == {"name=hv1"}
with subtest("with no backend left the service answers 503"):
hv1.succeed("touch /tmp/sick")
router.wait_until_succeeds("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | grep '^be_api,BACKEND' | grep -q ',DOWN,'", timeout=60)
code = upstream.succeed(f"{outside}/ -o /dev/null -w '%{{http_code}}'").strip()
assert code == "503", code
'';
}