[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
This commit is contained in:
@@ -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.<system>.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 ]
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
}
|
||||
@@ -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
|
||||
'';
|
||||
};
|
||||
}
|
||||
@@ -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
|
||||
'';
|
||||
})
|
||||
Executable
+119
@@ -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"
|
||||
Reference in New Issue
Block a user