Files
skyg-linux-tracker/README.md
T

185 lines
10 KiB
Markdown

# skyg-linux-tracker
A small, read-only monitor for a single Linux host. One binary, `slinuxm`, serves:
- a REST API (with Server-Sent Events for follow endpoints),
- an MCP server (Streamable HTTP) so agents can inspect the host,
- optional OpenTelemetry export (metrics and logs over OTLP).
Data sources are systemd (D-Bus), the journal (libsystemd) and the Docker Engine API (unix socket). Nothing here can start, stop or modify anything.
## Build
```sh
devenv shell # toolchain, pkg-config, libsystemd, otelcol-contrib
cargo build --release # target/release/slinuxm
```
Without devenv you need a Rust toolchain, `pkg-config` and the libsystemd development files.
## Install
```sh
sudo install -m 0755 target/release/slinuxm /usr/local/bin/slinuxm
sudo useradd --system --no-create-home --shell /usr/sbin/nologin skyg
sudo install -m 0644 config.example.toml /etc/skyg-linux-tracker.toml # then edit
sudo install -m 0644 systemd/skyg-linux-tracker.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now skyg-linux-tracker
```
The unit runs as the `skyg` user with `SupplementaryGroups=systemd-journal` and a private `StateDirectory` (`/var/lib/skyg-linux-tracker`, mode 0700) holding the token database. Its sandbox options are listed in the unit file.
### Config
See `config.example.toml`; every value shown is the default. Precedence, lowest to highest: defaults, config file, `SKYG_*` environment variables (nesting with `__`, for example `SKYG_SERVER__PORT`), CLI flags. `slinuxm --print-config` prints the effective configuration with secrets redacted.
Startup refuses `auth.enabled = false` on a non-loopback `server.bind`.
## Tokens
All `/api/v1/*` and `/mcp` requests need `Authorization: Bearer <token>`. `/healthz` is public. Tokens are stored hashed (sha256) in SQLite, and the plaintext is shown once.
Run the token CLI **as the service user** so the database keeps the right owner and mode:
```sh
sudo -u skyg slinuxm token create my-laptop --config /etc/skyg-linux-tracker.toml
sudo -u skyg slinuxm token list --config /etc/skyg-linux-tracker.toml
sudo -u skyg slinuxm token revoke my-laptop --config /etc/skyg-linux-tracker.toml
```
Revocation takes effect immediately; no restart is needed.
Notes:
- `auth.db_path` must stay under the unit's `StateDirectory` (`/var/lib/skyg-linux-tracker`). The unit uses `ProtectSystem=strict`, so any other location needs a matching `ReadWritePaths=`.
- `token create` needs the state directory to exist, so start the service once first (systemd creates it with the right owner), then run the CLI as `skyg`.
## REST
Base: `http://127.0.0.1:9109`. Errors are `{"error":{"code","message"}}`.
| Route | Notes |
|---|---|
| `GET /healthz` | public, `{"status":"ok","version":...}` |
| `GET /api/v1/systemd/units?state=failed` | `state` is an active state (`failed`, `active`, ...) |
| `GET /api/v1/systemd/units/{name}` | one unit with details |
| `GET /api/v1/systemd/timers` | |
| `GET /api/v1/journal?unit=&priority=err&lines=100` | priority by name or number |
| `GET /api/v1/journal/follow?unit=&priority=` | SSE, event `journal` |
| `GET /api/v1/docker/ps` | `503` when Docker is unavailable |
| `GET /api/v1/docker/containers/{name}` | |
| `GET /api/v1/docker/containers/{name}/logs?tail=&since=&follow=0\|1` | JSON, or SSE with events `stdout`/`stderr` |
```sh
TOKEN=slinuxm_...
curl -H "Authorization: Bearer $TOKEN" 'http://127.0.0.1:9109/api/v1/systemd/units?state=failed'
curl -N -H "Authorization: Bearer $TOKEN" 'http://127.0.0.1:9109/api/v1/journal/follow?priority=err'
```
## MCP
Endpoint: `http://127.0.0.1:9109/mcp` (Streamable HTTP). Eight tools (`list_systemd_units`, `get_systemd_unit`, `list_systemd_timers`, `get_journal_logs`, `tail_journal`, `list_containers`, `get_container`, `get_container_logs`), two prompts (`diagnose_unit`, `container_health_report`) and two resources (`systemd://units/failed`, `docker://containers`). Log content is untrusted data and is labelled as such in tool results.
Generic client config (header-capable clients):
```json
{
"mcpServers": {
"linux-tracker": {
"url": "http://127.0.0.1:9109/mcp",
"headers": { "Authorization": "Bearer slinuxm_..." }
}
}
}
```
Claude Code: `claude mcp add --transport http linux-tracker http://127.0.0.1:9109/mcp --header "Authorization: Bearer $TOKEN"`.
Inspector: `npx @modelcontextprotocol/inspector`, transport Streamable HTTP, add the bearer header.
Raw handshake with curl:
```sh
curl -si -X POST http://127.0.0.1:9109/mcp \
-H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}'
```
### Origin and Host checks
`/mcp` validates `Origin` and `Host` to defend against DNS rebinding from browsers. Loopback names, `server.bind` and the configured port are accepted by default. Requests without an `Origin` header (non-browser clients) pass this check, so the bearer token remains the real gate. If you bind to `0.0.0.0` or serve behind a name, add the names clients use to `server.allowed_hosts` (for example `["monitor.lan:9109"]`) and any browser origins to `server.allowed_origins`. With `auth.enabled = false` (loopback only), REST requests are checked against a Host allowlist (loopback names, `server.bind` and `server.allowed_hosts`) and get `403` otherwise, to blunt DNS rebinding. There is no Origin check on REST and no token in that mode, so keep auth enabled on any multi-user host. If the host is reachable beyond a trusted network, enable native TLS (see the TLS section) or terminate TLS in a reverse proxy.
## TLS
TLS is optional and off by default. With `server.tls.enabled = false` (the default) the server speaks plain HTTP exactly as before, the certificate paths are ignored and never read, and no TLS code runs. A non-loopback `bind` without TLS logs a startup warning (it is not refused).
Enable it in the config file or the environment (`SKYG_SERVER__TLS__ENABLED=true`, `SKYG_SERVER__TLS__CERT_FILE`, `SKYG_SERVER__TLS__KEY_FILE`):
```toml
[server.tls]
enabled = true
cert_file = "/etc/skyg/tls/cert.pem" # PEM chain, leaf first
key_file = "/etc/skyg/tls/key.pem" # PEM, PKCS#8, PKCS#1 or SEC1
```
Both files are required and checked at startup; a missing, unparsable or mismatched pair stops the server with an error naming the file (key contents are never logged). REST and `/mcp` are then served over HTTPS only (plain HTTP on that port fails), and the default MCP `Origin` allowlist uses `https://` instead of `http://`. Add your public names to `server.allowed_hosts` and `server.allowed_origins` as before. TLS is rustls with the ring provider; openssl is not used.
Self-signed example:
```sh
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 365 \
-keyout key.pem -out cert.pem -subj '/CN=monitor.lan' \
-addext 'subjectAltName=DNS:monitor.lan,DNS:localhost,IP:127.0.0.1'
curl --cacert cert.pem -H "Authorization: Bearer $TOKEN" https://localhost:9109/api/v1/systemd/units
```
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. The TLS listener is HTTP/1.1 only, caps concurrent connections at 1024 and closes 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.
## 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:
```toml
[sources]
docker_socket = "/run/docker-proxy/docker.sock"
```
A stock install does not add the `docker` group, so out of the box the Docker routes return `503` until you either grant access or configure a proxy. If the socket is missing or unreadable, Docker routes return `503` and everything else keeps working.
## OpenTelemetry
```toml
[otel]
enabled = true
endpoint = "http://localhost:4317" # gRPC; or http://localhost:4318 with protocol = "http/protobuf"
export_logs = true
```
Metrics are polled every `metrics_interval_secs` (systemd unit active/failed/restarts and timer next elapse; container running/healthy/uptime/restarts). Logs fan out from the journal and from Docker containers. For a local collector with a debug exporter: `devenv up` (runs `otelcol-contrib --config dev/otelcol.yaml`). On SIGTERM pending records are flushed before exit.
## Verifying a release binary
```sh
ldd /usr/local/bin/slinuxm # libc, libm, libgcc_s, libsystemd and its dependencies only
```
## Testing
```sh
devenv shell -- smoke # same as: cargo test --test binary_smoke -- --nocapture
```
The smoke test runs the real built `slinuxm` binary against a throwaway SQLite database in a temp directory: it creates a token with the CLI, starts `serve` on a free loopback port, exercises `/healthz`, REST and MCP with and without the token, revokes the token, and checks a clean SIGTERM exit and a 0600 database. It needs no root and no network. Checks that depend on host data (systemd over D-Bus, the journal) are skipped with a printed reason when the source is unavailable; Docker is never required.
## Development
```sh
cargo test
cargo clippy --all-targets -- -D warnings
cargo fmt --check
```
The integration tests in `tests/` start the real router on an ephemeral port with fake sources. Design notes live in `plan.md` and `plan/`.