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:
1 parent
46b4f5ac0b
commit
34da657fdf
6 files changed
+193
-16
No files matched your search
@@ -160,6 +160,43 @@ curl --cacert cert.pem -H "Authorization: Bearer $TOKEN" https://localhost:1984/
|
||||
|
||||
Rotation: replace the files and send `SIGHUP` (`kill -HUP $(pidof slinuxm)`, or `systemctl kill -s HUP <unit>`). New connections get the new certificate; established ones are not dropped. The certificate and key are read as two separate files, so rotation tooling must send SIGHUP only after BOTH are in place; if the pair is unreadable or mismatched (for example the cert was replaced but the key not yet), the old certificate stays, an error is logged, and you send SIGHUP again once the files are consistent. Any intermediate certificates must be in the `cert_file` chain. Both the TLS and the plain listener are HTTP/1.1 only, share one accept loop, cap concurrent connections at 1024 and close connections that send no request header within 30 seconds. SIGHUP is harmless when TLS is disabled (it is logged and ignored). For ACME, point `cert_file` and `key_file` at the client's output (for example certbot's `live/<name>/fullchain.pem` and `privkey.pem`, or the NixOS `security.acme` directory) and send SIGHUP from the renewal hook. For sops-nix or systemd `LoadCredential`, point at the decrypted or credential path (`/run/credentials/<unit>/...`) so the service user needs no access to the original key file.
|
||||
|
||||
## NixOS
|
||||
|
||||
The flake exports `packages.<system>.default` and `nixosModules.default`.
|
||||
|
||||
```nix
|
||||
# flake.nix
|
||||
inputs.skyg-linux-tracker.url = "github:<owner>/linux-system-monitor";
|
||||
|
||||
# in your nixosSystem modules
|
||||
modules = [
|
||||
skyg-linux-tracker.nixosModules.default
|
||||
{ services.skyg-linux-tracker.enable = true; }
|
||||
];
|
||||
```
|
||||
|
||||
That runs the service as the `skyg-linux-tracker` user on `127.0.0.1:1984` with the same sandbox as `systemd/skyg-linux-tracker.service`, writes `/etc/skyg-linux-tracker.toml` (the path the CLI reads by default) and installs `slinuxm` system-wide. Mint the first token as the service user:
|
||||
|
||||
```sh
|
||||
sudo -u skyg-linux-tracker slinuxm token create my-laptop
|
||||
```
|
||||
|
||||
Options (under `services.skyg-linux-tracker`): `port` (1984), `bind` (`"127.0.0.1"`), `tls.{enable,certFile,keyFile}` (passed through `LoadCredential`, so the service user never reads the original key; `systemctl reload skyg-linux-tracker` re-reads them; for ACME add `security.acme.certs.<name>.reloadServices = [ "skyg-linux-tracker" ]`), `openFirewall` (all interfaces), `firewallInterfaces` (recommended for a LAN), `allowedHosts`, `docker.enable` (adds the root-equivalent `docker` group), `settings` (freeform TOML merged over the module defaults) and `environmentFile` (secrets such as `SKYG_OTEL__HEADERS__AUTHORIZATION`, kept out of the store and out of the generated TOML).
|
||||
|
||||
Exposure: keep the default loopback bind and reach it over Tailscale or a TLS reverse proxy. Bearer tokens over plain HTTP are readable on a LAN. A non-loopback `bind` with `auth.enabled = false` fails at evaluation time. For `bind = "0.0.0.0"` add the names clients use to `allowedHosts` (`networking.hostName` is added for you), and prefer `firewallInterfaces = [ "enp3s0" ]` over `openFirewall`.
|
||||
|
||||
```nix
|
||||
services.skyg-linux-tracker = {
|
||||
enable = true;
|
||||
bind = "0.0.0.0";
|
||||
firewallInterfaces = [ "enp3s0" ];
|
||||
allowedHosts = [ "monitor.lan:1984" ];
|
||||
tls = { enable = true; certFile = "/var/lib/acme/monitor.lan/fullchain.pem"; keyFile = "/var/lib/acme/monitor.lan/key.pem"; };
|
||||
};
|
||||
```
|
||||
|
||||
`nix flake check` runs a two-machine VM test (plain and TLS) covering healthz, 401, token mint and revoke through the CLI, `/mcp` and the Origin check.
|
||||
|
||||
## Docker access
|
||||
|
||||
Reading the Docker socket directly requires group `docker`, which is root-equivalent. The unit file has this commented out. Prefer a read-only socket proxy that allows only `GET /containers/*`, `/events` and `/version`, for example [tecnativa/docker-socket-proxy](https://github.com/Tecnativa/docker-socket-proxy) with `CONTAINERS=1 EVENTS=1 POST=0`, exposed as a unix socket (or loopback TCP through a socat bridge), then:
|
||||
|
||||
@@ -116,14 +116,14 @@ Design: [`plan.md`](plan.md) · Review fixes: [`plan/review.md`](plan/review.md)
|
||||
- [x] **T8** Live check with `curl --cacert` and an `/mcp` initialize over HTTPS
|
||||
|
||||
### WS-H NixOS · [card](plan/workstreams/WS-H-nixos.md)
|
||||
- [ ] **H1** `nix/package.nix`: `buildRustPackage` from `Cargo.lock` with pkg-config, cmake, systemd. Binary `slinuxm`.
|
||||
- [ ] **H2** `flake.nix` with `packages.default`, `nixosModules.default` and `checks`
|
||||
- [ ] **H3** `nix/module.nix` options: `enable`, `package`, `port` (default 1984), `bind` (default loopback), `tls.*`, `openFirewall`, `allowedHosts`, `docker.enable`, `settings`, `environmentFile`
|
||||
- [ ] **H4** Service: dedicated user, `StateDirectory` 0700, `systemd-journal` group, P3 hardening set, config at `/etc/skyg-linux-tracker.toml`
|
||||
- [ ] **H5** **CLI installed system-wide**, plain binary (DEC-10). Token commands refuse to run as root against another user's DB and print the `sudo -u skyg-linux-tracker …` command.
|
||||
- [ ] **H6** Firewall: global `openFirewall` plus interface-scoped option. Eval assertion: non-loopback bind requires auth.
|
||||
- [ ] **H7** README NixOS section: flake input, token workflow, exposure model, `allowedHosts`
|
||||
- [ ] **H8** NixOS VM test: healthz, 401, mint token via CLI (`sudo -u`), 200, `/mcp`, revoke, 401, bad Origin 403, plus a TLS case
|
||||
- [x] **H1** `nix/package.nix`: `buildRustPackage` from `Cargo.lock` with pkg-config, cmake, systemd. Binary `slinuxm`.
|
||||
- [x] **H2** `flake.nix` with `packages.default`, `nixosModules.default` and `checks`
|
||||
- [x] **H3** `nix/module.nix` options: `enable`, `package`, `port` (default 1984), `bind` (default loopback), `tls.*`, `openFirewall`, `allowedHosts`, `docker.enable`, `settings`, `environmentFile`
|
||||
- [x] **H4** Service: dedicated user, `StateDirectory` 0700, `systemd-journal` group, P3 hardening set, config at `/etc/skyg-linux-tracker.toml`
|
||||
- [x] **H5** **CLI installed system-wide**, plain binary (DEC-10). Token commands refuse to run as root against another user's DB and print the `sudo -u skyg-linux-tracker …` command.
|
||||
- [x] **H6** Firewall: global `openFirewall` plus interface-scoped option. Eval assertion: non-loopback bind requires auth.
|
||||
- [x] **H7** README NixOS section: flake input, token workflow, exposure model, `allowedHosts`
|
||||
- [x] **H8** NixOS VM test: healthz, 401, mint token via CLI (`sudo -u`), 200, `/mcp`, revoke, 401, bad Origin 403, plus a TLS case
|
||||
- [ ] **Gate:** `nix build` and `nix flake check` pass. `ldd` shows no openssl. A fresh NixOS host serves `:1984` and a token can be minted from a login shell.
|
||||
|
||||
## Future
|
||||
|
||||
Generated
+27
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"nodes": {
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1791956154,
|
||||
"narHash": "sha256-jBYGPi4udQ9uo4KQp9m2J0546nJVQitG15gvZSaVVAs=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "55bfb4d7437bd4e09ab7cba58a43bd68eb310044",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
+23
-8
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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"
|
||||
'';
|
||||
}
|
||||
Reference in new issue
Block a user