From ca9bf3fdd4984a32f7333092596c45f2467455de Mon Sep 17 00:00:00 2001 From: mnovak Date: Sun, 8 Nov 2026 00:04:13 +0100 Subject: [PATCH] [repo] NixOS: flake with the release build (test hooks off) and the web UI, services.ianitor module (edge, control, caddy-fallback, engine-select, per-boot UI proof, polkit for exactly two units), four VM tests, deploy/test-access.sh --- deploy/nixos/module.nix | 392 +++++++++++++++++++++++++ deploy/nixos/package.nix | 54 ++++ deploy/nixos/tests/default.nix | 220 ++++++++++++++ deploy/nixos/web.nix | 44 +++ deploy/test-access.sh | 119 ++++++++ docs/ROADMAP.md | 6 +- docs/api.md | 96 +++++- docs/deploy/beside-caddy.md | 126 ++++++++ docs/deploy/configuration-server.patch | 119 ++++++++ docs/pki.md | 112 +++++++ docs/ui-api.md | 31 ++ flake.lock | 27 ++ flake.nix | 33 +++ 13 files changed, 1375 insertions(+), 4 deletions(-) create mode 100644 deploy/nixos/module.nix create mode 100644 deploy/nixos/package.nix create mode 100644 deploy/nixos/tests/default.nix create mode 100644 deploy/nixos/web.nix create mode 100755 deploy/test-access.sh create mode 100644 docs/deploy/beside-caddy.md create mode 100644 docs/deploy/configuration-server.patch create mode 100644 docs/pki.md create mode 100644 flake.lock create mode 100644 flake.nix diff --git a/deploy/nixos/module.nix b/deploy/nixos/module.nix new file mode 100644 index 0000000..8812af5 --- /dev/null +++ b/deploy/nixos/module.nix @@ -0,0 +1,392 @@ +# 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/. + +# services.ianitor: ianitor-edge (the only public listener), ianitor-control (loopback), +# caddy-fallback (the same routes as Caddy JSON), the engine-select unit, the per-boot UI proof, +# and a polkit rule that lets control start, stop and restart exactly the two engine units. +# +# Secrets never enter the Nix store: every credential is a *path string* to a file outside the +# store (sops-nix, agenix, Custos provisioning, ...), loaded with systemd LoadCredential; an +# assertion refuses any /nix/store path. +self: +{ config, lib, pkgs, ... }: + +let + cfg = config.services.ianitor; + inherit (lib) mkOption mkEnableOption mkIf types; + pkg = cfg.package; + stateRoot = "/var/lib/ianitor"; + runProof = "/run/ianitor-proof"; + toml = pkgs.formats.toml { }; + + isStore = p: lib.hasPrefix builtins.storeDir (toString p); + # Every credential file the units load, by credential name. + edgeCreds = + cfg.credentials + // lib.optionalAttrs (cfg.shareLinkKeyFile != null) { "share-link-key" = cfg.shareLinkKeyFile; }; + controlCreds = + lib.optionalAttrs (cfg.shareLinkKeyFile != null) { "share-link-key" = cfg.shareLinkKeyFile; } + // lib.optionalAttrs (cfg.pki.enable) { "pki-password" = cfg.pki.passwordFile; } + // lib.optionalAttrs (cfg.routes.pushCredentialFile != null) { push = cfg.routes.pushCredentialFile; }; + userCreds = edgeCreds // controlCreds; + loadCreds = creds: lib.mapAttrsToList (n: p: "${n}:${p}") creds; + + compile = { + http_listen = cfg.edge.httpListen; + https_listen = cfg.edge.httpsListen; + cert_dir = "${stateRoot}/certs"; + state_dir = "${stateRoot}/edge-state"; + access_log = "/var/log/ianitor/access.log"; + caddy_credentials_dir = "/run/credentials/caddy-fallback.service"; + }; + + controlToml = toml.generate "control.toml" ( + { + listen = cfg.control.listen; + state_dir = "${stateRoot}/control"; + git = "${pkgs.git}/bin/git"; + watch_secs = cfg.watchSeconds; + routes = + { + repo = "${stateRoot}/control/routes.git"; + remote_name = cfg.routes.remoteName; + push_username = cfg.routes.pushUsername; + } + // lib.optionalAttrs (cfg.routes.remote != null) { remote = cfg.routes.remote; } + // lib.optionalAttrs (cfg.routes.pushCredentialFile != null) { push_credential = "push"; }; + edge = { + config = "${stateRoot}/edge/edge.json"; + admin_socket = "/run/ianitor-edge/admin.sock"; + share_revocations = "${stateRoot}/edge/share-revocations.json"; + }; + caddy.config = "${stateRoot}/caddy/caddy.json"; + inherit compile; + # Caddy keeps its own storage and access log; the listeners and certificates are the same. + compile_caddy = compile // { + state_dir = "${stateRoot}/caddy-state"; + access_log = "/var/log/ianitor/caddy-access.log"; + }; + ui = + { + proof_credential = "ui-proof"; + static_dir = "${pkg}/share/ianitor/web"; + } + // lib.optionalAttrs (cfg.ui.hostname != null) { hostname = cfg.ui.hostname; } + // lib.optionalAttrs (cfg.ui.logoutUrl != null) { logout_url = cfg.ui.logoutUrl; }; + engine = { + file = "${stateRoot}/engine"; + systemctl = "${config.systemd.package}/bin/systemctl"; + }; + } + // lib.optionalAttrs cfg.pki.enable { + pki = { + root_cert = toString cfg.pki.rootCertificate; + password_credential = "pki-password"; + }; + } + ); + + hardening = { + NoNewPrivileges = true; + PrivateTmp = true; + ProtectSystem = "strict"; + ProtectHome = true; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectControlGroups = true; + ProtectClock = true; + ProtectHostname = true; + RestrictSUIDSGID = true; + RestrictNamespaces = true; + LockPersonality = true; + MemoryDenyWriteExecute = true; + SystemCallArchitectures = "native"; + RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ]; + UMask = "0027"; + }; +in +{ + options.services.ianitor = { + enable = mkEnableOption "Ianitor Domi, the reverse proxy on Pingora with its control plane"; + + package = mkOption { + type = types.package; + default = self.packages.${pkgs.stdenv.hostPlatform.system}.ianitor; + defaultText = lib.literalExpression "ianitor.packages.\${system}.ianitor"; + description = "The release build (test hooks off)."; + }; + + caddyPackage = mkOption { + type = types.package; + # The Caddy the differential tests run against (Ianitor's own pinned nixpkgs), not the host's: + # the Caddy JSON is only proven equal for that version. + default = self.inputs.nixpkgs.legacyPackages.${pkgs.stdenv.hostPlatform.system}.caddy; + defaultText = lib.literalExpression "ianitor.inputs.nixpkgs.legacyPackages..caddy"; + description = "The Caddy that runs the fallback."; + }; + + edge = { + httpListen = mkOption { + type = types.str; + default = "0.0.0.0:80"; + description = "Plain-HTTP listener (ACME HTTP-01, redirects). The only public listeners are edge's."; + }; + httpsListen = mkOption { + type = types.str; + default = "0.0.0.0:443"; + description = "TLS listener serving every host by SNI."; + }; + openFirewall = mkOption { + type = types.bool; + default = false; + description = "Open edge's two ports in the firewall."; + }; + }; + + control.listen = mkOption { + type = types.str; + default = "127.0.0.1:7878"; + description = "The API and UI. Loopback only (an assertion refuses anything else)."; + }; + + watchSeconds = mkOption { + type = types.ints.between 1 3600; + default = 60; + description = "How long the health watch after an apply lasts."; + }; + + defaultEngine = mkOption { + type = types.enum [ "pingora" "caddy" ]; + default = "pingora"; + description = "The engine at first boot; afterwards the UI's choice in ${stateRoot}/engine."; + }; + + routes = { + remote = mkOption { + type = types.nullOr types.str; + default = null; + example = "https://gitea.example/mnovak/ianitor-routes.git"; + description = "Where kept changes are pushed."; + }; + remoteName = mkOption { + type = types.str; + default = "Gitea"; + description = "Shown in the UI."; + }; + pushUsername = mkOption { + type = types.str; + default = "ianitor"; + description = "User name for HTTPS pushes."; + }; + pushCredentialFile = mkOption { + type = types.nullOr types.str; + default = null; + description = "File (outside the Nix store) holding the push token."; + }; + }; + + shareLinkKeyFile = mkOption { + type = types.nullOr types.str; + default = null; + description = "File (outside the Nix store) with the share-link key, at least 32 characters. Without it, share links are off."; + }; + + credentials = mkOption { + type = types.attrsOf types.str; + default = { }; + example = { wiki_token = "/run/secrets/wiki-token"; }; + description = "Secrets that header rules reference, by name: files outside the Nix store, loaded into edge and caddy-fallback with LoadCredential."; + }; + + pki = { + enable = mkEnableOption "the Domi CA (docs/pki.md)"; + rootCertificate = mkOption { + type = types.path; + description = "The Domi root certificate (public; it may be in the store). The root key never comes to the server."; + }; + passwordFile = mkOption { + type = types.str; + description = "File (outside the Nix store) with the password that encrypts the intermediate and device keys at rest."; + }; + }; + + ui = { + hostname = mkOption { + type = types.nullOr types.str; + default = null; + example = "ianitor.example"; + description = "The admin host edge serves the UI on (a host in the routes repository with forward-auth and the X-Ianitor-Proof rule, docs/api.md)."; + }; + logoutUrl = mkOption { + type = types.nullOr types.str; + default = null; + example = "https://auth.example/logout"; + description = "Authelia's logout address, for the UI's Sign out."; + }; + }; + }; + + config = mkIf cfg.enable { + assertions = + [ + { + assertion = lib.any (p: lib.hasPrefix p cfg.control.listen) [ "127." "[::1]:" "localhost:" ]; + message = "services.ianitor.control.listen must be a loopback address; only ianitor-edge binds public ports."; + } + ] + ++ lib.mapAttrsToList (n: p: { + assertion = !isStore p; + message = "services.ianitor: the credential ${n} points into the Nix store (${toString p}); secrets must come from systemd credentials, never the store."; + }) userCreds; + + users.groups.ianitor = { }; + users.users.ianitor-control = { isSystemUser = true; group = "ianitor"; home = "${stateRoot}/control"; }; + users.users.ianitor-edge = { isSystemUser = true; group = "ianitor"; }; + users.users.caddy-fallback = { isSystemUser = true; group = "ianitor"; }; + + systemd.tmpfiles.rules = [ + "d ${stateRoot} 0755 ianitor-control ianitor - -" + "d ${stateRoot}/control 0700 ianitor-control ianitor - -" + "d ${stateRoot}/edge 0750 ianitor-control ianitor - -" + "d ${stateRoot}/caddy 0750 ianitor-control ianitor - -" + "d ${stateRoot}/certs 0750 ianitor-control ianitor - -" + "d ${stateRoot}/edge-state 0700 ianitor-edge ianitor - -" + "d ${stateRoot}/caddy-state 0700 caddy-fallback ianitor - -" + "f ${stateRoot}/engine 0644 ianitor-control ianitor - ${cfg.defaultEngine}" + "d /var/log/ianitor 0770 ianitor-edge ianitor - -" + ]; + + environment.systemPackages = [ pkg ]; + # The non-secret config, so the CLI (token, pki) finds it: --config /etc/ianitor/control.toml. + environment.etc."ianitor/control.toml".source = controlToml; + + # A new secret every boot, readable by root only; edge and control load it as a credential. + systemd.services.ianitor-ui-proof = { + description = "Ianitor: per-boot proof for the admin host"; + before = [ "ianitor-edge.service" "ianitor-control.service" "caddy-fallback.service" ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + RuntimeDirectory = "ianitor-proof"; + RuntimeDirectoryMode = "0700"; + RuntimeDirectoryPreserve = true; + UMask = "0077"; + }; + script = '' + head -c 32 /dev/urandom | ${pkgs.coreutils}/bin/base64 -w0 > ${runProof}/ui-proof + ''; + }; + + systemd.services.ianitor-control = { + description = "Ianitor control (API and UI on loopback)"; + wantedBy = [ "multi-user.target" ]; + after = [ "network-online.target" "ianitor-ui-proof.service" ]; + wants = [ "network-online.target" ]; + requires = [ "ianitor-ui-proof.service" ]; + environment.IANITOR_LOG = "info"; + serviceConfig = hardening // { + User = "ianitor-control"; + Group = "ianitor"; + ExecStart = "${pkg}/bin/ianitor-control --config ${controlToml}"; + LoadCredential = loadCreds controlCreds ++ [ "ui-proof:${runProof}/ui-proof" ]; + ReadWritePaths = [ stateRoot ]; + Restart = "on-failure"; + RestartSec = 2; + }; + }; + + systemd.services.ianitor-edge = { + description = "Ianitor edge (Pingora)"; + after = [ "network-online.target" "ianitor-control.service" "ianitor-ui-proof.service" ]; + wants = [ "network-online.target" ]; + requires = [ "ianitor-ui-proof.service" ]; + conflicts = [ "caddy-fallback.service" ]; + environment.IANITOR_LOG = "info"; + serviceConfig = hardening // { + User = "ianitor-edge"; + Group = "ianitor"; + ExecStart = lib.concatStringsSep " " [ + "${pkg}/bin/ianitor-edge" + "--config ${stateRoot}/edge/edge.json" + "--admin-socket /run/ianitor-edge/admin.sock" + "--share-revocations ${stateRoot}/edge/share-revocations.json" + ]; + LoadCredential = loadCreds edgeCreds ++ [ "ui-proof:${runProof}/ui-proof" ]; + RuntimeDirectory = "ianitor-edge"; + RuntimeDirectoryMode = "0750"; + ReadWritePaths = [ "${stateRoot}/edge-state" "/var/log/ianitor" ]; + AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ]; + CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ]; + # The first start may come before control has written edge.json. + Restart = "always"; + RestartSec = 2; + # The Pingora runtime needs W^X off for nothing; keep the default hardening. + LimitNOFILE = 65536; + }; + }; + + systemd.services.caddy-fallback = { + description = "Ianitor fallback: Caddy with the same routes"; + after = [ "network-online.target" "ianitor-ui-proof.service" ]; + wants = [ "network-online.target" ]; + requires = [ "ianitor-ui-proof.service" ]; + conflicts = [ "ianitor-edge.service" ]; + environment = { + XDG_DATA_HOME = "${stateRoot}/caddy-state"; + XDG_CONFIG_HOME = "${stateRoot}/caddy-state"; + HOME = "${stateRoot}/caddy-state"; + }; + serviceConfig = hardening // { + User = "caddy-fallback"; + Group = "ianitor"; + ExecStart = "${cfg.caddyPackage}/bin/caddy run --config ${stateRoot}/caddy/caddy.json"; + LoadCredential = loadCreds cfg.credentials ++ [ "ui-proof:${runProof}/ui-proof" ]; + ReadWritePaths = [ "${stateRoot}/caddy-state" "/var/log/ianitor" ]; + AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ]; + CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ]; + # Go needs W^X for its runtime on some platforms. + MemoryDenyWriteExecute = false; + Restart = "on-failure"; + RestartSec = 2; + }; + }; + + # At boot: start the engine the UI chose last (ROADMAP §3). + systemd.services.ianitor-engine-select = { + description = "Ianitor: start the chosen engine"; + wantedBy = [ "multi-user.target" ]; + after = [ "ianitor-control.service" "systemd-tmpfiles-setup.service" ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + }; + script = '' + engine=$(cat ${stateRoot}/engine 2>/dev/null || echo ${cfg.defaultEngine}) + case "$engine" in + caddy) exec ${config.systemd.package}/bin/systemctl start --no-block caddy-fallback.service ;; + *) exec ${config.systemd.package}/bin/systemctl start --no-block ianitor-edge.service ;; + esac + ''; + }; + + # Control may start, stop and restart exactly the two engine units, nothing else. + security.polkit.enable = true; + security.polkit.extraConfig = '' + polkit.addRule(function (action, subject) { + if (action.id == "org.freedesktop.systemd1.manage-units" && subject.user == "ianitor-control") { + var unit = action.lookup("unit"); + var verb = action.lookup("verb"); + if ((unit == "ianitor-edge.service" || unit == "caddy-fallback.service") && + (verb == "start" || verb == "stop" || verb == "restart")) { + return polkit.Result.YES; + } + } + }); + ''; + + networking.firewall.allowedTCPPorts = mkIf cfg.edge.openFirewall ( + map (a: lib.toInt (lib.last (lib.splitString ":" a))) [ cfg.edge.httpListen cfg.edge.httpsListen ] + ); + }; +} diff --git a/deploy/nixos/package.nix b/deploy/nixos/package.nix new file mode 100644 index 0000000..65aae88 --- /dev/null +++ b/deploy/nixos/package.nix @@ -0,0 +1,54 @@ +# 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/. + +# The release build: ianitor-edge and ianitor-control with --no-default-features, so the +# crash and write-failure test hooks (IANITOR_TEST_*) are not in the binaries. The built web UI +# goes to share/ianitor/web, where control serves it. +{ lib, rustPlatform, cmake, ianitor-web }: + +rustPlatform.buildRustPackage { + pname = "ianitor"; + version = "0.1.0"; + + src = lib.fileset.toSource { + root = ../..; + fileset = lib.fileset.unions [ + ../../Cargo.toml + ../../Cargo.lock + ../../crates + ../../tests/diff + ../../tests/support + ]; + }; + + cargoLock.lockFile = ../../Cargo.lock; + # libz-ng-sys (Pingora's compression) builds zlib-ng with CMake. + nativeBuildInputs = [ cmake ]; + dontUseCmakeConfigure = true; + cargoBuildFlags = [ "-p" "ianitor-edge" "-p" "ianitor-control" ]; + buildNoDefaultFeatures = true; + # The test suites need Caddy, Pebble and loopback servers; they run in `cargo test` and in + # the NixOS VM tests, not inside this sandboxed build. + doCheck = false; + + postInstall = '' + mkdir -p $out/share/ianitor + cp -r ${ianitor-web} $out/share/ianitor/web + ''; + + # The release binaries must not carry the test hooks. + postFixup = '' + if grep -q IANITOR_TEST_CRASH_AT $out/bin/ianitor-control; then + echo "the release ianitor-control still has the test hooks" >&2 + exit 1 + fi + ''; + + meta = { + description = "Ianitor Domi: a reverse proxy on Pingora with a small Domi CA, a web UI and an API"; + license = lib.licenses.mpl20; + mainProgram = "ianitor-control"; + platforms = lib.platforms.linux; + }; +} diff --git a/deploy/nixos/tests/default.nix b/deploy/nixos/tests/default.nix new file mode 100644 index 0000000..4a3f5d7 --- /dev/null +++ b/deploy/nixos/tests/default.nix @@ -0,0 +1,220 @@ +# 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 ]; + }; + + # 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. + log = server.succeed("runuser -u ianitor-control -- git -C /var/lib/ianitor/control/routes.git log --oneline") + assert "broken.test" in log, log + ''; + + 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") + + 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 .") + ''; + + 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 + ''; + }; +} diff --git a/deploy/nixos/web.nix b/deploy/nixos/web.nix new file mode 100644 index 0000000..f42e8a5 --- /dev/null +++ b/deploy/nixos/web.nix @@ -0,0 +1,44 @@ +# 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/. + +# The web UI (apps/web with packages/ui), built with pnpm from the lockfile. No outside +# requests at runtime: the fonts are bundled. +{ lib, stdenv, nodejs_22, pnpm_11, fetchPnpmDeps, pnpmConfigHook }: + +stdenv.mkDerivation (finalAttrs: { + pname = "ianitor-web"; + version = "0.1.0"; + + src = lib.fileset.toSource { + root = ../..; + fileset = lib.fileset.unions [ + ../../package.json + ../../pnpm-workspace.yaml + ../../pnpm-lock.yaml + ../../apps/web + ../../packages/ui + ]; + }; + + nativeBuildInputs = [ nodejs_22 pnpm_11 pnpmConfigHook ]; + + pnpmDeps = fetchPnpmDeps { + inherit (finalAttrs) pname version src; + pnpm = pnpm_11; + fetcherVersion = 4; + hash = "sha256-Hq6LE6Bwb1AeMSMDF0RUbCSX+mMAl8uLt9rPwV6tKBs="; + }; + + buildPhase = '' + runHook preBuild + pnpm --filter web build + runHook postBuild + ''; + + installPhase = '' + runHook preInstall + cp -r apps/web/dist $out + runHook postInstall + ''; +}) diff --git a/deploy/test-access.sh b/deploy/test-access.sh new file mode 100755 index 0000000..d9fa4a5 --- /dev/null +++ b/deploy/test-access.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# +# After every server change (CLAUDE.md): the hosts still answer as they should, protected hosts +# still send strangers to Authelia, and Ianitor's control is not reachable from outside. +# Run it from another machine on the LAN, not from the server (loopback would hide exactly the +# exposure this looks for). Read-only: it sends GET requests and nothing else. +# +# deploy/test-access.sh --server 192.168.100.166 \ +# --public flowers.stage.marek-novak.cz --public esp32.stage.marek-novak.cz \ +# --protected wiki.example --auth-host auth.example \ +# --via-ianitor flowers.stage.marek-novak.cz --via-ianitor esp32.stage.marek-novak.cz +# +# --server ADDR the server's LAN address (requests go there, whatever DNS says) +# --public HOST must answer 2xx or 3xx (not a sign-in redirect) +# --protected HOST without a session, must redirect to --auth-host (302/303) or answer 401 +# --auth-host HOST Authelia's portal name, for --protected +# --via-ianitor HOST must answer 2xx/3xx, and the answer must not come from Caddy alone +# (Ianitor adds no Via; Caddy adds "Via: 1.1 Caddy" once, so exactly one) +# --control-port N control's port (default 7878): must NOT answer from outside +# --insecure accept a certificate the client does not trust (staging: tls internal) +# +# Exit status: 0 when every check passes, 1 otherwise. Each check prints one line. + +set -u +server="" +auth_host="" +control_port=7878 +insecure=() +public=() +protected=() +via=() + +while [ $# -gt 0 ]; do + case "$1" in + --server) server="$2"; shift 2 ;; + --public) public+=("$2"); shift 2 ;; + --protected) protected+=("$2"); shift 2 ;; + --auth-host) auth_host="$2"; shift 2 ;; + --via-ianitor) via+=("$2"); shift 2 ;; + --control-port) control_port="$2"; shift 2 ;; + --insecure) insecure=(-k); shift ;; + -h|--help) sed -n '2,26p' "$0"; exit 0 ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done +if [ -z "$server" ]; then + echo "--server is required" >&2 + exit 2 +fi +if [ ${#protected[@]} -gt 0 ] && [ -z "$auth_host" ]; then + echo "--protected needs --auth-host" >&2 + exit 2 +fi + +failures=0 +pass() { printf 'ok %s\n' "$1"; } +fail() { printf 'FAIL %s\n' "$1"; failures=$((failures + 1)); } + +# status, location and the number of Via headers for https://HOST/ sent to the server +probe() { + curl -sS -o /dev/null -D - --max-time 15 "${insecure[@]}" \ + --resolve "$1:443:$server" "https://$1/" 2>/dev/null | tr -d '\r' +} + +for h in "${public[@]}"; do + head=$(probe "$h") + code=$(printf '%s\n' "$head" | awk 'NR==1 {print $2}') + loc=$(printf '%s\n' "$head" | awk 'tolower($1)=="location:" {print $2}') + if [[ "$code" =~ ^[23][0-9][0-9]$ ]] && { [ -z "$auth_host" ] || [[ "$loc" != *"$auth_host"* ]]; }; then + pass "public $h answers $code" + else + fail "public $h answers '${code:-nothing}'${loc:+ -> $loc}" + fi +done + +for h in "${protected[@]}"; do + head=$(probe "$h") + code=$(printf '%s\n' "$head" | awk 'NR==1 {print $2}') + loc=$(printf '%s\n' "$head" | awk 'tolower($1)=="location:" {print $2}') + if { [[ "$code" =~ ^30[23]$ ]] && [[ "$loc" == *"$auth_host"* ]]; } || [ "$code" = "401" ]; then + pass "protected $h sends strangers to sign-in ($code)" + else + fail "protected $h answers '${code:-nothing}'${loc:+ -> $loc} without a session" + fi +done + +for h in "${via[@]}"; do + head=$(probe "$h") + code=$(printf '%s\n' "$head" | awk 'NR==1 {print $2}') + vias=$(printf '%s\n' "$head" | grep -ci '^via:' || true) + if [[ "$code" =~ ^[23][0-9][0-9]$ ]]; then + pass "through Ianitor $h answers $code (Via headers: $vias)" + else + fail "through Ianitor $h answers '${code:-nothing}'" + fi +done + +# Control must not answer from outside loopback, on any address of the server. +if curl -sS -o /dev/null --max-time 5 "http://$server:$control_port/api/v1/overview" 2>/dev/null; then + fail "control answers on $server:$control_port from outside loopback" +else + pass "control is not reachable on $server:$control_port" +fi +# Nor Ianitor edge's loopback listeners in the beside-Caddy setup. +for p in 18080 18443; do + if curl -sS -o /dev/null --max-time 5 -k "https://$server:$p/" 2>/dev/null || + curl -sS -o /dev/null --max-time 5 "http://$server:$p/" 2>/dev/null; then + fail "Ianitor edge's loopback port $p answers from outside" + else + pass "port $p is not reachable from outside" + fi +done + +if [ "$failures" -gt 0 ]; then + echo "$failures check(s) failed" + exit 1 +fi +echo "all checks passed" diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a6adcfa..b858ded 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -64,7 +64,10 @@ Main screen: host list with health dots, engine chip, intermediate-expiry banner | API token: ⚙ → API → New token | 3 | Accepted exceptions [M 2026-11-07]: copying a new API token and installing a device certificate may take a 4th click -(deliberate secret-handling steps). +(deliberate secret-handling steps). A share link on a host with links off takes 4 clicks (⋯ → Share link → Turn on +share links → Copy, after the apply is kept; no `turn_on` API change). Signing the intermediate by hand on the offline +machine (openssl) is outside the 1-click Renew budget while Custos lacks the operation (§8.6). Share links are off +while Caddy serves (v1); a validator Caddy calls through forward_auth comes before v1.1's monthly switch rehearsal. ## 5. Test layers (all run in an Artifex pipeline by phase 4) 1. Differential: the same request corpus against Ianitor and Caddy; status, selected headers and body compared. @@ -133,6 +136,7 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit 5. Authelia forward-auth endpoint and headers to mirror exactly. (phase 1) **Answer: `GET /api/authz/forward-auth` (ForwardAuth implementation; legacy `/api/verify` not used).** Edge sends X-Forwarded-Method, -Proto, -Host, -URI (required) and X-Forwarded-For, and always sets them itself. It also forwards the client's headers (Cookie, Authorization) without hop-by-hop headers or body. A 2xx answer copies Remote-User, Remote-Groups, Remote-Email and Remote-Name onto the request (client copies removed). Any other answer (302 portal, 401 + WWW-Authenticate, 403) goes back to the client verbatim. An unreachable, silent (10 s deadline), oversized (>1 MiB), broken or `101` auth answer fails closed with 502; 1xx heads are skipped. Client-sent Remote-* headers are always stripped on forward-auth hosts, whatever copy_headers says. This mirrors `caddy adapt` output for Authelia's documented `forward_auth` snippet; tested against a mock, not a real Authelia. [S authelia.com/reference/guides/proxy-authorization, authelia.com/integration/proxies/caddy] 6. Custos CSR-signing operation with match-code approval. (phase 3) + **Answer: Custos has none (desktop 0.8.0, CustosPublic v0.13.0).** Its `sign` op signs only minisign, SHA256SUMS manifests, Authenticode digests and deploy approvals, refuses any request against `domi-root` (the RSA-3072 Authenticode root), and no path takes a CSR. Its server reach is the factor-service sign mailbox (`POST /api/sign/requests`, Bearer sign token, answers sealed to a one-time X25519 key, 5-minute match-code card on the PC with a push to the phone). So, per §6: the operation is written as a ticket, [custos-ticket.md](custos-ticket.md) (a new key `domi-pki-root`, ECDSA P-256; a sign kind `x509_csr` through the same mailbox that builds the intermediate from a fixed profile and takes only the CSR's key and CN; the match code computed from the CSR on both screens), not filed. Until then the intermediate is signed **by hand on the offline machine with openssl** ([pki.md](pki.md); Mark accepted it as a §4 exception, 2026-11-07) and device certificates are approved on the server with `sudo -u ianitor-control ianitor-control pki approve ` (Q5). API tokens: Custos stores them as "Local app credential" items with a `domi-ref`; the intended import is Provisio's `offer` (the server seals the value to the PC's key and Mark accepts a match-code card), or copy and paste in the item editor. [S Custos docs/09_signing.md, 07_domi_identity.md, 10_provisio.md, apps/desktop/src-tauri/src/signing.rs] Configuration_Server findings (domains, Caddy, no Authelia in the repository, sops-nix secrets, the two trial hosts): [deploy/beside-caddy.md](deploy/beside-caddy.md). 7. Red Panda Network donation route for a non-US individual and the receipt they issue. (phase 4, Mark) ## 9. Status diff --git a/docs/api.md b/docs/api.md index 0589e4c..2b08a93 100644 --- a/docs/api.md +++ b/docs/api.md @@ -10,9 +10,12 @@ Everything below was run end to end on loopback against `--dev` with a real edge ## Ground rules -- **Token.** Every call needs `Authorization: Bearer `. Nothing else identifies a - caller (no `Remote-User`). Without a valid token: `401` with `token.missing`, - `token.unknown`, `token.expired` or `token.revoked`. 120 calls a minute per token. +- **Token or sign-in.** A script sends `Authorization: Bearer `. The web UI sends + no token: it comes through edge on the admin host, behind Authelia (see "Sign-in" below). + Without either: `401` with `token.missing`, `token.unknown`, `token.expired` or + `token.revoked`; a `Remote-*` header without edge's proof is `401 ui.no_proof`, whatever + else the request carries. 120 calls a minute per token or user. The one exception is the + one-time device download (`GET /device-bundles/{token}`), where the link is the secret. - **Host header.** Only `127.0.0.1:`, `localhost:`, `[::1]:` and the configured `allowed_hosts` are answered (DNS rebinding). A browser write (`Origin` or `Sec-Fetch-Site` present) also needs `X-Ianitor-UI: 1` (CSRF). @@ -232,6 +235,89 @@ curl -s -H "$H" -X DELETE "$API/tokens/" # 204; anything using it sto curl -s "$API/overview" | jq .error.code # "token.missing" ``` +## Sign-in (the web UI, G14) + +The UI is served by control (`[ui] static_dir`) and reached through edge on the **admin host**, +a host in the routes repository with forward-auth to Authelia and one header rule: + +```toml +# hosts/ianitor.example.toml +hostname = "ianitor.example" +upstreams = ["http://127.0.0.1:7878"] +tls = "domi" +auth = "forward-auth" + +[[request_headers]] +action = "set" +name = "X-Ianitor-Proof" +secret = "ui-proof" # listed in ianitor.toml: secrets = ["ui-proof"] +``` + +- `ui-proof` is a **per-boot secret**: the `ianitor-ui-proof` unit writes 32 random bytes to + `/run/ianitor-proof/ui-proof` (root only), and edge, caddy-fallback and control load it with + `LoadCredential`. No other process can read it. +- Edge strips every client-sent `Remote-*` header on forward-auth hosts, asks Authelia, copies + Authelia's `Remote-User` (and `Remote-Name`, …) onto the request, and *sets* `X-Ianitor-Proof` + (replacing anything the client sent) only on requests Authelia allowed. +- Control (`[ui] proof_credential = "ui-proof"`, `hostname = "ianitor.example"`) trusts + `Remote-User` only on a request whose `X-Ianitor-Proof` matches (constant-time compare). Then + `Remote-User` is the actor (history, logs) and `Remote-Name` the name the UI shows. Every write + also needs `X-Ianitor-UI: 1` (CSRF; the session is a cookie). +- Any request with a `Remote-*` header but without the proof is `401 ui.no_proof`, so a local + process on loopback cannot claim a user; the proof without `Remote-User` is `401 ui.no_user`. + Tested in `crates/control/tests/ui_auth.rs`, including end to end through edge and a mock Authelia. +- `[ui] logout_url` (Authelia's logout address) becomes `overview.site.auth_logout_url`, the UI's + "Sign out". A Unix socket only edge can reach is Phase 4 hardening (decision Q2). + +Why not the Unix socket now: edge's upstreams are `host:port` in the schema; a socket upstream is a +schema and compiler change in both engines, and the proof header needs neither. + +## Certificates (the Domi CA) + +Everything is in [pki.md](pki.md); the calls: + +```sh +curl -s -H "$H" "$API/certs" | jq '{intermediate: .intermediate.state, root: .root.offline, devices: [.devices[].name]}' +curl -s -H "$H" -X POST "$API/certs/intermediate/renewal" | jq '{request_id, match_code, approve_command}' +curl -s -H "$H" "$API/pki-requests/$ID/csr" > req.csr; curl -s -H "$H" "$API/pki-requests/$ID/ext" > req.ext +curl -s -H "$H" -H 'Content-Type: application/json' -X PUT "$API/pki-requests/$ID/certificate" \ + -d "$(jq -n --rawfile c int.crt '{certificate_pem: $c}')" | jq .state # "approved" +curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/certs/devices" \ + -d '{"name": "Mark'\''s phone", "kind": "phone"}' | jq '{request_id, match_code, approve_command}' +# on the server: sudo -u ianitor-control ianitor-control pki approve 47 19 83 --config /etc/ianitor/control.toml +curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/certs/devices/$DEV/bundle" \ + -d '{"format": "p12"}' | jq '{download_url, one_time_password}' +curl -s -o phone.p12 "$DOWNLOAD_URL" # once; a second try is 410 pki.bundle_used +curl -s -H "$H" -X DELETE "$API/certs/devices/$DEV" # 204, off the allow list at once +``` + +`overview.intermediate` is `{state ("ok"|"due"|"urgent"|"expired"|"missing"), subject, not_after, +days_left, renewal, banner}`, or `null` without `[pki]`. With `[pki]` configured, control issues +the server certificate of every `tls = "domi"` host before an apply is committed, renews it with 30 +days left, and an apply with a Domi host and no intermediate fails with `pki.no_intermediate`. + +## Engine switch (G18) + +```sh +curl -s -H "$H" "$API/engine" | jq '{running, state, switchable}' +curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/engine" -d '{"target": "caddy"}' # 202 +# poll GET /engine until state = "running"; last_error says why if it went back +``` + +Control writes `/var/lib/ianitor/engine` first, stops the serving unit, starts the other one (polkit +allows exactly `ianitor-edge.service` and `caddy-fallback.service`, verbs start/stop/restart) and +waits until it serves; if it does not within 20 s, it starts the old one again and reports +`engine.switch_failed`. The switch waits for a running apply (same lock). Refusals: +`engine.unmanaged` (no `[engine]` in control.toml), `engine.same`, `engine.switching`, +`engine.not_ready` (Caddy's settings cannot be built from the current routes). + +While Caddy serves (decisions Q3, Q4): +- changes are paused: `overview.paused_reason = "engine.caddy"`, writes get `409 control.paused`; +- **share links are off**: minting is `409 share.engine_caddy`, and a visitor with a link gets the + normal sign-in (fails closed). Caddy cannot check a share token and control never serves + visitors; a validator Caddy calls through `forward_auth` is planned before v1.1; +- device revocations restart caddy-fallback (Caddy reads the allow list when it starts). + ## All calls | Call | Does | @@ -248,4 +334,8 @@ curl -s "$API/overview" | jq .error.code # "token.missing" | `GET/POST /tokens`, `PATCH/DELETE /tokens/{id}` | API tokens | | `POST /hosts/{h}/share-links`, `GET /share-links`, `DELETE /share-links/{id}`, `POST /share-links/stop-all` | share links | | `GET /health` | edge reachability, config hash, trial, paused state, hosts | +| `GET /certs`, `POST /certs/devices`, `DELETE /certs/devices/{id}`, `POST /certs/devices/{id}/bundle` | the Domi CA screen, device requests, revocation, one-time install files | +| `POST /certs/intermediate/renewal`, `GET/DELETE /pki-requests/{id}`, `GET /pki-requests/{id}/csr`, `GET /pki-requests/{id}/ext`, `PUT /pki-requests/{id}/certificate` | renewals and approvals | +| `GET /device-bundles/{token}` | the one-time PKCS#12 download (no token; the link is the secret) | +| `GET /engine`, `POST /engine` | which engine serves; switch | | `GET /openapi.json` | the OpenAPI document | diff --git a/docs/deploy/beside-caddy.md b/docs/deploy/beside-caddy.md new file mode 100644 index 0000000..0104ef1 --- /dev/null +++ b/docs/deploy/beside-caddy.md @@ -0,0 +1,126 @@ +# Ianitor beside Caddy on two low-risk hosts + +ROADMAP §1.12 and §6 Phase 3: Ianitor runs beside Caddy on two low-risk hosts before any +cut-over. This is **prepared, not applied**: Mark runs every command below himself. + +## What was found in Configuration_Server (read-only, 2026-11-07) + +- `hyperv-infra/` is the active flake (`nixosConfigurations.hyperv-vm`, the staging mirror on + 192.168.100.166), pinned to production's nixpkgs (24.11, rev 50ab793). Production (.217) is a + classic-channels install whose real config is not in the repository; `nixos-live/` is a + snapshot. +- Caddy is the only listener on 80/443 and the only service beyond loopback (decision D-21a); + every backend binds 127.0.0.1. Secrets come from sops-nix (`/run/secrets/...`). +- There is **no Authelia** in the repository; hosts rely on their applications' own logins. +- Lowest-risk hosts: `flowers.stage.marek-novak.cz` (a static presentation app, nginx on + 127.0.0.1:8091) and `esp32.stage.marek-novak.cz` (a static web IDE, 127.0.0.1:8093, used only + by Mark). Both are on the staging mirror, "the one machine safe to break". + +## The shape + +```text +visitor ── Caddy :443 (as today) ── https://127.0.0.1:18443 Ianitor edge ── the app +``` + +- Ianitor edge listens on **loopback only** (127.0.0.1:18080 and :18443), so D-21a holds: + nothing new is reachable from the LAN. Control is on 127.0.0.1:7878. +- Caddy keeps the public side for the two names and hands them to Ianitor over TLS; Ianitor + serves them with Domi certificates, which Caddy checks against the Domi root (a public file). +- Every other host is untouched. Rollback: revert the patch and switch (below). + +## The patch + +[configuration-server.patch](configuration-server.patch), against Configuration_Server `main` +(5124e9d): adds the `ianitor` flake input, `hyperv-infra/modules/ianitor.nix`, and routes the two +vhosts in `hyperv-infra/modules/caddy.nix` through Ianitor. No secret is in it. + +## Commands (Mark) + +On the offline machine (once; see [../pki.md](../pki.md)): + +```sh +openssl req -x509 -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 \ + -keyout domi-root.key -out domi-root.crt -days 3653 \ + -subj "/CN=Domi PKI Root/O=Fabrica Domi" \ + -addext "basicConstraints=critical,CA:TRUE,pathlen:1" -addext "keyUsage=critical,keyCertSign,cRLSign" +``` + +In Configuration_Server, on a branch, per the repository's workflow: + +```sh +git switch -c feature/ianitor-beside-caddy +git apply /path/to/Ianitor/docs/deploy/configuration-server.patch +mkdir -p hyperv-infra/ianitor && cp /path/to/domi-root.crt hyperv-infra/ianitor/domi-root.crt +# Two new secrets (values generated, never typed into a file in the repository): +cd hyperv-infra +sops set secrets/secrets.yaml '["ianitor"]["share-link-key"]' "\"$(head -c 32 /dev/urandom | base64 -w0)\"" +sops set secrets/secrets.yaml '["ianitor"]["pki-password"]' "\"$(head -c 32 /dev/urandom | base64 -w0)\"" +# Pin Ianitor to the reviewed commit: +nix flake lock --override-input ianitor "git+https://gitea.marek-novak.cz/mnovak/Ianitor.git?rev=" +nix flake check --no-build +git add -A && git commit +``` + +Deploy to the staging mirror (build first, as the repository's rules say): + +```powershell +scripts/staging/Deploy-Staging.ps1 -Mode Build +scripts/staging/Deploy-Staging.ps1 -Mode Test +scripts/staging/Deploy-Staging.ps1 -Mode Switch +``` + +On the mirror, the first intermediate and the two hosts: + +```sh +sudo -u ianitor-control ianitor-control token create --name mark-laptop --config /etc/ianitor/control.toml +# -> save the token in Custos; then, from the laptop: +ssh -L 7878:127.0.0.1:7878 mirror +TOKEN=ian_...; API=http://127.0.0.1:7878/api/v1; H="Authorization: Bearer $TOKEN" +curl -s -H "$H" -X POST "$API/certs/intermediate/renewal" | jq -r .csr_pem > req.csr +curl -s -H "$H" "$API/pki-requests/$(curl -s -H "$H" $API/overview | jq -r .intermediate.renewal.request_id)/ext" > req.ext +# offline: openssl x509 -req -in req.csr -CA domi-root.crt -CAkey domi-root.key -days 365 -sha256 -extfile req.ext -out int.crt +scp int.crt mirror:/tmp/ && ssh mirror sudo -u ianitor-control ianitor-control pki install /tmp/int.crt --config /etc/ianitor/control.toml +for h in flowers esp32; do + curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/hosts" \ + -d "$(jq -c --arg h "$h.stage.marek-novak.cz" '.[] | select(.hostname == $h) | {host: .}' /etc/ianitor/trial-hosts.json)" +done # each is kept or reverted within 60 s; GET $API/applies/ +``` + +(The web UI needs the admin host behind Authelia, which this repository does not have. For the +trial, run it locally against the tunnel: `IANITOR_CONTROL=http://127.0.0.1:7878 +IANITOR_DEV_TOKEN=$TOKEN pnpm --filter web dev`; the dev proxy adds the token, the browser never +holds it.) + +Then, from the desktop (192.168.100.140): + +```sh +deploy/test-access.sh --server 192.168.100.166 --insecure \ + --public git.stage.marek-novak.cz --public ha.stage.marek-novak.cz \ + --via-ianitor flowers.stage.marek-novak.cz --via-ianitor esp32.stage.marek-novak.cz +``` + +`--insecure` because the stage names use Caddy's `tls internal` (or the stage wildcard). It must +print `all checks passed`; the two-week run (§1.12) starts then. + +Rollback at any time: `git revert` the commit, `Deploy-Staging.ps1 -Mode Switch`. Ianitor's +state stays in /var/lib/ianitor and is ignored. + +## The Let's Encrypt staging check (moved to phase 3, Mark 2026-11-07) + +ACME HTTP-01 needs a name that resolves publicly to the machine that receives port 80, which is +production (.217; the mirror has no port forward). It is one documented check, not part of the +trial: + +1. At Forpsi, add `ianitor-le.marek-novak.cz` (A record, the public IP). +2. On production's Caddy, hand that name's challenge path to Ianitor (the rest of the name can 404): + ```caddy + http://ianitor-le.marek-novak.cz { + reverse_proxy /.well-known/acme-challenge/* 127.0.0.1:18080 + } + ``` +3. In Ianitor's routes, `ianitor.toml` gets `[acme] directory = "https://acme-staging-v02.api.letsencrypt.org/directory"` + and a host `ianitor-le.marek-novak.cz` with `tls = "letsencrypt"` and any upstream. +4. Check: `openssl s_client -connect 127.0.0.1:18443 -servername ianitor-le.marek-novak.cz Caddy :443 (tls as today) -> https://127.0.0.1:18443 Ianitor edge -> the app ++# ++# Ianitor edge listens on loopback only (18080/18443) and terminates TLS with a Domi certificate; ++# Caddy trusts the Domi root (a public certificate, ianitor/domi-root.crt) for that hop. Control ++# listens on 127.0.0.1:7878. Nothing new is reachable from the LAN. ++# ++# Secrets come from sops-nix (paths under /run/secrets, never the store); the module asserts it. ++# Rollback: remove this import and the two `viaIanitor` lines in caddy.nix, nixos-rebuild switch. ++ ++let ++ stage = "stage.marek-novak.cz"; ++in ++{ ++ imports = [ inputs.ianitor.nixosModules.ianitor ]; ++ ++ sops.secrets."ianitor/share-link-key" = { }; ++ sops.secrets."ianitor/pki-password" = { }; ++ ++ services.ianitor = { ++ enable = true; ++ edge = { ++ httpListen = "127.0.0.1:18080"; ++ httpsListen = "127.0.0.1:18443"; ++ openFirewall = false; ++ }; ++ control.listen = "127.0.0.1:7878"; ++ shareLinkKeyFile = config.sops.secrets."ianitor/share-link-key".path; ++ pki = { ++ enable = true; ++ rootCertificate = ../ianitor/domi-root.crt; ++ passwordFile = config.sops.secrets."ianitor/pki-password".path; ++ }; ++ }; ++ ++ # The trial hosts, as Ianitor route files. They are applied through the API after the first ++ # start (docs/deploy/beside-caddy.md in the Ianitor repo); listed here so the review sees them. ++ environment.etc."ianitor/trial-hosts.json".text = builtins.toJSON [ ++ { hostname = "flowers.${stage}"; upstreams = [ "http://127.0.0.1:8091" ]; tls = "domi"; auth = "none"; health_check = { path = "/"; interval_secs = 30; }; } ++ { hostname = "esp32.${stage}"; upstreams = [ "http://127.0.0.1:8093" ]; tls = "domi"; auth = "none"; health_check = { path = "/"; interval_secs = 30; }; } ++ ]; ++} diff --git a/docs/pki.md b/docs/pki.md new file mode 100644 index 0000000..2e855c2 --- /dev/null +++ b/docs/pki.md @@ -0,0 +1,112 @@ +# The Domi CA + +ROADMAP §1.1, §1.2, §1.8, §3. Code: `crates/core/src/pki.rs` (the CA, pure), +`crates/control/src/pki.rs` (state, requests, devices), `crates/edge/src/tls.rs` (device +certificates in the handshake). + +```text +Domi PKI Root ~10 years, pathLen 1 offline; never on the server + └ Ianitor Domi Intermediate 1 year, pathLen 0 on the server, key encrypted at rest + ├ 90 days, serverAuth tls = "domi" hosts, renewed by control + └ 1 year, clientAuth mTLS for hosts with device_certs = true +``` + +All keys are ECDSA P-256. + +## Lifetimes, and why + +| Certificate | Lifetime | Why | +|:--|:--|:--| +| Root | 3653 days | ROADMAP §3 ("~10 years"). It signs once a year, offline. | +| Intermediate | 365 days | ROADMAP §3 ("~1 year"); renewed through the banner, signed by the root. | +| Server | 90 days, renewed at 30 days left | Control renews them by itself (hourly check), so a short life costs nothing and bounds a key read from the certificate directory; 30 days of slack survive a long control outage. | +| Device | 365 days, "renew soon" at 30 days | Installing is a deliberate manual step (§4 accepts its 4th click), so not more than once a year; a lost device is revoked (allow list) rather than waited out. Mark, 2026-11-07 (Q7). | + +No certificate is ever issued past its issuer's `notAfter`. + +## What is where on the server + +`/var/lib/ianitor/control/pki/` (mode 0700, owner ianitor-control): + +| File | What | +|:--|:--| +| `intermediate.crt`, `previous.crt` | the intermediate, and the one before while it is valid | +| `intermediate.key` | its key, `IANITOR ENCRYPTED PRIVATE KEY` (PBKDF2-HMAC-SHA256 600,000 rounds + AES-256-GCM), password from the `pki-password` credential | +| `pending-.key` | the new key of an open renewal, encrypted the same way | +| `devices.json`, `devices/.key` | issued device certificates; their keys, encrypted, kept to make an install file again until revoked | +| `requests.json`, `approvals/` | approval requests, and the manual approvals the CLI writes | + +`/var/lib/ianitor/certs/`: `.crt` (leaf + intermediate) and `.key` (0640, group +ianitor), `domi-devices-ca.pem` (the intermediates that issue device certificates) and +`domi-devices.pem` (the allow list: every issued, unrevoked, unexpired device certificate). Edge +and Caddy read these files; a presented device certificate must chain to the bundle **and** be +on the list, or the handshake fails. + +The root key is never here. Control refuses to start when a file named like a root key is in +its state directory (tested: `control_refuses_to_start_with_a_root_key_in_its_state_dir`). + +## Until Custos can sign: the manual offline step + +Custos has no CSR-signing operation yet (ROADMAP §8.6, [custos-ticket.md](custos-ticket.md)). +Mark accepted this as a §4 exception (2026-11-07, Q6): **the offline machine runs openssl.** + +### Once: the root, on the offline machine + +```sh +openssl req -x509 -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 \ + -keyout domi-root.key -out domi-root.crt -days 3653 \ + -subj "/CN=Domi PKI Root/O=Fabrica Domi" \ + -addext "basicConstraints=critical,CA:TRUE,pathlen:1" \ + -addext "keyUsage=critical,keyCertSign,cRLSign" +# asks for a passphrase: domi-root.key is stored encrypted +openssl x509 -in domi-root.crt -noout -fingerprint -sha256 +``` + +(`ianitor-control ca init --out ` makes the same root with Ianitor's own encrypted key +format, on a machine that has Ianitor.) Copy **only `domi-root.crt`** to the server's +configuration (`services.ianitor.pki.rootCertificate`). `domi-root.key` and its passphrase stay +offline (and go into Custos once it can hold them). + +### Each year (and the first time): the intermediate + +1. In the UI: the banner's **Renew** (or **Set up**) makes a new key on the server and a CSR, and + shows a match code. **Sign it by hand** downloads `domi-intermediate-.csr` and + `domi-intermediate-.ext` (the signing profile: CA, pathLen 0, keyCertSign + cRLSign). By + API: `POST /certs/intermediate/renewal`, `GET /pki-requests/{id}/csr`, `GET /pki-requests/{id}/ext`. +2. On the offline machine, check the request, then sign: + ```sh + openssl req -in domi-intermediate-.csr -noout -subject # CN=Ianitor Domi Intermediate + openssl x509 -req -in domi-intermediate-.csr -CA domi-root.crt -CAkey domi-root.key \ + -days 365 -sha256 -extfile domi-intermediate-.ext -out domi-intermediate-.crt + ``` + (`ianitor-control ca sign --root --csr … --out …` does the same and asks for the match + code before it signs.) +3. Back on the server: upload the `.crt` in the UI (step 3), or + `sudo -u ianitor-control ianitor-control pki install domi-intermediate-.crt --config /etc/ianitor/control.toml`. + +Control checks that the certificate is signed by the configured root, is a CA with path length 0, +is valid now, and carries the pending key; then it swaps the intermediate, reissues every +`tls = "domi"` certificate and reloads the engine that serves. Tested with real openssl +(`an_intermediate_signed_with_openssl_is_installed`). + +## Device certificates + +ROADMAP §4: Certificates → + Device → Issue (3 clicks), then install (the accepted 4th). + +1. `POST /certs/devices {name, kind}` opens a request with a six-digit match code, for 10 minutes. +2. Until Custos can approve (Mark, Q5): approve it on the server, comparing the code with the UI: + `sudo -u ianitor-control ianitor-control pki approve 47 19 83 --config /etc/ianitor/control.toml` + (`pki deny ` turns it down; `pki status` lists open requests). Control issues the + certificate within two seconds and puts it on the allow list; edge re-reads the list at once. +3. Install: `POST /certs/devices/{id}/bundle {format: "qr"|"p12"}` gives a one-time link (10 + minutes, one download) to a PKCS#12 file (AES-256, SHA-256 MAC) and a one-time password. When + `[ui] hostname` is set the link goes through edge on the admin host, as a share link when that + host has share links on, so a device without a sign-in can fetch it; the token is the secret. +4. Revoke: `DELETE /certs/devices/{id}`. It is off the allow list at once (edge: + `/v1/device-certs/reload`; Caddy: control restarts caddy-fallback, which reads the list at start). + +A host asks for device certificates with `device_certs = true` in its file. Only such hosts send a +certificate request in the TLS handshake (other hosts never prompt a browser). Without a +certificate, or with one not on the list, the handshake fails on both engines; a request whose +`Host` is another name than the connection's SNI is answered 421 once any host needs device +certificates (as Caddy does). diff --git a/docs/ui-api.md b/docs/ui-api.md index df49d2e..d905cc1 100644 --- a/docs/ui-api.md +++ b/docs/ui-api.md @@ -508,3 +508,34 @@ written above. `share.not_found`, `share.replaces`, `share.password_long`, `share.too_many`, `request.in_progress`, `control.files_unwritten`, `token.not_found`, `token.name`, `token.expiry`, `file.*`, `site.*` (problems in `ianitor.toml`). + +## 7. Phase 3: the deferred items as built + +Recorded by the Phase 3 implementation (branch `phase-3`); docs/api.md has the calls. + +- **G7** (share links under Caddy): off for v1 (Mark, Q4). Minting is refused with + `409 share.engine_caddy` while Caddy serves, `overview.site.share_links_available` is false and + the engine popover, share dialog and Settings say so. Visitors fail closed (normal sign-in). +- **G12**: the token dialog keeps "Copy token" as the accepted 4th click (Mark); the POST answers + well under a second. Tokens never reach storage, URLs or logs (tested in the smoke test). +- **G13**: device install is the accepted 4th click. +- **G14**: edge's per-boot proof header on the admin host; control trusts `Remote-User` (actor) + and `Remote-Name` (shown) only with it; a forged `Remote-User` is `401 ui.no_proof`. + `overview.viewer {name, via}` and `overview.site.auth_logout_url` are new. +- **G15**: `POST /certs/devices/{id}/bundle` → one-time `GET /device-bundles/{token}` (10 min, + one use, PKCS#12 with a one-time password, `qr_svg` for `format = "qr"`); through edge on the + admin host, as a share link when that host has share links on. +- **G18**: `GET/POST /engine` (shape in docs/api.md). Differences from §1.9: no `fallback_ready + {compared, matched}` (control cannot run the differential suite at runtime; it reports + `{built_at, current}`), and **changes are paused while Caddy serves** (`paused_reason = + "engine.caddy"`). +- **G19**: the UI shows "No websockets" only when off, and "Open to anyone" for `auth = none` (Q11). +- **PKI** (§1.7, §1.8, §3.6): built as drawn, with two differences while Custos lacks the + operations: device requests are approved on the server (`pki approve `, the UI shows the + command and the code; `message_code = "pki.waiting.manual"`), and renewals are signed by hand + with openssl (`approve_command`, `file_base`, `GET /pki-requests/{id}/ext`). Requests carry + `problem` (not `error`) for why they failed. Renewal requests stay open 7 days, device requests + 10 minutes. +- New host field `device_certs` (bool): only Domi device certificates on the allow list get in. +- `overview.paused_reason` gives the underlying code (`apply.needs_attention`, + `control.files_unwritten`, `repo.*`, `engine.caddy`) next to `paused {code: "control.paused"}`. diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..8eb81e2 --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1793865203, + "narHash": "sha256-/cpdPHaySDIyCgZI6EWngiM6jK3YLUNzv1b7lTzy6Bk=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "c56a87d8e41ce69bd2af57eb35dcc117a9dfca33", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-26.05", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..c64e23a --- /dev/null +++ b/flake.nix @@ -0,0 +1,33 @@ +# 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/. +{ + description = "Ianitor Domi: a reverse proxy on Pingora with a small Domi CA, a web UI and an API"; + + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05"; + + outputs = + { self, nixpkgs }: + let + systems = [ "x86_64-linux" "aarch64-linux" ]; + forAll = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system}); + in + { + packages = forAll (pkgs: rec { + ianitor-web = pkgs.callPackage ./deploy/nixos/web.nix { }; + ianitor = pkgs.callPackage ./deploy/nixos/package.nix { inherit ianitor-web; }; + default = ianitor; + }); + + nixosModules.ianitor = import ./deploy/nixos/module.nix self; + nixosModules.default = self.nixosModules.ianitor; + + # NixOS VM tests (ROADMAP §5 layer 4); they need KVM. + checks.x86_64-linux = import ./deploy/nixos/tests { + pkgs = nixpkgs.legacyPackages.x86_64-linux; + inherit self; + }; + + formatter = forAll (pkgs: pkgs.nixfmt-rfc-style); + }; +}