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
5 changed files with 158 additions and 5 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.
+1
View File
@@ -252,6 +252,7 @@ A service on several hosts that must be reachable from outside and inside, with
- **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`.
+1 -1
View File
@@ -1 +1 @@
0.14.0
0.14.1
+36 -2
View File
@@ -13,9 +13,24 @@ let
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 toString lb.certificate else acmePem;
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);
@@ -69,7 +84,7 @@ let
secure = lb.backendTls.enable;
verify =
if lb.backendTls.verify then
"verify required${lib.optionalString (lb.backendTls.caFile != null) " ca-file ${toString lb.backendTls.caFile}"}"
"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.
@@ -119,6 +134,25 @@ in
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} = {
+22 -2
View File
@@ -129,6 +129,13 @@ pkgs.testers.runNixOSTest {
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";
@@ -162,12 +169,18 @@ pkgs.testers.runNixOSTest {
"main"
];
hosts = [ "api.lb.test" ];
certificate = "${cert}/both.pem";
# 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;
backendTls = {
enable = true;
verify = true;
caFile = "/var/lib/router/lb/ca.pem";
};
check.path = "/healthz";
check.interval = "1s";
check.fall = 2;
@@ -279,6 +292,13 @@ pkgs.testers.runNixOSTest {
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)