{ config, lib, pkgs, ... }: let cfg = config.services.skyg-linux-tracker; inherit (lib) mkOption mkEnableOption mkIf mkMerge types; name = "skyg-linux-tracker"; credDir = "/run/credentials/${name}.service"; toml = pkgs.formats.toml { }; scheme = if cfg.tls.enable then "https" else "http"; hostName = config.networking.fqdnOrHostName; # Names clients use, with the port, so both the Host and the Origin # allowlists on /mcp accept them. Entries with a scheme are origins only. withPort = h: if lib.hasInfix ":" h then h else "${h}:${toString cfg.port}"; hosts = lib.unique (map withPort ( lib.optional (hostName != "") hostName ++ lib.filter (h: !lib.hasInfix "://" h) cfg.allowedHosts )); # Declared peers that stay in the rendered config. A peer with `enable = # false` is left out entirely: no credential is shipped for it, and the # service refuses to start while an enabled peer's token file is missing. enabledPeerNames = lib.attrNames (lib.filterAttrs (_: peer: peer.enable) cfg.peers.peers); # The config file holds paths only. Each peer reads its bearer token from # the credential directory, which systemd populates from `tokenFile`, so # the service user never needs access to the agenix output. renderedPeers = map ( peerName: { name = peerName; url = cfg.peers.peers.${peerName}.url; token_file = "${credDir}/peer-${peerName}"; allow_plain_http = cfg.peers.peers.${peerName}.allowPlainHttp; } // lib.optionalAttrs (cfg.peers.peers.${peerName}.caFile != null) { ca_file = cfg.peers.peers.${peerName}.caFile; } ) enabledPeerNames; # The first-class options are in use once either one is set. From then on # they own `enabled` and `peer`: the freeform bags (`peers.settings` and the # legacy `settings.peers`) may not set either, and the assertions below # reject a config that tries. usingFirstClassPeers = cfg.peers.enable || cfg.peers.peers != { }; freeformPeers = lib.recursiveUpdate cfg.peers.settings (cfg.settings.peers or { }); # Only rendered when the feature is in use, so a peer-less deployment keeps # the same generated config as before. Freeform keys first, the first-class # values last, so a stale `enabled = false` in a freeform bag cannot switch # off the feature the module believes is on. peersSection = freeformPeers // lib.optionalAttrs (renderedPeers != [ ]) { peer = renderedPeers; } // lib.optionalAttrs usingFirstClassPeers { enabled = cfg.peers.enable; }; peersInUse = usingFirstClassPeers || freeformPeers != { }; moduleDefaults = { server = { bind = cfg.bind; port = cfg.port; allowed_hosts = hosts; allowed_origins = map (h: "${scheme}://${h}") (lib.filter (h: !lib.hasInfix "://" h) hosts) ++ lib.filter (h: lib.hasInfix "://" h) cfg.allowedHosts; } // lib.optionalAttrs cfg.tls.enable { tls = { enabled = true; cert_file = "${credDir}/cert"; key_file = "${credDir}/key"; }; }; auth.db_path = "/var/lib/${name}/db.sqlite"; } // lib.optionalAttrs cfg.docker.enable { sources.docker_socket = "/var/run/docker.sock"; } // lib.optionalAttrs peersInUse { peers = peersSection; }; settings = lib.recursiveUpdate moduleDefaults cfg.settings # `recursiveUpdate` lets a freeform `settings.peers.enabled` win over the # first-class option, so put the settled section back on top. // lib.optionalAttrs peersInUse { peers = peersSection; }; # SIGHUP re-reads the TLS certificate and, with the feature on, the `[peers]` # block. It cannot re-bind the listener, reopen the database or replace the # transport that holds the deny list and the concurrency/size limits, so the # parts of `settings` that only take effect at startup are restarted on. # `enabled` counts as one of them because the peer routes are mounted once, # at startup. Without this, a `switch` that changes e.g. the port would # reload into a file the running process never reads and leave the old port # in effect. restartOnlyPeerKeys = [ "enabled" "deny_cidrs" "max_response_bytes" "max_concurrent_per_peer" "max_concurrent_total" ]; restartSettings = lib.filterAttrs (key: _: key != "peers") settings // lib.optionalAttrs (settings ? peers) { peers = builtins.intersectAttrs (lib.genAttrs restartOnlyPeerKeys (_: null)) settings.peers; }; # A plain string (the JSON) rather than a path: the unit carries it as the # content of `X-Restart-Triggers`, which `switch-to-configuration` compares, # and evaluating the unit then needs no store path or build. restartTrigger = builtins.toJSON restartSettings; configFile = toml.generate "${name}.toml" settings; port = settings.server.port; bind = settings.server.bind; authEnabled = settings.auth.enabled or true; isLoopback = a: lib.hasPrefix "127." a || a == "::1"; # Names become file names and TOML keys; the regex is the one the binary # enforces, so a bad name fails at build time instead of at startup. validPeerName = n: builtins.match "[a-z0-9][a-z0-9_-]{0,31}" n != null; # A path literal is rejected by the string type; an interpolated one # (`"${./secret}"`) becomes a store path. That is rejected too, so the file # is never handed to the service from the store. Interpolation has already # copied it into the local store by then: the assertion stops the deployment, # not the copy, so a secret used this way must be rotated. outsideStore = p: !lib.hasPrefix "${builtins.storeDir}/" p; # `LoadCredential=:` splits on the first colon; a colon or a space # in the path would hand systemd a different path (or a different ID). credentialSafe = p: !(lib.hasInfix ":" p || lib.hasInfix " " p || lib.hasInfix "\t" p); peerTokenPathOk = peer: lib.hasPrefix "/" peer.tokenFile && outsideStore peer.tokenFile; # The binary refuses more than 64 rendered peers at startup; legacy freeform # entries count too because they end up in the same list. legacyPeers = cfg.settings.peers.peer or [ ]; peerCount = builtins.length renderedPeers + (if usingFirstClassPeers then 0 else builtins.length legacyPeers); firstClassOwnedKeys = [ "enabled" "peer" ]; freeformOwnedKeys = lib.filter (key: lib.elem key firstClassOwnedKeys) (lib.attrNames freeformPeers); in { options.services.skyg-linux-tracker = { enable = mkEnableOption "skyg-linux-tracker, a read-only systemd/journal/Docker monitor (REST, MCP, OTel)"; package = mkOption { type = types.package; description = "The skyg-linux-tracker package (provides `slinuxm`)."; }; port = mkOption { type = types.port; default = 1984; description = "TCP port for the REST API and /mcp."; }; bind = mkOption { type = types.str; default = "127.0.0.1"; description = '' Listen address. A non-loopback address requires authentication to stay enabled. Bearer tokens over plain HTTP are readable on a LAN; prefer loopback plus a TLS proxy or Tailscale, or enable `tls`. ''; }; tls = { enable = mkEnableOption "native TLS for REST and /mcp"; certFile = mkOption { type = types.nullOr types.str; default = null; description = "Absolute path, kept out of the store (use a string, not a path literal). PEM certificate chain. Passed through systemd LoadCredential, so the service user needs no access to the original file."; }; keyFile = mkOption { type = types.nullOr types.str; default = null; description = "Absolute path, kept out of the store (use a string, not a path literal). PEM private key. Passed through systemd LoadCredential."; }; }; openFirewall = mkOption { type = types.bool; default = false; description = "Open the port on all interfaces."; }; firewallInterfaces = mkOption { type = types.listOf types.str; default = [ ]; example = [ "enp3s0" ]; description = "Open the port only on these interfaces (the recommended LAN setup)."; }; allowedHosts = mkOption { type = types.listOf types.str; default = [ ]; example = [ "monitor.lan:1984" ]; description = "Extra Host/Origin names accepted on /mcp. `networking.hostName` is added automatically."; }; docker.enable = mkEnableOption '' Docker access by adding the service user to the `docker` group. WARNING: that group is root-equivalent; prefer a read-only socket proxy and `settings.sources.docker_socket`''; settings = mkOption { type = toml.type; default = { }; example = { limits.max_lines = 500; }; description = '' Freeform config merged over the module defaults and written to /etc/skyg-linux-tracker.toml. Never put secrets here. A change that the service cannot apply on SIGHUP (everything except the TLS certificate and most of `[peers]`) restarts it; peer edits and intervals reload it. ''; }; environmentFile = mkOption { type = types.nullOr types.path; default = null; example = "/run/secrets/skyg-linux-tracker.env"; description = "systemd EnvironmentFile for secrets such as `SKYG_OTEL__HEADERS__AUTHORIZATION`, kept out of the store."; }; peers = { enable = mkEnableOption "the consolidator (health checks and GET proxying to the peers declared below)"; settings = mkOption { type = toml.type; default = { }; example = { tcp_interval_secs = 10; api_interval_secs = 30; fail_threshold = 2; }; description = '' Freeform `[peers]` tuning (snake_case keys as in config.example.toml), merged over the defaults. `enabled` and `peer` are owned by `peers.enable` and `peers.peers` and must not be set here. Never put a token here: secrets come from `peers.peers..tokenFile`. The intervals, timeouts and peer list are applied on reload; `enabled`, `deny_cidrs` and the `max_*` limits need a restart and trigger one. ''; }; peers = mkOption { type = types.attrsOf (types.submodule { options = { url = mkOption { type = types.str; example = "https://minipc1:1984"; description = "Base URL of the peer. `http` to a non-loopback host also needs `allowPlainHttp`."; }; tokenFile = mkOption { type = types.str; example = "/run/agenix/peer-minipc1"; description = '' Path of a file holding this peer's bearer token, normally `config.age.secrets..path`. Must be an absolute path outside the Nix store, without `:` or whitespace: the file is handed to the service with systemd `LoadCredential`, which splits its argument on the first colon, so the token does not appear in the generated config or in files the service user can read. A store path is rejected at evaluation; a secret interpolated that way (`"${./secret}"`) has already been copied into the local store by then, so rotate it. ''; }; caFile = mkOption { type = types.nullOr types.str; default = null; example = "/etc/ssl/private-ca.pem"; description = '' Optional PEM CA bundle used to verify this peer's TLS certificate. Unlike `tokenFile` it is not passed through `LoadCredential`: the service reads it directly as the `skyg-linux-tracker` user, so that user needs read access and a root-only file such as `/run/agenix/*` fails at startup. ''; }; enable = mkOption { type = types.bool; default = true; description = "Set to false to keep the declaration without contacting the peer."; }; allowPlainHttp = mkOption { type = types.bool; default = false; description = "Allow plain http to a non-loopback host. The bearer token travels in cleartext."; }; }; }); default = { }; description = "Peers this instance consolidates, keyed by peer name (`^[a-z0-9][a-z0-9_-]{0,31}$`)."; }; }; }; config = mkIf cfg.enable { assertions = [ { assertion = isLoopback bind || authEnabled; message = "services.skyg-linux-tracker: a non-loopback bind (${bind}) requires auth.enabled = true."; } { assertion = !cfg.docker.enable || config.virtualisation.docker.enable; message = "services.skyg-linux-tracker.docker.enable needs virtualisation.docker.enable (or use a socket proxy via settings.sources.docker_socket instead)."; } { assertion = !cfg.tls.enable || (cfg.tls.certFile != null && cfg.tls.keyFile != null); message = "services.skyg-linux-tracker.tls.enable requires tls.certFile and tls.keyFile."; } { assertion = cfg.peers.peers == { } || cfg.peers.enable; message = "services.skyg-linux-tracker.peers.peers. requires peers.enable = true."; } { assertion = !cfg.peers.enable || enabledPeerNames != [ ] || (!usingFirstClassPeers && legacyPeers != [ ]); message = "services.skyg-linux-tracker.peers.enable requires at least one enabled peer under peers.peers.."; } { assertion = !usingFirstClassPeers || !(lib.elem "enabled" freeformOwnedKeys); message = "services.skyg-linux-tracker: peers.settings.enabled and settings.peers.enabled conflict with peers.enable; use the first-class option only."; } { assertion = !usingFirstClassPeers || !(lib.elem "peer" freeformOwnedKeys); message = "services.skyg-linux-tracker: declare peers with peers.peers., not settings.peers.peer or peers.settings.peer."; } { # Option attribute names are unique by construction, so only the # character set needs checking. assertion = lib.all validPeerName (lib.attrNames cfg.peers.peers); message = "services.skyg-linux-tracker.peers.peers.: names must match ^[a-z0-9][a-z0-9_-]{0,31}$."; } { assertion = peerCount <= 64; message = "services.skyg-linux-tracker: at most 64 peers may be configured."; } { assertion = lib.all peerTokenPathOk (lib.attrValues cfg.peers.peers); message = "services.skyg-linux-tracker.peers.peers..tokenFile must be an absolute path outside the Nix store (use config.age.secrets..path)."; } { assertion = lib.all credentialSafe (map (peer: peer.tokenFile) (lib.attrValues cfg.peers.peers)); message = "services.skyg-linux-tracker.peers.peers..tokenFile must not contain ':', spaces or tabs (systemd splits LoadCredential on the first colon)."; } { assertion = lib.all (peer: peer.caFile == null || lib.hasPrefix "/" peer.caFile) (lib.attrValues cfg.peers.peers); message = "services.skyg-linux-tracker.peers.peers..caFile must be an absolute path when set."; } ]; users.users.${name} = { isSystemUser = true; group = name; extraGroups = lib.optional cfg.docker.enable "docker"; }; users.groups.${name} = { }; # Same path the app reads by default, so `slinuxm` and the service agree. environment.etc."${name}.toml".source = configFile; # Plain binary, no wrapper. Mint tokens with # sudo -u skyg-linux-tracker slinuxm token create environment.systemPackages = [ cfg.package ]; networking.firewall = lib.mkMerge [ (mkIf cfg.openFirewall { allowedTCPPorts = [ port ]; }) { interfaces = lib.genAttrs cfg.firewallInterfaces (_: { allowedTCPPorts = [ port ]; }); } ]; systemd.services.${name} = { description = "skyg-linux-tracker: read-only systemd, journal and Docker monitor (REST, MCP, OTel)"; wantedBy = [ "multi-user.target" ]; after = [ "network.target" ] ++ lib.optional cfg.docker.enable "docker.service"; # The config file is a reload trigger: SIGHUP re-reads the TLS # certificate and, with peers on, the `[peers]` block, so a peer edit or # an interval change is applied without dropping connections. Anything # SIGHUP cannot apply (listener, auth, sources, otel, transport limits) # also changes the restart trigger, and `switch-to-configuration` # restarts when that differs, so a `switch` never leaves the service # running on the old port or auth settings. restartTriggers = [ restartTrigger ]; reloadTriggers = [ configFile ]; # Mirrors systemd/skyg-linux-tracker.service; keep the two in step. serviceConfig = { Type = "simple"; ExecStart = "${lib.getExe cfg.package} serve --config /etc/${name}.toml"; ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID"; # Credentials are copied at start; refresh them so a reload rotates # the certificate and the peer tokens. RefreshOnReload = mkIf (cfg.tls.enable || cfg.peers.enable) "credentials"; Restart = "on-failure"; RestartSec = 5; TimeoutStopSec = 30; User = name; Group = name; SupplementaryGroups = [ "systemd-journal" ] ++ lib.optional cfg.docker.enable "docker"; StateDirectory = name; StateDirectoryMode = "0700"; EnvironmentFile = mkIf (cfg.environmentFile != null) cfg.environmentFile; LoadCredential = mkMerge [ (mkIf cfg.tls.enable [ "cert:${toString cfg.tls.certFile}" "key:${toString cfg.tls.keyFile}" ]) (mkIf cfg.peers.enable (map ( peerName: "peer-${peerName}:${cfg.peers.peers.${peerName}.tokenFile}" ) enabledPeerNames)) ]; NoNewPrivileges = true; ProtectSystem = "strict"; ProtectHome = true; PrivateTmp = true; PrivateDevices = true; ProtectKernelTunables = true; ProtectKernelModules = true; ProtectControlGroups = true; ProtectClock = true; RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ]; RestrictNamespaces = true; RestrictRealtime = true; LockPersonality = true; MemoryDenyWriteExecute = true; SystemCallArchitectures = "native"; SystemCallFilter = [ "@system-service" "~@privileged @resources" ]; ProtectProc = "invisible"; ProcSubset = "pid"; RestrictSUIDSGID = true; UMask = "0077"; CapabilityBoundingSet = ""; AmbientCapabilities = ""; }; }; }; }