10 Commits

Author SHA1 Message Date
urania bb5cc8268f cleanup
build-and-release / release (push) Successful in 1m10s
2026-06-26 10:17:45 +02:00
urania cad6c1f421 fix: install sh
build-and-release / release (push) Successful in 2m32s
2026-06-25 20:42:05 +02:00
urania 22e6812d4b feat: add interactive CLI setup wizard for server configuration and log file registration 2026-06-25 20:41:52 +02:00
urania 0415e905af Feat: GPU detection via DRM sysfs, integrated into system info endpoint
build-and-release / release (push) Successful in 2m34s
Adds GPUInfo struct and readGPUsFromSysfs parsing DRM card entries
(/sys/class/drm/card*). Supports:
- AMD GPUs (amdgpu driver): VRAM totals/utilization from sysfs files
- NVIDIA GPUs: enrichment via nvidia-smi query
- Intel/other: basic PCI vendor/device/driver identification

Includes full test coverage for AMD enrichment, i915 fallback, missing
sysfs dir, and non-GPU DRM entry filtering.
2026-06-25 18:34:34 +02:00
urania d4364a6cb7 feat(system): enhance system architecture
build-and-release / release (push) Successful in 2m39s
2026-06-25 14:44:47 +02:00
urania 54108c263f fix: remove terminal module and implement concurrent log stream limiting
build-and-release / release (push) Successful in 2m39s
2026-06-24 17:29:45 +02:00
urania 37e5b97507 fix: crt
build-and-release / release (push) Successful in 2m38s
2026-06-23 19:47:19 +02:00
urania 63c9a272b5 feat: add configurable TLS/proxy installation options for the systemd service
build-and-release / release (push) Successful in 2m34s
2026-06-23 19:13:34 +02:00
urania 411f7fd6d9 feat: persistent TLS cert and token auto-generation during install 2026-06-23 19:05:26 +02:00
urania 8fc4b236ac fix: whomai with bearer
build-and-release / release (push) Successful in 2m39s
2026-06-23 18:02:52 +02:00
62 changed files with 2481 additions and 1481 deletions
-15
View File
@@ -1,15 +0,0 @@
{
"permissions": {
"allow": [
"Bash(go get *)",
"Bash(go build *)",
"Bash(go vet *)",
"Read(//usr/lib/**)",
"Read(//proc/**)",
"Bash(systemctl show *)",
"Bash(echo \"exit=$?\")",
"Bash(systemctl list-units *)",
"Bash(go test *)"
]
}
}
+2 -1
View File
@@ -13,4 +13,5 @@ config.yml
CLAUDE.md
minisign.key
minisign.key
./.claude
+51 -25
View File
@@ -19,7 +19,7 @@ Functionality is organized into **modules**. Each module owns a slice of the
API and declares its own permission vocabulary.
- **System** - Dashboard overview (OS/kernel, CPU, memory, disks, load, uptime,
network interfaces, temperatures); get/set hostname; time, timezone, and NTP;
network interfaces, GPU, temperatures); get/set hostname; time, timezone, and NTP;
locale and console keymap; reboot and power off.
- **Services** - List and inspect systemd units; start / stop / restart / enable
/ disable; read service logs from the journal or an allowlisted file, as a
@@ -29,11 +29,11 @@ API and declares its own permission vocabulary.
- **Groups** - List, inspect, create, and delete local groups.
- **Packages** - List installed packages and available updates; install, remove,
and upgrade - streamed live over SSE. Auto-detects `dnf`, `apt`, or `pacman`.
- **Networking** - List network interfaces, routing tables, and DNS settings; configure IPv4 settings with temporary applying and safety auto-rollback; bring interfaces up or down.
- **Networking** - List network interfaces, routing tables, and DNS settings; configure IPv4 settings with temporary applying and safety auto-rollback; bring interfaces up or down; edit `/etc/hosts`.
- **Storage** - List active mounts and `/etc/fstab` entries; add, edit, and delete fstab entries; mount and unmount filesystems.
- **Audit** - Read-only trail of every privileged write (who, what, when, result).
- **Terminal** - Interactive shell access. Upgrades connection to a WebSocket and spawns a PTY shell as the logged-in user (requires `root` permission).
- **Meta** - Self-description for clients: `/api/_modules`, `/api/whoami`,
`/api/health`.
`/api/health`; trigger a self-update via `POST /api/update`.
### Security model at a glance
@@ -160,14 +160,18 @@ assigns the admin role to the installing user.
| Command | Effect |
| ------------------------------------------------ | --------------------------------------------------------------------------- |
| `nadir [run] [-d]` | Start the server. `-d` / `--detach` runs it in the background. |
| `nadir --save-config` | Save the default configuration template to the target path and exit. |
| `nadir install` | Install + enable the systemd service (starts now and on boot). |
| `nadir uninstall` | Stop, disable, and remove the systemd service. |
| `nadir start` \| `stop` \| `restart` \| `status` | Control the running service. |
| `nadir enable` \| `disable` | Toggle start-on-boot without removing the unit. |
| `nadir logs` | Follow logs - journald if installed as a service, otherwise the detach log. |
| `nadir help` | Show usage. |
| `nadir [run] [-d]` | Start the server. `-d` / `--detach` runs it in the background. |
| `nadir --save-config` | Save the default configuration template to the target path and exit. |
| `nadir install` | Install + enable the systemd service (starts now and on boot). |
| `nadir uninstall` | Stop, disable, and remove the systemd service. |
| `nadir start` \| `stop` \| `restart` \| `status` | Control the running service. |
| `nadir enable` \| `disable` | Toggle start-on-boot without removing the unit. |
| `nadir logs` | Follow logs - journald if installed as a service, otherwise the detach log. |
| `nadir update [--check] [--force]` | Download and install the latest release (requires `server.release_repo` in config). `--check` reports the available version without downloading; `--force` re-downloads even when already current. |
| `nadir token add <name>` | Mint a machine API token (shown once, not stored in plain text). |
| `nadir token rm <name>` | Revoke a token immediately (no restart needed). |
| `nadir token ls` | List token names (not the raw keys). |
| `nadir help` | Show usage. |
Most commands need root.
@@ -188,6 +192,7 @@ server:
# tls_key: /etc/nadir/tls/key.pem
hostname: 100.64.0.189
port: 9999
# release_repo: https://gitea.example.com/owner/nadir # enables `nadir update`
# Quote "*" - bare * is YAML alias syntax and fails to parse.
roles:
@@ -217,6 +222,7 @@ log_files:
| `tls_cert`, `tls_key` | - | PEM paths. When both are set (and `trust_proxy` is off), nadir terminates TLS with this pair. |
| `hostname` | - | Address to bind. Use `127.0.0.1` for local-only, or an overlay/VPN address to expose nadir only on that interface. |
| `port` | - | TCP port to listen on. |
| `release_repo` | - | Gitea repo URL (`https://host/owner/repo`). When set, enables `nadir update` and `POST /api/update`. Must be `https://`. |
TLS selection is covered in [Deployment note 2](#2-tls-three-modes).
@@ -390,7 +396,27 @@ forwarded headers are trustworthy. Without step 1 you're trusting every peer on
the overlay - fine for a single-tenant network you fully control, risky on a
shared one.
### 4. Connecting a dashboard (machine clients)
### 4. Self-update
When `server.release_repo` points at a Gitea repo, nadir can update itself:
```bash
sudo nadir update # download + install latest, restart service
sudo nadir update --check # report available version, do nothing
sudo nadir update --force # re-download even if already at latest
```
The updater:
1. Fetches the latest release from the Gitea API.
2. Downloads the binary for the host's architecture (`linux-amd64`, `linux-arm64`, …).
3. Verifies the release: checks the minisign signature on `sha256sums.txt`, then checks the binary's SHA-256 against it. Refuses to install if either check fails.
4. Atomically replaces the running binary (`os.Rename` on the same filesystem) and runs `systemctl restart nadir`.
The same flow is also reachable via `POST /api/update` (requires the admin wildcard role), which runs the updater detached and returns 202 immediately. Poll `GET /api/health` to confirm the new version is running after the restart drops in-flight connections.
`release_repo` must use `https://` — the update downloads and executes the binary, and a plaintext URL would expose the host to on-path replacement.
### 5. Connecting a dashboard (machine clients)
To manage one or more Nadir instances via a central dashboard or non-interactive client, authenticate requests using a static Bearer token rather than interactive PAM credentials.
@@ -440,23 +466,23 @@ To connect a browser-based dashboard hosted on a different origin, choose one of
## Layout
```
cmd/ process entry point + CLI (run / install / logs …), TLS, service wiring
internal/auth PAM auth, sessions, login/logout, login throttle, PAM service install
cmd/ process entry point + CLI (run / install / update / token / logs …), TLS, service wiring
internal/auth PAM auth, sessions, login/logout, login throttle, bearer tokens, PAM service install
internal/auditlog SQLite-backed audit log writer
internal/config config.yaml loader + startup validation
internal/meta /api/_modules, /api/whoami, /api/health discovery endpoints
internal/meta /api/_modules, /api/whoami, /api/health, /api/update discovery + update endpoints
internal/module the Module interface
internal/modules concrete modules:
system - info, hostname, time/timezone/NTP, locale/keymap, power
services - systemd unit control + journal/file logs (snapshot + SSE)
users - local accounts
groups - local groups
packages - dnf/apt/pacman install/remove/upgrade (streamed)
audit - read-only audit trail
networking - network interfaces, routing tables, DNS, and IP configurations
terminal - interactive PTY shell over WebSocket
system - info, hostname, time/timezone/NTP, locale/keymap, power
services - systemd unit control + journal/file logs (snapshot + SSE)
users - local accounts
groups - local groups
packages - dnf/apt/pacman install/remove/upgrade (streamed)
networking - interfaces, routing tables, DNS, IP config, /etc/hosts
storage - active mounts, /etc/fstab read/write, mount/unmount
internal/mounts /proc/mounts parser (used by storage module)
internal/oscmd shared command runner (timeouts, stderr surfacing) + helpers
internal/rbac roles, permissions ("*" wildcards), HTTP middleware (RBAC + CSRF)
internal/audit SQLite-backed audit log writer
```
## API docs
+87 -25
View File
@@ -24,14 +24,12 @@ import (
"nadir/internal/config"
"nadir/internal/meta"
"nadir/internal/module"
"nadir/internal/modules/audit"
"nadir/internal/modules/groups"
"nadir/internal/modules/networking"
"nadir/internal/modules/packages"
"nadir/internal/modules/services"
"nadir/internal/modules/storage"
"nadir/internal/modules/system"
"nadir/internal/modules/terminal"
"nadir/internal/modules/users"
"nadir/internal/rbac"
@@ -39,6 +37,15 @@ import (
"github.com/danielgtaylor/huma/v2/adapters/humago"
)
// auditModule is a synthetic module so the config validator knows the "audit"
// permission vocabulary. The actual endpoint is registered by meta.RegisterAudit —
// a full module for one GET is too shallow.
type auditModule struct{}
func (auditModule) ID() string { return "audit" }
func (auditModule) Permissions() []rbac.Permission { return []rbac.Permission{rbac.Read} }
func (auditModule) Register(huma.API) {}
// main is a thin command dispatcher. With no subcommand (or "run") it starts the
// server; the rest manage nadir as a systemd service or tail its logs. Service
// plumbing lives in service.go, TLS in tls.go.
@@ -63,6 +70,12 @@ func main() {
}
args = append(args, rest[0])
rest = rest[1:]
if len(args) > 0 {
// Once we have identified the subcommand, the remaining arguments
// belong to it (including its own flags), so we stop parsing global flags.
args = append(args, rest...)
break
}
}
if *showVersion {
@@ -81,7 +94,7 @@ func main() {
fmt.Printf("configuration file already exists at %s\n", configPath)
os.Exit(0)
}
fatalIf(saveDefaultConfig(configPath))
fatalIf(saveDefaultConfig(configPath, DefaultConfigContent(getUsername())))
os.Exit(0)
}
@@ -96,7 +109,7 @@ func main() {
runCmd(args)
case "install":
ensureRoot()
fatalIf(installService())
fatalIf(installService(args))
case "uninstall":
ensureRoot()
fatalIf(uninstallService(slices.Contains(args, "--complete")))
@@ -200,13 +213,12 @@ func runServer() {
mods := []module.Module{
system.New(),
services.New(cfg.LogFiles),
users.New(),
users.New(sessions),
groups.New(),
packages.New(),
networking.New(),
storage.New(),
audit.New(auditStore),
terminal.New(sessions),
auditModule{},
}
roles := rbac.New()
@@ -230,6 +242,8 @@ func runServer() {
humaConfig.DocsPath = ""
api := humago.New(mux, humaConfig)
rateLimiter := auth.NewRateLimiter(100, time.Minute)
api.UseMiddleware(auth.RateLimitMiddleware(api, rateLimiter))
api.UseMiddleware(rbac.RbacMiddleware(api, sessions, tokenAuth, roles, auditStore))
for _, m := range mods {
@@ -238,8 +252,9 @@ func runServer() {
meta.Register(api, mods)
meta.RegisterHealth(api, sessions)
meta.RegisterWhoami(api, sessions, roles, mods)
meta.RegisterWhoami(api, sessions, tokenAuth, roles, mods)
meta.RegisterUpdate(api, configPath)
meta.RegisterAudit(api, auditStore)
auth.RegisterLogin(api, sessions, auditStore, cfg.SecureCookie())
auth.RegisterLogout(api, sessions, cfg.SecureCookie())
@@ -271,18 +286,18 @@ func runServer() {
})
mux.HandleFunc("GET /docs", func(w http.ResponseWriter, _ *http.Request) {
// /docs needs to execute the Scalar bundle, so loosen the strict CSP set
// by secHeaders for this one page: allow scripts/styles from the jsdelivr
// CDN plus inline (Scalar uses inline <script> + inline styles). The CDN
// host is the supply-chain trust boundary; pinning a version + SRI here
// is the follow-up (M5 partial).
w.Header().Set("Content-Security-Policy",
"default-src 'self'; "+
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net; "+
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
"img-src 'self' data: https:; "+
"connect-src 'self'; "+
"font-src 'self' data: https://cdn.jsdelivr.net https://fonts.scalar.com")
// /docs needs to execute the Scalar bundle, so loosen the strict CSP set
// by secHeaders for this one page: allow scripts/styles from the pinned
// jsdelivr CDN version + inline (Scalar uses inline <script> + inline styles).
// unsafe-eval is removed Scalar does not need it. The CDN host is the
// supply-chain trust boundary; SRI pinning would close the remaining gap.
w.Header().Set("Content-Security-Policy",
"default-src 'self'; "+
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
"img-src 'self' data: https:; "+
"connect-src 'self'; "+
"font-src 'self' data: https://cdn.jsdelivr.net https://fonts.scalar.com")
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`<!doctype html><html><head><title>API</title>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
@@ -297,7 +312,7 @@ func runServer() {
Addr: addr,
// WithClientIP records the source IP for the login throttle (H1); behind a
// trusted proxy it reads X-Forwarded-For instead of the proxy's address.
Handler: secHeaders(auth.WithClientIP(cfg.Server.TrustProxy, mux)),
Handler: bodySizeLimit(requestTimeout(secHeaders(auth.WithClientIP(cfg.Server.TrustProxy, mux)))),
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 0, // unset: SSE endpoints stream indefinitely
@@ -307,14 +322,14 @@ func runServer() {
// Pick how the connection is secured (see config.Server doc):
// 1. trust_proxy - a reverse proxy terminates TLS; we serve plaintext HTTP.
// 2. tls_cert/tls_key - we terminate TLS with the admin's PEM pair.
// 3. neither - a fresh in-memory self-signed cert (dev only).
// 3. neither - plain HTTP (localhost-only default).
var serve func() error
switch {
case cfg.Server.TrustProxy:
log.Printf("tls: trust_proxy set - serving plaintext HTTP, TLS terminated upstream; bind to localhost so X-Forwarded-For can't be spoofed")
log.Printf("tls: trust_proxy set serving plaintext HTTP, TLS terminated upstream; bind to localhost so X-Forwarded-For can't be spoofed")
serve = srv.ListenAndServe
default:
cert, err := serverCert(cfg.Server.TLSCert, cfg.Server.TLSKey)
case cfg.Server.TLSCert != "" && cfg.Server.TLSKey != "":
cert, err := tls.LoadX509KeyPair(cfg.Server.TLSCert, cfg.Server.TLSKey)
if err != nil {
log.Fatalf("tls cert: %v", err)
}
@@ -325,8 +340,19 @@ func runServer() {
srv.TLSConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
},
}
serve = func() error { return srv.ListenAndServeTLS("", "") }
default:
log.Printf("tls: no TLS configured — serving plain HTTP on %s", addr)
serve = srv.ListenAndServe
}
go func() {
@@ -354,6 +380,40 @@ func runServer() {
}
}
// bodySizeLimit rejects requests with a body larger than 1 MB, preventing
// OOM from arbitrarily large JSON payloads. Wraps the entire mux so it
// covers both Huma-registered routes and raw mux handlers (/docs, /install.sh).
func bodySizeLimit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
next.ServeHTTP(w, r)
})
}
// requestTimeout cancels slow requests via context deadline. SSE endpoints
// (package streams, log following) are exempt because they keep the
// connection open indefinitely.
func requestTimeout(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if isSSEEndpoint(r) {
next.ServeHTTP(w, r)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// isSSEEndpoint identifies routes that stream data indefinitely and must
// not have a context deadline.
func isSSEEndpoint(r *http.Request) bool {
if strings.HasPrefix(r.URL.Path, "/api/packages") {
return r.Method == "POST" || r.Method == "DELETE"
}
return r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/logs/stream")
}
// secHeaders sets defensive response headers on every HTTP response. The
// default Content-Security-Policy denies everything (`default-src 'none'`) —
// correct for the JSON API and the tiny landing/favicon endpoints. /docs
@@ -371,6 +431,8 @@ func secHeaders(next http.Handler) http.Handler {
h.Set("Referrer-Policy", "no-referrer")
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
h.Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")
h.Set("Cache-Control", "no-store, no-cache, must-revalidate, private")
h.Set("Pragma", "no-cache")
next.ServeHTTP(w, r)
})
}
+276 -32
View File
@@ -1,38 +1,46 @@
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"github.com/mattn/go-isatty"
"nadir/internal/auth"
"nadir/internal/config"
)
const defaultConfigTemplate = `# Nadir configuration - config.yaml
const configTemplateBase = `# Nadir configuration - config.yaml
#
# Single source of truth for runtime settings.
#
server:
secure_tls: true
# trust_proxy: false
# tls_cert: /etc/nadir/tls/cert.pem
# tls_key: /etc/nadir/tls/key.pem
hostname: 127.0.0.1
port: 9999
secure_tls: %s
%s
%s
%s
hostname: %s
port: %d
release_repo: https://tea.urania.dev/urania/nadir-agent
roles:
admin:
"*": ["*"]
auditor:
"*": ["read"]
assignments:
%s: [admin]
dashboard: [auditor]
`
// resolveConfigPath returns the config file path: CONFIG_PATH env (with ~ expanded)
@@ -101,7 +109,157 @@ const (
// installService writes the systemd unit, enables it on boot, and starts it.
// The unit pins the absolute executable and config paths captured now, so the
// service doesn't depend on the working directory at boot.
func installService() error {
func installService(args []string) error {
// Parse options
fs := flag.NewFlagSet("install", flag.ContinueOnError)
tlsOpt := fs.Bool("tls", false, "Generate persistent self-signed TLS cert/key and enable HTTPS")
unsecureOpt := fs.Bool("unsecure", false, "Serve plaintext HTTP directly")
trustProxyOpt := fs.Bool("trust-proxy", false, "Serve plaintext HTTP behind a trusted TLS-terminating reverse proxy")
hostnameOpt := fs.String("hostname", "127.0.0.1", "Hostname to bind to")
portOpt := fs.Int("port", 9999, "Port to bind to")
if err := fs.Parse(args); err != nil {
return err
}
optCount := 0
if *tlsOpt {
optCount++
}
if *unsecureOpt {
optCount++
}
if *trustProxyOpt {
optCount++
}
if optCount > 1 {
return fmt.Errorf("options --tls, --unsecure, and --trust-proxy are mutually exclusive")
}
// Default to unsecure (plain HTTP) if nothing is specified
isTLS := *tlsOpt
isUnsecure := *unsecureOpt || optCount == 0
isTrustProxy := *trustProxyOpt
cfgPath, err := resolveConfigPath()
if err != nil {
return err
}
shouldWriteConfig := false
if _, err := os.Stat(cfgPath); os.IsNotExist(err) {
shouldWriteConfig = true
}
username := getUsername()
var logFiles map[string][]string
if fs.NFlag() == 0 && (isatty.IsTerminal(os.Stdin.Fd()) || isatty.IsCygwinTerminal(os.Stdin.Fd())) {
reader := bufio.NewReader(os.Stdin)
if !shouldWriteConfig {
fmt.Printf("Configuration file already exists at %s. Overwrite? [y/N] (default n): ", cfgPath)
overwriteInput, _ := reader.ReadString('\n')
overwriteInput = strings.ToLower(strings.TrimSpace(overwriteInput))
if overwriteInput != "y" && overwriteInput != "yes" {
fmt.Println("Keeping existing configuration. Proceeding with installation...")
if existingCfg, loadErr := config.Load(cfgPath); loadErr == nil {
*hostnameOpt = existingCfg.Server.Hostname
if p, err := strconv.Atoi(existingCfg.Server.Port); err == nil {
*portOpt = p
}
isTLS = existingCfg.Server.TLSCert != "" && existingCfg.Server.TLSKey != ""
isTrustProxy = existingCfg.Server.TrustProxy
isUnsecure = !isTLS && !isTrustProxy
}
goto skipConfigPrompt
}
shouldWriteConfig = true
}
fmt.Println("Configuring Nadir installation:")
fmt.Println(" 1) Serve plaintext HTTP directly (unsecure) [default]")
fmt.Println(" 2) Generate persistent self-signed TLS cert/key and enable HTTPS (tls)")
fmt.Println(" 3) Serve plaintext HTTP behind a trusted TLS-terminating reverse proxy (trust-proxy)")
fmt.Print("Enter choice [1-3] (default 1): ")
choice, _ := reader.ReadString('\n')
choice = strings.TrimSpace(choice)
if choice == "" || choice == "1" {
isUnsecure = true
isTLS = false
isTrustProxy = false
} else if choice == "2" {
isTLS = true
isUnsecure = false
isTrustProxy = false
} else if choice == "3" {
isTrustProxy = true
isTLS = false
isUnsecure = false
} else {
return fmt.Errorf("invalid choice: %q", choice)
}
fmt.Printf("Enter hostname to bind to (default %s): ", *hostnameOpt)
hostChoice, _ := reader.ReadString('\n')
hostChoice = strings.TrimSpace(hostChoice)
if hostChoice != "" {
*hostnameOpt = hostChoice
}
fmt.Printf("Enter port to bind to (default %d): ", *portOpt)
portChoice, _ := reader.ReadString('\n')
portChoice = strings.TrimSpace(portChoice)
if portChoice != "" {
p, err := strconv.Atoi(portChoice)
if err != nil || p <= 0 || p > 65535 {
return fmt.Errorf("invalid port: %q", portChoice)
}
*portOpt = p
}
fmt.Printf("Enter main admin username (default %s): ", username)
userChoice, _ := reader.ReadString('\n')
userChoice = strings.TrimSpace(userChoice)
if userChoice != "" {
username = userChoice
}
fmt.Print("Would you like to expose any log files to the Nadir UI? [y/N] (default n): ")
logInput, _ := reader.ReadString('\n')
logInput = strings.ToLower(strings.TrimSpace(logInput))
if logInput == "y" || logInput == "yes" {
logFiles = make(map[string][]string)
for {
fmt.Print(" Enter service/unit name (e.g. nginx): ")
unit, _ := reader.ReadString('\n')
unit = strings.TrimSpace(unit)
if unit == "" {
fmt.Println(" Service name cannot be empty. Skipping.")
continue
}
fmt.Printf(" Enter absolute path to log file for %s: ", unit)
path, _ := reader.ReadString('\n')
path = strings.TrimSpace(path)
if path == "" {
fmt.Println(" Path cannot be empty. Skipping.")
continue
}
logFiles[unit] = append(logFiles[unit], path)
fmt.Print(" Add another log file? [y/N] (default n): ")
another, _ := reader.ReadString('\n')
another = strings.ToLower(strings.TrimSpace(another))
if another != "y" && another != "yes" {
break
}
}
}
}
skipConfigPrompt:
// Provision the PAM service the server authenticates against, so it exists
// before the unit starts rather than appearing on first login. Idempotent:
// EnsurePAMService leaves an existing /etc/pam.d/nadir untouched. runServer
@@ -130,14 +288,56 @@ func installService() error {
return fmt.Errorf("create data directory: %w", err)
}
cfgPath, err := resolveConfigPath()
if err != nil {
return err
// Generate and save persistent self-signed TLS certificates if TLS mode
certPath := filepath.Join("/var/lib/nadir/tls", "cert.pem")
if isTLS {
tlsDir := "/var/lib/nadir/tls"
if err := os.MkdirAll(tlsDir, 0700); err != nil {
return fmt.Errorf("create tls directory: %w", err)
}
keyPath := filepath.Join(tlsDir, "key.pem")
if _, err := os.Stat(certPath); os.IsNotExist(err) {
if err := generateAndSaveCert(certPath, keyPath, *hostnameOpt); err != nil {
return fmt.Errorf("generate certificates: %w", err)
}
fmt.Printf("generated persistent self-signed TLS certificate at %s\n", certPath)
}
}
// Ensure default config file exists
if _, err := os.Stat(cfgPath); os.IsNotExist(err) {
if err := saveDefaultConfig(cfgPath); err != nil {
// Construct configuration template content based on installation options
secureTLSVal := "true"
trustProxyLine := "# trust_proxy: false"
certLine := "tls_cert: /var/lib/nadir/tls/cert.pem"
keyLine := "tls_key: /var/lib/nadir/tls/key.pem"
if isUnsecure {
secureTLSVal = "false"
trustProxyLine = "# trust_proxy: false"
certLine = "# tls_cert: /var/lib/nadir/tls/cert.pem"
keyLine = "# tls_key: /var/lib/nadir/tls/key.pem"
} else if isTrustProxy {
secureTLSVal = "false"
trustProxyLine = "trust_proxy: true"
certLine = "# tls_cert: /var/lib/nadir/tls/cert.pem"
keyLine = "# tls_key: /var/lib/nadir/tls/key.pem"
}
configContent := fmt.Sprintf(configTemplateBase, secureTLSVal, trustProxyLine, certLine, keyLine, *hostnameOpt, *portOpt, username)
if len(logFiles) > 0 {
var logFilesSection strings.Builder
logFilesSection.WriteString("\nlog_files:\n")
for unit, paths := range logFiles {
logFilesSection.WriteString(fmt.Sprintf(" %s:\n", unit))
for _, path := range paths {
logFilesSection.WriteString(fmt.Sprintf(" - %s\n", path))
}
}
configContent += logFilesSection.String()
}
// Ensure default config file exists or we explicitly overwrote it
if shouldWriteConfig {
if err := saveDefaultConfig(cfgPath, configContent); err != nil {
return err
}
}
@@ -182,6 +382,44 @@ WantedBy=multi-user.target
fmt.Printf("created logrotate configuration %s\n", logrotatePath)
}
// Generate a token for the dashboard if it doesn't exist
var tokenStr string
store, err := auth.NewTokenStore(tokenDBPath)
if err == nil {
defer store.Close()
infos, err := store.List()
hasDashboard := false
if err == nil {
for _, t := range infos {
if t.Name == "dashboard" {
hasDashboard = true
break
}
}
}
if !hasDashboard {
tokenStr, _ = store.Create("dashboard")
} else {
tokenStr = "(already created; run 'nadir token add dashboard' to replace/generate a new one if lost)"
}
} else {
fmt.Printf("warning: failed to open token store: %v\n", err)
}
// Output credentials to copy to the frontend
fmt.Println("\n======================================================================")
fmt.Println(" NADIR CLIENT CREDENTIALS (COPY THESE TO NADIR WEBUI)")
fmt.Println("======================================================================")
fmt.Printf("Token for \"dashboard\" (Bearer):\n %s\n", tokenStr)
if isTLS {
certBytes, err := os.ReadFile(certPath)
if err == nil {
fmt.Println("\nCA Certificate (Trust Store):")
fmt.Println(string(certBytes))
}
}
fmt.Println("======================================================================")
fmt.Printf("installed and started %s; follow logs with: %s logs\n", serviceName, filepath.Base(exe))
return nil
}
@@ -393,21 +631,24 @@ func fatalIf(err error) {
}
}
// DefaultConfigContent returns the default configuration template filled with the username.
func DefaultConfigContent(username string) string {
return fmt.Sprintf(configTemplateBase, "false", "# trust_proxy: false", "# tls_cert: /var/lib/nadir/tls/cert.pem", "# tls_key: /var/lib/nadir/tls/key.pem", "127.0.0.1", 9999, username)
}
// saveDefaultConfig writes the default configuration template to cfgPath.
func saveDefaultConfig(cfgPath string) error {
func saveDefaultConfig(cfgPath, content string) error {
dir := filepath.Dir(cfgPath)
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("create config directory: %w", err)
}
chownToSudoUser(dir)
username := getUsername()
configContent := fmt.Sprintf(defaultConfigTemplate, username)
if err := os.WriteFile(cfgPath, []byte(configContent), 0600); err != nil {
if err := os.WriteFile(cfgPath, []byte(content), 0600); err != nil {
return fmt.Errorf("write default config: %w", err)
}
chownToSudoUser(cfgPath)
fmt.Printf("created default configuration file at %s (assigned admin role to user %q)\n", cfgPath, username)
fmt.Printf("created default configuration file at %s\n", cfgPath)
return nil
}
@@ -415,19 +656,22 @@ func usage(w io.Writer) {
fmt.Fprint(w, `nadir - Linux system administration backend
Usage:
nadir [run] [-d] [-f <path>] Start the server (-d / --detach: run in background)
nadir --save-config [-f <path>] Save default configuration to path and exit
nadir install [-f <path>] Install + enable the systemd service (starts on boot)
nadir uninstall [--complete] Remove the service (keeps data/config; --complete wipes all)
nadir start|stop|restart|status Control the running service
nadir enable|disable Toggle start-on-boot without removing the unit
nadir logs [clear] Follow (default) or clear server logs
nadir token add <name> Mint a machine credential (Bearer token), shown once
nadir token rm <name> Revoke a token (effective immediately, no restart)
nadir token ls List token names and when they were created
nadir update [--check|--force] Fetch the latest release from server.release_repo and restart
(--check: report only; --force: re-download when already current)
nadir help Show this help
nadir [run] [-d] [-f <path>] Start the server (-d / --detach: run in background)
nadir --save-config [-f <path>] Save default configuration to path and exit
nadir install [--tls|--unsecure|--trust-proxy] Install + enable the systemd service (starts on boot)
(--tls: enable HTTPS with self-signed certificate)
(--unsecure: serve HTTP directly, default)
(--trust-proxy: serve HTTP behind a reverse proxy)
nadir uninstall [--complete] Remove the service (keeps data/config; --complete wipes all)
nadir start|stop|restart|status Control the running service
nadir enable|disable Toggle start-on-boot without removing the unit
nadir logs [clear] Follow (default) or clear server logs
nadir token add <name> Mint a machine credential (Bearer token), shown once
nadir token rm <name> Revoke a token (effective immediately, no restart)
nadir token ls List token names and when they were created
nadir update [--check|--force] Fetch the latest release from server.release_repo and restart
(--check: report only; --force: re-download when already current)
nadir help Show this help
Most commands need root. Config path is specified via -f/--config or CONFIG_PATH (default ~/.config/config.yaml).
`)
+53 -22
View File
@@ -4,44 +4,33 @@ import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"log"
"encoding/pem"
"math/big"
"net"
"os"
"time"
)
// serverCert returns the TLS certificate to serve: the admin-supplied PEM pair
// when both paths are set, otherwise a freshly generated in-memory self-signed
// cert for local development.
func serverCert(certPath, keyPath string) (tls.Certificate, error) {
if certPath != "" && keyPath != "" {
return tls.LoadX509KeyPair(certPath, keyPath)
}
log.Printf("tls: no tls_cert/tls_key configured - generating a self-signed certificate (dev only)")
return generateSelfSignedCert()
}
func generateSelfSignedCert() (tls.Certificate, error) {
// generateAndSaveCert generates a self-signed certificate and private key,
// and saves them as PEM files.
func generateAndSaveCert(certPath, keyPath string, hostname string) error {
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return tls.Certificate{}, err
return err
}
// Random serial: a fixed serial (1) makes every generated cert collide in a
// browser/OS trust store, so a previously-accepted cert can't be replaced.
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
return tls.Certificate{}, err
return err
}
template := x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{Organization: []string{"nadir-dev-local"}},
Subject: pkix.Name{Organization: []string{"nadir-agent-tls"}},
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 * time.Hour),
NotAfter: time.Now().Add(365 * 24 * time.Hour), // 1 year
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
@@ -49,9 +38,51 @@ func generateSelfSignedCert() (tls.Certificate, error) {
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback},
}
if hostname != "" && hostname != "localhost" && hostname != "127.0.0.1" && hostname != "::1" {
if ip := net.ParseIP(hostname); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, hostname)
}
}
// Automatically add the machine's external IP addresses to SANs so it can be verified
// correctly over the local network (e.g. Tailscale or Netbird).
if addrs, err := net.InterfaceAddrs(); err == nil {
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
template.IPAddresses = append(template.IPAddresses, ipnet.IP)
template.DNSNames = append(template.DNSNames, ipnet.IP.String())
}
}
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return tls.Certificate{}, err
return err
}
return tls.Certificate{Certificate: [][]byte{derBytes}, PrivateKey: priv}, nil
certOut, err := os.Create(certPath)
if err != nil {
return err
}
defer certOut.Close()
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return err
}
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer keyOut.Close()
privBytes, err := x509.MarshalECPrivateKey(priv)
if err != nil {
return err
}
if err := pem.Encode(keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: privBytes}); err != nil {
return err
}
return nil
}
+1 -3
View File
@@ -7,8 +7,6 @@ require github.com/msteinert/pam v1.2.0
require github.com/danielgtaylor/huma/v2 v2.38.0
require (
github.com/coder/websocket v1.8.15
github.com/creack/pty v1.1.24
gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.52.0
)
@@ -18,7 +16,7 @@ require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jedisct1/go-minisign v0.0.0-20260527172527-a09352b57a22
github.com/mattn/go-isatty v0.0.21 // indirect
github.com/mattn/go-isatty v0.0.21
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/crypto v0.52.0 // indirect
-4
View File
@@ -1,9 +1,5 @@
aead.dev/minisign v0.3.0 h1:8Xafzy5PEVZqYDNP60yJHARlW1eOQtsKNp/Ph2c0vRA=
aead.dev/minisign v0.3.0/go.mod h1:NLvG3Uoq3skkRMDuc3YHpWUTMTrSExqm+Ij73W13F6Y=
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/danielgtaylor/huma/v2 v2.38.0 h1:fb0WZCatnaiHLphMQDDWDjygNxfMkX/ENma3QsRl7vY=
github.com/danielgtaylor/huma/v2 v2.38.0/go.mod h1:k9hwjlgWFt1t2jsmQGlsgXAG2FBTZa4kkjV581qAtfo=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+5 -1
View File
@@ -99,7 +99,11 @@ do_install() {
echo "binary installed at /usr/local/bin/nadir"
echo "installing as a systemd service ..."
/usr/local/bin/nadir install
if [ -c /dev/tty ]; then
/usr/local/bin/nadir install < /dev/tty
else
/usr/local/bin/nadir install
fi
echo
echo "done. check status with: nadir status"
+13 -12
View File
@@ -13,7 +13,7 @@ import (
// loginNameRe is the useradd default NAME_REGEX. Validating at this trust
// boundary keeps a flag-like name (e.g. "-c", "--help") from reaching `su` in
// the terminal handler or showing up verbatim in audit logs / throttle keys.
// showing up verbatim in audit logs / throttle keys.
var loginNameRe = regexp.MustCompile(`^[a-z_][a-z0-9_-]{0,31}\$?$`)
// authenticator verifies a username/password (PAM in production). It's a field
@@ -43,8 +43,9 @@ type LoginOutput struct {
// development over plain HTTP, where a Secure cookie would never be sent back.
func RegisterLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store, secure bool) {
// loginThrottle blunts brute force: 5 failures for a username+source IP
// trigger a one-minute cooldown. See throttle.go for the ceiling/upgrade path.
registerLogin(api, sessions, auditor, secure, Authenticate, newFailLimiter(5, time.Minute))
// trigger a one-minute cooldown. Persisted in SQLite so cooldowns survive
// process restarts.
registerLogin(api, sessions, auditor, secure, Authenticate, sessions.NewPersistentFailLimiter(5, time.Minute))
}
func registerLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store, secure bool, authenticate authenticator, throttle *failLimiter) {
@@ -85,15 +86,15 @@ func registerLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store
return nil, huma.Error500InternalServerError("could not create session", err)
}
out := &LoginOutput{
SetCookie: http.Cookie{
Name: "nadir_session_id",
Value: sessionID,
Path: "/",
HttpOnly: true,
Secure: secure,
SameSite: http.SameSiteStrictMode,
Expires: time.Now().Add(24 * time.Hour),
},
SetCookie: http.Cookie{
Name: "nadir_session_id",
Value: sessionID,
Path: "/",
HttpOnly: true,
Secure: secure,
SameSite: http.SameSiteStrictMode,
MaxAge: 86400,
},
}
out.Body.Status = "logged in"
return out, nil
+78 -82
View File
@@ -68,110 +68,106 @@ func TestLoginLogoutThrottling(t *testing.T) {
mux := http.NewServeMux()
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
// Inject a stub authenticator and a short-window throttle (3 failures) at
// registration — no package globals to mutate. The throttle keys on
// username+IP, so the success/failure cases below and the throttle case (a
// distinct user) don't interfere.
authMock := func(username, password string) error {
if password == "correct" {
return nil
}
return errors.New("pam error")
}
registerLogin(api, sessions, auditStore, false, authMock, newFailLimiter(3, 500*time.Millisecond))
throttle := newFailLimiter(3, 500*time.Millisecond)
registerLogin(api, sessions, auditStore, false, authMock, throttle)
RegisterLogout(api, sessions, false)
// 1. Test failed login
resp := api.Post("/api/login", struct {
Username string `json:"username"`
Password string `json:"password"`
}{
Username: "admin",
Password: "wrong",
t.Run("failed login returns 401", func(t *testing.T) {
resp := api.Post("/api/login", struct {
Username string `json:"username"`
Password string `json:"password"`
}{
Username: "admin",
Password: "wrong",
})
if resp.Code != http.StatusUnauthorized {
t.Errorf("got code %d, want %d", resp.Code, http.StatusUnauthorized)
}
})
if resp.Code != http.StatusUnauthorized {
t.Errorf("failed login: got code %d, want %d", resp.Code, http.StatusUnauthorized)
}
// 2. Test successful login
resp = api.Post("/api/login", struct {
Username string `json:"username"`
Password string `json:"password"`
}{
Username: "admin",
Password: "correct",
})
if resp.Code != http.StatusOK {
t.Errorf("successful login: got code %d, want %d", resp.Code, http.StatusOK)
}
cookieHeader := resp.Header().Get("Set-Cookie")
if !strings.Contains(cookieHeader, "nadir_session_id=") {
t.Fatalf("Set-Cookie header missing nadir_session_id: %q", cookieHeader)
}
var sessionID string
parts := strings.SplitSeq(cookieHeader, ";")
for part := range parts {
part = strings.TrimSpace(part)
if after, ok := strings.CutPrefix(part, "nadir_session_id="); ok {
sessionID = after
break
t.Run("successful login returns session cookie", func(t *testing.T) {
resp := api.Post("/api/login", struct {
Username string `json:"username"`
Password string `json:"password"`
}{
Username: "admin",
Password: "correct",
})
if resp.Code != http.StatusOK {
t.Fatalf("got code %d, want %d", resp.Code, http.StatusOK)
}
}
if sessionID == "" {
t.Fatal("nadir_session_id cookie not found")
}
cookieHeader := resp.Header().Get("Set-Cookie")
if !strings.Contains(cookieHeader, "nadir_session_id=") {
t.Fatalf("Set-Cookie header missing nadir_session_id: %q", cookieHeader)
}
_, ok := sessions.GetByToken(sessionID)
if !ok {
t.Fatal("session not found in session store")
}
parts := strings.SplitSeq(cookieHeader, ";")
for part := range parts {
part = strings.TrimSpace(part)
if after, ok := strings.CutPrefix(part, "nadir_session_id="); ok {
sessionID = after
break
}
}
if sessionID == "" {
t.Fatal("nadir_session_id cookie not found")
}
if _, ok := sessions.GetByToken(sessionID); !ok {
t.Fatal("session not found in session store")
}
})
// 3. Test logout
resp = api.Post("/api/logout", "Cookie: nadir_session_id="+sessionID, struct{}{})
if resp.Code != http.StatusOK {
t.Errorf("logout failed: got code %d, want %d", resp.Code, http.StatusOK)
}
t.Run("logout invalidates session", func(t *testing.T) {
resp := api.Post("/api/logout", "Cookie: nadir_session_id="+sessionID, struct{}{})
if resp.Code != http.StatusOK {
t.Fatalf("logout failed: got code %d, want %d", resp.Code, http.StatusOK)
}
if _, ok := sessions.GetByToken(sessionID); ok {
t.Fatal("session still valid after logout")
}
})
_, ok = sessions.GetByToken(sessionID)
if ok {
t.Fatal("session still valid after logout")
}
// 4. Test throttling (the handler was registered with a 3-failure limiter).
for range 3 {
api.Post("/api/login", struct {
t.Run("throttling blocks after 3 failures", func(t *testing.T) {
for range 3 {
api.Post("/api/login", struct {
Username string `json:"username"`
Password string `json:"password"`
}{
Username: "throttled-user",
Password: "wrong",
})
}
resp := api.Post("/api/login", struct {
Username string `json:"username"`
Password string `json:"password"`
}{
Username: "throttled-user",
Password: "wrong",
Password: "correct",
})
}
resp = api.Post("/api/login", struct {
Username string `json:"username"`
Password string `json:"password"`
}{
Username: "throttled-user",
Password: "correct",
if resp.Code != http.StatusTooManyRequests {
t.Errorf("got code %d, want %d", resp.Code, http.StatusTooManyRequests)
}
})
if resp.Code != http.StatusTooManyRequests {
t.Errorf("throttled login: got code %d, want %d", resp.Code, http.StatusTooManyRequests)
}
time.Sleep(600 * time.Millisecond)
resp = api.Post("/api/login", struct {
Username string `json:"username"`
Password string `json:"password"`
}{
Username: "throttled-user",
Password: "correct",
t.Run("throttle reset allows login", func(t *testing.T) {
throttle.reset("throttled-user|")
resp := api.Post("/api/login", struct {
Username string `json:"username"`
Password string `json:"password"`
}{
Username: "throttled-user",
Password: "correct",
})
if resp.Code != http.StatusOK {
t.Errorf("got code %d, want %d", resp.Code, http.StatusOK)
}
})
if resp.Code != http.StatusOK {
t.Errorf("login after cooldown: got code %d, want %d", resp.Code, http.StatusOK)
}
}
+72
View File
@@ -0,0 +1,72 @@
package auth
import (
"net/http"
"sync"
"time"
"github.com/danielgtaylor/huma/v2"
)
// RateLimiter provides per-IP rate limiting for authenticated API endpoints,
// complementing the login-specific failLimiter with a broader cap on all
// requests. The window aligns to wall-clock intervals so all IPs share the
// same boundary.
type RateLimiter struct {
mu sync.Mutex
buckets map[string]*tokenBucket
limit int
interval time.Duration
}
type tokenBucket struct {
count int
windowEnd time.Time
}
const maxRateLimitKeys = 10000
func NewRateLimiter(limit int, interval time.Duration) *RateLimiter {
return &RateLimiter{
buckets: map[string]*tokenBucket{},
limit: limit,
interval: interval,
}
}
// Allow reports whether ip may make a request now. Returns false when the
// limit is exceeded OR the map is full (fail-closed).
func (l *RateLimiter) Allow(ip string) bool {
l.mu.Lock()
defer l.mu.Unlock()
now := time.Now()
b, ok := l.buckets[ip]
if !ok || now.After(b.windowEnd) {
if len(l.buckets) >= maxRateLimitKeys {
return false
}
l.buckets[ip] = &tokenBucket{count: 1, windowEnd: now.Add(l.interval)}
return true
}
if b.count >= l.limit {
return false
}
b.count++
return true
}
// RateLimitMiddleware returns Huma middleware that rejects requests exceeding
// the per-IP rate limit with 429 Too Many Requests. It runs before the RBAC
// check so abusive IPs are dropped early. The IP is read from the context set
// by WithClientIP; if absent the request passes through unthrottled.
func RateLimitMiddleware(api huma.API, rl *RateLimiter) func(huma.Context, func(huma.Context)) {
return func(ctx huma.Context, next func(huma.Context)) {
ip := ClientIP(ctx.Context())
if ip != "" && !rl.Allow(ip) {
huma.WriteErr(api, ctx, http.StatusTooManyRequests, "rate limit exceeded, try again later")
return
}
next(ctx)
}
}
+66 -5
View File
@@ -2,6 +2,7 @@ package auth
import (
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/hex"
"fmt"
@@ -12,7 +13,7 @@ import (
_ "modernc.org/sqlite"
)
const sessionTTL = 24 * time.Hour
var sessionTTL = 24 * time.Hour
type Session struct {
Username string
@@ -45,6 +46,17 @@ func NewSessionStore(path string) (*SessionStore, error) {
)`); err != nil {
return nil, fmt.Errorf("create sessions table: %w", err)
}
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS throttle (
key TEXT PRIMARY KEY,
count INTEGER NOT NULL,
until INTEGER NOT NULL
)`); err != nil {
return nil, fmt.Errorf("create throttle table: %w", err)
}
// Restrict the DB file so only the owning user (root) can read it.
if err := os.Chmod(path, 0600); err != nil {
return nil, fmt.Errorf("chmod session db: %w", err)
}
return &SessionStore{db: db}, nil
}
@@ -57,7 +69,7 @@ func (s *SessionStore) Create(username string) (string, error) {
expires := time.Now().Add(sessionTTL)
if _, err := s.db.Exec(
`INSERT INTO sessions (token, username, expires_at) VALUES (?, ?, ?)`,
token, username, expires.Unix(),
hashSessionToken(token), username, expires.Unix(),
); err != nil {
return "", err
}
@@ -67,26 +79,75 @@ func (s *SessionStore) Create(username string) (string, error) {
// Delete removes a session, invalidating it immediately (logout). Deleting an
// unknown token is a no-op.
func (s *SessionStore) Delete(token string) error {
_, err := s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token)
_, err := s.db.Exec(`DELETE FROM sessions WHERE token = ?`, hashSessionToken(token))
return err
}
// DeleteByUsername removes every session for the given user, used when a
// password change should invalidate all existing sessions.
func (s *SessionStore) DeleteByUsername(username string) error {
_, err := s.db.Exec(`DELETE FROM sessions WHERE username = ?`, username)
return err
}
func (s *SessionStore) GetByToken(token string) (Session, bool) {
var username string
var expires int64
h := hashSessionToken(token)
err := s.db.QueryRow(
`SELECT username, expires_at FROM sessions WHERE token = ?`, token,
`SELECT username, expires_at FROM sessions WHERE token = ?`, h,
).Scan(&username, &expires)
if err != nil {
return Session{}, false
}
if time.Now().Unix() > expires {
s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token)
s.db.Exec(`DELETE FROM sessions WHERE token = ?`, h)
return Session{}, false
}
return Session{Username: username}, true
}
// NewPersistentFailLimiter returns a failLimiter whose state survives process
// restarts via the session SQLite database.
func (s *SessionStore) NewPersistentFailLimiter(max int, window time.Duration) *failLimiter {
l := newFailLimiter(max, window)
// Load existing entries, skipping expired ones.
rows, err := s.db.Query(`SELECT key, count, until FROM throttle`)
if err != nil {
return l
}
defer rows.Close()
now := time.Now()
for rows.Next() {
var k string
var c int
var u int64
if err := rows.Scan(&k, &c, &u); err != nil {
continue
}
until := time.Unix(u, 0)
if now.After(until) {
s.db.Exec(`DELETE FROM throttle WHERE key = ?`, k)
continue
}
l.attempts[k] = &attemptState{count: c, until: until}
}
// Wire persistence: writes to DB on every mutation.
l.sync = func(key string, st *attemptState) {
if st == nil {
s.db.Exec(`DELETE FROM throttle WHERE key = ?`, key)
} else {
s.db.Exec(`INSERT OR REPLACE INTO throttle (key, count, until) VALUES (?, ?, ?)`, key, st.count, st.until.Unix())
}
}
return l
}
func hashSessionToken(token string) string {
h := sha256.Sum256([]byte(token))
return hex.EncodeToString(h[:])
}
func randomToken() string {
b := make([]byte, 32)
rand.Read(b) // never fails; rand.Read panics internally on misconfigured platforms.
+9 -10
View File
@@ -34,22 +34,21 @@ func TestExpiredSessionRejected(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// Write a row that expired an hour ago, bypassing Create's TTL.
_, err = store.db.Exec(
`INSERT INTO sessions (token, username, expires_at) VALUES (?, ?, ?)`,
"stale", "urania", time.Now().Add(-time.Hour).Unix(),
)
// Create a session with an already-expired TTL (-2s ensures the Unix
// second-rounded timestamp is safely in the past).
oldTTL := sessionTTL
sessionTTL = -2 * time.Second
token, err := store.Create("urania")
sessionTTL = oldTTL
if err != nil {
t.Fatal(err)
}
if _, ok := store.GetByToken("stale"); ok {
if _, ok := store.GetByToken(token); ok {
t.Fatal("expired session was accepted")
}
// Lazy cleanup should have deleted the row.
var n int
store.db.QueryRow(`SELECT count(*) FROM sessions WHERE token = ?`, "stale").Scan(&n)
if n != 0 {
t.Fatalf("expired row not cleaned up: %d rows remain", n)
if _, ok := store.GetByToken(token); ok {
t.Fatal("expired session still in store")
}
}
+14 -5
View File
@@ -24,6 +24,7 @@ type failLimiter struct {
attempts map[string]*attemptState
max int
window time.Duration
sync func(key string, s *attemptState) // optional: persist to DB
}
type attemptState struct {
@@ -32,8 +33,8 @@ type attemptState struct {
}
// maxTrackedKeys bounds memory: an attacker rotating username/IP can't grow the
// map without limit. When exceeded we drop all throttle state - a crude reset
// that briefly forgets cooldowns, acceptable for a single-node panel.
// map without limit. When exceeded we fail closed instead of wiping state, so
// existing cooldowns are preserved.
const maxTrackedKeys = 10000
func newFailLimiter(max int, window time.Duration) *failLimiter {
@@ -49,11 +50,13 @@ func (l *failLimiter) blocked(key string) bool {
}
// fail records a failed attempt and starts a cooldown once max is reached.
// When the map is full we stop tracking new keys rather than wiping existing
// cooldowns (which an attacker could use to clear a target's throttle).
func (l *failLimiter) fail(key string) {
l.mu.Lock()
defer l.mu.Unlock()
if len(l.attempts) > maxTrackedKeys {
l.attempts = map[string]*attemptState{}
if len(l.attempts) >= maxTrackedKeys {
return
}
s := l.attempts[key]
if s == nil {
@@ -63,7 +66,10 @@ func (l *failLimiter) fail(key string) {
s.count++
if s.count >= l.max {
s.until = time.Now().Add(l.window)
s.count = 0 // restart the window after the cooldown is set
s.count = 0
}
if l.sync != nil {
l.sync(key, s)
}
}
@@ -72,6 +78,9 @@ func (l *failLimiter) reset(key string) {
l.mu.Lock()
defer l.mu.Unlock()
delete(l.attempts, key)
if l.sync != nil {
l.sync(key, nil)
}
}
type ctxKey int
+3
View File
@@ -56,6 +56,9 @@ func NewTokenStore(path string) (*TokenStore, error) {
)`); err != nil {
return nil, fmt.Errorf("create tokens table: %w", err)
}
if err := os.Chmod(path, 0600); err != nil {
return nil, fmt.Errorf("chmod token db: %w", err)
}
return &TokenStore{db: db}, nil
}
+3 -3
View File
@@ -16,8 +16,8 @@ func TestTokenStore(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(raw) < len(tokenPrefix)+32 || raw[:len(tokenPrefix)] != tokenPrefix {
t.Fatalf("token %q lacks %q prefix or is too short", raw, tokenPrefix)
if len(raw) < 36 || raw[:4] != "nad_" {
t.Fatalf("token %q lacks %q prefix or is too short", raw, "nad_")
}
// Round-trip: the minted secret resolves to its name.
@@ -25,7 +25,7 @@ func TestTokenStore(t *testing.T) {
t.Errorf("Lookup(valid) = %q,%v; want dash,true", name, ok)
}
// A wrong secret (and a non-prefixed one) must not resolve.
if _, ok := store.Lookup(tokenPrefix + "wrong"); ok {
if _, ok := store.Lookup("nad_wrong"); ok {
t.Error("Lookup(wrong) succeeded")
}
if _, ok := store.Lookup("no-prefix"); ok {
+11 -6
View File
@@ -69,10 +69,10 @@ type Server struct {
}
// SecureCookie reports whether the session cookie should carry the Secure
// attribute, defaulting to true when server.secure_tls is omitted.
// attribute, defaulting to false when server.secure_tls is omitted (plain HTTP).
func (f *File) SecureCookie() bool {
if f.Server.SecureTLS == nil {
return true
return false
}
return *f.Server.SecureTLS
}
@@ -109,10 +109,10 @@ func Load(path string) (*File, error) {
if err := yaml.Unmarshal(data, &f); err != nil {
return nil, fmt.Errorf("parse config %s: %w", path, err)
}
// release_repo, when set, is downloaded over the wire and (for /api/update)
// executed. Validate shape + scheme once here so /install.sh and the updater
// can use the string directly. Trim any trailing slash so downstream string
// concatenation produces a clean URL.
// release_repo, when set, is substituted into shell scripts and downloaded
// over the wire. Validate shape + scheme + shell-safety once here so
// /install.sh and the updater can use the string directly. Trim any trailing
// slash so downstream string concatenation produces a clean URL.
if f.Server.ReleaseRepo != "" {
f.Server.ReleaseRepo = strings.TrimRight(f.Server.ReleaseRepo, "/")
u, err := url.Parse(f.Server.ReleaseRepo)
@@ -129,6 +129,11 @@ func Load(path string) (*File, error) {
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return nil, fmt.Errorf("server.release_repo must be https://host/owner/repo, got %q", f.Server.ReleaseRepo)
}
// Shell-safety: reject characters that could break out of a double-quoted
// string when substituted into the install.sh template.
if strings.ContainsAny(f.Server.ReleaseRepo, "`$\"\\;|&") {
return nil, fmt.Errorf("server.release_repo contains unsafe characters: %q", f.Server.ReleaseRepo)
}
}
return &f, nil
}
+6 -6
View File
@@ -30,13 +30,13 @@ func mods() []module.Module {
}
}
func TestSecureCookieDefaultsTrue(t *testing.T) {
if !(&File{}).SecureCookie() {
t.Error("omitted secure_tls should default to true")
func TestSecureCookieDefaultsFalse(t *testing.T) {
if (&File{}).SecureCookie() {
t.Error("omitted secure_tls should default to false")
}
no := false
if (&File{Server: Server{SecureTLS: &no}}).SecureCookie() {
t.Error("secure_tls: false should disable the Secure flag")
yes := true
if !(&File{Server: Server{SecureTLS: &yes}}).SecureCookie() {
t.Error("secure_tls: true should enable the Secure flag")
}
}
@@ -1,33 +1,13 @@
package audit
package meta
import (
"context"
"nadir/internal/auditlog"
"nadir/internal/rbac"
"github.com/danielgtaylor/huma/v2"
)
const ModuleID = "audit"
type Module struct {
store *auditlog.Store
}
func New(store *auditlog.Store) *Module { return &Module{store: store} }
func (m *Module) ID() string { return ModuleID }
// Permissions: read to view the audit trail. There is no write - entries are
// produced by the middleware, never by an API call.
func (m *Module) Permissions() []rbac.Permission {
return []rbac.Permission{rbac.Read}
}
// Types are named AuditList* (not ListInput/ListOutput) because Huma derives
// OpenAPI schema names from the Go type name alone, not package-qualified, so a
// bare "ListOutput" here would collide with the packages module's.
type AuditListInput struct {
Limit int `query:"limit" default:"200" minimum:"1" maximum:"10000" doc:"Max entries to return, newest first"`
}
@@ -38,7 +18,11 @@ type AuditListOutput struct {
}
}
func (m *Module) Register(api huma.API) {
// RegisterAudit wires GET /api/audit. It lives in meta because a full module
// for a single read-only endpoint is too shallow — the interface is nearly as
// wide as the implementation. The audit trail is produced by the RBAC
// middleware; this endpoint provides read-only access to it.
func RegisterAudit(api huma.API, store *auditlog.Store) {
huma.Register(api, huma.Operation{
OperationID: "audit-list",
Method: "GET",
@@ -46,11 +30,11 @@ func (m *Module) Register(api huma.API) {
Summary: "List recorded actions",
Description: "Returns the audit trail of privileged write operations " +
"(who, what, when, result), newest first.",
Tags: []string{"Audit"},
Metadata: map[string]any{"module": ModuleID, "permission": "read"},
Tags: []string{"Meta", "Audit"},
Metadata: map[string]any{"module": "audit", "permission": "read"},
Errors: []int{401, 403, 500},
}, func(ctx context.Context, in *AuditListInput) (*AuditListOutput, error) {
entries, err := m.store.List(in.Limit)
entries, err := store.List(in.Limit)
if err != nil {
return nil, huma.Error500InternalServerError("read audit log failed", err)
}
+26 -7
View File
@@ -15,6 +15,7 @@ import (
// itself.
type WhoamiInput struct {
SessionID string `cookie:"nadir_session_id"`
Auth string `header:"Authorization"`
}
// WhoamiBody reports who the caller is and, per module, which permissions they
@@ -30,7 +31,7 @@ type WhoamiOutput struct{ Body WhoamiBody }
// RegisterWhoami adds the current-user endpoint. It resolves the caller's
// concrete grants by asking the RBAC store about each module's permissions,
// so "*" wildcards in roles are expanded for free.
func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC, mods []module.Module) {
func RegisterWhoami(api huma.API, sessions *auth.SessionStore, tokens *auth.TokenAuth, roles *rbac.RBAC, mods []module.Module) {
huma.Register(api, huma.Operation{
OperationID: "whoami",
Method: "GET",
@@ -40,18 +41,35 @@ func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC,
"permissions the caller holds (wildcards resolved). Pair with " +
"/api/_modules to render the full permission matrix.",
Tags: []string{"Meta"},
Errors: []int{401},
Errors: []int{401, 429},
}, func(ctx context.Context, in *WhoamiInput) (*WhoamiOutput, error) {
sess, ok := sessions.GetByToken(in.SessionID)
if !ok {
return nil, huma.Error401Unauthorized("unauthorized")
var username string
if raw, isBearer := auth.BearerToken(in.Auth); isBearer {
if tokens == nil {
return nil, huma.Error401Unauthorized("unauthorized")
}
name, ok, throttled := tokens.Verify(auth.ClientIP(ctx), raw)
if throttled {
return nil, huma.Error429TooManyRequests("too many failed token attempts; wait a minute")
}
if !ok {
return nil, huma.Error401Unauthorized("unauthorized")
}
username = name
} else {
sess, ok := sessions.GetByToken(in.SessionID)
if !ok {
return nil, huma.Error401Unauthorized("unauthorized")
}
username = sess.Username
}
held := make(map[string][]string)
for _, m := range mods {
var perms []string
for _, p := range m.Permissions() {
if roles.Can(sess.Username, m.ID(), p) {
if roles.Can(username, m.ID(), p) {
perms = append(perms, string(p))
}
}
@@ -61,7 +79,8 @@ func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC,
}
out := &WhoamiOutput{}
out.Body = WhoamiBody{Username: sess.Username, Permissions: held}
out.Body = WhoamiBody{Username: username, Permissions: held}
return out, nil
})
}
+115
View File
@@ -0,0 +1,115 @@
package meta
import (
"encoding/json"
"net/http"
"path/filepath"
"slices"
"testing"
"nadir/internal/auth"
"nadir/internal/module"
"nadir/internal/rbac"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
"github.com/danielgtaylor/huma/v2/humatest"
)
type dummyModule struct {
id string
perms []rbac.Permission
}
func (m *dummyModule) ID() string { return m.id }
func (m *dummyModule) Name() string { return m.id }
func (m *dummyModule) Permissions() []rbac.Permission { return m.perms }
func (m *dummyModule) Register(api huma.API) {}
func TestWhoami(t *testing.T) {
tempDir := t.TempDir()
sessions, err := auth.NewSessionStore(filepath.Join(tempDir, "sessions.db"))
if err != nil {
t.Fatal(err)
}
tokenStore, err := auth.NewTokenStore(filepath.Join(tempDir, "tokens.db"))
if err != nil {
t.Fatal(err)
}
defer tokenStore.Close()
tokenAuth := auth.NewTokenAuth(tokenStore)
roles := rbac.New()
roles.DefineRole(rbac.Role{
Name: "admin-role",
ModuleGrants: map[string][]rbac.Permission{
"system": {rbac.Read},
},
})
roles.AssignRole("admin", "admin-role")
mods := []module.Module{
&dummyModule{
id: "system",
perms: []rbac.Permission{rbac.Read, rbac.Write},
},
}
mux := http.NewServeMux()
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
RegisterWhoami(api, sessions, tokenAuth, roles, mods)
// 1. Unauthorized request (no token, no session)
resp := api.Get("/api/whoami")
if resp.Code != http.StatusUnauthorized {
t.Errorf("expected 401, got %d", resp.Code)
}
// 2. Cookie session request
sessToken, err := sessions.Create("admin")
if err != nil {
t.Fatal(err)
}
resp = api.Get("/api/whoami", "Cookie: nadir_session_id="+sessToken)
if resp.Code != http.StatusOK {
t.Errorf("expected 200, got %d", resp.Code)
}
var body WhoamiBody
if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.Username != "admin" {
t.Errorf("expected username admin, got %q", body.Username)
}
if !slices.Contains(body.Permissions["system"], "read") {
t.Errorf("expected system read permission, got %v", body.Permissions["system"])
}
// 3. Token request
bearerToken, err := tokenStore.Create("api-user")
if err != nil {
t.Fatal(err)
}
roles.DefineRole(rbac.Role{
Name: "api-role",
ModuleGrants: map[string][]rbac.Permission{
"system": {rbac.Write},
},
})
roles.AssignRole("api-user", "api-role")
resp = api.Get("/api/whoami", "Authorization: Bearer "+bearerToken)
if resp.Code != http.StatusOK {
t.Errorf("expected 200, got %d", resp.Code)
}
if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.Username != "api-user" {
t.Errorf("expected username api-user, got %q", body.Username)
}
if !slices.Contains(body.Permissions["system"], "write") {
t.Errorf("expected system write permission, got %v", body.Permissions["system"])
}
}
+4 -4
View File
@@ -70,7 +70,7 @@ func registerGroups(api huma.API) {
}, func(ctx context.Context, _ *struct{}) (*ListGroupsOutput, error) {
list, err := listGroups()
if err != nil {
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
return nil, huma.Error500InternalServerError("group lookup failed", err)
}
out := &ListGroupsOutput{}
out.Body.Groups = list
@@ -92,7 +92,7 @@ func registerGroups(api huma.API) {
}
g, ok, err := lookupGroup(in.Group)
if err != nil {
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
return nil, huma.Error500InternalServerError("group lookup failed", err)
}
if !ok {
return nil, huma.Error404NotFound("group not found: " + in.Group)
@@ -114,7 +114,7 @@ func registerGroups(api huma.API) {
return nil, err
}
if _, ok, err := lookupGroup(in.Body.Name); err != nil {
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
return nil, huma.Error500InternalServerError("group lookup failed", err)
} else if ok {
return nil, huma.Error409Conflict("group already exists: " + in.Body.Name)
}
@@ -154,7 +154,7 @@ func registerGroups(api huma.API) {
return nil, err
}
if _, ok, err := lookupGroup(in.Group); err != nil {
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
return nil, huma.Error500InternalServerError("group lookup failed", err)
} else if !ok {
return nil, huma.Error404NotFound("group not found: " + in.Group)
}
+25 -9
View File
@@ -38,14 +38,30 @@ short:x:5
}
func TestValidateGroupName(t *testing.T) {
for _, n := range []string{"wheel", "_svc", "dev-team", "g1"} {
if err := validateGroupName(n); err != nil {
t.Errorf("validateGroupName(%q) = %v, want nil", n, err)
}
}
for _, n := range []string{"", "-x", "Wheel", "a,b", "foo;rm", "1grp"} {
if err := validateGroupName(n); err == nil {
t.Errorf("validateGroupName(%q) = nil, want error", n)
}
for _, tt := range []struct {
name string
value string
valid bool
}{
{name: "wheel", value: "wheel", valid: true},
{name: "underscore prefix", value: "_svc", valid: true},
{name: "dev-team", value: "dev-team", valid: true},
{name: "alphanumeric", value: "g1", valid: true},
{name: "empty", value: "", valid: false},
{name: "flag injection", value: "-x", valid: false},
{name: "uppercase", value: "Wheel", valid: false},
{name: "comma", value: "a,b", valid: false},
{name: "shell metachar", value: "foo;rm", valid: false},
{name: "leading digit", value: "1grp", valid: false},
} {
t.Run(tt.name, func(t *testing.T) {
err := validateGroupName(tt.value)
if tt.valid && err != nil {
t.Errorf("validateGroupName(%q) = %v, want nil", tt.value, err)
}
if !tt.valid && err == nil {
t.Errorf("validateGroupName(%q) = nil, want error", tt.value)
}
})
}
}
+26 -12
View File
@@ -49,17 +49,31 @@ func TestValidateIfaceConfig(t *testing.T) {
}
func TestValidateIface(t *testing.T) {
valid := []string{"eth0", "enp3s0", "wlan0", "br-lan", "veth1234567", "docker0"}
for _, name := range valid {
if err := validateIface(name); err != nil {
t.Errorf("validateIface(%q) unexpected error: %v", name, err)
}
}
invalid := []string{"", "-eth0", "/dev/net", "a b", "name_that_is_way_too_long_for_linux"}
for _, name := range invalid {
if err := validateIface(name); err == nil {
t.Errorf("validateIface(%q) expected error", name)
}
for _, tt := range []struct {
name string
value string
valid bool
}{
{name: "eth0", value: "eth0", valid: true},
{name: "enp3s0", value: "enp3s0", valid: true},
{name: "wlan0", value: "wlan0", valid: true},
{name: "bridge", value: "br-lan", valid: true},
{name: "veth", value: "veth1234567", valid: true},
{name: "docker", value: "docker0", valid: true},
{name: "empty", value: "", valid: false},
{name: "leading dash", value: "-eth0", valid: false},
{name: "path", value: "/dev/net", valid: false},
{name: "space", value: "a b", valid: false},
{name: "too long", value: "name_that_is_way_too_long_for_linux", valid: false},
} {
t.Run(tt.name, func(t *testing.T) {
err := validateIface(tt.value)
if tt.valid && err != nil {
t.Errorf("validateIface(%q) unexpected error: %v", tt.value, err)
}
if !tt.valid && err == nil {
t.Errorf("validateIface(%q) expected error", tt.value)
}
})
}
}
+27 -3
View File
@@ -6,6 +6,7 @@ import (
"os"
"regexp"
"strings"
"sync"
"nadir/internal/oscmd"
@@ -18,6 +19,10 @@ import (
var hostsFile = "/etc/hosts"
// hostsMu serialises writes to /etc/hosts so concurrent requests don't
// clobber each other's read-modify-write.
var hostsMu sync.Mutex
// hostnameRe matches a single hostname/alias. It forbids whitespace and '#' (so
// an entry can't inject extra fields or a comment) and a leading dash.
var hostnameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`)
@@ -156,9 +161,26 @@ func renderHostLine(ip string, hostnames []string) string {
// --- writes ------------------------------------------------------------------
// writeHostsAtomically writes content to /etc/hosts via a temp file + rename,
// so a crash mid-write leaves the original file intact.
func writeHostsAtomically(content string) error {
tmp := hostsFile + ".nadir.tmp"
if err := os.WriteFile(tmp, []byte(content), 0644); err != nil {
return err
}
if err := os.Rename(tmp, hostsFile); err != nil {
os.Remove(tmp)
return err
}
return nil
}
// upsertHost replaces the line for ip (matched on the address field) or appends
// a new one, preserving every other line.
func upsertHost(ip string, hostnames []string) error {
hostsMu.Lock()
defer hostsMu.Unlock()
data, err := os.ReadFile(hostsFile)
if err != nil {
return err
@@ -174,7 +196,6 @@ func upsertHost(ip string, hostnames []string) error {
}
}
if !replaced {
// Append, avoiding a blank line if the file already ended with one.
if n := len(lines); n > 0 && strings.TrimSpace(lines[n-1]) == "" {
lines[n-1] = newLine
} else {
@@ -182,11 +203,14 @@ func upsertHost(ip string, hostnames []string) error {
}
lines = append(lines, "")
}
return os.WriteFile(hostsFile, []byte(strings.Join(lines, "\n")), 0644)
return writeHostsAtomically(strings.Join(lines, "\n"))
}
// deleteHost removes every line mapping ip and reports whether any were removed.
func deleteHost(ip string) (bool, error) {
hostsMu.Lock()
defer hostsMu.Unlock()
data, err := os.ReadFile(hostsFile)
if err != nil {
return false, err
@@ -204,5 +228,5 @@ func deleteHost(ip string) (bool, error) {
if !removed {
return false, nil
}
return true, os.WriteFile(hostsFile, []byte(strings.Join(kept, "\n")), 0644)
return true, writeHostsAtomically(strings.Join(kept, "\n"))
}
@@ -10,7 +10,6 @@ import (
"reflect"
"strings"
"testing"
"time"
"nadir/internal/oscmd"
@@ -168,14 +167,18 @@ func TestNetworkingHandlers(t *testing.T) {
t.Errorf("pending change should be cleared: got %d, want %d", resp.Code, http.StatusNotFound)
}
// 6. Test automatic rollback
// 6. Test explicit rollback (same revert path as automatic rollback).
applyPayload.RollbackSeconds = 1
resp = api.Put("/api/networking/interfaces/eth0", applyPayload)
if resp.Code != http.StatusOK {
t.Errorf("apply config again: got %d, want %d", resp.Code, http.StatusOK)
}
time.Sleep(1200 * time.Millisecond)
if m.pending == nil {
t.Fatal("expected pending change after apply")
}
if err := m.rollbackNow("eth0"); err != nil {
t.Fatal(err)
}
resp = api.Get("/api/networking/pending")
if resp.Code != http.StatusNotFound {
+1 -1
View File
@@ -157,7 +157,7 @@ func registerReads(api huma.API, m *Module) {
}, func(ctx context.Context, _ *struct{}) (*DNSOutput, error) {
data, err := os.ReadFile(resolvConf)
if err != nil {
return nil, huma.Error500InternalServerError("read resolv.conf failed", err)
return nil, huma.Error500InternalServerError("DNS config lookup failed", err)
}
res := &DNSOutput{}
res.Body.Servers = parseResolv(string(data))
+14 -6
View File
@@ -8,7 +8,7 @@ import (
"time"
)
const defaultRollbackSeconds = 60
const defaultRollbackSeconds = 120
// errAlreadyPending is returned when another change is awaiting confirmation.
// The write handlers map this to 409 Conflict.
@@ -113,18 +113,26 @@ func (m *Module) armPending(iface string, revert func() error, seconds int) (int
// revert even if the server is otherwise idle — the whole point is protecting
// against being locked out of a remote box.
pc.Timer = time.AfterFunc(dur, func() {
// Check validity under lock, then revert outside it so a slow
// nmcli/networkctl call doesn't block the entire networking module.
m.mu.Lock()
defer m.mu.Unlock()
// Only revert if this exact change is still pending (it may have been
// confirmed or manually rolled back in the meantime).
if m.pending != pc {
m.mu.Unlock()
return
}
iface := pc.Iface
revert := pc.revert
m.mu.Unlock()
log.Printf("networking: rollback timer expired for %s — reverting", iface)
if err := pc.revert(); err != nil {
if err := revert(); err != nil {
log.Printf("networking: auto-rollback of %s failed: %v", iface, err)
}
m.pending = nil
m.mu.Lock()
if m.pending == pc {
m.pending = nil
}
m.mu.Unlock()
})
m.pending = pc
+12
View File
@@ -83,6 +83,11 @@ type PkgDoneEvent struct {
Error string `json:"error,omitempty" doc:"Exit error when it failed"`
}
// pkgSem limits concurrent package manager operations. Package managers are
// heavy (dnf/apt/pacman grab a lock), so running more than a few in parallel
// just thrashes; 3 concurrent ops is generous for an admin panel.
var pkgSem = make(chan struct{}, 3)
// pkgEvents maps SSE event names to their payload types for the streaming
// install/remove/upgrade operations.
var pkgEvents = map[string]any{
@@ -193,6 +198,13 @@ func streamOp(ctx context.Context, send sse.Sender, bin string, args []string) {
send.Data(PkgErrorEvent{Message: "no supported package manager found"})
return
}
select {
case pkgSem <- struct{}{}:
default:
send.Data(PkgErrorEvent{Message: "too many concurrent package operations, try again later"})
return
}
defer func() { <-pkgSem }()
// DEBIAN_FRONTEND keeps apt from blocking on an interactive prompt.
lines, errc, err := oscmd.RunStreamCombined(ctx, []string{"DEBIAN_FRONTEND=noninteractive"}, bin, args...)
if err != nil {
+40 -17
View File
@@ -54,27 +54,50 @@ func TestParsePacmanUpdates(t *testing.T) {
}
func TestStripArch(t *testing.T) {
cases := map[string]string{
"code.x86_64": "code",
"python3.11.noarch": "python3.11", // arch is only the final segment
"noarchhere": "noarchhere",
tests := []struct {
name string
in string
want string
}{
{name: "x86_64 arch", in: "code.x86_64", want: "code"},
{name: "noarch suffix", in: "python3.11.noarch", want: "python3.11"},
{name: "no arch segment", in: "noarchhere", want: "noarchhere"},
}
for in, want := range cases {
if got := stripArch(in); got != want {
t.Errorf("stripArch(%q) = %q, want %q", in, got, want)
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := stripArch(tt.in); got != tt.want {
t.Errorf("stripArch(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}
func TestValidateName(t *testing.T) {
for _, n := range []string{"htop", "openssh-server", "lib32-glibc", "g++", "python3.11"} {
if err := validateName(n); err != nil {
t.Errorf("validateName(%q) = %v, want nil", n, err)
}
}
for _, n := range []string{"", "-rf", "foo;rm", "foo bar", "pkg=1.0", "a/b"} {
if err := validateName(n); err == nil {
t.Errorf("validateName(%q) = nil, want error", n)
}
for _, tt := range []struct {
name string
value string
valid bool
}{
{name: "htop", value: "htop", valid: true},
{name: "openssh-server", value: "openssh-server", valid: true},
{name: "lib32-glibc", value: "lib32-glibc", valid: true},
{name: "g++", value: "g++", valid: true},
{name: "python3.11", value: "python3.11", valid: true},
{name: "empty", value: "", valid: false},
{name: "flag injection", value: "-rf", valid: false},
{name: "shell metachar", value: "foo;rm", valid: false},
{name: "space", value: "foo bar", valid: false},
{name: "equals", value: "pkg=1.0", valid: false},
{name: "path sep", value: "a/b", valid: false},
} {
t.Run(tt.name, func(t *testing.T) {
err := validateName(tt.value)
if tt.valid && err != nil {
t.Errorf("validateName(%q) = %v, want nil", tt.value, err)
}
if !tt.valid && err == nil {
t.Errorf("validateName(%q) = nil, want error", tt.value)
}
})
}
}
+12
View File
@@ -19,6 +19,10 @@ const (
maxLogLines = 10000
)
// logStreamSem limits concurrent log-follow connections. Each one forks a
// journalctl or tail subprocess, so too many would exhaust system resources.
var logStreamSem = make(chan struct{}, 10)
// LogEntry is one log record. For the journal source it is distilled from
// journalctl's JSON; for the file source only Message is set (the raw line,
// which usually carries its own embedded timestamp).
@@ -128,6 +132,14 @@ func registerLogs(api huma.API, logFiles map[string][]string) {
return
}
select {
case logStreamSem <- struct{}{}:
default:
send.Data(ErrorEvent{Message: "too many concurrent log streams, try again later"})
return
}
defer func() { <-logStreamSem }()
var cmd string
var args []string
if in.Source == "file" {
+58 -33
View File
@@ -48,49 +48,74 @@ func TestResolveLogPath(t *testing.T) {
"nginx.service": {"/var/log/nginx/access.log", "/var/log/nginx/error.log"},
}
// Allowlisted path resolves whether the caller uses the bare or .service
// form, regardless of which form the config key used.
for _, unit := range []string{"nginx.service", "nginx"} {
if p, err := resolveLogPath(allow, unit, "/var/log/nginx/error.log"); err != nil || p != "/var/log/nginx/error.log" {
t.Errorf("allowlisted path for %q: got %q, %v", unit, p, err)
t.Run("allowlisted path via bare name", func(t *testing.T) {
p, err := resolveLogPath(allow, "nginx", "/var/log/nginx/error.log")
if err != nil || p != "/var/log/nginx/error.log" {
t.Errorf("got %q, %v", p, err)
}
}
})
t.Run("allowlisted path via service suffix", func(t *testing.T) {
p, err := resolveLogPath(allow, "nginx.service", "/var/log/nginx/error.log")
if err != nil || p != "/var/log/nginx/error.log" {
t.Errorf("got %q, %v", p, err)
}
})
// Everything else is rejected: empty path, non-listed path (traversal),
// listed path but wrong unit, and unit with no allowlist at all.
bad := []struct{ unit, path string }{
{"nginx.service", ""},
{"nginx.service", "/etc/shadow"},
{"nginx.service", "/var/log/nginx/access.log/../../../etc/shadow"},
{"sshd.service", "/var/log/nginx/error.log"},
{"unknown.service", "/var/log/nginx/error.log"},
}
for _, b := range bad {
if _, err := resolveLogPath(allow, b.unit, b.path); err == nil {
t.Errorf("resolveLogPath(%q, %q) = nil error, want rejection", b.unit, b.path)
}
for _, tt := range []struct {
name string
unit string
path string
}{
{name: "empty path", unit: "nginx.service", path: ""},
{name: "non-allowlisted path", unit: "nginx.service", path: "/etc/shadow"},
{name: "path traversal", unit: "nginx.service", path: "/var/log/nginx/access.log/../../../etc/shadow"},
{name: "wrong unit", unit: "sshd.service", path: "/var/log/nginx/error.log"},
{name: "unknown unit", unit: "unknown.service", path: "/var/log/nginx/error.log"},
} {
t.Run(tt.name, func(t *testing.T) {
if _, err := resolveLogPath(allow, tt.unit, tt.path); err == nil {
t.Errorf("resolveLogPath(%q, %q) = nil error, want rejection", tt.unit, tt.path)
}
})
}
}
func TestJournalUnit(t *testing.T) {
cases := map[string]string{
"docker.service": "docker",
"docker": "docker",
"sshd.service": "sshd",
"foo.socket": "foo.socket", // only .service is stripped
tests := []struct {
name string
in string
want string
}{
{name: "docker service", in: "docker.service", want: "docker"},
{name: "docker bare", in: "docker", want: "docker"},
{name: "sshd service", in: "sshd.service", want: "sshd"},
{name: "socket unit", in: "foo.socket", want: "foo.socket"},
}
for in, want := range cases {
if got := journalUnit(in); got != want {
t.Errorf("journalUnit(%q) = %q, want %q", in, got, want)
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := journalUnit(tt.in); got != tt.want {
t.Errorf("journalUnit(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}
func TestClampLines(t *testing.T) {
cases := map[int]int{0: defaultLogLines, -5: defaultLogLines, 50: 50, 999999: maxLogLines}
for in, want := range cases {
if got := clampLines(in); got != want {
t.Errorf("clampLines(%d) = %d, want %d", in, got, want)
}
tests := []struct {
name string
in int
want int
}{
{name: "zero", in: 0, want: defaultLogLines},
{name: "negative", in: -5, want: defaultLogLines},
{name: "fifty", in: 50, want: 50},
{name: "too large", in: 999999, want: maxLogLines},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := clampLines(tt.in); got != tt.want {
t.Errorf("clampLines(%d) = %d, want %d", tt.in, got, tt.want)
}
})
}
}
+3 -8
View File
@@ -3,10 +3,8 @@ package services
import (
"context"
"encoding/json"
"os/exec"
"regexp"
"strings"
"syscall"
"nadir/internal/oscmd"
@@ -166,14 +164,11 @@ func isSelf(unit string) bool {
// Returns success once the subprocess has *started* — the actual systemd
// operation may complete after the response is sent, which is the whole point.
func runDetached(action, unit string) (*oscmd.StatusOutput, error) {
cmd := exec.Command("systemctl", action, "--", unit)
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
if err := cmd.Start(); err != nil {
out, err := oscmd.RunDetached("systemctl", action, "--", unit)
if err != nil {
return nil, huma.Error500InternalServerError("could not start detached systemctl", err)
}
// Reap in the background so the child doesn't become a zombie.
go cmd.Wait()
return oscmd.OK(), nil
return out, nil
}
// validateUnit guards against empty, flag-like, or malformed unit names.
+45 -25
View File
@@ -3,20 +3,33 @@ package services
import "testing"
func TestValidateUnit(t *testing.T) {
valid := []string{"sshd.service", "getty@tty1.service", "foo.bar:baz-1.service", "a_b.timer"}
for _, u := range valid {
if err := validateUnit(u); err != nil {
t.Errorf("validateUnit(%q) = %v, want nil", u, err)
}
}
// Empty, flag-injection, and anything with shell/path metacharacters must
// be rejected before reaching systemctl.
invalid := []string{"", "-rf", "--now", "a b", "foo;rm -rf /", "a/b", "naughty$()", "x|y"}
for _, u := range invalid {
if err := validateUnit(u); err == nil {
t.Errorf("validateUnit(%q) = nil, want error", u)
}
for _, tt := range []struct {
name string
value string
valid bool
}{
{name: "sshd.service", value: "sshd.service", valid: true},
{name: "template", value: "getty@tty1.service", valid: true},
{name: "dots and colons", value: "foo.bar:baz-1.service", valid: true},
{name: "timer", value: "a_b.timer", valid: true},
{name: "empty", value: "", valid: false},
{name: "flag injection", value: "-rf", valid: false},
{name: "double dash", value: "--now", valid: false},
{name: "space", value: "a b", valid: false},
{name: "shell metachar", value: "foo;rm -rf /", valid: false},
{name: "path sep", value: "a/b", valid: false},
{name: "subshell", value: "naughty$()", valid: false},
{name: "pipe", value: "x|y", valid: false},
} {
t.Run(tt.name, func(t *testing.T) {
err := validateUnit(tt.value)
if tt.valid && err != nil {
t.Errorf("validateUnit(%q) = %v, want nil", tt.value, err)
}
if !tt.valid && err == nil {
t.Errorf("validateUnit(%q) = nil, want error", tt.value)
}
})
}
}
@@ -25,16 +38,23 @@ func TestValidateUnit(t *testing.T) {
// else (including substrings) must not, or unrelated services would also get
// detached and bypass the synchronous error path.
func TestIsSelf(t *testing.T) {
yes := []string{"nadir", "nadir.service"}
for _, u := range yes {
if !isSelf(u) {
t.Errorf("isSelf(%q) = false, want true", u)
}
}
no := []string{"", "sshd.service", "nadir-something.service", "nadir.timer", "not-nadir.service"}
for _, u := range no {
if isSelf(u) {
t.Errorf("isSelf(%q) = true, want false", u)
}
for _, tt := range []struct {
name string
value string
want bool
}{
{name: "bare name", value: "nadir", want: true},
{name: "with service suffix", value: "nadir.service", want: true},
{name: "empty", value: "", want: false},
{name: "other service", value: "sshd.service", want: false},
{name: "prefix substring", value: "nadir-something.service", want: false},
{name: "wrong suffix", value: "nadir.timer", want: false},
{name: "suffix mismatch", value: "not-nadir.service", want: false},
} {
t.Run(tt.name, func(t *testing.T) {
if got := isSelf(tt.value); got != tt.want {
t.Errorf("isSelf(%q) = %v, want %v", tt.value, got, tt.want)
}
})
}
}
+32 -7
View File
@@ -6,6 +6,7 @@ import (
"os"
"strconv"
"strings"
"sync"
"nadir/internal/mounts"
"nadir/internal/oscmd"
@@ -16,6 +17,10 @@ import (
// fstabFile is a var so tests can point it at a fixture.
var fstabFile = "/etc/fstab"
// fstabMu serialises writes to /etc/fstab so concurrent HTTP requests don't
// clobber each other's read-modify-write.
var fstabMu sync.Mutex
// FstabEntry is one /etc/fstab line. Dump and Pass are the last two numeric
// fields (fs_freq and fs_passno).
type FstabEntry struct {
@@ -67,7 +72,7 @@ func registerStorage(api huma.API) {
}, func(ctx context.Context, _ *struct{}) (*ListMountsOutput, error) {
entries, err := mounts.Proc()
if err != nil {
return nil, huma.Error500InternalServerError("read mounts failed", err)
return nil, huma.Error500InternalServerError("mount table lookup failed", err)
}
res := &ListMountsOutput{}
res.Body.Mounts = entries
@@ -86,7 +91,7 @@ func registerStorage(api huma.API) {
}, func(ctx context.Context, _ *struct{}) (*ListFstabOutput, error) {
data, err := os.ReadFile(fstabFile)
if err != nil {
return nil, huma.Error500InternalServerError("read fstab failed", err)
return nil, huma.Error500InternalServerError("fstab lookup failed", err)
}
res := &ListFstabOutput{}
res.Body.Entries = parseFstab(string(data))
@@ -121,7 +126,7 @@ func registerStorage(api huma.API) {
existing, err := readFstab()
if err != nil {
return nil, huma.Error500InternalServerError("read fstab failed", err)
return nil, huma.Error500InternalServerError("fstab lookup failed", err)
}
if findEntry(existing, e.Mountpoint) != nil {
return nil, huma.Error409Conflict("an fstab entry already exists for " + e.Mountpoint)
@@ -158,13 +163,13 @@ func registerStorage(api huma.API) {
entries, err := readFstab()
if err != nil {
return nil, huma.Error500InternalServerError("read fstab failed", err)
return nil, huma.Error500InternalServerError("fstab lookup failed", err)
}
inFstab := findEntry(entries, in.Mountpoint) != nil
mounted, err := isMounted(in.Mountpoint)
if err != nil {
return nil, huma.Error500InternalServerError("read mounts failed", err)
return nil, huma.Error500InternalServerError("mount table lookup failed", err)
}
if !inFstab && !mounted {
return nil, huma.Error404NotFound("no mount or fstab entry for " + in.Mountpoint)
@@ -231,8 +236,25 @@ func renderFstabLine(e FstabEntry) string {
return fmt.Sprintf("%s\t%s\t%s\t%s\t%d\t%d", e.Device, e.Mountpoint, e.FSType, e.Options, e.Dump, e.Pass)
}
// writeFstabAtomically writes content to /etc/fstab using a temporary file and
// rename, so a crash mid-write leaves the original file intact.
func writeFstabAtomically(content string) error {
tmp := fstabFile + ".nadir.tmp"
if err := os.WriteFile(tmp, []byte(content), 0644); err != nil {
return err
}
if err := os.Rename(tmp, fstabFile); err != nil {
os.Remove(tmp)
return err
}
return nil
}
// appendFstabLine adds one entry, leaving every existing line untouched.
func appendFstabLine(e FstabEntry) error {
fstabMu.Lock()
defer fstabMu.Unlock()
data, err := os.ReadFile(fstabFile)
if err != nil {
return err
@@ -242,12 +264,15 @@ func appendFstabLine(e FstabEntry) error {
content += "\n"
}
content += renderFstabLine(e) + "\n"
return os.WriteFile(fstabFile, []byte(content), 0644)
return writeFstabAtomically(content)
}
// removeFstabLines drops every line mapping mountpoint, preserving comments and
// other entries. Reports whether anything was removed.
func removeFstabLines(mountpoint string) (bool, error) {
fstabMu.Lock()
defer fstabMu.Unlock()
data, err := os.ReadFile(fstabFile)
if err != nil {
return false, err
@@ -268,7 +293,7 @@ func removeFstabLines(mountpoint string) (bool, error) {
if !removed {
return false, nil
}
return true, os.WriteFile(fstabFile, []byte(strings.Join(kept, "\n")), 0644)
return true, writeFstabAtomically(strings.Join(kept, "\n"))
}
func findEntry(entries []FstabEntry, mountpoint string) *FstabEntry {
+22 -18
View File
@@ -79,23 +79,27 @@ func mustReadFstab(t *testing.T) []FstabEntry {
}
func TestValidateEntry(t *testing.T) {
ok := FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/data", FSType: "ext4", Options: "defaults"}
if err := validateEntry(ok); err != nil {
t.Errorf("valid entry rejected: %v", err)
}
if err := validateEntry(FstabEntry{Device: "UUID=ab-cd", Mountpoint: "/mnt/x", FSType: "xfs", Options: "rw,noatime"}); err != nil {
t.Errorf("UUID entry rejected: %v", err)
}
bad := []FstabEntry{
{Device: "/dev/sdb1; rm -rf /", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults"}, // shell metachars
{Device: "/dev/sdb1", Mountpoint: "../etc", FSType: "ext4", Options: "defaults"}, // not absolute
{Device: "/dev/sdb1", Mountpoint: "/mnt/../../etc", FSType: "ext4", Options: "defaults"}, // traversal
{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4!", Options: "defaults"}, // bad fstype
{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults; reboot"}, // bad options
}
for i, e := range bad {
if err := validateEntry(e); err == nil {
t.Errorf("bad entry %d accepted: %+v", i, e)
}
for _, tt := range []struct {
name string
entry FstabEntry
valid bool
}{
{name: "valid", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/data", FSType: "ext4", Options: "defaults"}, valid: true},
{name: "UUID", entry: FstabEntry{Device: "UUID=ab-cd", Mountpoint: "/mnt/x", FSType: "xfs", Options: "rw,noatime"}, valid: true},
{name: "shell metachar in device", entry: FstabEntry{Device: "/dev/sdb1; rm -rf /", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults"}, valid: false},
{name: "relative mountpoint", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "../etc", FSType: "ext4", Options: "defaults"}, valid: false},
{name: "traversal in mountpoint", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/../../etc", FSType: "ext4", Options: "defaults"}, valid: false},
{name: "bad fstype", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4!", Options: "defaults"}, valid: false},
{name: "bad options", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults; reboot"}, valid: false},
} {
t.Run(tt.name, func(t *testing.T) {
err := validateEntry(tt.entry)
if tt.valid && err != nil {
t.Errorf("valid entry rejected: %v", err)
}
if !tt.valid && err == nil {
t.Errorf("bad entry accepted: %+v", tt.entry)
}
})
}
}
+146
View File
@@ -0,0 +1,146 @@
package system
import (
"math"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"nadir/internal/oscmd"
)
type CPUInfo struct {
Model string `json:"model" example:"AMD Ryzen 7 7840U" doc:"CPU model name"`
LogicalCPUs int `json:"logical_cpus" example:"16" doc:"Number of logical CPUs (cores × threads)"`
MinMHz int `json:"min_mhz" example:"400" doc:"Lowest frequency the scaling governor can select"`
MaxMHz int `json:"max_mhz" example:"5137" doc:"Highest frequency (boost ceiling)"`
CurrentMHz int `json:"current_mhz" example:"3157" doc:"Peak current clock across all cores (instantaneous snapshot; 0 if cpufreq unavailable)"`
}
func cpuInfo() CPUInfo {
data, _ := os.ReadFile("/proc/cpuinfo")
c := CPUInfo{Model: cpuModel(string(data)), LogicalCPUs: runtime.NumCPU()}
c.MinMHz, c.MaxMHz, c.CurrentMHz = cpuFreqMHz("/sys/devices/system/cpu")
mhz := cpuinfoMaxMHz(string(data))
if c.Model == "" || mhz == 0 {
model, lscpuMHz := lscpuFallback()
if c.Model == "" {
c.Model = model
}
if mhz == 0 {
mhz = lscpuMHz
}
}
if mhz > 0 {
if c.CurrentMHz == 0 {
c.CurrentMHz = mhz
}
if c.MaxMHz == 0 {
c.MaxMHz = mhz
}
if c.MinMHz == 0 {
c.MinMHz = mhz
}
}
return c
}
func lscpuFallback() (model string, mhz int) {
out, err := oscmd.Run("lscpu")
if err != nil {
return "", 0
}
for line := range strings.SplitSeq(out, "\n") {
k, v, ok := strings.Cut(line, ":")
if !ok {
continue
}
k, v = strings.TrimSpace(k), strings.TrimSpace(v)
switch k {
case "Model name":
if model == "" {
model = v
}
case "BIOS Model name":
if model == "" {
model = v
}
case "CPU max MHz", "CPU MHz":
if f, err := strconv.ParseFloat(v, 64); err == nil && int(f) > mhz {
mhz = int(math.Round(f))
}
}
}
if mhz == 0 {
mhz = parseGHzSuffix(model)
}
return model, mhz
}
func parseGHzSuffix(s string) int {
i := strings.LastIndex(s, "@")
if i < 0 {
return 0
}
rest := strings.TrimSpace(s[i+1:])
rest = strings.TrimSuffix(strings.TrimSuffix(rest, "GHz"), "Ghz")
rest = strings.TrimSpace(strings.TrimSuffix(rest, "G"))
f, err := strconv.ParseFloat(strings.TrimSpace(rest), 64)
if err != nil {
return 0
}
return int(math.Round(f * 1000))
}
func cpuinfoMaxMHz(cpuinfo string) int {
var max float64
for line := range strings.SplitSeq(cpuinfo, "\n") {
k, v, ok := strings.Cut(line, ":")
if !ok || strings.TrimSpace(k) != "cpu MHz" {
continue
}
if f, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil && f > max {
max = f
}
}
return int(math.Round(max))
}
func cpuFreqMHz(root string) (min, max, cur int) {
min = readKHzAsMHz(filepath.Join(root, "cpu0/cpufreq/cpuinfo_min_freq"))
max = readKHzAsMHz(filepath.Join(root, "cpu0/cpufreq/cpuinfo_max_freq"))
cores, _ := filepath.Glob(filepath.Join(root, "cpu[0-9]*/cpufreq/scaling_cur_freq"))
for _, f := range cores {
if v := readKHzAsMHz(f); v > cur {
cur = v
}
}
return min, max, cur
}
func readKHzAsMHz(path string) int {
khz, err := strconv.Atoi(readTrim(path))
if err != nil {
return 0
}
return khz / 1000
}
func cpuModel(cpuinfo string) string {
var fallback string
for line := range strings.SplitSeq(cpuinfo, "\n") {
k, v, ok := strings.Cut(line, ":")
if !ok {
continue
}
switch strings.TrimSpace(k) {
case "model name":
return strings.TrimSpace(v)
case "Model":
fallback = strings.TrimSpace(v)
}
}
return fallback
}
+137
View File
@@ -0,0 +1,137 @@
package system
import (
"context"
"math"
"os"
"strconv"
"strings"
"sync"
"time"
)
// Sampler samples /proc/stat periodically and caches per-core CPU usage
// percentages. Create with New, start the background goroutine with Start, and
// read the latest snapshot with Snapshot.
type Sampler struct {
statPath string
interval time.Duration
mu sync.RWMutex
cache []CoreUsage
once sync.Once
}
// NewSampler creates a Sampler that reads statPath and samples every interval.
func NewSampler(statPath string, interval time.Duration) *Sampler {
return &Sampler{statPath: statPath, interval: interval}
}
// Start launches the background sampling goroutine. Only the first call starts
// it; subsequent calls are no-ops. The goroutine exits when ctx is cancelled.
func (s *Sampler) Start(ctx context.Context) {
s.once.Do(func() {
go s.loop(ctx)
})
}
// Snapshot returns a copy of the latest per-core usage snapshot. Returns nil
// before the first sample completes.
func (s *Sampler) Snapshot() []CoreUsage {
s.mu.RLock()
defer s.mu.RUnlock()
if s.cache == nil {
return nil
}
out := make([]CoreUsage, len(s.cache))
copy(out, s.cache)
return out
}
func (s *Sampler) loop(ctx context.Context) {
prev := readProcStat(s.statPath)
ticker := time.NewTicker(s.interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
cur := readProcStat(s.statPath)
usage := computeUsage(prev, cur)
s.mu.Lock()
s.cache = usage
s.mu.Unlock()
prev = cur
}
}
}
// cpuCoreTicks holds the cumulative jiffies for one "cpuN" line.
type cpuCoreTicks struct {
core int
total uint64
idle uint64
}
// readProcStat reads /proc/stat and returns per-core tick totals. The
// aggregate "cpu" line (no digit suffix) is skipped.
func readProcStat(path string) []cpuCoreTicks {
data, _ := os.ReadFile(path)
var cores []cpuCoreTicks
for line := range strings.SplitSeq(string(data), "\n") {
if !strings.HasPrefix(line, "cpu") {
continue
}
fields := strings.Fields(line)
if len(fields) < 5 {
continue
}
name := fields[0]
if name == "cpu" {
continue
}
coreIdx, err := strconv.Atoi(strings.TrimPrefix(name, "cpu"))
if err != nil {
continue
}
var total, idle uint64
for _, f := range fields[1:] {
v, _ := strconv.ParseUint(f, 10, 64)
total += v
}
if len(fields) > 5 {
v4, _ := strconv.ParseUint(fields[4], 10, 64)
v5, _ := strconv.ParseUint(fields[5], 10, 64)
idle = v4 + v5
} else {
v4, _ := strconv.ParseUint(fields[4], 10, 64)
idle = v4
}
cores = append(cores, cpuCoreTicks{core: coreIdx, total: total, idle: idle})
}
return cores
}
// computeUsage converts two snapshots into per-core usage percentages.
func computeUsage(prev, cur []cpuCoreTicks) []CoreUsage {
prevMap := make(map[int]cpuCoreTicks, len(prev))
for _, c := range prev {
prevMap[c.core] = c
}
usage := make([]CoreUsage, 0, len(cur))
for _, c := range cur {
p, ok := prevMap[c.core]
if !ok {
continue
}
dTotal := c.total - p.total
dIdle := c.idle - p.idle
var pct float64
if dTotal > 0 {
pct = float64(dTotal-dIdle) / float64(dTotal) * 100
pct = math.Round(pct*10) / 10
}
usage = append(usage, CoreUsage{Core: c.core, UsagePct: pct})
}
return usage
}
+134
View File
@@ -0,0 +1,134 @@
package system
import (
"context"
"os"
"path/filepath"
"reflect"
"testing"
"time"
)
func TestNewSampler(t *testing.T) {
s := NewSampler("/proc/stat", time.Second)
if s == nil {
t.Fatal("NewSampler returned nil")
}
if s.statPath != "/proc/stat" {
t.Errorf("statPath = %q, want /proc/stat", s.statPath)
}
if s.interval != time.Second {
t.Errorf("interval = %v, want 1s", s.interval)
}
}
func TestSamplerSnapshotsRealProcStat(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s := NewSampler("/proc/stat", 10*time.Millisecond)
s.Start(ctx)
// Wait for at least two samples so there is a delta to compute.
time.Sleep(50 * time.Millisecond)
snap := s.Snapshot()
if snap == nil {
t.Fatal("Snapshot returned nil (expected at least one sample)")
}
if len(snap) == 0 {
t.Fatal("Snapshot returned empty (expected at least one core)")
}
for _, c := range snap {
if c.UsagePct < 0 || c.UsagePct > 100 {
t.Errorf("core %d: usage_pct = %f, want 0100", c.Core, c.UsagePct)
}
}
}
func TestSamplerReturnsCopy(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s := NewSampler("/proc/stat", 10*time.Millisecond)
s.Start(ctx)
time.Sleep(50 * time.Millisecond)
snap1 := s.Snapshot()
snap2 := s.Snapshot()
// Both should be non-nil and deep-equal.
if snap1 == nil || snap2 == nil {
t.Fatal("Snapshot returned nil")
}
if !reflect.DeepEqual(snap1, snap2) {
t.Error("two sequential snapshots should be deep-equal")
}
// Mutating the returned slice should not affect the sampler.
if len(snap1) > 0 {
snap1[0].UsagePct = 999
if snap2[0].UsagePct == 999 {
t.Error("mutating one snapshot affected the other — expected a copy")
}
}
}
func TestSamplerStartOnce(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s := NewSampler("/proc/stat", 10*time.Millisecond)
s.Start(ctx)
s.Start(ctx) // second call must not panic or create a second goroutine
time.Sleep(30 * time.Millisecond)
if snap := s.Snapshot(); snap == nil {
t.Fatal("Snapshot returned nil after Start")
}
}
func TestSamplerContextCancelStopsGoroutine(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
s := NewSampler("/proc/stat", 10*time.Millisecond)
s.Start(ctx)
time.Sleep(30 * time.Millisecond)
if snap := s.Snapshot(); snap == nil {
t.Fatal("Snapshot returned nil before cancel")
}
cancel()
// Give the goroutine time to exit. If it doesn't, the test will hang.
time.Sleep(20 * time.Millisecond)
// Snapshot should still return the last cached value (no panic).
if snap := s.Snapshot(); snap == nil {
t.Fatal("Snapshot returned nil after cancel (cache should persist)")
}
}
func TestSamplerWithFakeStat(t *testing.T) {
dir := t.TempDir()
statPath := filepath.Join(dir, "stat")
content := []byte("cpu 100 20 30 400 10 5 3 2 0 0\ncpu0 50 10 15 200 5 3 1 1 0 0\ncpu1 50 10 15 200 5 2 2 1 0 0\n")
if err := os.WriteFile(statPath, content, 0o644); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s := NewSampler(statPath, 20*time.Millisecond)
s.Start(ctx)
time.Sleep(50 * time.Millisecond)
snap := s.Snapshot()
if snap == nil {
t.Fatal("Snapshot returned nil")
}
// With the stat file not changing between reads, deltas are zero → 0% usage.
for _, c := range snap {
if c.UsagePct != 0 {
t.Errorf("core %d: expected 0%% usage (static stat file), got %f", c.Core, c.UsagePct)
}
}
}
+73
View File
@@ -0,0 +1,73 @@
package system
import (
"syscall"
"nadir/internal/mounts"
)
type DiskInfo struct {
Mountpoint string `json:"mountpoint" example:"/"`
Filesystem string `json:"filesystem" example:"/dev/nvme0n1p2" doc:"Backing device"`
FSType string `json:"fstype" example:"btrfs"`
TotalBytes uint64 `json:"total_bytes" example:"512000000000"`
FreeBytes uint64 `json:"free_bytes" example:"256000000000" doc:"Space available to unprivileged users"`
UsedBytes uint64 `json:"used_bytes" example:"256000000000"`
}
func diskInfo() []DiskInfo {
entries, err := mounts.Proc()
if err != nil {
return nil
}
disks := []DiskInfo{}
seen := map[string]bool{}
for _, e := range entries {
if pseudoFS[e.FSType] || seen[e.Mountpoint] {
continue
}
var st syscall.Statfs_t
if syscall.Statfs(e.Mountpoint, &st) != nil || st.Blocks == 0 {
continue
}
seen[e.Mountpoint] = true
bs := uint64(st.Bsize)
disks = append(disks, DiskInfo{
Mountpoint: e.Mountpoint,
Filesystem: e.Device,
FSType: e.FSType,
TotalBytes: st.Blocks * bs,
FreeBytes: st.Bavail * bs,
UsedBytes: (st.Blocks - st.Bfree) * bs,
})
}
return disks
}
var pseudoFS = map[string]bool{
"autofs": true,
"binfmt_misc": true,
"bpf": true,
"cgroup": true,
"cgroup2": true,
"configfs": true,
"debugfs": true,
"devpts": true,
"devtmpfs": true,
"fuse.gvfsd-fuse": true,
"fuse.lxcfs": true,
"fusectl": true,
"hugetlbfs": true,
"mqueue": true,
"nsfs": true,
"overlay": true,
"proc": true,
"pstore": true,
"ramfs": true,
"rpc_pipefs": true,
"securityfs": true,
"squashfs": true,
"sysfs": true,
"tmpfs": true,
"tracefs": true,
}
+187
View File
@@ -0,0 +1,187 @@
package system
import (
"os"
"path/filepath"
"strconv"
"strings"
"nadir/internal/oscmd"
)
type GPUInfo struct {
Model string `json:"model" example:"AMD Radeon RX 7900 XTX" doc:"GPU model name, or vendor:device hex ID if lspci unavailable"`
Vendor string `json:"vendor" example:"1002" doc:"PCI vendor ID (hex)"`
DeviceID string `json:"device_id" example:"744c" doc:"PCI device ID (hex)"`
Driver string `json:"driver" example:"amdgpu" doc:"Kernel driver in use"`
MemoryTotalBytes uint64 `json:"memory_total_bytes" example:"8589934592" doc:"Total VRAM in bytes (driver-dependent; 0 if unavailable)"`
MemoryUsedBytes uint64 `json:"memory_used_bytes" example:"27267072" doc:"Used VRAM in bytes (driver-dependent; 0 if unavailable)"`
UtilizationPct float64 `json:"utilization_pct" example:"23.5" doc:"GPU compute utilization percentage (driver-dependent; 0 if unavailable)"`
MemUtilizationPct float64 `json:"mem_utilization_pct" example:"15.0" doc:"GPU memory controller utilization percentage (driver-dependent; 0 if unavailable)"`
}
func gpuInfo() []GPUInfo {
return readGPUsFromSysfs("/sys/class/drm")
}
func readGPUsFromSysfs(drmRoot string) []GPUInfo {
entries, err := os.ReadDir(drmRoot)
if err != nil {
return nil
}
seen := map[string]bool{}
var gpus []GPUInfo
for _, e := range entries {
if !isGPUCard(e.Name()) {
continue
}
pciAddr, vendor, device, driver := readGPUFromCard(drmRoot, e.Name())
if pciAddr == "" || seen[pciAddr] {
continue
}
seen[pciAddr] = true
model := vendor + ":" + device
if m := lookupGPUName(pciAddr); m != "" {
model = m
}
gpu := GPUInfo{
Model: model,
Vendor: vendor,
DeviceID: device,
Driver: driver,
}
devPath := filepath.Join(drmRoot, e.Name(), "device")
enrichGPUInfo(&gpu, devPath, pciAddr, driver)
gpus = append(gpus, gpu)
}
return gpus
}
func enrichGPUInfo(gpu *GPUInfo, devPath, pciAddr, driver string) {
switch driver {
case "amdgpu":
enrichAMDGPU(gpu, devPath)
case "nvidia":
enrichNvidiaGPU(gpu, pciAddr)
}
}
func enrichAMDGPU(gpu *GPUInfo, devPath string) {
if total := readUint64FromFile(filepath.Join(devPath, "mem_info_vram_total")); total > 0 {
gpu.MemoryTotalBytes = total
gpu.MemoryUsedBytes = readUint64FromFile(filepath.Join(devPath, "mem_info_vram_used"))
}
if pct := readIntFromFile(filepath.Join(devPath, "gpu_busy_percent")); pct >= 0 {
gpu.UtilizationPct = float64(pct)
}
if pct := readIntFromFile(filepath.Join(devPath, "mem_busy_percent")); pct >= 0 {
gpu.MemUtilizationPct = float64(pct)
}
}
func enrichNvidiaGPU(gpu *GPUInfo, pciAddr string) {
out, err := oscmd.Run("nvidia-smi",
"-i", pciAddr,
"--query-gpu=memory.total,memory.used,utilization.gpu,utilization.memory",
"--format=csv,noheader,nounits",
)
if err != nil {
return
}
parts := strings.Split(strings.TrimSpace(out), ", ")
if len(parts) < 4 {
return
}
if total, err := strconv.ParseUint(parts[0], 10, 64); err == nil && total > 0 {
gpu.MemoryTotalBytes = total * 1024 * 1024
if used, err := strconv.ParseUint(parts[1], 10, 64); err == nil {
gpu.MemoryUsedBytes = used * 1024 * 1024
}
}
if pct, err := strconv.ParseFloat(parts[2], 64); err == nil {
gpu.UtilizationPct = pct
}
if pct, err := strconv.ParseFloat(parts[3], 64); err == nil {
gpu.MemUtilizationPct = pct
}
}
func isGPUCard(name string) bool {
if !strings.HasPrefix(name, "card") {
return false
}
if len(name) == 4 {
return false
}
ch := name[4]
return ch >= '0' && ch <= '9'
}
func readGPUFromCard(drmRoot, name string) (pciAddr, vendor, device, driver string) {
cardPath := filepath.Join(drmRoot, name)
devPath := filepath.Join(cardPath, "device")
resolved, err := filepath.EvalSymlinks(cardPath)
if err != nil {
return "", "", "", ""
}
parts := strings.Split(resolved, "/")
for i, p := range parts {
if p == "drm" && i > 0 {
pciAddr = parts[i-1]
break
}
}
if pciAddr == "" {
return "", "", "", ""
}
vendor = strings.TrimPrefix(readTrim(filepath.Join(devPath, "vendor")), "0x")
device = strings.TrimPrefix(readTrim(filepath.Join(devPath, "device")), "0x")
driver = readDriver(devPath)
return
}
func readDriver(devPath string) string {
target, err := os.Readlink(filepath.Join(devPath, "driver"))
if err != nil {
return ""
}
return filepath.Base(target)
}
func lookupGPUName(pciAddr string) string {
out, err := oscmd.Run("lspci", "-nns", pciAddr)
if err != nil {
return ""
}
_, rest, ok := strings.Cut(out, " ")
if !ok {
return ""
}
return strings.TrimSpace(rest)
}
func readUint64FromFile(path string) uint64 {
v, err := strconv.ParseUint(readTrim(path), 10, 64)
if err != nil {
return 0
}
return v
}
func readIntFromFile(path string) int {
v, err := strconv.Atoi(readTrim(path))
if err != nil {
return -1
}
return v
}
+8 -580
View File
@@ -2,26 +2,16 @@ package system
import (
"context"
"math"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
"nadir/internal/mounts"
"nadir/internal/oscmd"
"github.com/danielgtaylor/huma/v2"
)
// SystemInfoBody is the dashboard overview: OS identity plus live CPU, memory,
// disk, load, network, and temperature readings. Every section is best-effort —
// disk, load, network, GPU, and temperature readings. Every section is best-effort —
// a source that's unavailable (e.g. no thermal zones in a VM) yields a zero
// value or empty list rather than failing the whole call.
type SystemInfoBody struct {
@@ -34,71 +24,12 @@ type SystemInfoBody struct {
Disks []DiskInfo `json:"disks" doc:"Mounted block-device filesystems"`
NetworkInterfaces []NetInterface `json:"network_interfaces" doc:"Network interfaces and their addresses"`
Temperatures []Temperature `json:"temperatures" doc:"Thermal sensor readings in Celsius"`
}
type OSInfo struct {
PrettyName string `json:"pretty_name" example:"Fedora Linux 44 (Workstation Edition)" doc:"Distro name from /etc/os-release PRETTY_NAME"`
Kernel string `json:"kernel" example:"7.0.12-201.fc44.x86_64" doc:"Running kernel release (uname -r)"`
Architecture string `json:"architecture" example:"x86_64" doc:"Machine hardware architecture (uname -m)"`
Hostname string `json:"hostname" example:"server01" doc:"System hostname"`
}
type CPUInfo struct {
Model string `json:"model" example:"AMD Ryzen 7 7840U" doc:"CPU model name"`
LogicalCPUs int `json:"logical_cpus" example:"16" doc:"Number of logical CPUs (cores × threads)"`
MinMHz int `json:"min_mhz" example:"400" doc:"Lowest frequency the scaling governor can select"`
MaxMHz int `json:"max_mhz" example:"5137" doc:"Highest frequency (boost ceiling)"`
CurrentMHz int `json:"current_mhz" example:"3157" doc:"Peak current clock across all cores (instantaneous snapshot; 0 if cpufreq unavailable)"`
}
type MemoryInfo struct {
TotalBytes uint64 `json:"total_bytes" example:"16384000000"`
AvailableBytes uint64 `json:"available_bytes" example:"8192000000" doc:"Memory available for new allocations without swapping"`
UsedBytes uint64 `json:"used_bytes" example:"8192000000" doc:"total - available"`
SwapTotalBytes uint64 `json:"swap_total_bytes" example:"8589934592"`
SwapFreeBytes uint64 `json:"swap_free_bytes" example:"8589934592"`
}
type LoadInfo struct {
Load1 float64 `json:"load1" example:"0.42"`
Load5 float64 `json:"load5" example:"0.55"`
Load15 float64 `json:"load15" example:"0.61"`
CPUUsage []CoreUsage `json:"cpu_usage" doc:"Per-core CPU usage percentage (sampled over ~1 s); empty until the first sample completes"`
}
// CoreUsage holds the usage percentage for a single logical core, computed as
// the delta of non-idle ticks over total ticks between two /proc/stat reads.
type CoreUsage struct {
Core int `json:"core" example:"0" doc:"Logical core index"`
UsagePct float64 `json:"usage_pct" example:"23.4" doc:"Usage percentage (0100)"`
}
type DiskInfo struct {
Mountpoint string `json:"mountpoint" example:"/"`
Filesystem string `json:"filesystem" example:"/dev/nvme0n1p2" doc:"Backing device"`
FSType string `json:"fstype" example:"btrfs"`
TotalBytes uint64 `json:"total_bytes" example:"512000000000"`
FreeBytes uint64 `json:"free_bytes" example:"256000000000" doc:"Space available to unprivileged users"`
UsedBytes uint64 `json:"used_bytes" example:"256000000000"`
}
type NetInterface struct {
Name string `json:"name" example:"eth0"`
MAC string `json:"mac" example:"aa:bb:cc:dd:ee:ff"`
Up bool `json:"up" doc:"Interface is administratively up"`
Addresses []string `json:"addresses" doc:"Assigned addresses in CIDR notation"`
}
type Temperature struct {
Chip string `json:"chip" example:"k10temp" doc:"hwmon chip name; identifies the source (k10temp/coretemp=CPU, amdgpu/nvidia=GPU, nvme=disk)"`
Label string `json:"label" example:"Tctl" doc:"Per-sensor label, or the chip name when the sensor is unlabelled"`
Celsius float64 `json:"celsius" example:"47.5"`
GPUs []GPUInfo `json:"gpus" doc:"Graphics processors detected via DRM sysfs"`
}
type GetInfoOutput struct{ Body SystemInfoBody }
func registerInfo(api huma.API) {
startCPUSampler()
func registerInfo(api huma.API, sampler *Sampler) {
huma.Register(api, huma.Operation{
OperationID: "system-get-info",
Method: "GET",
@@ -106,9 +37,9 @@ func registerInfo(api huma.API) {
Summary: "Get system information",
Description: "Returns an overview for a dashboard: OS/kernel identity, CPU, " +
"memory and swap, mounted disks, load averages, uptime, network " +
"interfaces, and temperatures. All values come from cheap local reads " +
"(/proc, /sys, syscalls) with no D-Bus dependency; each section is " +
"best-effort.",
"interfaces, temperatures, and GPU information. All values come from cheap " +
"local reads (/proc, /sys, syscalls) with no D-Bus dependency; each " +
"section is best-effort.",
Tags: []string{tagSystem},
Metadata: op("read"),
Errors: readErrors,
@@ -118,360 +49,17 @@ func registerInfo(api huma.API) {
OS: osInfo(),
CPU: cpuInfo(),
Memory: memInfo(),
Load: loadInfo(),
Load: loadInfo(sampler),
UptimeSec: uptime,
BootTime: boot.Format(time.RFC3339),
Disks: diskInfo(),
NetworkInterfaces: netInfo(),
Temperatures: tempInfo(),
GPUs: gpuInfo(),
}}, nil
})
}
func osInfo() OSInfo {
host, _ := os.Hostname()
return OSInfo{
PrettyName: osReleasePretty(),
Kernel: firstLine(oscmd.Run("uname", "-r")),
Architecture: firstLine(oscmd.Run("uname", "-m")),
Hostname: host,
}
}
// firstLine discards a command error and returns its (already trimmed) output,
// used where a missing value is acceptable.
func firstLine(out string, _ error) string { return out }
func osReleasePretty() string {
data, err := os.ReadFile("/etc/os-release")
if err != nil {
return ""
}
for line := range strings.SplitSeq(string(data), "\n") {
if v, ok := strings.CutPrefix(line, "PRETTY_NAME="); ok {
return strings.Trim(v, `"`)
}
}
return ""
}
func cpuInfo() CPUInfo {
data, _ := os.ReadFile("/proc/cpuinfo")
c := CPUInfo{Model: cpuModel(string(data)), LogicalCPUs: runtime.NumCPU()}
c.MinMHz, c.MaxMHz, c.CurrentMHz = cpuFreqMHz("/sys/devices/system/cpu")
// ponytail: cpufreq sysfs is absent on many VMs and stock Ubuntu server
// kernels; fall back to /proc/cpuinfo "cpu MHz" — VMs have a fixed clock,
// so min == max == cur is the honest answer.
mhz := cpuinfoMaxMHz(string(data))
// ponytail: ARM /proc/cpuinfo has no "cpu MHz" and often no "model name";
// lscpu decodes the ARM part-id table and reads DMI, so use it as last resort.
if c.Model == "" || mhz == 0 {
model, lscpuMHz := lscpuFallback()
if c.Model == "" {
c.Model = model
}
if mhz == 0 {
mhz = lscpuMHz
}
}
if mhz > 0 {
if c.CurrentMHz == 0 {
c.CurrentMHz = mhz
}
if c.MaxMHz == 0 {
c.MaxMHz = mhz
}
if c.MinMHz == 0 {
c.MinMHz = mhz
}
}
return c
}
// lscpuFallback parses `lscpu` for "Model name" and any embedded "@ X.X GHz"
// or "CPU max MHz:" value. Returns zeros when lscpu is missing or silent.
func lscpuFallback() (model string, mhz int) {
out, err := exec.Command("lscpu").Output()
if err != nil {
return "", 0
}
for line := range strings.SplitSeq(string(out), "\n") {
k, v, ok := strings.Cut(line, ":")
if !ok {
continue
}
k, v = strings.TrimSpace(k), strings.TrimSpace(v)
switch k {
case "Model name":
if model == "" {
model = v
}
case "BIOS Model name":
if model == "" {
model = v
}
case "CPU max MHz", "CPU MHz":
if f, err := strconv.ParseFloat(v, 64); err == nil && int(f) > mhz {
mhz = int(math.Round(f))
}
}
}
if mhz == 0 {
mhz = parseGHzSuffix(model)
}
return model, mhz
}
// parseGHzSuffix pulls "2.0GHz" / "@ 2.0 GHz" out of a model string.
func parseGHzSuffix(s string) int {
i := strings.LastIndex(s, "@")
if i < 0 {
return 0
}
rest := strings.TrimSpace(s[i+1:])
rest = strings.TrimSuffix(strings.TrimSuffix(rest, "GHz"), "Ghz")
rest = strings.TrimSpace(strings.TrimSuffix(rest, "G"))
f, err := strconv.ParseFloat(strings.TrimSpace(rest), 64)
if err != nil {
return 0
}
return int(math.Round(f * 1000))
}
// cpuinfoMaxMHz returns the highest "cpu MHz" value across all cores in
// /proc/cpuinfo, rounded to an int. Returns 0 when no such line exists.
func cpuinfoMaxMHz(cpuinfo string) int {
var max float64
for line := range strings.SplitSeq(cpuinfo, "\n") {
k, v, ok := strings.Cut(line, ":")
if !ok || strings.TrimSpace(k) != "cpu MHz" {
continue
}
if f, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil && f > max {
max = f
}
}
return int(math.Round(max))
}
// cpuFreqMHz reads cpufreq sysfs: min/max are stable hardware limits (from
// cpu0); current is the highest scaling_cur_freq across all cores — the "is it
// boosting" figure. Values are kHz in sysfs. Returns zeros when cpufreq is
// absent (e.g. some VMs).
func cpuFreqMHz(root string) (min, max, cur int) {
min = readKHzAsMHz(filepath.Join(root, "cpu0/cpufreq/cpuinfo_min_freq"))
max = readKHzAsMHz(filepath.Join(root, "cpu0/cpufreq/cpuinfo_max_freq"))
cores, _ := filepath.Glob(filepath.Join(root, "cpu[0-9]*/cpufreq/scaling_cur_freq"))
for _, f := range cores {
if v := readKHzAsMHz(f); v > cur {
cur = v
}
}
return min, max, cur
}
func readKHzAsMHz(path string) int {
khz, err := strconv.Atoi(readTrim(path))
if err != nil {
return 0
}
return khz / 1000
}
// cpuModel extracts the processor model from /proc/cpuinfo. x86 uses "model
// name"; many ARM boards use "Model" instead, so fall back to it.
func cpuModel(cpuinfo string) string {
var fallback string
for line := range strings.SplitSeq(cpuinfo, "\n") {
k, v, ok := strings.Cut(line, ":")
if !ok {
continue
}
switch strings.TrimSpace(k) {
case "model name":
return strings.TrimSpace(v)
case "Model":
fallback = strings.TrimSpace(v)
}
}
return fallback
}
func memInfo() MemoryInfo {
data, _ := os.ReadFile("/proc/meminfo")
return parseMeminfo(data)
}
// parseMeminfo reads the kB values in /proc/meminfo and converts them to bytes.
func parseMeminfo(data []byte) MemoryInfo {
kv := map[string]uint64{}
for line := range strings.SplitSeq(string(data), "\n") {
k, v, ok := strings.Cut(line, ":")
if !ok {
continue
}
fields := strings.Fields(v) // e.g. "16384000 kB"
if len(fields) == 0 {
continue
}
if n, err := strconv.ParseUint(fields[0], 10, 64); err == nil {
kv[k] = n * 1024 // values are in kB
}
}
return MemoryInfo{
TotalBytes: kv["MemTotal"],
AvailableBytes: kv["MemAvailable"],
UsedBytes: kv["MemTotal"] - kv["MemAvailable"],
SwapTotalBytes: kv["SwapTotal"],
SwapFreeBytes: kv["SwapFree"],
}
}
func loadInfo() LoadInfo {
data, _ := os.ReadFile("/proc/loadavg")
l := parseLoadavg(string(data))
l.CPUUsage = cachedCPUUsage()
return l
}
// parseLoadavg reads the three load averages from /proc/loadavg.
func parseLoadavg(loadavg string) LoadInfo {
f := strings.Fields(loadavg)
if len(f) < 3 {
return LoadInfo{}
}
at := func(i int) float64 { v, _ := strconv.ParseFloat(f[i], 64); return v }
return LoadInfo{Load1: at(0), Load5: at(1), Load15: at(2)}
}
// ---------------------------------------------------------------------------
// Per-core CPU usage sampler
// ---------------------------------------------------------------------------
//
// /proc/stat exposes cumulative jiffies per core:
//
// cpuN user nice system idle iowait irq softirq steal guest guest_nice
//
// We sample every second, compute the delta, and derive:
//
// usage% = (totalΔ idleΔ) / totalΔ × 100
//
// The result is cached behind a RWMutex so the HTTP handler never blocks.
var (
usageMu sync.RWMutex
usageCache []CoreUsage
)
func cachedCPUUsage() []CoreUsage {
usageMu.RLock()
defer usageMu.RUnlock()
// Return a copy so callers can't mutate the cache.
if usageCache == nil {
return nil
}
out := make([]CoreUsage, len(usageCache))
copy(out, usageCache)
return out
}
// startCPUSampler launches a goroutine that samples /proc/stat once per second
// for the lifetime of the process. Safe to call multiple times (only the first
// call starts the goroutine).
var samplerOnce sync.Once
func startCPUSampler() {
samplerOnce.Do(func() {
go cpuSamplerLoop("/proc/stat", 1*time.Second)
})
}
func cpuSamplerLoop(statPath string, interval time.Duration) {
prev := readProcStat(statPath)
for {
time.Sleep(interval)
cur := readProcStat(statPath)
usage := computeUsage(prev, cur)
usageMu.Lock()
usageCache = usage
usageMu.Unlock()
prev = cur
}
}
// cpuCoreTicks holds the cumulative jiffies for one "cpuN" line.
type cpuCoreTicks struct {
core int
total uint64
idle uint64
}
// readProcStat reads /proc/stat and returns per-core tick totals. The
// aggregate "cpu" line (no digit suffix) is skipped.
func readProcStat(path string) []cpuCoreTicks {
data, _ := os.ReadFile(path)
var cores []cpuCoreTicks
for line := range strings.SplitSeq(string(data), "\n") {
if !strings.HasPrefix(line, "cpu") {
continue
}
fields := strings.Fields(line)
if len(fields) < 5 {
continue
}
// Skip the aggregate "cpu" line; we only want "cpu0", "cpu1", …
name := fields[0]
if name == "cpu" {
continue
}
coreIdx, err := strconv.Atoi(strings.TrimPrefix(name, "cpu"))
if err != nil {
continue
}
// Fields: user(1) nice(2) system(3) idle(4) iowait(5) irq(6) softirq(7) steal(8) …
var total, idle uint64
for _, f := range fields[1:] {
v, _ := strconv.ParseUint(f, 10, 64)
total += v
}
// idle = idle + iowait (indices 4 and 5 in the original line).
if len(fields) > 5 {
v4, _ := strconv.ParseUint(fields[4], 10, 64)
v5, _ := strconv.ParseUint(fields[5], 10, 64)
idle = v4 + v5
} else {
v4, _ := strconv.ParseUint(fields[4], 10, 64)
idle = v4
}
cores = append(cores, cpuCoreTicks{core: coreIdx, total: total, idle: idle})
}
return cores
}
func computeUsage(prev, cur []cpuCoreTicks) []CoreUsage {
prevMap := make(map[int]cpuCoreTicks, len(prev))
for _, c := range prev {
prevMap[c.core] = c
}
usage := make([]CoreUsage, 0, len(cur))
for _, c := range cur {
p, ok := prevMap[c.core]
if !ok {
continue
}
dTotal := c.total - p.total
dIdle := c.idle - p.idle
var pct float64
if dTotal > 0 {
pct = float64(dTotal-dIdle) / float64(dTotal) * 100
// Round to one decimal.
pct = math.Round(pct*10) / 10
}
usage = append(usage, CoreUsage{Core: c.core, UsagePct: pct})
}
return usage
}
// uptimeAndBoot reads /proc/uptime (seconds since boot) and derives boot time.
// On any read error it returns zero values rather than failing the request.
func uptimeAndBoot() (int64, time.Time) {
@@ -490,163 +78,3 @@ func uptimeAndBoot() (int64, time.Time) {
boot := time.Now().Add(-time.Duration(secs * float64(time.Second))).UTC()
return int64(secs), boot
}
func diskInfo() []DiskInfo {
entries, err := mounts.Proc()
if err != nil {
return nil
}
disks := []DiskInfo{}
seen := map[string]bool{}
for _, e := range entries {
// ponytail: filter by fstype, not device path. LXC/Docker containers
// expose their rootfs as a ZFS dataset name, an overlayfs, or a bind
// path — never /dev/* — so a "must start with /dev/" check silently
// returned no disks on those hosts. statfs + non-zero blocks already
// excludes mounts that aren't real storage.
if pseudoFS[e.FSType] || seen[e.Mountpoint] {
continue
}
var st syscall.Statfs_t
if syscall.Statfs(e.Mountpoint, &st) != nil || st.Blocks == 0 {
continue
}
seen[e.Mountpoint] = true
bs := uint64(st.Bsize)
disks = append(disks, DiskInfo{
Mountpoint: e.Mountpoint,
Filesystem: e.Device,
FSType: e.FSType,
TotalBytes: st.Blocks * bs,
FreeBytes: st.Bavail * bs,
UsedBytes: (st.Blocks - st.Bfree) * bs,
})
}
return disks
}
// pseudoFS lists kernel-virtual filesystems that show up in /proc/mounts but
// aren't user-facing storage. squashfs covers snap loop mounts; fuse.lxcfs is
// LXC's per-container /proc/* shim. Anything not on this list and statfs-able
// with non-zero blocks is treated as real storage — covers ext*, btrfs, xfs,
// zfs, nfs, cifs, overlay, and the bind-mount cases inside Proxmox LXC.
var pseudoFS = map[string]bool{
"autofs": true,
"binfmt_misc": true,
"bpf": true,
"cgroup": true,
"cgroup2": true,
"configfs": true,
"debugfs": true,
"devpts": true,
"devtmpfs": true,
"fuse.gvfsd-fuse": true,
"fuse.lxcfs": true,
"fusectl": true,
"hugetlbfs": true,
"mqueue": true,
"nsfs": true,
"overlay": true,
"proc": true,
"pstore": true,
"ramfs": true,
"rpc_pipefs": true,
"securityfs": true,
"squashfs": true,
"sysfs": true,
"tmpfs": true,
"tracefs": true,
}
func netInfo() []NetInterface {
ifaces, err := net.Interfaces()
if err != nil {
return nil
}
out := []NetInterface{}
for _, ifi := range ifaces {
addrs, _ := ifi.Addrs()
strs := []string{}
for _, a := range addrs {
strs = append(strs, a.String())
}
out = append(out, NetInterface{
Name: ifi.Name,
MAC: ifi.HardwareAddr.String(),
Up: ifi.Flags&net.FlagUp != 0,
Addresses: strs,
})
}
return out
}
func tempInfo() []Temperature {
if t := readHwmonTemps("/sys/class/hwmon"); len(t) > 0 {
return t
}
// ponytail: stock Ubuntu server has no coretemp/k10temp loaded, so hwmon
// is empty; thermal_zone exposes ACPI sensors (coarser, no chip name).
return readThermalZones("/sys/class/thermal")
}
// readThermalZones reads /sys/class/thermal/thermal_zone*/temp as a fallback
// for hosts without hwmon chip drivers. "type" names the zone (e.g. acpitz,
// x86_pkg_temp); used as both chip and label.
func readThermalZones(root string) []Temperature {
zones, _ := filepath.Glob(filepath.Join(root, "thermal_zone*"))
temps := []Temperature{}
for _, dir := range zones {
milli, err := strconv.Atoi(readTrim(filepath.Join(dir, "temp")))
if err != nil {
continue
}
c := float64(milli) / 1000
if c <= 0 || c >= 150 {
continue
}
name := readTrim(filepath.Join(dir, "type"))
if name == "" {
name = filepath.Base(dir)
}
temps = append(temps, Temperature{Chip: name, Label: name, Celsius: c})
}
return temps
}
// readHwmonTemps walks /sys/class/hwmon, which (unlike /sys/class/thermal, that
// only exposes generic ACPI zones like "acpitz") names each chip — so callers
// can split CPU (k10temp/coretemp) from GPU (amdgpu/nvidia) from disk (nvme).
// Each tempN_input may carry a tempN_label; when absent we fall back to the
// chip name. Best-effort: unreadable, empty, or implausible sensors are skipped.
func readHwmonTemps(root string) []Temperature {
chips, _ := filepath.Glob(filepath.Join(root, "hwmon*"))
temps := []Temperature{}
for _, dir := range chips {
chip := readTrim(filepath.Join(dir, "name"))
inputs, _ := filepath.Glob(filepath.Join(dir, "temp*_input"))
for _, in := range inputs {
milli, err := strconv.Atoi(readTrim(in))
if err != nil {
continue
}
c := float64(milli) / 1000
// Disabled/placeholder sensors report absurd values (e.g. -0.15 or
// 179.8 °C). Drop anything outside a plausible band.
if c <= 0 || c >= 150 {
continue
}
label := readTrim(strings.TrimSuffix(in, "_input") + "_label")
if label == "" {
label = chip
}
temps = append(temps, Temperature{Chip: chip, Label: label, Celsius: c})
}
}
return temps
}
// readTrim reads a sysfs file and trims it; a missing file yields "".
func readTrim(path string) string {
b, _ := os.ReadFile(path)
return strings.TrimSpace(string(b))
}
+114
View File
@@ -6,6 +6,106 @@ import (
"testing"
)
func TestReadGPUsFromSysfs(t *testing.T) {
root := t.TempDir()
// card0 — AMD GPU with VRAM and utilization files
pciDev := filepath.Join(root, "devices/pci0000:00/0000:00:02.0")
mkdirAll(t, pciDev)
write(t, pciDev, ".", "vendor", "0x1002")
write(t, pciDev, ".", "device", "0x7480")
write(t, pciDev, ".", "mem_info_vram_total", "8573157376")
write(t, pciDev, ".", "mem_info_vram_used", "27267072")
write(t, pciDev, ".", "gpu_busy_percent", "23")
write(t, pciDev, ".", "mem_busy_percent", "15")
driverDir := filepath.Join(root, "bus/pci/drivers/amdgpu")
mkdirAll(t, driverDir)
mustSymlink(t, driverDir, filepath.Join(pciDev, "driver"))
cardTarget := filepath.Join(pciDev, "drm", "card0")
mkdirAll(t, cardTarget)
mustSymlink(t, pciDev, filepath.Join(cardTarget, "device"))
mustSymlink(t, cardTarget, filepath.Join(root, "card0"))
// Distractors
write(t, root, ".", "card0-HDMI-1", "distract")
write(t, root, ".", "renderD128", "distract")
gpus := readGPUsFromSysfs(root)
if len(gpus) != 1 {
t.Fatalf("want 1 GPU, got %d: %+v", len(gpus), gpus)
}
if gpus[0].Vendor != "1002" {
t.Errorf("vendor = %q, want 1002", gpus[0].Vendor)
}
if gpus[0].DeviceID != "7480" {
t.Errorf("device_id = %q, want 7480", gpus[0].DeviceID)
}
if gpus[0].Driver != "amdgpu" {
t.Errorf("driver = %q, want amdgpu", gpus[0].Driver)
}
if gpus[0].MemoryTotalBytes != 8573157376 {
t.Errorf("MemoryTotalBytes = %d, want 8573157376", gpus[0].MemoryTotalBytes)
}
if gpus[0].MemoryUsedBytes != 27267072 {
t.Errorf("MemoryUsedBytes = %d, want 27267072", gpus[0].MemoryUsedBytes)
}
if gpus[0].UtilizationPct != 23.0 {
t.Errorf("UtilizationPct = %f, want 23.0", gpus[0].UtilizationPct)
}
if gpus[0].MemUtilizationPct != 15.0 {
t.Errorf("MemUtilizationPct = %f, want 15.0", gpus[0].MemUtilizationPct)
}
}
func TestReadGPUsFromSysfsNoEnrichment(t *testing.T) {
root := t.TempDir()
// i915 GPU with no VRAM or utilization files
pciDev := filepath.Join(root, "devices/pci0000:00/0000:00:02.0")
mkdirAll(t, pciDev)
write(t, pciDev, ".", "vendor", "0x8086")
write(t, pciDev, ".", "device", "0x46a6")
driverDir := filepath.Join(root, "bus/pci/drivers/i915")
mkdirAll(t, driverDir)
mustSymlink(t, driverDir, filepath.Join(pciDev, "driver"))
cardTarget := filepath.Join(pciDev, "drm", "card0")
mkdirAll(t, cardTarget)
mustSymlink(t, pciDev, filepath.Join(cardTarget, "device"))
mustSymlink(t, cardTarget, filepath.Join(root, "card0"))
gpus := readGPUsFromSysfs(root)
if len(gpus) != 1 {
t.Fatalf("want 1 GPU, got %d", len(gpus))
}
if gpus[0].MemoryTotalBytes != 0 || gpus[0].MemoryUsedBytes != 0 {
t.Errorf("expected 0 VRAM for i915, got total=%d used=%d", gpus[0].MemoryTotalBytes, gpus[0].MemoryUsedBytes)
}
if gpus[0].UtilizationPct != 0 || gpus[0].MemUtilizationPct != 0 {
t.Errorf("expected 0 utilization for i915, got gpu=%f mem=%f", gpus[0].UtilizationPct, gpus[0].MemUtilizationPct)
}
}
func TestReadGPUsFromSysfsMissingDir(t *testing.T) {
gpus := readGPUsFromSysfs("/nonexistent/drm")
if gpus != nil {
t.Errorf("expected nil, got %+v", gpus)
}
}
func TestReadGPUsFromSysfsSkipsNonGPU(t *testing.T) {
root := t.TempDir()
write(t, root, ".", "renderD128", "x")
write(t, root, ".", "card0-HDMI-1", "x")
gpus := readGPUsFromSysfs(root)
if len(gpus) != 0 {
t.Errorf("expected 0 GPUs, got %d", len(gpus))
}
}
func TestReadHwmonTemps(t *testing.T) {
root := t.TempDir()
// k10temp: CPU, labelled Tctl.
@@ -33,6 +133,20 @@ func TestReadHwmonTemps(t *testing.T) {
}
}
func mkdirAll(t *testing.T, path string) {
t.Helper()
if err := os.MkdirAll(path, 0o755); err != nil {
t.Fatal(err)
}
}
func mustSymlink(t *testing.T, target, link string) {
t.Helper()
if err := os.Symlink(target, link); err != nil {
t.Fatal(err)
}
}
func write(t *testing.T, root, chip, file, val string) {
t.Helper()
dir := filepath.Join(root, chip)
+37
View File
@@ -0,0 +1,37 @@
package system
import (
"os"
"strconv"
"strings"
)
// CoreUsage holds the usage percentage for a single logical core, computed as
// the delta of non-idle ticks over total ticks between two /proc/stat reads.
type CoreUsage struct {
Core int `json:"core" example:"0" doc:"Logical core index"`
UsagePct float64 `json:"usage_pct" example:"23.4" doc:"Usage percentage (0100)"`
}
type LoadInfo struct {
Load1 float64 `json:"load1" example:"0.42"`
Load5 float64 `json:"load5" example:"0.55"`
Load15 float64 `json:"load15" example:"0.61"`
CPUUsage []CoreUsage `json:"cpu_usage" doc:"Per-core CPU usage percentage (sampled over ~1 s); empty until the first sample completes"`
}
func loadInfo(sampler *Sampler) LoadInfo {
data, _ := os.ReadFile("/proc/loadavg")
l := parseLoadavg(string(data))
l.CPUUsage = sampler.Snapshot()
return l
}
func parseLoadavg(loadavg string) LoadInfo {
f := strings.Fields(loadavg)
if len(f) < 3 {
return LoadInfo{}
}
at := func(i int) float64 { v, _ := strconv.ParseFloat(f[i], 64); return v }
return LoadInfo{Load1: at(0), Load5: at(1), Load15: at(2)}
}
+44
View File
@@ -0,0 +1,44 @@
package system
import (
"os"
"strconv"
"strings"
)
type MemoryInfo struct {
TotalBytes uint64 `json:"total_bytes" example:"16384000000"`
AvailableBytes uint64 `json:"available_bytes" example:"8192000000" doc:"Memory available for new allocations without swapping"`
UsedBytes uint64 `json:"used_bytes" example:"8192000000" doc:"total - available"`
SwapTotalBytes uint64 `json:"swap_total_bytes" example:"8589934592"`
SwapFreeBytes uint64 `json:"swap_free_bytes" example:"8589934592"`
}
func memInfo() MemoryInfo {
data, _ := os.ReadFile("/proc/meminfo")
return parseMeminfo(data)
}
func parseMeminfo(data []byte) MemoryInfo {
kv := map[string]uint64{}
for line := range strings.SplitSeq(string(data), "\n") {
k, v, ok := strings.Cut(line, ":")
if !ok {
continue
}
fields := strings.Fields(v)
if len(fields) == 0 {
continue
}
if n, err := strconv.ParseUint(fields[0], 10, 64); err == nil {
kv[k] = n * 1024
}
}
return MemoryInfo{
TotalBytes: kv["MemTotal"],
AvailableBytes: kv["MemAvailable"],
UsedBytes: kv["MemTotal"] - kv["MemAvailable"],
SwapTotalBytes: kv["SwapTotal"],
SwapFreeBytes: kv["SwapFree"],
}
}
+13 -3
View File
@@ -1,6 +1,9 @@
package system
import (
"context"
"time"
"nadir/internal/rbac"
"github.com/danielgtaylor/huma/v2"
@@ -8,9 +11,15 @@ import (
const ModuleID = "system"
type Module struct{}
type Module struct {
sampler *Sampler
}
func New() *Module { return &Module{} }
func New() *Module {
return &Module{
sampler: NewSampler("/proc/stat", 1*time.Second),
}
}
func (m *Module) ID() string { return ModuleID }
@@ -19,7 +28,8 @@ func (m *Module) Permissions() []rbac.Permission {
}
func (m *Module) Register(api huma.API) {
registerInfo(api)
m.sampler.Start(context.Background())
registerInfo(api, m.sampler)
registerHostname(api)
registerTimedate(api)
registerLocale(api)
+32
View File
@@ -0,0 +1,32 @@
package system
import "net"
type NetInterface struct {
Name string `json:"name" example:"eth0"`
MAC string `json:"mac" example:"aa:bb:cc:dd:ee:ff"`
Up bool `json:"up" doc:"Interface is administratively up"`
Addresses []string `json:"addresses" doc:"Assigned addresses in CIDR notation"`
}
func netInfo() []NetInterface {
ifaces, err := net.Interfaces()
if err != nil {
return nil
}
out := []NetInterface{}
for _, ifi := range ifaces {
addrs, _ := ifi.Addrs()
strs := []string{}
for _, a := range addrs {
strs = append(strs, a.String())
}
out = append(out, NetInterface{
Name: ifi.Name,
MAC: ifi.HardwareAddr.String(),
Up: ifi.Flags&net.FlagUp != 0,
Addresses: strs,
})
}
return out
}
+42
View File
@@ -0,0 +1,42 @@
package system
import (
"os"
"strings"
"nadir/internal/oscmd"
)
type OSInfo struct {
PrettyName string `json:"pretty_name" example:"Fedora Linux 44 (Workstation Edition)" doc:"Distro name from /etc/os-release PRETTY_NAME"`
Kernel string `json:"kernel" example:"7.0.12-201.fc44.x86_64" doc:"Running kernel release (uname -r)"`
Architecture string `json:"architecture" example:"x86_64" doc:"Machine hardware architecture (uname -m)"`
Hostname string `json:"hostname" example:"server01" doc:"System hostname"`
}
func osInfo() OSInfo {
host, _ := os.Hostname()
return OSInfo{
PrettyName: osReleasePretty(),
Kernel: firstLine(oscmd.Run("uname", "-r")),
Architecture: firstLine(oscmd.Run("uname", "-m")),
Hostname: host,
}
}
// firstLine discards a command error and returns its (already trimmed) output,
// used where a missing value is acceptable.
func firstLine(out string, _ error) string { return out }
func osReleasePretty() string {
data, err := os.ReadFile("/etc/os-release")
if err != nil {
return ""
}
for line := range strings.SplitSeq(string(data), "\n") {
if v, ok := strings.CutPrefix(line, "PRETTY_NAME="); ok {
return strings.Trim(v, `"`)
}
}
return ""
}
+29 -11
View File
@@ -3,16 +3,34 @@ package system
import "testing"
func TestWhenRe(t *testing.T) {
valid := []string{"now", "+0", "+5", "+120", "0:00", "9:30", "23:59", "07:05"}
for _, w := range valid {
if !whenRe.MatchString(w) {
t.Errorf("whenRe.MatchString(%q) = false, want true", w)
}
}
invalid := []string{"", "-r", "-h", "--help", "24:00", "9:60", "+5; reboot", "now ", "5", "1:2"}
for _, w := range invalid {
if whenRe.MatchString(w) {
t.Errorf("whenRe.MatchString(%q) = true, want false", w)
}
for _, tt := range []struct {
name string
value string
want bool
}{
{name: "now", value: "now", want: true},
{name: "plus zero", value: "+0", want: true},
{name: "plus five", value: "+5", want: true},
{name: "plus 120", value: "+120", want: true},
{name: "0:00", value: "0:00", want: true},
{name: "9:30", value: "9:30", want: true},
{name: "23:59", value: "23:59", want: true},
{name: "07:05", value: "07:05", want: true},
{name: "empty", value: "", want: false},
{name: "flag r", value: "-r", want: false},
{name: "flag h", value: "-h", want: false},
{name: "help", value: "--help", want: false},
{name: "24:00", value: "24:00", want: false},
{name: "9:60", value: "9:60", want: false},
{name: "injected command", value: "+5; reboot", want: false},
{name: "trailing space", value: "now ", want: false},
{name: "just digit", value: "5", want: false},
{name: "single colon", value: "1:2", want: false},
} {
t.Run(tt.name, func(t *testing.T) {
if got := whenRe.MatchString(tt.value); got != tt.want {
t.Errorf("whenRe.MatchString(%q) = %v, want %v", tt.value, got, tt.want)
}
})
}
}
@@ -22,7 +22,7 @@ func TestSystemHandlers(t *testing.T) {
registerTimedate(api)
registerLocale(api)
registerPower(api)
registerInfo(api)
registerInfo(api, NewSampler("/proc/stat", 0))
// Mock uname for GET /api/system/info
oscmd.SetMock("uname", func(args []string) oscmd.MockCommand {
@@ -34,6 +34,14 @@ func TestSystemHandlers(t *testing.T) {
}
return oscmd.MockCommand{ExitCode: 1}
})
// Mock lspci to prevent real calls in case the test host has GPUs.
oscmd.SetMock("lspci", func(args []string) oscmd.MockCommand {
return oscmd.MockCommand{ExitCode: 1}
})
// Mock nvidia-smi: return failure so enrichment is a no-op.
oscmd.SetMock("nvidia-smi", func(args []string) oscmd.MockCommand {
return oscmd.MockCommand{ExitCode: 1}
})
defer oscmd.ClearMocks()
// 1. Test GET /api/system/info
+73
View File
@@ -0,0 +1,73 @@
package system
import (
"os"
"path/filepath"
"strconv"
"strings"
)
type Temperature struct {
Chip string `json:"chip" example:"k10temp" doc:"hwmon chip name; identifies the source (k10temp/coretemp=CPU, amdgpu/nvidia=GPU, nvme=disk)"`
Label string `json:"label" example:"Tctl" doc:"Per-sensor label, or the chip name when the sensor is unlabelled"`
Celsius float64 `json:"celsius" example:"47.5"`
}
func tempInfo() []Temperature {
if t := readHwmonTemps("/sys/class/hwmon"); len(t) > 0 {
return t
}
return readThermalZones("/sys/class/thermal")
}
func readThermalZones(root string) []Temperature {
zones, _ := filepath.Glob(filepath.Join(root, "thermal_zone*"))
temps := []Temperature{}
for _, dir := range zones {
milli, err := strconv.Atoi(readTrim(filepath.Join(dir, "temp")))
if err != nil {
continue
}
c := float64(milli) / 1000
if c <= 0 || c >= 150 {
continue
}
name := readTrim(filepath.Join(dir, "type"))
if name == "" {
name = filepath.Base(dir)
}
temps = append(temps, Temperature{Chip: name, Label: name, Celsius: c})
}
return temps
}
func readHwmonTemps(root string) []Temperature {
chips, _ := filepath.Glob(filepath.Join(root, "hwmon*"))
temps := []Temperature{}
for _, dir := range chips {
chip := readTrim(filepath.Join(dir, "name"))
inputs, _ := filepath.Glob(filepath.Join(dir, "temp*_input"))
for _, in := range inputs {
milli, err := strconv.Atoi(readTrim(in))
if err != nil {
continue
}
c := float64(milli) / 1000
if c <= 0 || c >= 150 {
continue
}
label := readTrim(strings.TrimSuffix(in, "_input") + "_label")
if label == "" {
label = chip
}
temps = append(temps, Temperature{Chip: chip, Label: label, Celsius: c})
}
}
return temps
}
// readTrim reads a sysfs file and trims it; a missing file yields "".
func readTrim(path string) string {
b, _ := os.ReadFile(path)
return strings.TrimSpace(string(b))
}
-209
View File
@@ -1,209 +0,0 @@
package terminal
import (
"context"
"encoding/json"
"net/http"
"os/exec"
"strings"
"sync/atomic"
"time"
"nadir/internal/auth"
"nadir/internal/module"
"nadir/internal/rbac"
"github.com/coder/websocket"
"github.com/creack/pty"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
)
// tagTerminal is the OpenAPI tag for this module (registered in server.go),
// keeping tags 1:1 with modules per the project convention.
const tagTerminal = "Terminal"
const (
// maxTerminals caps concurrent shells so a buggy frontend or careless admin
// can't pile up PTYs (guideline: limit everything). Raise if it's ever a real
// limit in practice.
maxTerminals = 10
// idleTimeout closes a session after this long with no I/O in either
// direction, reclaiming abandoned shells.
idleTimeout = 15 * time.Minute
)
// terminalSem is the concurrency limiter; a slot is held for the life of a session.
var terminalSem = make(chan struct{}, maxTerminals)
type terminalModule struct {
sessions *auth.SessionStore
}
// New creates a new Terminal module that allows interactive shell access.
func New(sessions *auth.SessionStore) module.Module {
return &terminalModule{sessions: sessions}
}
func (m *terminalModule) ID() string { return "terminal" }
func (m *terminalModule) Permissions() []rbac.Permission {
return []rbac.Permission{rbac.Root}
}
type TerminalInput struct {
Ctx huma.Context `json:"-"`
}
// Resolve extracts the huma.Context into the input struct.
func (i *TerminalInput) Resolve(ctx huma.Context) []error {
i.Ctx = ctx
return nil
}
type resizeMessage struct {
Cols uint16 `json:"cols"`
Rows uint16 `json:"rows"`
}
func (m *terminalModule) Register(api huma.API) {
huma.Register(api, huma.Operation{
OperationID: "terminal-connect",
Method: "GET",
Path: "/api/terminal",
Summary: "Connect to an interactive terminal",
Description: "Upgrades the connection to a WebSocket and spawns a PTY shell as the logged-in user. Send JSON `{cols, rows}` text messages to resize, and raw binary/text messages for stdin. This is a raw WebSocket endpoint — it cannot be exercised from the API docs \"Try it\" panel; use a WebSocket client.",
Tags: []string{tagTerminal},
Metadata: map[string]any{"module": m.ID(), "permission": string(rbac.Root)},
Errors: []int{401, 403, 426, 500},
}, func(ctx context.Context, in *TerminalInput) (*struct{}, error) {
// The RBAC middleware already authenticated this request and enforced the
// "root" permission before we got here. We re-read the session only to get
// the username for `su`; the 401 below is the fallback for when the module
// is mounted without the middleware (e.g. in unit tests).
cookie, err := huma.ReadCookie(in.Ctx, "nadir_session_id")
if err != nil || cookie == nil {
return nil, huma.Error401Unauthorized("unauthorized")
}
sess, ok := m.sessions.GetByToken(cookie.Value)
if !ok {
return nil, huma.Error401Unauthorized("unauthorized")
}
req, res := humago.Unwrap(in.Ctx)
if req == nil || res == nil {
return nil, huma.Error500InternalServerError("missing http context")
}
// Reject plain GETs (e.g. the docs "Try it" button) with a clear 426 rather
// than letting websocket.Accept emit a raw protocol-violation error.
if !strings.EqualFold(req.Header.Get("Upgrade"), "websocket") {
return nil, huma.NewError(http.StatusUpgradeRequired,
"this endpoint requires a WebSocket connection; connect with a WebSocket client")
}
// InsecureSkipVerify is deliberately NOT set: coder/websocket then enforces
// that the Origin host matches the request Host, rejecting cross-site upgrade
// attempts. Defense-in-depth on top of the SameSite=Strict session cookie —
// important because this endpoint hands out an interactive shell.
conn, err := websocket.Accept(res, req, nil)
if err != nil {
// websocket.Accept already wrote the error response (e.g. 403 on an
// Origin mismatch). Just stop; writing again would corrupt the response.
return nil, nil
}
defer conn.CloseNow()
// Bound concurrent shells: take a slot or reject (don't pile up PTYs).
select {
case terminalSem <- struct{}{}:
defer func() { <-terminalSem }()
default:
conn.Close(websocket.StatusTryAgainLater, "too many terminal sessions")
return nil, nil
}
// Launch the user's login shell via su.
// "su - <username>" ensures we get their actual environment and shell.
cmd := exec.CommandContext(req.Context(), "su", "-", "--", sess.Username)
// Start the command with a PTY.
ptmx, err := pty.Start(cmd)
if err != nil {
conn.Close(websocket.StatusInternalError, "failed to start pty")
return nil, nil
}
defer ptmx.Close()
// lastActive is bumped by both pumps; the watchdog uses it to close idle
// sessions. Output activity (e.g. `top`) counts, so it isn't killed.
var lastActive atomic.Int64
lastActive.Store(time.Now().UnixNano())
go func() {
tick := time.NewTicker(idleTimeout / 4)
defer tick.Stop()
for {
select {
case <-req.Context().Done():
return
case <-tick.C:
if time.Since(time.Unix(0, lastActive.Load())) > idleTimeout {
conn.Close(websocket.StatusGoingAway, "idle timeout")
return
}
}
}
}()
// Pump stdout/stderr from PTY to WebSocket.
go func() {
buf := make([]byte, 8192)
for {
n, err := ptmx.Read(buf)
if err != nil {
break
}
lastActive.Store(time.Now().UnixNano())
// We write PTY output as binary messages. The frontend (e.g., xterm.js)
// can handle UTF-8 binary or text transparently.
err = conn.Write(req.Context(), websocket.MessageBinary, buf[:n])
if err != nil {
break
}
}
conn.Close(websocket.StatusNormalClosure, "")
}()
// Pump stdin and resize commands from WebSocket to PTY.
for {
typ, b, err := conn.Read(req.Context())
if err != nil {
break
}
lastActive.Store(time.Now().UnixNano())
if typ == websocket.MessageText {
var resize resizeMessage
if err := json.Unmarshal(b, &resize); err == nil && resize.Cols > 0 && resize.Rows > 0 {
// Handle resize
_ = pty.Setsize(ptmx, &pty.Winsize{
Cols: resize.Cols,
Rows: resize.Rows,
})
continue
}
}
// If not a valid resize message, or if it's MessageBinary, pass to PTY stdin.
_, _ = ptmx.Write(b)
}
// The read loop has ended (client gone or PTY closed). Tear down the shell
// and reap it: closing the PTY sends EOF, Kill covers shells that ignore it.
_ = ptmx.Close()
_ = cmd.Process.Kill()
_ = cmd.Wait()
return nil, nil
})
}
-124
View File
@@ -1,124 +0,0 @@
package terminal
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"nadir/internal/auth"
"github.com/coder/websocket"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
)
func TestTerminalConnectUnauthorized(t *testing.T) {
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
if err != nil {
t.Fatalf("session db: %v", err)
}
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
mod := New(sessions)
mod.Register(api)
srv := httptest.NewServer(mux)
defer srv.Close()
wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) + "/api/terminal"
// Try without cookie
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
_, resp, err := websocket.Dial(ctx, wsURL, nil)
if err == nil {
t.Fatal("expected error, got success")
}
if resp != nil && resp.StatusCode != http.StatusUnauthorized {
t.Errorf("expected 401, got %d", resp.StatusCode)
}
}
func TestTerminalConnectPlainGET(t *testing.T) {
// An authenticated but non-WebSocket GET (e.g. the docs "Try it" button) must
// get a clean 426 Upgrade Required, not a raw websocket protocol error.
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
if err != nil {
t.Fatalf("session db: %v", err)
}
token, err := sessions.Create("root")
if err != nil {
t.Fatalf("create session: %v", err)
}
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
New(sessions).Register(api)
srv := httptest.NewServer(mux)
defer srv.Close()
req, _ := http.NewRequest(http.MethodGet, srv.URL+"/api/terminal", nil)
req.Header.Set("Cookie", "nadir_session_id="+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("GET failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusUpgradeRequired {
t.Errorf("expected 426, got %d", resp.StatusCode)
}
}
func TestTerminalConnectAuthorized(t *testing.T) {
// Root or specific system configs might cause PTY or su to fail if run in constrained environments.
// But we expect the websocket upgrade to succeed and then maybe close with an error if PTY fails.
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
if err != nil {
t.Fatalf("session db: %v", err)
}
token, err := sessions.Create("root")
if err != nil {
t.Fatalf("create session: %v", err)
}
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
mod := New(sessions)
mod.Register(api)
srv := httptest.NewServer(mux)
defer srv.Close()
wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) + "/api/terminal"
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
opts := &websocket.DialOptions{
HTTPHeader: http.Header{},
}
opts.HTTPHeader.Set("Cookie", "nadir_session_id="+token)
conn, resp, err := websocket.Dial(ctx, wsURL, opts)
if err != nil {
// Depending on the test environment, "su" or "pty" might fail, but
// the websocket upgrade itself should succeed before it drops.
// If it fails to upgrade, that's a real error.
t.Fatalf("dial failed: %v (status %d)", err, resp.StatusCode)
}
defer conn.CloseNow()
// The connection was upgraded successfully.
// If PTY allocation failed or su failed, the server might close the connection immediately.
// We just verify the upgrade succeeded.
if resp.StatusCode != http.StatusSwitchingProtocols {
t.Errorf("expected 101, got %d", resp.StatusCode)
}
}
+11 -3
View File
@@ -8,9 +8,17 @@ import (
const ModuleID = "users"
type Module struct{}
// sessionStore is the subset of SessionStore that password changes need:
// invalidate all existing sessions for a user whose password just changed.
type sessionStore interface {
DeleteByUsername(username string) error
}
func New() *Module { return &Module{} }
type Module struct {
sessions sessionStore
}
func New(sessions sessionStore) *Module { return &Module{sessions: sessions} }
func (m *Module) ID() string { return ModuleID }
@@ -21,7 +29,7 @@ func (m *Module) Permissions() []rbac.Permission {
}
func (m *Module) Register(api huma.API) {
registerUsers(api)
registerUsers(api, m.sessions)
}
func op(permission string) map[string]any {
+13 -7
View File
@@ -2,6 +2,7 @@ package users
import (
"context"
"log"
"os"
"path/filepath"
"regexp"
@@ -91,7 +92,7 @@ type UserGroupsOutput struct {
}
}
func registerUsers(api huma.API) {
func registerUsers(api huma.API, sessions sessionStore) {
huma.Register(api, huma.Operation{
OperationID: "users-list",
Method: "GET",
@@ -105,7 +106,7 @@ func registerUsers(api huma.API) {
}, func(ctx context.Context, _ *struct{}) (*ListUsersOutput, error) {
list, err := listUsers()
if err != nil {
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
return nil, huma.Error500InternalServerError("user lookup failed", err)
}
out := &ListUsersOutput{}
out.Body.Users = list
@@ -127,7 +128,7 @@ func registerUsers(api huma.API) {
}
u, ok, err := lookupUser(in.Username)
if err != nil {
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
return nil, huma.Error500InternalServerError("user lookup failed", err)
}
if !ok {
return nil, huma.Error404NotFound("user not found: " + in.Username)
@@ -163,7 +164,7 @@ func registerUsers(api huma.API) {
return nil, huma.Error400BadRequest("home must be an absolute path")
}
if _, ok, err := lookupUser(in.Body.Username); err != nil {
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
return nil, huma.Error500InternalServerError("user lookup failed", err)
} else if ok {
return nil, huma.Error409Conflict("user already exists: " + in.Body.Username)
}
@@ -212,7 +213,7 @@ func registerUsers(api huma.API) {
return nil, err
}
if _, ok, err := lookupUser(in.Username); err != nil {
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
return nil, huma.Error500InternalServerError("user lookup failed", err)
} else if !ok {
return nil, huma.Error404NotFound("user not found: " + in.Username)
}
@@ -253,7 +254,7 @@ func registerUsers(api huma.API) {
return nil, huma.Error400BadRequest("password may not contain newlines")
}
if _, ok, err := lookupUser(in.Username); err != nil {
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
return nil, huma.Error500InternalServerError("user lookup failed", err)
} else if !ok {
return nil, huma.Error404NotFound("user not found: " + in.Username)
}
@@ -261,6 +262,11 @@ func registerUsers(api huma.API) {
if _, err := oscmd.RunStdin(in.Username+":"+in.Body.Password+"\n", "chpasswd"); err != nil {
return nil, huma.Error500InternalServerError("chpasswd failed", err)
}
if sessions != nil {
if err := sessions.DeleteByUsername(in.Username); err != nil {
log.Printf("failed to invalidate sessions for %s: %v", in.Username, err)
}
}
return oscmd.OK(), nil
})
@@ -290,7 +296,7 @@ func registerUsers(api huma.API) {
}
}
if _, ok, err := lookupUser(in.Username); err != nil {
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
return nil, huma.Error500InternalServerError("user lookup failed", err)
} else if !ok {
return nil, huma.Error404NotFound("user not found: " + in.Username)
}
+1 -1
View File
@@ -28,7 +28,7 @@ func TestUsersHandlers(t *testing.T) {
mux := http.NewServeMux()
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
registerUsers(api)
registerUsers(api, nil)
// 1. Test GET /api/users
resp := api.Get("/api/users")
+29 -21
View File
@@ -28,26 +28,34 @@ short:x:2:2
}
func TestValidateUsername(t *testing.T) {
valid := []string{"alice", "_svc", "user-1", "a", "machine$", "abc_def"}
for _, n := range valid {
if err := validateUsername(n); err != nil {
t.Errorf("validateUsername(%q) = %v, want nil", n, err)
}
}
invalid := []string{
"", // empty
"-rf", // leading dash (flag injection)
"Alice", // uppercase
"1user", // leading digit
"a b", // space
"foo;rm", // shell metachar
"root:x", // colon (passwd separator)
"waytoolongusernamethatexceedsthirtytwochars", // >32
}
for _, n := range invalid {
if err := validateUsername(n); err == nil {
t.Errorf("validateUsername(%q) = nil, want error", n)
}
for _, n := range []struct {
name string
value string
valid bool
}{
{name: "alice", value: "alice", valid: true},
{name: "underscore prefix", value: "_svc", valid: true},
{name: "hyphen", value: "user-1", valid: true},
{name: "single char", value: "a", valid: true},
{name: "dollar suffix", value: "machine$", valid: true},
{name: "underscore", value: "abc_def", valid: true},
{name: "empty", value: "", valid: false},
{name: "leading dash", value: "-rf", valid: false},
{name: "uppercase", value: "Alice", valid: false},
{name: "leading digit", value: "1user", valid: false},
{name: "space", value: "a b", valid: false},
{name: "shell metachar", value: "foo;rm", valid: false},
{name: "colon", value: "root:x", valid: false},
{name: "too long", value: "waytoolongusernamethatexceedsthirtytwochars", valid: false},
} {
t.Run(n.name, func(t *testing.T) {
err := validateUsername(n.value)
if n.valid && err != nil {
t.Errorf("validateUsername(%q) = %v, want nil", n.value, err)
}
if !n.valid && err == nil {
t.Errorf("validateUsername(%q) = nil, want error", n.value)
}
})
}
}
+15 -9
View File
@@ -25,16 +25,22 @@ func TestParseProc(t *testing.T) {
}
func TestUnescape(t *testing.T) {
cases := map[string]string{
`/mnt/my\040disk`: "/mnt/my disk",
`/no/escapes`: "/no/escapes",
`tab\011here`: "tab\there",
`back\134slash`: `back\slash`,
tests := []struct {
name string
in string
want string
}{
{name: "octal space", in: `/mnt/my\040disk`, want: "/mnt/my disk"},
{name: "no escapes", in: `/no/escapes`, want: "/no/escapes"},
{name: "tab", in: `tab\011here`, want: "tab\there"},
{name: "backslash", in: `back\134slash`, want: `back\slash`},
}
for in, want := range cases {
if got := Unescape(in); got != want {
t.Errorf("Unescape(%q) = %q, want %q", in, got, want)
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Unescape(tt.in); got != tt.want {
t.Errorf("Unescape(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}
+10 -6
View File
@@ -14,14 +14,12 @@ import (
"nadir/internal/auth"
"nadir/internal/meta"
"nadir/internal/module"
"nadir/internal/modules/audit"
"nadir/internal/modules/groups"
"nadir/internal/modules/networking"
"nadir/internal/modules/packages"
"nadir/internal/modules/services"
"nadir/internal/modules/storage"
"nadir/internal/modules/system"
"nadir/internal/modules/terminal"
"nadir/internal/modules/users"
"nadir/internal/rbac"
@@ -29,6 +27,12 @@ import (
"github.com/danielgtaylor/huma/v2/adapters/humago"
)
type auditModule struct{}
func (auditModule) ID() string { return "audit" }
func (auditModule) Permissions() []rbac.Permission { return []rbac.Permission{rbac.Read} }
func (auditModule) Register(huma.API) {}
func TestOpenAPISchemaNoCollisions(t *testing.T) {
auditStore, err := auditlog.New(filepath.Join(t.TempDir(), "audit.db"))
if err != nil {
@@ -44,13 +48,12 @@ func TestOpenAPISchemaNoCollisions(t *testing.T) {
mods := []module.Module{
system.New(),
services.New(nil),
users.New(),
users.New(nil),
groups.New(),
packages.New(),
networking.New(),
storage.New(),
audit.New(auditStore),
terminal.New(sessions),
auditModule{},
}
mux := http.NewServeMux()
@@ -60,7 +63,8 @@ func TestOpenAPISchemaNoCollisions(t *testing.T) {
}
meta.Register(api, mods)
meta.RegisterHealth(api, sessions)
meta.RegisterWhoami(api, sessions, roles, mods)
meta.RegisterWhoami(api, sessions, nil, roles, mods)
meta.RegisterAudit(api, auditStore)
auth.RegisterLogin(api, sessions, auditStore, true)
auth.RegisterLogout(api, sessions, true)
+18
View File
@@ -14,6 +14,7 @@ import (
"os/exec"
"strings"
"sync"
"syscall"
"time"
)
@@ -276,6 +277,23 @@ func ParseKV(lines []string) map[string]string {
return m
}
// RunDetached starts name with args in a new process group (Setsid) and returns
// immediately once the child has started. The child is reaped in the background
// so it does not become a zombie.
//
// Use this for operations where the synchronous path would kill the caller
// (e.g. "systemctl restart nadir" would SIGTERM the process serving the
// request before the response is written).
func RunDetached(name string, args ...string) (*StatusOutput, error) {
cmd := exec.Command(name, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
if err := cmd.Start(); err != nil {
return nil, err
}
go cmd.Wait()
return OK(), nil
}
// StatusOutput is the shared response for write operations that just report
// success. Reusing one type means all such endpoints share a single OpenAPI
// schema.
+78 -70
View File
@@ -41,8 +41,6 @@ func TestRbacMiddleware(t *testing.T) {
},
})
r.AssignRole("alice", "test-role")
// A machine credential is just another RBAC subject: the token name is
// assigned a role exactly like a username.
r.AssignRole("dash", "test-role")
mux := http.NewServeMux()
@@ -76,81 +74,91 @@ func TestRbacMiddleware(t *testing.T) {
return &struct{ Body string }{Body: "gated-write"}, nil
})
// 1. Test public route
resp := api.Get("/public")
if resp.Code != http.StatusOK {
t.Errorf("public GET: got status %d, want %d", resp.Code, http.StatusOK)
}
t.Run("public route", func(t *testing.T) {
resp := api.Get("/public")
if resp.Code != http.StatusOK {
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
}
})
// 2. Test gated route without cookie -> 401 Unauthorized
resp = api.Get("/gated-read")
if resp.Code != http.StatusUnauthorized {
t.Errorf("gated GET no cookie: got status %d, want %d", resp.Code, http.StatusUnauthorized)
}
t.Run("no auth returns 401", func(t *testing.T) {
resp := api.Get("/gated-read")
if resp.Code != http.StatusUnauthorized {
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
}
})
// 3. Test gated route with invalid cookie -> 401 Unauthorized
resp = api.Get("/gated-read", "Cookie: nadir_session_id=invalid")
if resp.Code != http.StatusUnauthorized {
t.Errorf("gated GET invalid cookie: got status %d, want %d", resp.Code, http.StatusUnauthorized)
}
t.Run("invalid cookie returns 401", func(t *testing.T) {
resp := api.Get("/gated-read", "Cookie: nadir_session_id=invalid")
if resp.Code != http.StatusUnauthorized {
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
}
})
// Create valid session
token, err := sessions.Create("alice")
if err != nil {
t.Fatal(err)
}
var aliceToken string
t.Run("valid session returns 200", func(t *testing.T) {
var err error
aliceToken, err = sessions.Create("alice")
if err != nil {
t.Fatal(err)
}
resp := api.Get("/gated-read", "Cookie: nadir_session_id="+aliceToken)
if resp.Code != http.StatusOK {
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
}
})
// 4. Test gated route with valid cookie -> 200 OK
resp = api.Get("/gated-read", "Cookie: nadir_session_id="+token)
if resp.Code != http.StatusOK {
t.Errorf("gated GET valid cookie: got status %d, want %d", resp.Code, http.StatusOK)
}
t.Run("csrf mismatched origin returns 403", func(t *testing.T) {
resp := api.Post("/gated-write", "Cookie: nadir_session_id="+aliceToken, "Origin: http://evil.com", "Host: example.com", struct{}{})
if resp.Code != http.StatusForbidden {
t.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
}
})
// 5. Test CSRF violation: POST with mismatched Origin header -> 403 Forbidden
resp = api.Post("/gated-write", "Cookie: nadir_session_id="+token, "Origin: http://evil.com", "Host: example.com", struct{}{})
if resp.Code != http.StatusForbidden {
t.Errorf("CSRF mismatched Origin: got status %d, want %d", resp.Code, http.StatusForbidden)
}
t.Run("csrf matching origin returns 200", func(t *testing.T) {
resp := api.Post("/gated-write", "Cookie: nadir_session_id="+aliceToken, "Origin: http://example.com", "Host: example.com", struct{}{})
if resp.Code != http.StatusOK {
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
}
})
// 6. Test CSRF success: POST with matching Origin header -> 200 OK
resp = api.Post("/gated-write", "Cookie: nadir_session_id="+token, "Origin: http://example.com", "Host: example.com", struct{}{})
if resp.Code != http.StatusOK {
t.Errorf("CSRF matching Origin: got status %d, want %d", resp.Code, http.StatusOK)
}
t.Run("unauthorized user returns 403", func(t *testing.T) {
bobToken, err := sessions.Create("bob")
if err != nil {
t.Fatal(err)
}
resp := api.Get("/gated-read", "Cookie: nadir_session_id="+bobToken)
if resp.Code != http.StatusForbidden {
t.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
}
})
// 7. Test gated route with unauthorized user -> 403 Forbidden
tokenBob, err := sessions.Create("bob")
if err != nil {
t.Fatal(err)
}
resp = api.Get("/gated-read", "Cookie: nadir_session_id="+tokenBob)
if resp.Code != http.StatusForbidden {
t.Errorf("bob unauthorized GET: got status %d, want %d", resp.Code, http.StatusForbidden)
}
t.Run("valid bearer token returns 200", func(t *testing.T) {
rawToken, err := tokenStore.Create("dash")
if err != nil {
t.Fatal(err)
}
resp := api.Get("/gated-read", "Authorization: Bearer "+rawToken)
if resp.Code != http.StatusOK {
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
}
})
// 8. Bearer token for an assigned name -> 200 OK
rawToken, err := tokenStore.Create("dash")
if err != nil {
t.Fatal(err)
}
resp = api.Get("/gated-read", "Authorization: Bearer "+rawToken)
if resp.Code != http.StatusOK {
t.Errorf("valid bearer GET: got status %d, want %d", resp.Code, http.StatusOK)
}
t.Run("bogus bearer token returns 401", func(t *testing.T) {
resp := api.Get("/gated-read", "Authorization: Bearer nad_deadbeef")
if resp.Code != http.StatusUnauthorized {
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
}
})
// 9. Bogus bearer token -> 401 Unauthorized
resp = api.Get("/gated-read", "Authorization: Bearer nad_deadbeef")
if resp.Code != http.StatusUnauthorized {
t.Errorf("bogus bearer GET: got status %d, want %d", resp.Code, http.StatusUnauthorized)
}
// 10. Bearer token with no role assignment -> 403 Forbidden
rawUnassigned, err := tokenStore.Create("orphan")
if err != nil {
t.Fatal(err)
}
resp = api.Get("/gated-read", "Authorization: Bearer "+rawUnassigned)
if resp.Code != http.StatusForbidden {
t.Errorf("unassigned bearer GET: got status %d, want %d", resp.Code, http.StatusForbidden)
}
t.Run("unassigned bearer token returns 403", func(t *testing.T) {
rawUnassigned, err := tokenStore.Create("orphan")
if err != nil {
t.Fatal(err)
}
resp := api.Get("/gated-read", "Authorization: Bearer "+rawUnassigned)
if resp.Code != http.StatusForbidden {
t.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
}
})
}