WS-H: NixOS module, VM test, README section

Module: Origin/Host allowlists from allowedHosts and the FQDN, credentials
refreshed on reload so SIGHUP rotates the TLS cert, string cert/key paths
kept out of the store, docker.enable asserts virtualisation.docker.
VM test covers healthz, 401, token mint/revoke via sudo -u, /mcp, Origin 403,
root refusal and a TLS node. Package skips two unit tests that need host
state the sandbox lacks.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017WMgwyHQQU9cB4ruRDrKow
This commit is contained in:
ariandClaude Sonnet 5.5 committed 2026-10-16 17:15:18 -04:00
1 parent 46b4f5ac0b
commit 34da657fdf
6 files changed
+193 -16

No files matched your search

+23 -8
View File
@@ -8,14 +8,23 @@ let
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
));
moduleDefaults = {
server = {
bind = cfg.bind;
port = cfg.port;
allowed_hosts = lib.unique ([
config.networking.hostName
"${config.networking.hostName}:${toString cfg.port}"
] ++ cfg.allowedHosts);
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;
@@ -64,14 +73,14 @@ in
tls = {
enable = mkEnableOption "native TLS for REST and /mcp";
certFile = mkOption {
type = types.nullOr types.path;
type = types.nullOr types.str;
default = null;
description = "PEM certificate chain. Passed through systemd LoadCredential, so the service user needs no access to the original file.";
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.path;
type = types.nullOr types.str;
default = null;
description = "PEM private key. Passed through systemd LoadCredential.";
description = "Absolute path, kept out of the store (use a string, not a path literal). PEM private key. Passed through systemd LoadCredential.";
};
};
@@ -121,6 +130,10 @@ in
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.";
@@ -161,6 +174,8 @@ in
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 cert.
RefreshOnReload = mkIf cfg.tls.enable "credentials";
Restart = "on-failure";
RestartSec = 5;
TimeoutStopSec = 30;
+7
View File
@@ -24,6 +24,13 @@ rustPlatform.buildRustPackage {
nativeBuildInputs = [ pkg-config cmake ];
buildInputs = [ systemd ];
# These two need host state the build sandbox lacks: a root-owned /usr, and a
# CA bundle for the reqwest client. They run under cargo test outside Nix.
checkFlags = [
"--skip=db::tests::cli_owner_check_uses_file_then_parent_and_allows_missing_dir"
"--skip=telemetry::tests::exporters_build_for_both_protocols"
];
meta = {
description = "Read-only Linux system monitor: systemd, journald and Docker over REST, MCP and OpenTelemetry";
license = lib.licenses.mit;
+91
View File
@@ -0,0 +1,91 @@
{ pkgs, module }:
let
# Self-signed pair for the TLS case.
cert = pkgs.runCommand "skyg-test-cert" { nativeBuildInputs = [ pkgs.openssl ]; } ''
mkdir $out
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 \
-keyout $out/key.pem -out $out/cert.pem -subj '/CN=tls' \
-addext 'subjectAltName=DNS:tls,DNS:localhost,IP:127.0.0.1'
'';
in
pkgs.testers.runNixOSTest {
name = "skyg-linux-tracker";
nodes.plain = { ... }: {
imports = [ module ];
services.skyg-linux-tracker = {
enable = true;
port = 1984;
};
};
nodes.tls = { ... }: {
imports = [ module ];
services.skyg-linux-tracker = {
enable = true;
tls = {
enable = true;
certFile = "${cert}/cert.pem";
keyFile = "${cert}/key.pem";
};
};
};
testScript = ''
CLI = "sudo -u skyg-linux-tracker slinuxm"
JSON = "-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream'"
INIT = '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"vm","version":"0"}}}'
def code(m, url, extra=""):
return m.succeed(f"curl -s -o /dev/null -w '%{{http_code}}' {extra} {url}").strip()
start_all()
with subtest("plain: healthz is public, API needs a token"):
plain.wait_for_unit("skyg-linux-tracker.service")
plain.wait_for_open_port(1984)
assert code(plain, "http://127.0.0.1:1984/healthz") == "200"
assert code(plain, "http://127.0.0.1:1984/api/v1/systemd/units") == "401"
with subtest("plain: token minted by the service user via the system CLI"):
token = plain.succeed(f"{CLI} token create t").strip()
auth = f"-H 'Authorization: Bearer {token}'"
assert code(plain, "http://127.0.0.1:1984/api/v1/systemd/units", auth) == "200"
with subtest("plain: /mcp initialize and tools/list"):
plain.succeed(
f"curl -sf -D /tmp/h {auth} {JSON} -d '{INIT}' http://127.0.0.1:1984/mcp >/dev/null"
)
sid = plain.succeed("awk -F': ' 'tolower($1)==\"mcp-session-id\"{print $2}' /tmp/h | tr -d '\\r'").strip()
sess = f"-H 'Mcp-Session-Id: {sid}'" if sid else ""
plain.succeed(
f"curl -sf {auth} {sess} {JSON} -d '{{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}}' http://127.0.0.1:1984/mcp >/dev/null"
)
out = plain.succeed(
f"curl -sf {auth} {sess} {JSON} -d '{{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\"}}' http://127.0.0.1:1984/mcp"
)
assert "tools" in out, out
with subtest("plain: bad Origin on /mcp is rejected"):
assert code(plain, "http://127.0.0.1:1984/mcp", f"{auth} {JSON} -H 'Origin: http://evil.example' -d '{INIT}'") == "403"
with subtest("plain: revoke takes effect without a restart"):
plain.succeed(f"{CLI} token revoke t")
assert code(plain, "http://127.0.0.1:1984/api/v1/systemd/units", auth) == "401"
with subtest("root is refused by the token CLI"):
out = plain.fail("slinuxm token list 2>&1")
assert "sudo -u skyg-linux-tracker slinuxm token" in out, out
with subtest("tls: healthz over HTTPS, plain HTTP refused, token works"):
tls.wait_for_unit("skyg-linux-tracker.service")
tls.wait_for_open_port(1984)
curl = "--cacert ${cert}/cert.pem"
assert code(tls, "https://localhost:1984/healthz", curl) == "200"
tls.fail("curl -sf http://localhost:1984/healthz")
assert code(tls, "https://localhost:1984/api/v1/systemd/units", curl) == "401"
t2 = tls.succeed(f"{CLI} token create t").strip()
assert code(tls, "https://localhost:1984/api/v1/systemd/units", f"{curl} -H 'Authorization: Bearer {t2}'") == "200"
'';
}