Author SHA1 Message Date
nils 8dceedbf19 Release 0.14.1 2026-11-28 21:23:09 +01:00
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
nils 2ebf45af81 Handover for 0.14.0 2026-11-27 21:00:11 +01:00
nils 205ad9a1c7 Release 0.14.0 2026-11-27 20:54:45 +01:00
nils 553361f811 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.
2026-11-27 20:54:45 +01:00
18 changed files with 1503 additions and 4 deletions
+98
View File
@@ -0,0 +1,98 @@
# Handover (state at release 0.14.0, 2026-11-27)
For an agent picking up nixos-router. Read `DEVELOPING.md` (how to build and test) and `SPECS.md` (what exists and
what is open) first; this file is what is not obvious from them.
## State
- Branch `installed-webui`, last release commit `Release 0.14.0`, tag `v0.14.0`, both pushed. `main` is the PR base.
Releases since the unified upgrade (0.13.7): 0.13.8 (fix below), 0.14.0 (load balancers).
- Unstaged, deliberately untouched: the mode change of `scripts/webui-dev.sh`. It makes the release script print
"built from a tree that differs from HEAD".
- `dist/router-update-0.14.0.bundle` (1.4 GB, signed) is the only bundle; delete the old one after each release.
- Nothing is half-done. 0.14.0 passed the Go tests, `fast`, `assertions`, `loadbalancer` and `webui`; `apply` and
`update` passed on the build just before the last change to the load balancer page (only `loadbalancer.go`),
not on the final one.
- Not yet tried: the git path against the real gitea (the VM test serves its own repository from the builder), and
load balancers on the user's real router (they want one for an API on hv1/hv2; they add it in Advanced).
## 0.13.8: names that became static (`leasesdns.go`)
`router-webui leases-dns` publishes DHCP clients' names in Unbound. When Unbound restarted it removed, by name, what
it had published before, which also removed the configuration's record if the name had become a reservation or a
`dns.hosts` entry in that same apply (`hv1`/`hv2`). It now stores the Unbound's pid with the status and forgets
(does not remove) what an older Unbound had (`stillThere`). Test: `TestNewUnboundForgetsWhatTheOldOneHad`.
## Load balancers (0.14.0)
`router.loadBalancers.<name>` (options in `modules/router/options.nix`, HAProxy config in
`modules/router/loadbalancer.nix`, port opening in `firewall.nix` as `lbInput`, assertions in `assertions.nix` as
`lbAssertions`). The full description is the "Load balancers" section of `SPECS.md`. Things that were not obvious:
- IPv4 and IPv6 are bound apart (`bind 0.0.0.0:P` and `bind :::P v6only`): a dual-stack socket shows IPv4 clients as
`::ffff:a.b.c.d` in `X-Forwarded-For`.
- NixOS's own `services.haproxy` assertion forces the whole config text, so the generator must never fail on a bad
setting (an unresolved backend is skipped there; our assertion reports it).
- The `addr` column of `show stat` is empty. The web UI (`loadbalancer.go`) reads addresses from
`show servers state` (`srv_addr`, `srv_port`). The `loadbalancer` VM test checks that the real HAProxy has the
columns the page reads; keep it when upgrading HAProxy.
- Certificates and CA files live in `/var/lib/router` (0700 root), which HAProxy cannot enter: they go in through
`LoadCredential` and the config names `/run/credentials/haproxy.service/…` (`fileOf`). A path unit restarts
HAProxy when a file changes. 0.14.0 lacked this (fixed after the release; see the git log).
- The stats socket is the NixOS module's `/run/haproxy/haproxy.sock`; `System.HAProxySocket` overrides it in tests.
- A service's `hosts` become `router.dns.hosts` entries (`mkDefault`) pointing at the router's address in the LANs it
listens in; that is how inside and outside use one name.
- Untested: the PROXY protocol, `balance = source`, `backendTls.verify`, shared ports in a VM, the router's own ACME
certificate for a service. Open: a settings form (services are edited in Advanced), backend state in `/metrics`
and MCP, UDP, taking a backend out of service from the page.
## How an upgrade works now (0.13.7)
nixos-router is an input of the configuration flake next to nixpkgs; one upgrade moves both.
- `modules/settings/upgrade.nix` (`router-upgrade`): `check` reads the channel's nixpkgs revision *and* the repository's
newest `vX.Y.Z` tag (`git ls-remote`) into `/var/lib/router/upgrade/check.json`. `preview` fetches the tag
(`nix flake prefetch`), builds a "release dir" from the source (version, serial = commit time, schema = number of
`migrations/*.jq`), writes the flake from `config-flake.nix` (`@SOURCE@` replaced with `git+<repo>?ref=refs/tags/vX&rev=<commit>`),
migrates the settings in a copy, locks it, and diffs packages into `preview.json` (`router: {from,to,tag,rev}` when
nixos-router changes too). `apply` snapshots, copies flake + migrated settings + lock, `router-apply` with
commit-confirm; rollback restores `config.pre-update`. `daily` is what the timer runs.
- `modules/settings/update.nix` (`router-update`): only signed bundles (`--bundle`, `--url`, `--request`, web upload).
The repository option `routerUpdate.repository` (default the real gitea) is a module option, not a setting; a test or
a fork overrides it in `local.nix`. `null` disables the repository.
- Web UI (`pkgs/router-webui`): `upgrade.go` (types, `/upgrade/{check,preview,download,apply,channel}`), `update.go`
(bundle upload, progress), `gitupdate.go` (repository file, Overview notice), `templates/update.html` (the one page).
Pages are Go templates with a strict CSP: no inline styles or handlers.
- `config-flake.nix` is a contract with every installed updater: change it only compatibly.
## Rules that cost time before
- Run VM tests **one at a time**: `nix run .#test -- <name>` (webui ~2 min, apply ~16, update ~14, assertions ~5).
Parallel runs OOM'd the machine. New files need `git add -N` first. `nix flake check --no-build` errors on these tests
for unrelated reasons.
- Edit files with the Edit/Write tools, not sed/python through Bash (the user asked for this).
- Git commit messages and PR descriptions get no attribution lines (the user's latest instruction).
- An assertion test (`tests/assertions.nix`) compares the exact number of failed assertions per case, so a case must
trigger only the assertion it is about.
- Do not commit, release, push or delete bundles until the user says so. The user's phrasing: "commit and release it as
X.Y.Z when the tests pass", then "yes push it and delete the old bundle". A release is a feature commit, then a
`Release X.Y.Z` commit bumping `VERSION`, then `nix run .#release -- --key ~/.config/nixos-router/update.sec`
(builds the bundle and creates the annotated tag; push the tag explicitly: `git push origin <branch> vX.Y.Z`).
The user's git signs tags, so tags need `-a -m`; the release script does that.
- Use `jq`, not bash substitution, to put the source address into the flake (`&` is special in bash 5.2 replacements).
- Nix against a git input needs `--option flake-registry ""`, or it tries to download the global registry.
- Waiting loops in tests must stop at `failed` and use a short ceiling (300 s); the user objected to 900 s.
- Transient systemd-run units cannot be restarted: start a new one.
## Open items (all in `SPECS.md`, "Not done yet")
- Release script: refuse a `flake.lock` whose nixpkgs is not a channel revision (so cache.nixos.org has the packages).
- "Reset to the release's nixpkgs" action; signed manifest / "not tested with this version" mark.
- Real package changes in upgrade tests (they use an identical nixpkgs copy).
- Web UI polish: folds that may jump, browser confirm dialogs, touch tooltips, word-level diff.
- Load balancers: a settings form, backend state in `/metrics` and MCP, UDP, drain/maintenance from the page; tidy the
indentation of the generated HAProxy config (cosmetic).
- API `apply` scope for tokens, more MCP read tools; WireGuard live status; host-based routing 80/443, IPv6,
multi-WAN/QoS; Prometheus alert rules and a Grafana dashboard.
- The user's own router tasks: apply the saved port 4001 forwards to 192.168.168.254 (tcp+udp) and check, install this
release and try the real git path, public ports of antigua, narrow `family` rules.
+15 -1
View File
@@ -246,6 +246,20 @@ Two sources, so nothing the machine already exports is written twice.
- **node_exporter** (`router.metrics.nodeExporter`, `modules/router/metrics.nix`): CPU, memory, disks, interfaces and systemd units. Off by default. It listens on all addresses, but the firewall opens its port (9100) only to the zones in `zones` (one allow rule each, to `local`); `wan` is refused by an assertion. With no zone it can only be read on the router itself. - **node_exporter** (`router.metrics.nodeExporter`, `modules/router/metrics.nix`): CPU, memory, disks, interfaces and systemd units. Off by default. It listens on all addresses, but the firewall opens its port (9100) only to the zones in `zones` (one allow rule each, to `local`); `wan` is refused by an assertion. With no zone it can only be read on the router itself.
- Tested in `webui` (token needed, the samples, node_exporter from the LAN and on the router, the rule names the LAN's device only) and `assertions`. The **Prometheus page** (Services → Prometheus, `exporter.go`) edits the exporter's settings (enable, port, zones to open it to; `wan` and the router's own ports are refused) and shows the scrape config for `/metrics` and for node_exporter. Not done: per-LAN traffic of the web UI's own history (node_exporter has the interface counters), and alert rules or a Grafana dashboard. - Tested in `webui` (token needed, the samples, node_exporter from the LAN and on the router, the rule names the LAN's device only) and `assertions`. The **Prometheus page** (Services → Prometheus, `exporter.go`) edits the exporter's settings (enable, port, zones to open it to; `wan` and the router's own ports are refused) and shows the scrape config for `/metrics` and for node_exporter. Not done: per-LAN traffic of the web UI's own history (node_exporter has the interface counters), and alert rules or a Grafana dashboard.
## Load balancers (2026-11-27)
A service on several hosts that must be reachable from outside and inside, with backend checks (the first case: an API on `hv1` and `hv2`). `router.loadBalancers.<name>` (`options.nix`, `modules/router/loadbalancer.nix`) generates an HAProxy configuration (`services.haproxy`); nothing else on the router changes.
- **Listening:** `listen.port` and `listen.zones` (`wan` = the uplink, or the zones of LANs and tunnels). The firewall opens that port in those zones itself (`lbInput` in `firewall.nix`), so no rule is needed. IPv4 and IPv6 are bound apart: one dual-stack socket shows IPv4 clients as `::ffff:a.b.c.d` in `X-Forwarded-For` (found by the VM test).
- **TLS, a decision per service:** `terminate` (the router decrypts with `certificate`, a PEM with chain and key, or with its own ACME certificate when `router.acme.domains` covers `hosts`; to the backends in the clear or, with `backendTls.enable`, encrypted again, verified only if `backendTls.verify`), `passthrough` (bytes only; the backends have the certificate, and only the checks speak TLS) or `none`. `protocol` is `http` (adds `X-Forwarded-For`) or `tcp` (always with passthrough). `proxyProtocol` sends the client's address to backends that read it (for tcp).
- **Files:** `certificate` and `backendTls.caFile` are paths in the state directory (the settings editor allows nothing else), which is 0700 root: HAProxy runs as its own user, so systemd reads the files as root and hands the service copies (`LoadCredential`, under `/run/credentials/haproxy.service/`; the configuration names those). A path unit restarts HAProxy when one of the files changes (a renewed certificate). Store paths are used as they are. (Found in use in 0.14.0: the `loadbalancer` test used store paths and so missed it; it now keeps both files in `/var/lib/router/lb/` and verifies the backends' certificate.)
- **Backends:** names of DHCP reservations or IPv4 addresses, on `backendPort` (default the listen port). `balance`: `roundrobin`, `leastconn`, `source`. Checks: an HTTP GET of `check.path` (2xx/3xx) every `check.interval`, `fall` failures take a backend out, `rise` successes bring it back; `check.useHttp = false` only connects. With no backend up the service answers 503.
- **Host names:** `hosts` is the Host header or TLS name that selects the service, so services may share a port (each needs `hosts`; they must agree on `tls` and `protocol`). The names are also published in the local DNS (`dns.hosts`, `mkDefault`) as the router's addresses on the LANs the service listens in, so inside and outside use the same name. This is the host-based routing that was open for ports 80/443 (TLS name or Host header; the web UI's own port still has to be another one).
- **Assertions:** a backend that is neither a reservation nor an address, an unknown zone, a port the router itself uses (SSH, DNS, the web UI) or that `firewall.nat` forwards, shared ports without `hosts`, services on a port that disagree, passthrough with `http`, no certificate without ACME, a certificate that does not cover `hosts`.
- **Web UI:** Network → Load balancers (`loadbalancer.go`): the saved configuration beside what HAProxy says (`show stat` on `/run/haproxy/haproxy.sock`: state, last check, connections, time in the state), refreshed every 10 s; "not applied" for a saved service HAProxy does not know yet. Services are edited in Advanced (no form yet).
- Tested in the `loadbalancer` VM test (both backends used from outside and inside, `X-Forwarded-For`, the DNS name, passthrough, the closed port, a sick and a stopped backend, 503, the statistics columns the page reads), `assertions` and the Go tests. Not tested: the PROXY protocol, `balance = source`, `backendTls.verify`, shared ports in a VM, the router's own ACME certificate.
- Open: a form for the settings, backend state in `/metrics` and the MCP tools, UDP, drain/maintenance of a backend from the page.
## Not done yet (2026-11-01, after 0.12.0) ## Not done yet (2026-11-01, after 0.12.0)
Remote access Remote access
@@ -256,7 +270,7 @@ Remote access
- Rule for all of it: changes go through `settings.json` and `router-apply` (commit-confirm), never straight to the live system; tokens have scopes; every call is logged. - Rule for all of it: changes go through `settings.json` and `router-apply` (commit-confirm), never straight to the live system; tokens have scopes; every call is logged.
Firewall and networking Firewall and networking
- **Host-based routing on 80/443**: decide by TLS server name (or the `Host` header) between the router's web UI and a host behind it. It needs an SNI proxy on the router and loses the client address unless the host takes the PROXY protocol. Until then, expose the web UI and SSH on their own ports with `wan -> local` rules. - **Host-based routing on 80/443**: *mostly done by the load balancers* (see above: services sharing a port by `hosts`). Still open: sharing 443 with the router's own web UI, which needs the web UI behind the proxy. Until then, expose the web UI and SSH on their own ports with `wan -> local` rules.
- **WireGuard**: live status (handshake, transfer) in the web UI; a tunnel with `dns = true` but no address. - **WireGuard**: live status (handshake, transfer) in the web UI; a tunnel with `dns = true` but no address.
- **IPv6** for forwards: a pinhole for a host behind the router is possible by hand (`wan -> lan` with an IPv6 `destination`), nothing helps with finding the host's delegated address. Also open: other LANs are IPv4-only (PD serves one LAN), DHCPv6 reservations, NPTv6. - **IPv6** for forwards: a pinhole for a host behind the router is possible by hand (`wan -> lan` with an IPv6 `destination`), nothing helps with finding the host's delegated address. Also open: other LANs are IPv4-only (PD serves one LAN), DHCPv6 reservations, NPTv6.
- **Multi-WAN failover**, **QoS** (CAKE/SQM): deferred, not started. - **Multi-WAN failover**, **QoS** (CAKE/SQM): deferred, not started.
+1 -1
View File
@@ -1 +1 @@
0.13.8 0.14.1
+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; overlapsLan = n: lib.any (l: ipv4.overlaps n l) lanNets;
wgAssertions = wgAssertions =
@@ -597,6 +690,7 @@ in
] ]
++ lib.concatLists (lib.mapAttrsToList perLan lansByName) ++ lib.concatLists (lib.mapAttrsToList perLan lansByName)
++ dnsAssertions ++ dnsAssertions
++ lib.concatLists (lib.mapAttrsToList lbAssertions lbs)
++ lib.concatMap ruleAssertions cfg.firewall.rules ++ lib.concatMap ruleAssertions cfg.firewall.rules
++ lib.concatMap natAssertions cfg.firewall.nat ++ lib.concatMap natAssertions cfg.firewall.nat
++ [ ++ [
+1
View File
@@ -8,6 +8,7 @@
./firewall.nix ./firewall.nix
./dhcp.nix ./dhcp.nix
./dns.nix ./dns.nix
./loadbalancer.nix
./ddns.nix ./ddns.nix
./acme.nix ./acme.nix
./rollback.nix ./rollback.nix
+14
View File
@@ -62,6 +62,19 @@ let
setOf = xs: "{ ${lib.concatMapStringsSep ", " toString xs} }"; 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. # Layer 4 match; `ports` and `sports` may be ints or "a-b" ranges.
l4 = l4 =
proto: ports: sports: proto: ports: sports:
@@ -261,6 +274,7 @@ in
lib.concatMapStringsSep ", " toString listenPorts lib.concatMapStringsSep ", " toString listenPorts
} } accept # wireguard" } } accept # wireguard"
} }
${lib.concatStringsSep "\n " lbInput}
${lib.optionalString (dhcpIfaces != [ ]) "iifname ${set dhcpIfaces} udp dport 67 accept"} ${lib.optionalString (dhcpIfaces != [ ]) "iifname ${set dhcpIfaces} udp dport 67 accept"}
${lib.optionalString (mgmtIfaces != [ ]) "iifname ${set mgmtIfaces} tcp dport { ${ ${lib.optionalString (mgmtIfaces != [ ]) "iifname ${set mgmtIfaces} tcp dport { ${
lib.concatMapStringsSep ", " toString ([ 22 ] ++ config.router.managementPorts) lib.concatMapStringsSep ", " toString ([ 22 ] ++ config.router.managementPorts)
+176
View File
@@ -0,0 +1,176 @@
{ 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;
# Files the services name (certificates with their keys, certificate
# authorities). The settings editor only accepts paths in the state directory
# (0700 root), which HAProxy, a user of its own, cannot enter: systemd reads
# them as root and hands HAProxy copies (LoadCredential). Store paths are
# public and are used as they are.
isStore = p: lib.hasPrefix "/nix/store/" (toString p);
filesOf =
lb:
lib.optional (lb.tls == "terminate" && lb.certificate != null) lb.certificate
++ lib.optional (lb.backendTls.caFile != null) lb.backendTls.caFile;
privateFiles = lib.unique (map toString (lib.filter (p: !isStore p) (lib.concatMap filesOf (lib.attrValues lbs))));
credentialName = p: "lb" + lib.replaceStrings [ "/" ] [ "_" ] p;
fileOf =
p: if isStore p then toString p else "/run/credentials/haproxy.service/${credentialName (toString p)}";
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 fileOf 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 ${fileOf 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;
};
systemd.services.haproxy.serviceConfig.LoadCredential = map (p: "${credentialName p}:${p}") privateFiles;
# HAProxy has its copies from when it started: a file that changes (a
# renewed certificate) needs it restarted.
systemd.paths.router-lb-files = lib.mkIf (privateFiles != [ ]) {
wantedBy = [ "multi-user.target" ];
pathConfig = {
PathChanged = privateFiles;
Unit = "router-lb-files.service";
};
};
systemd.services.router-lb-files = lib.mkIf (privateFiles != [ ]) {
description = "Restart the load balancers for changed certificates";
serviceConfig = {
Type = "oneshot";
ExecStart = "${config.systemd.package}/bin/systemctl restart haproxy.service";
};
};
# 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 { wireguardEndpointRefresh = mkOption {
type = types.nullOr (types.strMatching "[0-9]+(s|min|h)"); type = types.nullOr (types.strMatching "[0-9]+(s|min|h)");
default = "1min"; default = "1min";
+225
View File
@@ -0,0 +1,225 @@
package main
import (
"encoding/csv"
"errors"
"fmt"
"io"
"net"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
// Load balancers (router.loadBalancers) are run by HAProxy; this page shows
// what it says about each backend. The configuration is edited in Advanced.
// LBServer is one backend of a service, as HAProxy sees it.
type LBServer struct {
Name string
Address string
Status string // UP, DOWN, MAINT, NOLB, ... (HAProxy's words)
Check string // what the last check found, e.g. "L7OK/200"
Current int // connections now
Total int // connections since HAProxy started
Since int // seconds in this state
Up bool
}
// LBStatus is one service: the saved configuration and the running state.
type LBStatus struct {
Name string
Port int
Zones string
TLS string
Protocol string
Hosts string
Balance string
Servers []LBServer
Running bool // HAProxy knows the service
Up bool // the service has at least one backend that is up
}
func (s System) haproxySocket() string {
if s.HAProxySocket != "" {
return s.HAProxySocket
}
return "/run/haproxy/haproxy.sock"
}
// haproxyCommand sends one command to HAProxy's socket and returns the answer.
func haproxyCommand(socket, command string) (string, error) {
c, err := net.DialTimeout("unix", socket, 2*time.Second)
if err != nil {
return "", err
}
defer c.Close()
c.SetDeadline(time.Now().Add(3 * time.Second))
if _, err := io.WriteString(c, command+"\n"); err != nil {
return "", err
}
data, err := io.ReadAll(io.LimitReader(c, 4<<20))
return string(data), err
}
// parseServerAddresses reads `show servers state` (a version line, then a
// "# " line naming the columns, then one line per server) into the address
// of each server, keyed "backend/server". (The `addr` column of `show stat`
// is empty in the CSV.)
func parseServerAddresses(data string) map[string]string {
out := map[string]string{}
var col map[string]int
for _, line := range strings.Split(data, "\n") {
f := strings.Fields(line)
if len(f) == 0 {
continue
}
if f[0] == "#" {
col = map[string]int{}
for i, name := range f[1:] {
col[name] = i
}
continue
}
be, sv, addr, port := col["be_name"], col["srv_name"], col["srv_addr"], col["srv_port"]
if col == nil || len(f) <= max(be, sv, addr, port) {
continue
}
out[f[be]+"/"+f[sv]] = f[addr] + ":" + f[port]
}
return out
}
// parseHAProxyStat reads the CSV of `show stat` (its first line names the
// columns) into the servers of each backend, keyed by the proxy name.
func parseHAProxyStat(data string) (map[string][]LBServer, error) {
data = strings.TrimPrefix(strings.TrimSpace(data), "# ")
r := csv.NewReader(strings.NewReader(data))
r.FieldsPerRecord = -1
rows, err := r.ReadAll()
if err != nil {
return nil, err
}
if len(rows) == 0 {
return nil, errors.New("HAProxy answered nothing")
}
col := map[string]int{}
for i, name := range rows[0] {
col[name] = i
}
for _, need := range []string{"pxname", "svname", "status"} {
if _, ok := col[need]; !ok {
return nil, fmt.Errorf("the statistics have no %q column", need)
}
}
get := func(row []string, name string) string {
if i, ok := col[name]; ok && i < len(row) {
return row[i]
}
return ""
}
num := func(row []string, name string) int {
n, _ := strconv.Atoi(get(row, name))
return n
}
out := map[string][]LBServer{}
for _, row := range rows[1:] {
px, sv := get(row, "pxname"), get(row, "svname")
if !strings.HasPrefix(px, "be_") || sv == "" {
continue
}
status := get(row, "status")
srv := LBServer{
Name: sv, Address: get(row, "addr"), Status: status,
Current: num(row, "scur"), Total: num(row, "stot"), Since: num(row, "lastchg"),
Up: strings.HasPrefix(status, "UP") || status == "OPEN",
}
if cs := get(row, "check_status"); cs != "" {
srv.Check = cs
if code := get(row, "check_code"); code != "" {
srv.Check += "/" + code
}
}
out[strings.TrimPrefix(px, "be_")] = append(out[strings.TrimPrefix(px, "be_")], srv)
}
return out, nil
}
// loadBalancers is the saved configuration with HAProxy's state beside it.
func (a *app) loadBalancers(s Settings) ([]LBStatus, string) {
router, _ := s["router"].(map[string]any)
cfg, _ := router["loadBalancers"].(map[string]any)
var out []LBStatus
for name, v := range cfg {
lb, _ := v.(map[string]any)
st := LBStatus{Name: name, TLS: str(lb, "tls"), Protocol: str(lb, "protocol"), Balance: str(lb, "balance"),
Hosts: strings.Join(stringList(lb, "hosts"), ", ")}
if st.TLS == "" {
st.TLS = "terminate"
}
if st.Balance == "" {
st.Balance = "roundrobin"
}
if st.Protocol == "" {
st.Protocol = map[bool]string{true: "tcp", false: "http"}[st.TLS == "passthrough"]
}
listen, _ := lb["listen"].(map[string]any)
if p, ok := listen["port"].(float64); ok {
st.Port = int(p)
}
zones := stringList(listen, "zones")
if len(zones) == 0 {
zones = []string{"wan"}
}
st.Zones = strings.Join(zones, ", ")
out = append(out, st)
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
if len(out) == 0 {
return nil, ""
}
raw, err := haproxyCommand(a.sys.haproxySocket(), "show stat")
if err != nil {
return out, "HAProxy is not running: the services are saved but not applied yet, or it failed to start."
}
servers, err := parseHAProxyStat(raw)
if err != nil {
return out, err.Error()
}
state, _ := haproxyCommand(a.sys.haproxySocket(), "show servers state")
addrs := parseServerAddresses(state)
for i := range out {
if sv, ok := servers[out[i].Name]; ok {
out[i].Running = true
for _, x := range sv {
if x.Name == "BACKEND" {
out[i].Up = x.Up
} else if x.Name != "FRONTEND" {
if x.Address == "" {
x.Address = addrs["be_"+out[i].Name+"/"+x.Name]
}
out[i].Servers = append(out[i].Servers, x)
}
}
}
}
return out, ""
}
func (a *app) loadBalancersPage(w http.ResponseWriter, r *http.Request, sess session) {
p := page{Title: "Load balancers", CSRF: sess.csrf, LoggedIn: true, Flash: r.URL.Query().Get("msg"), Live: 10}
s, err := loadSettings(a.sys.settingsPath())
if err != nil {
p.Error = err.Error()
a.render(w, "loadbalancers", p)
return
}
services, note := a.loadBalancers(s)
p.Data = struct {
Services []LBStatus
Note string
}{services, note}
a.render(w, "loadbalancers", p)
}
+140
View File
@@ -0,0 +1,140 @@
package main
import (
"net"
"os"
"path/filepath"
"strings"
"testing"
)
// What `show stat` says for two services (columns cut down to the ones that matter).
const sampleStat = `# pxname,svname,qcur,qmax,scur,smax,slim,stot,bin,bout,dreq,dresp,ereq,econ,eresp,wretr,wredis,status,weight,act,bck,chkfail,chkdown,lastchg,downtime,qlimit,pid,iid,sid,throttle,lbtot,tracked,type,rate,rate_lim,rate_max,check_status,check_code,check_duration,addr
fe_8443,FRONTEND,,,0,5,,12,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,2,0,,,,0,0,0,1,,,,,
be_api,hv1,0,0,2,3,,7,0,0,,0,,0,0,0,0,UP,1,1,0,0,0,300,0,,1,3,1,,7,,2,0,,1,L7OK,200,3,
be_api,hv2,0,0,0,0,,5,0,0,,0,,0,0,0,0,DOWN,1,1,0,3,1,40,40,,1,3,2,,5,,2,0,,1,L7STS,503,2,
be_api,BACKEND,0,0,2,3,,12,0,0,0,0,,0,0,0,0,UP,1,1,0,,0,300,0,,1,3,0,,12,,1,0,,1,,,,
be_raw,hv1,0,0,0,0,,0,0,0,,0,,0,0,0,0,DOWN,1,1,0,5,1,10,10,,1,4,1,,0,,2,0,,0,L4CON,,0,
be_raw,BACKEND,0,0,0,0,,0,0,0,0,0,,0,0,0,0,DOWN,1,1,0,,1,10,10,,1,4,0,,0,,1,0,,0,,,,
`
func TestParseHAProxyStat(t *testing.T) {
got, err := parseHAProxyStat(sampleStat)
if err != nil {
t.Fatal(err)
}
api := got["api"]
if len(api) != 3 || api[0].Name != "hv1" || !api[0].Up || api[0].Address != "" ||
api[0].Check != "L7OK/200" || api[0].Current != 2 || api[0].Total != 7 || api[0].Since != 300 {
t.Fatalf("api: %+v", api)
}
if api[1].Up || api[1].Status != "DOWN" || api[1].Check != "L7STS/503" {
t.Fatalf("a down backend: %+v", api[1])
}
if _, ok := got["8443"]; ok || len(got["raw"]) != 2 {
t.Fatalf("frontends or raw: %+v", got)
}
if _, err := parseHAProxyStat("# a,b\n1,2\n"); err == nil {
t.Error("statistics without the columns were accepted")
}
if _, err := parseHAProxyStat(""); err == nil {
t.Error("nothing was accepted")
}
}
// The addresses are not in the CSV; `show servers state` has them.
const sampleState = `1
# be_id be_name srv_id srv_name srv_addr srv_op_state srv_port
3 be_api 1 hv1 192.168.10.21 2 8443
3 be_api 2 hv2 192.168.10.22 0 8443
4 be_raw 1 hv1 192.168.10.21 0 8443
`
func TestParseServerAddresses(t *testing.T) {
got := parseServerAddresses(sampleState)
if got["be_api/hv2"] != "192.168.10.22:8443" || got["be_raw/hv1"] != "192.168.10.21:8443" || len(got) != 3 {
t.Fatalf("%v", got)
}
if len(parseServerAddresses("")) != 0 || len(parseServerAddresses("1\n3 be_api 1 hv1 x\n")) != 0 {
t.Error("addresses out of nothing")
}
}
// serveStat answers `show stat` (and `show servers state`) on a socket, like HAProxy.
func serveStat(t *testing.T, path, answer string) {
t.Helper()
l, err := net.Listen("unix", path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { l.Close() })
go func() {
for {
c, err := l.Accept()
if err != nil {
return
}
buf := make([]byte, 64)
n, _ := c.Read(buf)
if strings.HasPrefix(string(buf[:n]), "show servers state") {
c.Write([]byte(sampleState))
} else {
c.Write([]byte(answer))
}
c.Close()
}
}()
}
func TestLoadBalancersPage(t *testing.T) {
a, sys := newTestApp(t)
// (A short path: a unix socket's name is limited.)
sys.HAProxySocket = filepath.Join(os.TempDir(), "lb-test-"+filepath.Base(t.TempDir())+".sock")
a.sys = sys
h := a.routes()
cookie := login(t, h)
menu := do(h, "GET", "/", nil, cookie).Body.String()
if !strings.Contains(menu, `href="/loadbalancers"`) {
t.Fatalf("no menu entry:\n%s", menu)
}
// Nothing configured: the page says how.
body := do(h, "GET", "/loadbalancers", nil, cookie).Body.String()
if !strings.Contains(body, "No load balancer is set up") || !strings.Contains(body, "router.loadBalancers") {
t.Fatalf("empty page:\n%s", body)
}
settings := `{"system":{"hostName":"router","stateVersion":"26.11"},"router":{"loadBalancers":{
"api":{"listen":{"port":8443,"zones":["wan","lan"]},"hosts":["api.example.org"],"backends":["hv1","hv2"]},
"raw":{"listen":{"port":9443},"tls":"passthrough","backends":["hv1"]}}}}`
os.WriteFile(sys.settingsPath(), []byte(settings), 0o600)
// Saved, HAProxy not running: say so, show the configuration.
body = do(h, "GET", "/loadbalancers", nil, cookie).Body.String()
for _, want := range []string{"HAProxy is not running", "<h2>api", "port 8443 in wan, lan", "api.example.org", "<h2>raw", "passed through", "roundrobin"} {
if !strings.Contains(body, want) {
t.Errorf("without HAProxy the page lacks %q:\n%s", want, body)
}
}
if strings.Contains(body, `class="badge`) {
t.Errorf("a status badge without knowing:\n%s", body)
}
// Running: one service up (one backend down), one down.
serveStat(t, sys.HAProxySocket, sampleStat)
body = do(h, "GET", "/loadbalancers", nil, cookie).Body.String()
for _, want := range []string{"192.168.10.21:8443", "L7OK/200", "L7STS/503", "badge ok", "badge bad", "7 in all", "300 s", `data-live="10"`} {
if !strings.Contains(body, want) {
t.Errorf("the page lacks %q:\n%s", want, body)
}
}
if strings.Contains(body, "HAProxy is not running") {
t.Errorf("claims HAProxy is down:\n%s", body)
}
// A service HAProxy does not know yet is "not applied".
os.WriteFile(sys.settingsPath(), []byte(strings.Replace(settings, `"raw"`, `"new"`, 1)), 0o600)
if body = do(h, "GET", "/loadbalancers", nil, cookie).Body.String(); !strings.Contains(body, `badge">not applied`) {
t.Errorf("a new service is not marked:\n%s", body)
}
}
+2 -1
View File
@@ -270,7 +270,7 @@ func newApp(sys System, metrics *Collector, dev bool) *app {
func (a *app) parseTemplates() (map[string]*template.Template, error) { func (a *app) parseTemplates() (map[string]*template.Template, error) {
files := map[string][]string{"overview": {"templates/dashboard.html"}} files := map[string][]string{"overview": {"templates/dashboard.html"}}
pages := map[string]*template.Template{} pages := map[string]*template.Template{}
for _, page := range []string{"login", "overview", "network", "dhcp", "dns", "wireguard", "firewall", "ddns", "dnsproviders", "certificate", "exporter", "advanced", "update", "tokens", "changes"} { for _, page := range []string{"login", "overview", "network", "dhcp", "dns", "wireguard", "firewall", "loadbalancers", "ddns", "dnsproviders", "certificate", "exporter", "advanced", "update", "tokens", "changes"} {
t, err := template.New("layout.html").Funcs(a.funcs). t, err := template.New("layout.html").Funcs(a.funcs).
ParseFS(assets, append([]string{"templates/layout.html", "templates/" + page + ".html"}, files[page]...)...) ParseFS(assets, append([]string{"templates/layout.html", "templates/" + page + ".html"}, files[page]...)...)
if err != nil { if err != nil {
@@ -328,6 +328,7 @@ func (a *app) routes() http.Handler {
mux.HandleFunc("POST /dnsproviders", a.auth(a.providersSave)) mux.HandleFunc("POST /dnsproviders", a.auth(a.providersSave))
mux.HandleFunc("GET /certificate", a.auth(a.certificatePage)) mux.HandleFunc("GET /certificate", a.auth(a.certificatePage))
mux.HandleFunc("POST /certificate", a.auth(a.certificateSave)) mux.HandleFunc("POST /certificate", a.auth(a.certificateSave))
mux.HandleFunc("GET /loadbalancers", a.auth(a.loadBalancersPage))
mux.HandleFunc("GET /prometheus", a.auth(a.exporterPage)) mux.HandleFunc("GET /prometheus", a.auth(a.exporterPage))
mux.HandleFunc("POST /prometheus", a.auth(a.exporterSave)) mux.HandleFunc("POST /prometheus", a.auth(a.exporterSave))
mux.HandleFunc("GET /firewall", a.auth(a.firewallPage)) mux.HandleFunc("GET /firewall", a.auth(a.firewallPage))
+1
View File
@@ -161,6 +161,7 @@ pre code { background: none; padding: 0; }
.muted { color: var(--muted); } .muted { color: var(--muted); }
.bad { color: var(--bad); } .bad { color: var(--bad); }
.ok { color: var(--good); } .ok { color: var(--good); }
.badge { font-size: .75em; font-weight: 600; padding: .1em .55em; border: 1px solid currentColor; border-radius: 1em; vertical-align: middle; }
body.bare { padding-left: 0; } body.bare { padding-left: 0; }
.bare header { position: static; width: auto; flex-direction: row; background: none; padding: 1rem 1.25rem; } .bare header { position: static; width: auto; flex-direction: row; background: none; padding: 1rem 1.25rem; }
+3 -1
View File
@@ -27,7 +27,9 @@ type System struct {
VersionFile string VersionFile string
// LeasesDNSDir is where leases-dns leaves its status; /run/router-leases-dns if empty. // LeasesDNSDir is where leases-dns leaves its status; /run/router-leases-dns if empty.
LeasesDNSDir string LeasesDNSDir string
ACMEDir string // where the ACME client keeps the web UI's certificate (fullchain.pem, key.pem), if any // HAProxySocket is where the load balancers' statistics are; /run/haproxy/haproxy.sock if empty.
HAProxySocket string
ACMEDir string // where the ACME client keeps the web UI's certificate (fullchain.pem, key.pem), if any
} }
func (s System) leasesDNSDir() string { func (s System) leasesDNSDir() string {
+1
View File
@@ -21,6 +21,7 @@
<a href="/dns"{{if eq .Title "DNS"}} aria-current="page"{{end}}>DNS</a> <a href="/dns"{{if eq .Title "DNS"}} aria-current="page"{{end}}>DNS</a>
<a href="/wireguard"{{if eq .Title "WireGuard"}} aria-current="page"{{end}}>WireGuard</a> <a href="/wireguard"{{if eq .Title "WireGuard"}} aria-current="page"{{end}}>WireGuard</a>
<a href="/firewall"{{if eq .Title "Firewall"}} aria-current="page"{{end}}>Firewall</a> <a href="/firewall"{{if eq .Title "Firewall"}} aria-current="page"{{end}}>Firewall</a>
<a href="/loadbalancers"{{if eq .Title "Load balancers"}} aria-current="page"{{end}}>Load balancers</a>
</div> </div>
<div class="group"><span>Services</span> <div class="group"><span>Services</span>
<a href="/ddns"{{if eq .Title "Dynamic DNS"}} aria-current="page"{{end}}>Dynamic DNS</a> <a href="/ddns"{{if eq .Title "Dynamic DNS"}} aria-current="page"{{end}}>Dynamic DNS</a>
@@ -0,0 +1,48 @@
{{define "content"}}
{{with .Data}}
{{if .Note}}<p class="flash">{{.Note}}</p>{{end}}
{{range .Services}}
<section>
<h2>{{.Name}}
{{if not $.Data.Note}}{{if not .Running}}<span class="badge">not applied</span>{{else if .Up}}<span class="badge ok">up</span>{{else}}<span class="badge bad">down</span>{{end}}{{end}}
</h2>
<dl>
<dt>Listens on</dt><dd>port {{.Port}} in {{.Zones}}</dd>
<dt>TLS</dt><dd>{{if eq .TLS "terminate"}}decrypted on the router{{else if eq .TLS "passthrough"}}passed through{{else}}none{{end}}, {{.Protocol}}</dd>
{{if .Hosts}}<dt>Names</dt><dd>{{.Hosts}}</dd>{{end}}
<dt>Balancing</dt><dd>{{.Balance}}</dd>
</dl>
{{if .Servers}}
<table>
<thead><tr><th>Backend</th><th>Address</th><th>State</th><th>Last check</th><th>Connections</th><th>In this state</th></tr></thead>
<tbody>
{{range .Servers}}<tr>
<td>{{.Name}}</td><td>{{.Address}}</td>
<td>{{if .Up}}<span class="badge ok">{{.Status}}</span>{{else}}<span class="badge bad">{{.Status}}</span>{{end}}</td>
<td>{{.Check}}</td><td>{{.Current}} now, {{.Total}} in all</td><td>{{.Since}} s</td>
</tr>{{end}}
</tbody>
</table>
{{else if .Running}}<p class="muted">HAProxy has no backend for it.</p>{{end}}
</section>
{{else}}
<section>
<p>No load balancer is set up. A load balancer spreads the connections to a service over several hosts and leaves out a host
that fails its checks. Add one under <code>router.loadBalancers</code> in <a href="/advanced">Advanced</a>, for example:</p>
<pre class="log">"loadBalancers": {
"api": {
"listen": { "port": 8443, "zones": ["wan", "lan"] },
"tls": "terminate",
"hosts": ["api.example.org"],
"backends": ["hv1", "hv2"],
"backendTls": { "enable": true },
"check": { "path": "/healthz" }
}
}</pre>
<p>The backends are names of DHCP reservations or addresses. With <code>"tls": "passthrough"</code> the backends keep their
certificate and the router only forwards; the client's address then reaches them with <code>"proxyProtocol": true</code>
(if they read it). Saved changes take effect when you apply them.</p>
</section>
{{end}}
{{end}}
{{end}}
+141
View File
@@ -61,6 +61,31 @@ let
}; };
} overrides; } overrides;
# A LAN with two reserved hosts, and a service on them.
lbLan = lan {
dhcp.reservations = {
hv1 = {
mac = "02:00:00:00:00:21";
address = "192.168.10.21";
};
hv2 = {
mac = "02:00:00:00:00:22";
address = "192.168.10.22";
};
};
};
lb =
overrides:
lib.recursiveUpdate {
listen.port = 8443;
certificate = "/var/lib/router/lb.pem";
backends = [
"hv1"
"hv2"
];
backendTls.enable = true;
} overrides;
failed = router: map (a: a.message) (lib.filter (a: !a.assertion) (evalRouter router).assertions); failed = router: map (a: a.message) (lib.filter (a: !a.assertion) (evalRouter router).assertions);
cases = { cases = {
@@ -704,6 +729,121 @@ let
}; };
expect = [ ]; expect = [ ];
}; };
lbValid = {
router = {
lans.main = lbLan;
loadBalancers.api = lb { };
# Two services share a port when the host name tells them apart.
loadBalancers.a = lb {
listen.port = 9443;
hosts = [ "a.example.org" ];
};
loadBalancers.b = lb {
listen.port = 9443;
hosts = [ "b.example.org" ];
};
};
expect = [ ];
};
lbUnknownBackend = {
router = {
lans.main = lbLan;
loadBalancers.api = lb { backends = [ "hv1" "nothere" ]; };
};
expect = [ "`nothere` is neither a DHCP reservation nor an IPv4 address" ];
};
lbNoBackends = {
router = {
lans.main = lbLan;
loadBalancers.api = lb { backends = lib.mkForce [ ]; };
};
expect = [ "at least one backend" ];
};
lbUnknownZone = {
router = {
lans.main = lbLan;
loadBalancers.api = lb { listen.zones = [ "dmz" ]; };
};
expect = [ "listen.zones: unknown zone" ];
};
lbPortOfTheRouter = {
router = {
lans.main = lbLan;
loadBalancers.api = lb { listen.port = 22; };
};
expect = [ "is used by the router itself" ];
};
lbPortForwarded = {
router = {
lans.main = lbLan;
loadBalancers.api = lb { listen.port = 8443; };
firewall.nat = [
{
type = "dnat";
from = "wan";
to = "main";
protocol = "tcp";
ports = [ 8443 ];
toAddress = "192.168.10.50";
}
];
};
expect = [ "is also forwarded by router.firewall.nat" ];
};
lbSharedPortWithoutHosts = {
router = {
lans.main = lbLan;
loadBalancers.a = lb { };
loadBalancers.b = lb { hosts = [ "b.example.org" ]; };
};
expect = [
"port 8443 is shared with b: every service on it needs `hosts`"
"port 8443 is shared with a: every service on it needs `hosts`"
];
};
lbSharedPortDisagrees = {
router = {
lans.main = lbLan;
loadBalancers.a = lb { hosts = [ "a.example.org" ]; };
loadBalancers.b = lb {
hosts = [ "b.example.org" ];
tls = "none";
certificate = lib.mkForce null;
};
};
expect = [
"must agree on tls and protocol"
"must agree on tls and protocol"
];
};
lbPassthroughNeedsTcp = {
router = {
lans.main = lbLan;
loadBalancers.api = lb {
tls = "passthrough";
protocol = "http";
certificate = lib.mkForce null;
};
};
expect = [ "passthrough only forwards bytes" ];
};
lbTerminateWithoutCertificate = {
router = {
lans.main = lbLan;
loadBalancers.api = lb { certificate = lib.mkForce null; };
};
expect = [ "has no `certificate` and router.acme is not enabled" ];
};
lbVerifyNeedsTls = {
router = {
lans.main = lbLan;
loadBalancers.api = lb {
backendTls.enable = lib.mkForce false;
backendTls.verify = true;
};
};
expect = [ "backendTls.verify needs backendTls.enable" ];
};
wgNoPeers = { wgNoPeers = {
router = { router = {
lans.main = lan { }; lans.main = lan { };
@@ -1589,6 +1729,7 @@ let
"ulaValid" "ulaValid"
"wgSourceOk" "wgSourceOk"
"dnsValid" "dnsValid"
"lbValid"
]; ];
subnet = subnet =
+1
View File
@@ -11,6 +11,7 @@
rollback = import ./rollback.nix { inherit self pkgs; }; rollback = import ./rollback.nix { inherit self pkgs; };
dns = import ./dns.nix { inherit self pkgs; }; dns = import ./dns.nix { inherit self pkgs; };
ddns = import ./ddns.nix { inherit self pkgs; }; ddns = import ./ddns.nix { inherit self pkgs; };
loadbalancer = import ./loadbalancer.nix { inherit self pkgs; };
installer = import ./installer.nix { inherit self pkgs; }; installer = import ./installer.nix { inherit self pkgs; };
apply = import ./apply.nix { inherit self pkgs; }; apply = import ./apply.nix { inherit self pkgs; };
webui = import ./webui.nix { inherit self pkgs; }; webui = import ./webui.nix { inherit self pkgs; };
+324
View File
@@ -0,0 +1,324 @@
# 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
'';
}