Load balancers

router.loadBalancers: services on several hosts (HAProxy) with HTTP
checks, TLS terminated on the router or passed through, the client in
X-Forwarded-For or the PROXY protocol, host names that choose a service
on a shared port and are published in the local DNS. A status page lists
the backends.
This commit is contained in:
2026-11-27 20:54:45 +01:00
parent 2aa70630d4
commit 553361f811
16 changed files with 1349 additions and 3 deletions
+94
View File
@@ -437,6 +437,99 @@ let
}
];
lbs = cfg.loadBalancers;
lbReserved = lib.foldl' (acc: l: acc // l.dhcp.reservations) { } lans;
lbBackendOk = b: validIp b || lib.hasAttr b lbReserved;
# A name the router's certificate covers (a wildcard covers one label).
acmeCovers =
h:
lib.any (
d:
d == h
|| (
lib.hasPrefix "*." d
&& lib.hasInfix "." h
&& lib.removePrefix "*" d == "." + lib.concatStringsSep "." (lib.tail (lib.splitString "." h))
)
) cfg.acme.domains;
lbPortsTaken = [ 22 ] ++ [ 53 ] ++ cfg.managementPorts;
lbDnatPorts = lib.concatMap (n: lib.filter lib.isInt n.ports) (
lib.filter (n: n.type == "dnat") cfg.firewall.nat
);
lbAssertions =
name: lb:
let
where = "router.loadBalancers.${name}";
sharing = lib.filter (n: n != name && lbs.${n}.listen.port == lb.listen.port) (lib.attrNames lbs);
in
[
{
assertion = lb.backends != [ ];
message = "${where}.backends: at least one backend.";
}
{
assertion = lib.all lbBackendOk lb.backends;
message = "${where}.backends: `${
lib.concatStringsSep ", " (lib.filter (b: !lbBackendOk b) lb.backends)
}` is neither a DHCP reservation nor an IPv4 address.";
}
{
assertion = lib.all (z: z == "wan" || lib.elem z zoneNames) lb.listen.zones && lb.listen.zones != [ ];
message = "${where}.listen.zones: unknown zone (zones: wan, ${lib.concatStringsSep ", " zoneNames}).";
}
{
assertion = lib.all dnsNameOk lb.hosts;
message = "${where}.hosts: a name is not a valid DNS name.";
}
{
assertion = lb.tls != "passthrough" || lb.protocol == "tcp";
message = "${where}: passthrough only forwards bytes: protocol must be \"tcp\".";
}
{
assertion = lb.hosts == [ ] || lb.tls != "none" || lb.protocol == "http";
message = "${where}.hosts: without TLS the host name is only visible in HTTP: use protocol \"http\", or leave hosts empty.";
}
{
assertion = lb.tls == "terminate" || lb.certificate == null;
message = "${where}.certificate: only a service that terminates TLS has one.";
}
{
assertion = lb.tls != "terminate" || lb.certificate != null || cfg.acme.enable;
message = "${where}: it terminates TLS but has no `certificate` and router.acme is not enabled.";
}
{
assertion =
lb.tls != "terminate" || lb.certificate != null || !cfg.acme.enable || lib.all acmeCovers lb.hosts;
message = "${where}.hosts: the router's certificate (router.acme.domains) does not cover ${
lib.concatStringsSep ", " (lib.filter (h: !acmeCovers h) lb.hosts)
}; add the name there or give the service its own `certificate`.";
}
{
assertion = lb.backendTls.enable || !lb.backendTls.verify;
message = "${where}.backendTls.verify needs backendTls.enable.";
}
{
assertion = !(lib.elem lb.listen.port lbPortsTaken);
message = "${where}.listen.port ${toString lb.listen.port} is used by the router itself (SSH, DNS, the web UI).";
}
{
assertion = !(lib.elem lb.listen.port lbDnatPorts);
message = "${where}.listen.port ${toString lb.listen.port} is also forwarded by router.firewall.nat: the forward would take the connections first.";
}
{
assertion = sharing == [ ] || (lb.hosts != [ ] && lib.all (n: lbs.${n}.hosts != [ ]) sharing);
message = "${where}: port ${toString lb.listen.port} is shared with ${lib.concatStringsSep ", " sharing}: every service on it needs `hosts`.";
}
{
assertion = lib.all (n: lbs.${n}.tls == lb.tls && lbs.${n}.protocol == lb.protocol) sharing;
message = "${where}: services that share port ${toString lb.listen.port} must agree on tls and protocol.";
}
{
assertion = lib.all (n: !(lib.any (h: lib.elem h lbs.${n}.hosts) lb.hosts)) sharing;
message = "${where}.hosts: another service on port ${toString lb.listen.port} has one of these names.";
}
];
overlapsLan = n: lib.any (l: ipv4.overlaps n l) lanNets;
wgAssertions =
@@ -597,6 +690,7 @@ in
]
++ lib.concatLists (lib.mapAttrsToList perLan lansByName)
++ dnsAssertions
++ lib.concatLists (lib.mapAttrsToList lbAssertions lbs)
++ lib.concatMap ruleAssertions cfg.firewall.rules
++ lib.concatMap natAssertions cfg.firewall.nat
++ [
+1
View File
@@ -8,6 +8,7 @@
./firewall.nix
./dhcp.nix
./dns.nix
./loadbalancer.nix
./ddns.nix
./acme.nix
./rollback.nix
+14
View File
@@ -62,6 +62,19 @@ let
setOf = xs: "{ ${lib.concatMapStringsSep ", " toString xs} }";
# Load balancers listen on the router: their port is open in their zones.
lbInput = lib.concatLists (
lib.mapAttrsToList (
name: lb:
let
devs = lib.unique (
lib.concatMap (z: if z == "wan" then uplinks else zoneDevices z) lb.listen.zones
);
in
lib.optional (devs != [ ]) "iifname ${set devs} tcp dport ${toString lb.listen.port} accept # load balancer ${name}"
) cfg.loadBalancers
);
# Layer 4 match; `ports` and `sports` may be ints or "a-b" ranges.
l4 =
proto: ports: sports:
@@ -261,6 +274,7 @@ in
lib.concatMapStringsSep ", " toString listenPorts
} } accept # wireguard"
}
${lib.concatStringsSep "\n " lbInput}
${lib.optionalString (dhcpIfaces != [ ]) "iifname ${set dhcpIfaces} udp dport 67 accept"}
${lib.optionalString (mgmtIfaces != [ ]) "iifname ${set mgmtIfaces} tcp dport { ${
lib.concatMapStringsSep ", " toString ([ 22 ] ++ config.router.managementPorts)
+142
View File
@@ -0,0 +1,142 @@
{ config, lib, ... }:
let
cfg = config.router;
lbs = cfg.loadBalancers;
names = lib.attrNames lbs;
lans = lib.attrValues cfg.lans;
acme = cfg.acme;
acmeName = if acme.domains == [ ] then "unset" else lib.head acme.domains;
acmePem = "/var/lib/acme/${acmeName}/full.pem";
# Reservation name -> address, across the LANs.
reserved = lib.foldl' (acc: l: acc // lib.mapAttrs (_: r: r.address) l.dhcp.reservations) { } lans;
isAddress = b: builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" b != null;
addressOf = b: if isAddress b then b else reserved.${b} or null;
backendPort = lb: if lb.backendPort != null then lb.backendPort else lb.listen.port;
usesAcme = lb: lb.tls == "terminate" && lb.certificate == null;
certOf = lb: if lb.certificate != null then toString lb.certificate else acmePem;
# Services by port: one frontend each, the host name chooses the backend.
ports = lib.unique (map (n: lbs.${n}.listen.port) names);
onPort = port: lib.filter (n: lbs.${n}.listen.port == port) names;
hostAcl =
lb: hosts:
let
list = lib.concatMapStringsSep " " (h: lib.toLower h) hosts;
in
if lb.tls == "passthrough" then
"{ req_ssl_sni -i ${list} }"
else if lb.protocol == "http" then
"{ hdr(host),field(1,:) -i ${list} }"
else
"{ ssl_fc_sni -i ${list} }";
frontend =
port:
let
members = onPort port;
first = lbs.${lib.head members};
certs = lib.unique (map (n: certOf lbs.${n}) (lib.filter (n: lbs.${n}.tls == "terminate") members));
withHosts = lib.filter (n: lbs.${n}.hosts != [ ]) members;
without = lib.filter (n: lbs.${n}.hosts == [ ]) members;
http = first.protocol == "http";
# (IPv4 and IPv6 apart: one dual-stack socket shows IPv4 clients as ::ffff:a.b.c.d.)
tlsArgs = lib.optionalString (first.tls == "terminate") (
" ssl ${lib.concatMapStringsSep " " (c: "crt ${c}") certs}${lib.optionalString http " alpn h2,http/1.1"}"
);
in
''
frontend fe_${toString port}
mode ${first.protocol}
bind 0.0.0.0:${toString port}${tlsArgs}
bind :::${toString port} v6only${tlsArgs}
${lib.optionalString (first.tls == "passthrough") ''
tcp-request inspect-delay 5s
tcp-request content accept if { req_ssl_hello_type 1 }
''}${lib.concatMapStrings (n: ''
use_backend be_${n} if ${hostAcl lbs.${n} lbs.${n}.hosts}
'') withHosts}${lib.concatMapStrings (n: ''
default_backend be_${n}
'') without}
'';
server =
lb: n: b:
let
addr = addressOf b;
secure = lb.backendTls.enable;
verify =
if lb.backendTls.verify then
"verify required${lib.optionalString (lb.backendTls.caFile != null) " ca-file ${toString lb.backendTls.caFile}"}"
else
"verify none";
# Passthrough sends the client's bytes as they are: only the checks speak TLS.
traffic = lib.optionalString (secure && lb.tls != "passthrough") " ssl ${verify}";
checks = " check${lib.optionalString secure " check-ssl ${verify}"}${lib.optionalString lb.proxyProtocol " check-send-proxy"}";
proxy = lib.optionalString lb.proxyProtocol " send-proxy-v2";
in
" server ${lib.replaceStrings [ "." ] [ "-" ] b} ${addr}:${toString (backendPort lb)}${checks}${traffic}${proxy}";
backend = n: ''
backend be_${n}
mode ${lbs.${n}.protocol}
balance ${lbs.${n}.balance}
timeout check ${lbs.${n}.check.timeout}
default-server inter ${lbs.${n}.check.interval} fall ${toString lbs.${n}.check.fall} rise ${toString lbs.${n}.check.rise}
${lib.optionalString lbs.${n}.check.useHttp ''
option httpchk
http-check send meth GET uri ${lbs.${n}.check.path} ver HTTP/1.1 hdr Host ${
if lbs.${n}.hosts == [ ] then "localhost" else lib.head lbs.${n}.hosts
}
''}${lib.optionalString (lbs.${n}.protocol == "http") ''
option forwardfor
''}${
# (An unknown backend is an assertion's to report; the text must still be valid.)
lib.concatMapStringsSep "\n" (b: server lbs.${n} n b) (lib.filter (b: addressOf b != null) lbs.${n}.backends)
}
'';
haproxyConfig = ''
defaults
log stdout format raw local0
timeout connect 5s
timeout client 1m
timeout server 1m
timeout check 2s
option redispatch
retries 2
${lib.concatMapStringsSep "\n" frontend ports}
${lib.concatMapStringsSep "\n" backend names}
'';
in
{
config = lib.mkIf (cfg.enable && names != [ ]) {
services.haproxy = {
enable = true;
config = haproxyConfig;
};
# The router's own certificate, for services that decrypt with it.
security.acme.certs = lib.mkIf (acme.enable && lib.any (n: usesAcme lbs.${n}) names) {
${acmeName} = {
group = "haproxy";
reloadServices = [ "haproxy.service" ];
};
};
# A service's names are the router's own for the LANs it listens in.
router.dns.hosts = lib.mkMerge (
map (
n:
let
lb = lbs.${n};
addrs = lib.concatMap (l: lib.optional (lib.elem l.zone lb.listen.zones) l.ipv4.address) lans;
in
lib.mkIf (addrs != [ ]) (lib.genAttrs lb.hosts (_: lib.mkDefault addrs))
) names
);
};
}
+218
View File
@@ -426,6 +426,224 @@ in
);
};
loadBalancers = mkOption {
default = { };
example = {
api = {
listen.port = 8443;
listen.zones = [
"wan"
"lan"
];
tls = "terminate";
hosts = [ "api.example.org" ];
backends = [
"hv1"
"hv2"
];
backendTls.enable = true;
check.path = "/healthz";
};
};
description = ''
Services that spread their connections over several hosts (HAProxy),
keyed by name. A backend that fails its checks gets no connections
until it passes them again. The service listens on the router, in the
zones named in `listen.zones` (`wan` is the uplink): the router opens
the port there, so no firewall rule is needed. Clients inside reach it
through the router's address; `hosts` also publishes those names in the
local DNS (to the router's LAN addresses), so that inside and outside
use the same name. Backends are names of DHCP reservations or
IPv4 addresses.
A service either decrypts TLS on the router (`tls = "terminate"`) or
passes the connections through untouched (`"passthrough"`); the
backend then sees the router's address, unless `proxyProtocol` hands
it the client's. For HTTP the client's address is in `X-Forwarded-For`.
'';
type = types.attrsOf (
types.submodule (
{ config, ... }:
{
options = {
listen = {
port = mkOption {
type = types.port;
example = 443;
description = ''
TCP port the service listens on, in every zone of `zones`.
Services may share a port when each has `hosts` and they
agree on `tls` and `protocol` (the host name chooses).
'';
};
zones = mkOption {
type = types.listOf types.str;
default = [ "wan" ];
example = [
"wan"
"lan"
];
description = ''
Where the service is reachable: `wan` (the uplink) and the
zones of LANs and tunnels.
'';
};
};
tls = mkOption {
type = types.enum [
"terminate"
"passthrough"
"none"
];
default = "terminate";
description = ''
`terminate`: the router decrypts (its certificate: see
`certificate`) and sends on to the backends, encrypted again
if `backendTls.enable`. `passthrough`: the connection goes to
the backend as it is; the router only reads the requested
host name, and the backend has the certificate. `none`: no
TLS between the client and the router.
'';
};
protocol = mkOption {
type = types.enum [
"http"
"tcp"
];
default = if config.tls == "passthrough" then "tcp" else "http";
defaultText = ''"tcp" with passthrough, else "http"'';
description = ''
`http`: the router reads the requests (adds `X-Forwarded-For`,
routes by `Host`). `tcp`: bytes only. Passthrough is always `tcp`.
'';
};
certificate = mkOption {
type = types.nullOr types.path;
default = null;
example = "/var/lib/router/lb-api.pem";
description = ''
`terminate`: a file with the certificate chain and the
private key (PEM). null: the router's own certificate
(`router.acme`), which then has to cover `hosts`.
'';
};
hosts = mkOption {
type = types.listOf types.str;
default = [ ];
example = [ "api.example.org" ];
description = ''
The names the service answers to: the request's `Host` (or the
requested TLS name) chooses the service on a shared port, and
a name that is not on a shared port still has to match. The
names are published in the local DNS for the LANs the service
listens in. Empty: the service takes everything on its port.
'';
};
backends = mkOption {
type = types.listOf types.str;
example = [
"hv1"
"hv2"
];
description = "Names of DHCP reservations, or IPv4 addresses.";
};
backendPort = mkOption {
type = types.nullOr types.port;
default = null;
description = "The port on the backends; null: the same as `listen.port`.";
};
backendTls = {
enable = mkOption {
type = types.bool;
default = config.tls == "passthrough";
defaultText = "true with passthrough, else false";
description = ''
The backends speak TLS. With `terminate` or `none` the
router encrypts toward them; with `passthrough` it only
makes its health checks encrypted.
'';
};
verify = mkOption {
type = types.bool;
default = false;
description = ''
Check the backends' certificates (against `caFile`, or the
system's) when connecting to them and when checking them.
Off by default: backends often have a self-signed one.
'';
};
caFile = mkOption {
type = types.nullOr types.path;
default = null;
description = "Certificate authority of the backends, for `verify`.";
};
};
balance = mkOption {
type = types.enum [
"roundrobin"
"leastconn"
"source"
];
default = "roundrobin";
description = ''
How a new connection picks a backend: in turn, the one with
the fewest connections, or by the client's address (the same
client keeps its backend while the backends stay as they are).
'';
};
proxyProtocol = mkOption {
type = types.bool;
default = false;
description = ''
Send the client's address to the backends in a PROXY protocol
(v2) header, for passthrough or `tcp`. The backends must expect
it, or every connection fails.
'';
};
check = {
path = mkOption {
type = types.str;
default = "/";
example = "/healthz";
description = ''
An HTTP GET of this path decides whether a backend is up
(a 2xx or 3xx answer), also for TLS backends and in
passthrough. With the first of `hosts` as `Host`, else
`localhost`.
'';
};
useHttp = mkOption {
type = types.bool;
default = true;
description = "Check with an HTTP request; false: only that the port accepts connections.";
};
interval = mkOption {
type = types.strMatching "[0-9]+(ms|s|m)";
default = "2s";
description = "Time between two checks of a backend.";
};
timeout = mkOption {
type = types.strMatching "[0-9]+(ms|s|m)";
default = "2s";
description = "How long a check may take before it counts as failed.";
};
fall = mkOption {
type = types.ints.positive;
default = 3;
description = "Failed checks in a row that take a backend out.";
};
rise = mkOption {
type = types.ints.positive;
default = 2;
description = "Passed checks in a row that bring it back.";
};
};
};
}
)
);
};
wireguardEndpointRefresh = mkOption {
type = types.nullOr (types.strMatching "[0-9]+(s|min|h)");
default = "1min";