Files

302 lines
15 KiB
Nix

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# NixOS VM tests, ROADMAP §5 layer 4: a failed apply auto-reverts; switching to Caddy and back
# keeps a host reachable; intermediate renewal with a test root; control unreachable from
# outside loopback. They need KVM (`nix flake check` on Linux with /dev/kvm).
{ pkgs, self }:
let
ianitor = self.packages.${pkgs.stdenv.hostPlatform.system}.ianitor;
# A test root made at build time with the release binary, as on the offline machine. A test
# root may live in the store; a real one never does (docs/pki.md).
testRoot = pkgs.runCommand "ianitor-test-root" { } ''
mkdir -p $out
printf 'test-root-passphrase-0123' > pass
${ianitor}/bin/ianitor-control ca init --out $out --passphrase-file pass
cp pass $out/passphrase
'';
# Secrets for the VM, written by tmpfiles to paths outside the store (the module refuses
# store paths for credentials). Test values only.
secrets = [
"d /var/lib/ianitor-secrets 0700 root root - -"
"f /var/lib/ianitor-secrets/share-link-key 0600 root root - vm-test-share-link-key-0123456789abcdef0123"
"f /var/lib/ianitor-secrets/pki-password 0600 root root - vm-test-pki-password-0123456789"
];
server =
{ ... }:
{
imports = [ self.nixosModules.ianitor ];
virtualisation.memorySize = 2048;
networking.firewall.enable = true;
services.ianitor = {
enable = true;
package = ianitor;
edge.openFirewall = true;
watchSeconds = 8;
shareLinkKeyFile = "/var/lib/ianitor-secrets/share-link-key";
pki = {
enable = true;
rootCertificate = "${testRoot}/domi-root.crt";
passwordFile = "/var/lib/ianitor-secrets/pki-password";
};
};
systemd.tmpfiles.rules = secrets;
# A test upstream.
systemd.services.upstream = {
wantedBy = [ "multi-user.target" ];
serviceConfig.ExecStart = "${pkgs.python3}/bin/python3 -m http.server 8000 --bind 127.0.0.1 --directory /etc";
};
environment.systemPackages = [ pkgs.curl pkgs.jq pkgs.openssl ];
};
# Python helpers shared by the test scripts.
helpers = ''
import json, shlex, time
def setup(m):
m.wait_for_unit("ianitor-control.service")
m.wait_for_unit("ianitor-engine-select.service")
m.wait_until_succeeds("test -S /run/ianitor-edge/admin.sock")
m.wait_for_unit("upstream.service")
return m.succeed(
"runuser -u ianitor-control -- ianitor-control token create --name vm --config /etc/ianitor/control.toml"
).strip()
def api(m, token, method, path, body=None, ok=True):
cmd = f"curl -s -X {method} -H 'Authorization: Bearer {token}' http://127.0.0.1:7878/api/v1{path}"
if body is not None:
cmd += " -H 'Content-Type: application/json' -d " + shlex.quote(json.dumps(body))
out = m.succeed(cmd)
return json.loads(out) if out.strip() else {}
def wait_apply(m, token, apply_id):
for _ in range(120):
a = api(m, token, "GET", f"/applies/{apply_id}")
if a.get("state") in ("kept", "reverted", "failed", "needs_attention"):
return a
time.sleep(1)
raise Exception(f"apply {apply_id} did not finish")
def install_intermediate(m, token):
r = api(m, token, "POST", "/certs/intermediate/renewal", {})
m.succeed("install -d -m 0700 /root/offline")
m.succeed("cat > /root/offline/req.csr << 'EOF'\n" + r["csr_pem"] + "EOF")
# The offline step (docs/pki.md), with the test root.
m.succeed(
"ianitor-control ca sign --root ${testRoot} --csr /root/offline/req.csr "
"--out /root/offline/int.crt --yes --passphrase-file ${testRoot}/passphrase"
)
m.succeed("install -m 0644 /root/offline/int.crt /tmp/int.crt")
m.succeed("runuser -u ianitor-control -- ianitor-control pki install /tmp/int.crt --config /etc/ianitor/control.toml")
for _ in range(30):
if api(m, token, "GET", f"/pki-requests/{r['request_id']}")["state"] == "approved":
return
time.sleep(1)
raise Exception("the intermediate was not installed")
def visit(m, host):
return m.succeed(
f"curl -s -o /dev/null -w '%{{http_code}}' --cacert ${testRoot}/domi-root.crt "
f"--resolve {host}:443:127.0.0.1 https://{host}/"
).strip()
'';
test =
name: script:
pkgs.testers.runNixOSTest {
name = "ianitor-${name}";
nodes.server = server;
testScript = helpers + script;
};
in
{
vm-apply-reverts = test "apply-reverts" ''
start_all()
t = setup(server)
install_intermediate(server, t)
before = server.succeed("sha256sum /var/lib/ianitor/edge/edge.json")
r = api(server, t, "POST", "/hosts", {"host": {
"hostname": "broken.test", "upstreams": ["http://127.0.0.1:9"], "tls": "domi", "auth": "none",
"health_check": {"path": "/", "interval_secs": 1}}})
a = wait_apply(server, t, r["apply"]["id"])
assert a["state"] == "reverted", a
# edge and its file never left the last good config.
assert server.succeed("sha256sum /var/lib/ianitor/edge/edge.json") == before
server.fail("grep -q broken.test /var/lib/ianitor/edge/edge.json")
# The routes repository holds the change and its revert.
history = server.succeed("runuser -u ianitor-control -- git -C /var/lib/ianitor/control/routes.git log --oneline")
assert "broken.test" in history, history
'';
vm-engine-switch = test "engine-switch" ''
start_all()
t = setup(server)
install_intermediate(server, t)
r = api(server, t, "POST", "/hosts", {"host": {
"hostname": "app.test", "upstreams": ["http://127.0.0.1:8000"], "tls": "domi", "auth": "none"}})
assert wait_apply(server, t, r["apply"]["id"])["state"] == "kept"
assert visit(server, "app.test") == "200"
api(server, t, "POST", "/engine", {"target": "caddy"})
server.wait_until_succeeds(
f"curl -s -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/engine | jq -e '.running == \"caddy\" and .state == \"running\"'"
)
server.wait_for_unit("caddy-fallback.service")
server.fail("systemctl is-active ianitor-edge.service")
assert server.succeed("cat /var/lib/ianitor/engine").strip() == "caddy"
server.wait_until_succeeds("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve app.test:443:127.0.0.1 https://app.test/ | grep -q 200")
# Changes keep working while Caddy serves: loaded through its admin socket and watched.
r = api(server, t, "POST", "/hosts", {"host": {
"hostname": "two.test", "upstreams": ["http://127.0.0.1:8000"], "tls": "domi", "auth": "none"}})
assert wait_apply(server, t, r["apply"]["id"])["state"] == "kept"
server.succeed("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve two.test:443:127.0.0.1 https://two.test/ | grep -q 200")
# The trial's deadline under Caddy does not depend on control (fix round 2, B2): the guard
# runs with Caddy, only control may use Caddy's admin socket, and a control killed during
# the watch leaves Caddy on the last good config (ExecStopPost=caddy-revert).
server.succeed("systemctl is-active ianitor-caddy-guard.service")
server.fail("runuser -u ianitor-edge -- test -w /run/caddy-fallback/admin.sock")
server.succeed("runuser -u ianitor-control -- test -w /run/caddy-fallback/admin.sock")
r = api(server, t, "POST", "/hosts", {"host": {
"hostname": "three.test", "upstreams": ["http://127.0.0.1:8000"], "tls": "domi", "auth": "none"}})
three = r["apply"]["id"]
for _ in range(60):
if api(server, t, "GET", f"/applies/{three}").get("state") == "watching":
break
time.sleep(0.5)
assert visit(server, "three.test") == "200", "the trial serves"
server.succeed("systemctl kill --signal=KILL ianitor-control.service")
server.wait_until_fails("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve three.test:443:127.0.0.1 https://three.test/ | grep -q 200", timeout=10)
server.wait_for_unit("ianitor-control.service")
server.wait_until_succeeds(f"curl -sf -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/overview")
assert wait_apply(server, t, three)["state"] == "reverted"
assert visit(server, "two.test") == "200"
api(server, t, "POST", "/engine", {"target": "pingora"})
server.wait_until_succeeds(
f"curl -s -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/engine | jq -e '.running == \"pingora\" and .state == \"running\"'"
)
server.wait_for_unit("ianitor-edge.service")
server.fail("systemctl is-active caddy-fallback.service")
assert visit(server, "app.test") == "200"
# The choice survives a reboot (engine-select).
api(server, t, "POST", "/engine", {"target": "caddy"})
server.wait_until_succeeds("grep -qx caddy /var/lib/ianitor/engine")
server.wait_for_unit("caddy-fallback.service")
server.shutdown()
server.start()
server.wait_for_unit("ianitor-engine-select.service")
server.wait_for_unit("caddy-fallback.service")
server.wait_until_succeeds("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve app.test:443:127.0.0.1 https://app.test/ | grep -q 200")
# polkit lets control manage exactly the two engine units, nothing else.
server.fail("runuser -u ianitor-control -- systemctl --no-ask-password restart upstream.service")
server.fail("runuser -u ianitor-control -- systemctl --no-ask-password stop ianitor-control.service")
'';
vm-intermediate-renewal = test "intermediate-renewal" ''
start_all()
t = setup(server)
ov = api(server, t, "GET", "/overview")
assert ov["intermediate"]["state"] == "missing", ov["intermediate"]
install_intermediate(server, t)
first = server.succeed("cat /var/lib/ianitor/control/pki/intermediate.crt")
r = api(server, t, "POST", "/hosts", {"host": {
"hostname": "app.test", "upstreams": ["http://127.0.0.1:8000"], "tls": "domi", "auth": "none"}})
assert wait_apply(server, t, r["apply"]["id"])["state"] == "kept"
assert visit(server, "app.test") == "200"
# Renew: a new intermediate, the host certificate reissued, still trusted by the root.
install_intermediate(server, t)
assert server.succeed("cat /var/lib/ianitor/control/pki/intermediate.crt") != first
server.wait_until_succeeds(
"openssl verify -CAfile ${testRoot}/domi-root.crt -untrusted /var/lib/ianitor/control/pki/intermediate.crt "
"<(openssl x509 -in /var/lib/ianitor/certs/app.test.crt) | grep -q OK"
)
assert visit(server, "app.test") == "200"
# The intermediate key is encrypted at rest, and no root key is on the server.
server.succeed("grep -q 'IANITOR ENCRYPTED' /var/lib/ianitor/control/pki/intermediate.key")
server.fail("grep -rqs 'BEGIN PRIVATE KEY' /var/lib/ianitor/control")
server.fail("find /var/lib/ianitor -name 'domi-root.key' | grep -q .")
'';
# G14 option b and the proxy socket (phase 4): another local user can neither open control's
# UI socket nor use the proof over the loopback port; the front proxy's socket is for the
# ianitor-proxy group only.
vm-sockets = pkgs.testers.runNixOSTest {
name = "ianitor-sockets";
nodes.server = {
imports = [ server ];
services.ianitor.edge.proxySocket = { enable = true; users = [ "front" ]; };
services.ianitor.ui.hostname = "ui.test";
users.users.front.isNormalUser = true;
users.users.mallory.isNormalUser = true;
};
testScript = helpers + ''
start_all()
t = setup(server)
install_intermediate(server, t)
server.succeed("test -S /run/ianitor-control/ui.sock")
assert server.succeed("stat -c %a /run/ianitor-control/ui.sock").strip() == "660"
assert server.succeed("stat -c %a /run/ianitor-control").strip() == "750"
# Another local user cannot reach the UI socket ...
server.fail("runuser -u mallory -- curl -sf -m 5 --unix-socket /run/ianitor-control/ui.sock http://localhost/api/v1/overview")
# ... nor sign in over the loopback port, even with the real proof (read here as root).
proof = server.succeed("cat /run/ianitor-proof/ui-proof").strip()
code = server.succeed(
"runuser -u mallory -- curl -s -o /dev/null -w '%{http_code}' -H 'Remote-User: mallory' "
+ "-H 'X-Ianitor-Proof: " + proof + "' http://127.0.0.1:7878/api/v1/overview"
).strip()
assert code == "401", code
# The same over the socket, as edge (group ianitor): signed in.
code = server.succeed(
"runuser -u ianitor-edge -- curl -s -o /dev/null -w '%{http_code}' -H 'Host: ui.test' "
+ "-H 'Remote-User: mark' -H 'X-Ianitor-Proof: " + proof + "' "
+ "--unix-socket /run/ianitor-control/ui.sock http://ui.test/api/v1/overview"
).strip()
assert code == "200", code
# The front proxy's socket: the front user may connect, mallory may not.
r = api(server, t, "POST", "/hosts", {"host": {
"hostname": "app.test", "upstreams": ["http://127.0.0.1:8000"], "tls": "domi", "auth": "none"}})
assert wait_apply(server, t, r["apply"]["id"])["state"] == "kept"
server.wait_until_succeeds("test -S /run/ianitor-proxy/edge.sock")
assert server.succeed("stat -c '%a %G' /run/ianitor-proxy/edge.sock").strip() == "660 ianitor-proxy"
# Sticky and setgid: the front proxy may connect but not unlink or replace edge's socket.
assert server.succeed("stat -c '%a %U %G' /run/ianitor-proxy").strip() == "3770 root ianitor-proxy"
server.fail("runuser -u front -- rm -f /run/ianitor-proxy/edge.sock")
server.succeed("test -S /run/ianitor-proxy/edge.sock")
code = server.succeed(
"runuser -u front -- curl -s -o /dev/null -w '%{http_code}' --unix-socket /run/ianitor-proxy/edge.sock http://app.test/"
).strip()
assert code == "200", code
server.fail("runuser -u mallory -- curl -sf -m 5 --unix-socket /run/ianitor-proxy/edge.sock http://app.test/")
'';
};
vm-control-loopback = pkgs.testers.runNixOSTest {
name = "ianitor-control-loopback";
nodes.server = server;
nodes.client = { environment.systemPackages = [ pkgs.curl ]; };
testScript = helpers + ''
start_all()
setup(server)
client.wait_for_unit("multi-user.target")
# Only edge listens beyond loopback.
listen = server.succeed("ss -Hltn")
assert "127.0.0.1:7878" in listen, listen
assert "0.0.0.0:7878" not in listen and "*:7878" not in listen and "[::]:7878" not in listen, listen
client.fail("curl -s -m 5 http://server:7878/api/v1/overview")
# Edge answers from outside (404 for an unknown host).
code = client.succeed("curl -s -o /dev/null -w '%{http_code}' -m 10 http://server/").strip()
assert code == "404", code
'';
};
}