Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0415e905af | |||
| d4364a6cb7 | |||
| 54108c263f | |||
| 37e5b97507 | |||
| 63c9a272b5 | |||
| 411f7fd6d9 | |||
| 8fc4b236ac | |||
| 37f03816e1 | |||
| 541260e65e | |||
| c4180bada1 | |||
| 088880f584 | |||
| 67d95475ee | |||
| aec04bfe02 | |||
| a54c42271c | |||
| b10abb24e3 | |||
| 9587d11e21 | |||
| ac196e720b | |||
| a106b7413f | |||
| 0e041fac5e | |||
| eba478471f |
@@ -10,13 +10,22 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0 # svu needs full history + tags
|
fetch-depth: 0
|
||||||
|
|
||||||
- uses: actions/setup-go@v5
|
- uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: '1.26'
|
go-version: "1.26"
|
||||||
cache: false
|
cache: false
|
||||||
|
|
||||||
|
- name: Install PAM headers (needed by go test)
|
||||||
|
run: sudo apt-get update && sudo apt-get install -y libpam0g-dev
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
run: |
|
||||||
|
set -ex
|
||||||
|
go vet ./...
|
||||||
|
go test ./...
|
||||||
|
|
||||||
- name: Install svu
|
- name: Install svu
|
||||||
timeout-minutes: 3
|
timeout-minutes: 3
|
||||||
run: |
|
run: |
|
||||||
@@ -87,6 +96,19 @@ jobs:
|
|||||||
go build -ldflags="$LDFLAGS" -o dist/nadir-$VERSION-linux-arm64 ./cmd/server
|
go build -ldflags="$LDFLAGS" -o dist/nadir-$VERSION-linux-arm64 ./cmd/server
|
||||||
upx --best --lzma dist/nadir-$VERSION-linux-amd64 dist/nadir-$VERSION-linux-arm64
|
upx --best --lzma dist/nadir-$VERSION-linux-amd64 dist/nadir-$VERSION-linux-arm64
|
||||||
|
|
||||||
|
- name: Sign checksums
|
||||||
|
if: steps.ver.outputs.release == 'true'
|
||||||
|
env:
|
||||||
|
MINISIGN_SECRET_KEY: ${{ secrets.MINISIGN_SECRET_KEY }}
|
||||||
|
MINISIGN_PASSWORD: ${{ secrets.MINISIGN_PASSWORD }}
|
||||||
|
run: |
|
||||||
|
set -ex
|
||||||
|
cd dist
|
||||||
|
sha256sum nadir-* > sha256sums.txt
|
||||||
|
cat sha256sums.txt
|
||||||
|
go run ../tools/sign-checksums sha256sums.txt
|
||||||
|
ls -la sha256sums.txt sha256sums.txt.minisig
|
||||||
|
|
||||||
- name: Tag and release
|
- name: Tag and release
|
||||||
if: steps.ver.outputs.release == 'true'
|
if: steps.ver.outputs.release == 'true'
|
||||||
env:
|
env:
|
||||||
|
|||||||
+3
-1
@@ -11,4 +11,6 @@ config.yml
|
|||||||
# Editor
|
# Editor
|
||||||
*.swp
|
*.swp
|
||||||
|
|
||||||
CLAUDE.md
|
CLAUDE.md
|
||||||
|
|
||||||
|
minisign.key
|
||||||
@@ -31,7 +31,6 @@ API and declares its own permission vocabulary.
|
|||||||
and upgrade - streamed live over SSE. Auto-detects `dnf`, `apt`, or `pacman`.
|
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.
|
||||||
- **Audit** - Read-only trail of every privileged write (who, what, when, result).
|
- **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`,
|
- **Meta** - Self-description for clients: `/api/_modules`, `/api/whoami`,
|
||||||
`/api/health`.
|
`/api/health`.
|
||||||
|
|
||||||
@@ -453,7 +452,6 @@ internal/modules concrete modules:
|
|||||||
packages - dnf/apt/pacman install/remove/upgrade (streamed)
|
packages - dnf/apt/pacman install/remove/upgrade (streamed)
|
||||||
audit - read-only audit trail
|
audit - read-only audit trail
|
||||||
networking - network interfaces, routing tables, DNS, and IP configurations
|
networking - network interfaces, routing tables, DNS, and IP configurations
|
||||||
terminal - interactive PTY shell over WebSocket
|
|
||||||
internal/oscmd shared command runner (timeouts, stderr surfacing) + helpers
|
internal/oscmd shared command runner (timeouts, stderr surfacing) + helpers
|
||||||
internal/rbac roles, permissions ("*" wildcards), HTTP middleware (RBAC + CSRF)
|
internal/rbac roles, permissions ("*" wildcards), HTTP middleware (RBAC + CSRF)
|
||||||
internal/audit SQLite-backed audit log writer
|
internal/audit SQLite-backed audit log writer
|
||||||
|
|||||||
@@ -28,3 +28,14 @@ var InstallScriptTemplate string
|
|||||||
// go build -ldflags "-X nadir.Version=v1.2.3"
|
// go build -ldflags "-X nadir.Version=v1.2.3"
|
||||||
// Local dev builds leave it as "dev".
|
// Local dev builds leave it as "dev".
|
||||||
var Version = "dev"
|
var Version = "dev"
|
||||||
|
|
||||||
|
// ReleasePublicKey is the minisign public key whose signature on a release's
|
||||||
|
// sha256sums.txt is required by the auto-updater. Replacing the binary is the
|
||||||
|
// most dangerous thing nadir does, so it gets the strongest verification: the
|
||||||
|
// updater downloads sha256sums.txt + .minisig from the configured Gitea repo,
|
||||||
|
// verifies the signature against this embedded key, then verifies the binary's
|
||||||
|
// sha256 against the file. Rotation requires a rebuild — intentional, so a
|
||||||
|
// compromised Gitea instance cannot also rotate the trust anchor.
|
||||||
|
//
|
||||||
|
//go:embed minisign.pub
|
||||||
|
var ReleasePublicKey string
|
||||||
|
|||||||
+117
-16
@@ -24,14 +24,12 @@ import (
|
|||||||
"nadir/internal/config"
|
"nadir/internal/config"
|
||||||
"nadir/internal/meta"
|
"nadir/internal/meta"
|
||||||
"nadir/internal/module"
|
"nadir/internal/module"
|
||||||
"nadir/internal/modules/audit"
|
|
||||||
"nadir/internal/modules/groups"
|
"nadir/internal/modules/groups"
|
||||||
"nadir/internal/modules/networking"
|
"nadir/internal/modules/networking"
|
||||||
"nadir/internal/modules/packages"
|
"nadir/internal/modules/packages"
|
||||||
"nadir/internal/modules/services"
|
"nadir/internal/modules/services"
|
||||||
"nadir/internal/modules/storage"
|
"nadir/internal/modules/storage"
|
||||||
"nadir/internal/modules/system"
|
"nadir/internal/modules/system"
|
||||||
"nadir/internal/modules/terminal"
|
|
||||||
"nadir/internal/modules/users"
|
"nadir/internal/modules/users"
|
||||||
"nadir/internal/rbac"
|
"nadir/internal/rbac"
|
||||||
|
|
||||||
@@ -39,6 +37,15 @@ import (
|
|||||||
"github.com/danielgtaylor/huma/v2/adapters/humago"
|
"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
|
// 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
|
// server; the rest manage nadir as a systemd service or tail its logs. Service
|
||||||
// plumbing lives in service.go, TLS in tls.go.
|
// plumbing lives in service.go, TLS in tls.go.
|
||||||
@@ -50,6 +57,8 @@ func main() {
|
|||||||
configFlag := fs.String("f", "", "config file path")
|
configFlag := fs.String("f", "", "config file path")
|
||||||
fs.StringVar(configFlag, "config", "", "alias for -f")
|
fs.StringVar(configFlag, "config", "", "alias for -f")
|
||||||
saveConfig := fs.Bool("save-config", false, "write default config and exit")
|
saveConfig := fs.Bool("save-config", false, "write default config and exit")
|
||||||
|
showVersion := fs.Bool("v", false, "print version and exit")
|
||||||
|
fs.BoolVar(showVersion, "version", false, "alias for -v")
|
||||||
|
|
||||||
rest := os.Args[1:]
|
rest := os.Args[1:]
|
||||||
var args []string
|
var args []string
|
||||||
@@ -61,6 +70,17 @@ func main() {
|
|||||||
}
|
}
|
||||||
args = append(args, rest[0])
|
args = append(args, rest[0])
|
||||||
rest = rest[1:]
|
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 {
|
||||||
|
fmt.Println(nadir.Version)
|
||||||
|
os.Exit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
if *configFlag != "" {
|
if *configFlag != "" {
|
||||||
@@ -74,7 +94,7 @@ func main() {
|
|||||||
fmt.Printf("configuration file already exists at %s\n", configPath)
|
fmt.Printf("configuration file already exists at %s\n", configPath)
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
}
|
}
|
||||||
fatalIf(saveDefaultConfig(configPath))
|
fatalIf(saveDefaultConfig(configPath, DefaultConfigContent(getUsername())))
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +109,7 @@ func main() {
|
|||||||
runCmd(args)
|
runCmd(args)
|
||||||
case "install":
|
case "install":
|
||||||
ensureRoot()
|
ensureRoot()
|
||||||
fatalIf(installService())
|
fatalIf(installService(args))
|
||||||
case "uninstall":
|
case "uninstall":
|
||||||
ensureRoot()
|
ensureRoot()
|
||||||
fatalIf(uninstallService(slices.Contains(args, "--complete")))
|
fatalIf(uninstallService(slices.Contains(args, "--complete")))
|
||||||
@@ -193,13 +213,12 @@ func runServer() {
|
|||||||
mods := []module.Module{
|
mods := []module.Module{
|
||||||
system.New(),
|
system.New(),
|
||||||
services.New(cfg.LogFiles),
|
services.New(cfg.LogFiles),
|
||||||
users.New(),
|
users.New(sessions),
|
||||||
groups.New(),
|
groups.New(),
|
||||||
packages.New(),
|
packages.New(),
|
||||||
networking.New(),
|
networking.New(),
|
||||||
storage.New(),
|
storage.New(),
|
||||||
audit.New(auditStore),
|
auditModule{},
|
||||||
terminal.New(sessions),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
roles := rbac.New()
|
roles := rbac.New()
|
||||||
@@ -223,6 +242,8 @@ func runServer() {
|
|||||||
humaConfig.DocsPath = ""
|
humaConfig.DocsPath = ""
|
||||||
|
|
||||||
api := humago.New(mux, humaConfig)
|
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))
|
api.UseMiddleware(rbac.RbacMiddleware(api, sessions, tokenAuth, roles, auditStore))
|
||||||
|
|
||||||
for _, m := range mods {
|
for _, m := range mods {
|
||||||
@@ -231,9 +252,9 @@ func runServer() {
|
|||||||
|
|
||||||
meta.Register(api, mods)
|
meta.Register(api, mods)
|
||||||
meta.RegisterHealth(api, sessions)
|
meta.RegisterHealth(api, sessions)
|
||||||
meta.RegisterWhoami(api, sessions, roles, mods)
|
meta.RegisterWhoami(api, sessions, tokenAuth, roles, mods)
|
||||||
meta.ConfigPath = configPath
|
meta.RegisterUpdate(api, configPath)
|
||||||
meta.RegisterUpdate(api)
|
meta.RegisterAudit(api, auditStore)
|
||||||
|
|
||||||
auth.RegisterLogin(api, sessions, auditStore, cfg.SecureCookie())
|
auth.RegisterLogin(api, sessions, auditStore, cfg.SecureCookie())
|
||||||
auth.RegisterLogout(api, sessions, cfg.SecureCookie())
|
auth.RegisterLogout(api, sessions, cfg.SecureCookie())
|
||||||
@@ -265,12 +286,24 @@ func runServer() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
mux.HandleFunc("GET /docs", func(w http.ResponseWriter, _ *http.Request) {
|
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 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.Header().Set("Content-Type", "text/html")
|
||||||
w.Write([]byte(`<!doctype html><html><head><title>API</title>
|
w.Write([]byte(`<!doctype html><html><head><title>API</title>
|
||||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg"></head>
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg"></head>
|
||||||
<body><script id="api-reference" data-url="/openapi.json" data-configuration='{"layout":"classic"}'></script>
|
<body><script id="api-reference" data-url="/openapi.json" data-configuration='{"layout":"classic"}'></script>
|
||||||
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script></body></html>`))
|
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference" crossorigin="anonymous"></script></body></html>`))
|
||||||
})
|
})
|
||||||
|
|
||||||
addr := cfg.Server.Hostname + ":" + cfg.Server.Port
|
addr := cfg.Server.Hostname + ":" + cfg.Server.Port
|
||||||
@@ -279,7 +312,7 @@ func runServer() {
|
|||||||
Addr: addr,
|
Addr: addr,
|
||||||
// WithClientIP records the source IP for the login throttle (H1); behind a
|
// 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.
|
// trusted proxy it reads X-Forwarded-For instead of the proxy's address.
|
||||||
Handler: auth.WithClientIP(cfg.Server.TrustProxy, mux),
|
Handler: bodySizeLimit(requestTimeout(secHeaders(auth.WithClientIP(cfg.Server.TrustProxy, mux)))),
|
||||||
ReadHeaderTimeout: 10 * time.Second,
|
ReadHeaderTimeout: 10 * time.Second,
|
||||||
ReadTimeout: 30 * time.Second,
|
ReadTimeout: 30 * time.Second,
|
||||||
WriteTimeout: 0, // unset: SSE endpoints stream indefinitely
|
WriteTimeout: 0, // unset: SSE endpoints stream indefinitely
|
||||||
@@ -289,14 +322,14 @@ func runServer() {
|
|||||||
// Pick how the connection is secured (see config.Server doc):
|
// Pick how the connection is secured (see config.Server doc):
|
||||||
// 1. trust_proxy - a reverse proxy terminates TLS; we serve plaintext HTTP.
|
// 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.
|
// 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
|
var serve func() error
|
||||||
switch {
|
switch {
|
||||||
case cfg.Server.TrustProxy:
|
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
|
serve = srv.ListenAndServe
|
||||||
default:
|
case cfg.Server.TLSCert != "" && cfg.Server.TLSKey != "":
|
||||||
cert, err := serverCert(cfg.Server.TLSCert, cfg.Server.TLSKey)
|
cert, err := tls.LoadX509KeyPair(cfg.Server.TLSCert, cfg.Server.TLSKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("tls cert: %v", err)
|
log.Fatalf("tls cert: %v", err)
|
||||||
}
|
}
|
||||||
@@ -307,8 +340,19 @@ func runServer() {
|
|||||||
srv.TLSConfig = &tls.Config{
|
srv.TLSConfig = &tls.Config{
|
||||||
Certificates: []tls.Certificate{cert},
|
Certificates: []tls.Certificate{cert},
|
||||||
MinVersion: tls.VersionTLS12,
|
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("", "") }
|
serve = func() error { return srv.ListenAndServeTLS("", "") }
|
||||||
|
default:
|
||||||
|
log.Printf("tls: no TLS configured — serving plain HTTP on %s", addr)
|
||||||
|
serve = srv.ListenAndServe
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
@@ -336,6 +380,63 @@ 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
|
||||||
|
// overrides it with a CDN-permissive policy because the Scalar bundle needs
|
||||||
|
// to execute.
|
||||||
|
//
|
||||||
|
// HSTS is set unconditionally: nadir always serves TLS directly or sits behind
|
||||||
|
// a TLS-terminating proxy (config rejects any other shape), so a browser
|
||||||
|
// receiving this header is on an HTTPS connection.
|
||||||
|
func secHeaders(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h := w.Header()
|
||||||
|
h.Set("X-Content-Type-Options", "nosniff")
|
||||||
|
h.Set("X-Frame-Options", "DENY")
|
||||||
|
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)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func ensureRoot() {
|
func ensureRoot() {
|
||||||
if os.Getuid() != 0 {
|
if os.Getuid() != 0 {
|
||||||
fatalIf(fmt.Errorf("nadir must run as root"))
|
fatalIf(fmt.Errorf("nadir must run as root"))
|
||||||
|
|||||||
+143
-27
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
@@ -13,26 +14,29 @@ import (
|
|||||||
"nadir/internal/config"
|
"nadir/internal/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
const defaultConfigTemplate = `# Nadir configuration - config.yaml
|
const configTemplateBase = `# Nadir configuration - config.yaml
|
||||||
#
|
#
|
||||||
# Single source of truth for runtime settings.
|
# Single source of truth for runtime settings.
|
||||||
#
|
#
|
||||||
|
|
||||||
server:
|
server:
|
||||||
secure_tls: true
|
secure_tls: %s
|
||||||
# trust_proxy: false
|
%s
|
||||||
# tls_cert: /etc/nadir/tls/cert.pem
|
%s
|
||||||
# tls_key: /etc/nadir/tls/key.pem
|
%s
|
||||||
hostname: 127.0.0.1
|
hostname: %s
|
||||||
port: 9999
|
port: %d
|
||||||
release_repo: https://tea.urania.dev/urania/nadir-agent
|
release_repo: https://tea.urania.dev/urania/nadir-agent
|
||||||
|
|
||||||
roles:
|
roles:
|
||||||
admin:
|
admin:
|
||||||
"*": ["*"]
|
"*": ["*"]
|
||||||
|
auditor:
|
||||||
|
"*": ["read"]
|
||||||
|
|
||||||
assignments:
|
assignments:
|
||||||
%s: [admin]
|
%s: [admin]
|
||||||
|
dashboard: [auditor]
|
||||||
`
|
`
|
||||||
|
|
||||||
// resolveConfigPath returns the config file path: CONFIG_PATH env (with ~ expanded)
|
// resolveConfigPath returns the config file path: CONFIG_PATH env (with ~ expanded)
|
||||||
@@ -101,7 +105,38 @@ const (
|
|||||||
// installService writes the systemd unit, enables it on boot, and starts it.
|
// 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
|
// The unit pins the absolute executable and config paths captured now, so the
|
||||||
// service doesn't depend on the working directory at boot.
|
// 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
|
||||||
|
|
||||||
// Provision the PAM service the server authenticates against, so it exists
|
// Provision the PAM service the server authenticates against, so it exists
|
||||||
// before the unit starts rather than appearing on first login. Idempotent:
|
// before the unit starts rather than appearing on first login. Idempotent:
|
||||||
// EnsurePAMService leaves an existing /etc/pam.d/nadir untouched. runServer
|
// EnsurePAMService leaves an existing /etc/pam.d/nadir untouched. runServer
|
||||||
@@ -130,14 +165,51 @@ func installService() error {
|
|||||||
return fmt.Errorf("create data directory: %w", err)
|
return fmt.Errorf("create data directory: %w", 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
cfgPath, err := resolveConfigPath()
|
cfgPath, err := resolveConfigPath()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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"
|
||||||
|
}
|
||||||
|
|
||||||
|
username := getUsername()
|
||||||
|
configContent := fmt.Sprintf(configTemplateBase, secureTLSVal, trustProxyLine, certLine, keyLine, *hostnameOpt, *portOpt, username)
|
||||||
|
|
||||||
// Ensure default config file exists
|
// Ensure default config file exists
|
||||||
if _, err := os.Stat(cfgPath); os.IsNotExist(err) {
|
if _, err := os.Stat(cfgPath); os.IsNotExist(err) {
|
||||||
if err := saveDefaultConfig(cfgPath); err != nil {
|
if err := saveDefaultConfig(cfgPath, configContent); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -182,6 +254,44 @@ WantedBy=multi-user.target
|
|||||||
fmt.Printf("created logrotate configuration %s\n", logrotatePath)
|
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))
|
fmt.Printf("installed and started %s; follow logs with: %s logs\n", serviceName, filepath.Base(exe))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -393,21 +503,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.
|
// saveDefaultConfig writes the default configuration template to cfgPath.
|
||||||
func saveDefaultConfig(cfgPath string) error {
|
func saveDefaultConfig(cfgPath, content string) error {
|
||||||
dir := filepath.Dir(cfgPath)
|
dir := filepath.Dir(cfgPath)
|
||||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
return fmt.Errorf("create config directory: %w", err)
|
return fmt.Errorf("create config directory: %w", err)
|
||||||
}
|
}
|
||||||
chownToSudoUser(dir)
|
chownToSudoUser(dir)
|
||||||
|
|
||||||
username := getUsername()
|
if err := os.WriteFile(cfgPath, []byte(content), 0600); err != nil {
|
||||||
configContent := fmt.Sprintf(defaultConfigTemplate, username)
|
|
||||||
if err := os.WriteFile(cfgPath, []byte(configContent), 0600); err != nil {
|
|
||||||
return fmt.Errorf("write default config: %w", err)
|
return fmt.Errorf("write default config: %w", err)
|
||||||
}
|
}
|
||||||
chownToSudoUser(cfgPath)
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -415,19 +528,22 @@ func usage(w io.Writer) {
|
|||||||
fmt.Fprint(w, `nadir - Linux system administration backend
|
fmt.Fprint(w, `nadir - Linux system administration backend
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
nadir [run] [-d] [-f <path>] Start the server (-d / --detach: run in background)
|
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 --save-config [-f <path>] Save default configuration to path and exit
|
||||||
nadir install [-f <path>] Install + enable the systemd service (starts on boot)
|
nadir install [--tls|--unsecure|--trust-proxy] Install + enable the systemd service (starts on boot)
|
||||||
nadir uninstall [--complete] Remove the service (keeps data/config; --complete wipes all)
|
(--tls: enable HTTPS with self-signed certificate)
|
||||||
nadir start|stop|restart|status Control the running service
|
(--unsecure: serve HTTP directly, default)
|
||||||
nadir enable|disable Toggle start-on-boot without removing the unit
|
(--trust-proxy: serve HTTP behind a reverse proxy)
|
||||||
nadir logs [clear] Follow (default) or clear server logs
|
nadir uninstall [--complete] Remove the service (keeps data/config; --complete wipes all)
|
||||||
nadir token add <name> Mint a machine credential (Bearer token), shown once
|
nadir start|stop|restart|status Control the running service
|
||||||
nadir token rm <name> Revoke a token (effective immediately, no restart)
|
nadir enable|disable Toggle start-on-boot without removing the unit
|
||||||
nadir token ls List token names and when they were created
|
nadir logs [clear] Follow (default) or clear server logs
|
||||||
nadir update [--check|--force] Fetch the latest release from server.release_repo and restart
|
nadir token add <name> Mint a machine credential (Bearer token), shown once
|
||||||
(--check: report only; --force: re-download when already current)
|
nadir token rm <name> Revoke a token (effective immediately, no restart)
|
||||||
nadir help Show this help
|
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).
|
Most commands need root. Config path is specified via -f/--config or CONFIG_PATH (default ~/.config/config.yaml).
|
||||||
`)
|
`)
|
||||||
|
|||||||
+56
-24
@@ -1,46 +1,36 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"crypto/rsa"
|
|
||||||
"crypto/tls"
|
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
"crypto/x509/pkix"
|
"crypto/x509/pkix"
|
||||||
"log"
|
"encoding/pem"
|
||||||
"math/big"
|
"math/big"
|
||||||
"net"
|
"net"
|
||||||
|
"os"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// serverCert returns the TLS certificate to serve: the admin-supplied PEM pair
|
// generateAndSaveCert generates a self-signed certificate and private key,
|
||||||
// when both paths are set, otherwise a freshly generated in-memory self-signed
|
// and saves them as PEM files.
|
||||||
// cert for local development.
|
func generateAndSaveCert(certPath, keyPath string, hostname string) error {
|
||||||
func serverCert(certPath, keyPath string) (tls.Certificate, error) {
|
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
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) {
|
|
||||||
priv, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
||||||
if err != nil {
|
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))
|
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return tls.Certificate{}, err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
template := x509.Certificate{
|
template := x509.Certificate{
|
||||||
SerialNumber: serial,
|
SerialNumber: serial,
|
||||||
Subject: pkix.Name{Organization: []string{"nadir-dev-local"}},
|
Subject: pkix.Name{Organization: []string{"nadir-agent-tls"}},
|
||||||
NotBefore: time.Now(),
|
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,
|
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
||||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
BasicConstraintsValid: true,
|
BasicConstraintsValid: true,
|
||||||
@@ -48,9 +38,51 @@ func generateSelfSignedCert() (tls.Certificate, error) {
|
|||||||
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback},
|
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)
|
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
|
||||||
if err != nil {
|
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
|
||||||
}
|
}
|
||||||
|
|||||||
+136
-3
@@ -1,6 +1,8 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -15,10 +17,13 @@ import (
|
|||||||
|
|
||||||
"nadir"
|
"nadir"
|
||||||
"nadir/internal/config"
|
"nadir/internal/config"
|
||||||
|
|
||||||
|
"github.com/jedisct1/go-minisign"
|
||||||
)
|
)
|
||||||
|
|
||||||
// updateCmd implements `nadir update`: hit the configured Gitea repo's
|
// updateCmd implements `nadir update`: hit the configured Gitea repo's
|
||||||
// releases/latest, pick the asset for the host's GOARCH, atomically replace
|
// releases/latest, pick the asset for the host's GOARCH, verify the release
|
||||||
|
// signature (minisign) and checksum (SHA-256), atomically replace
|
||||||
// /usr/local/bin/nadir (or wherever the running binary lives), and restart
|
// /usr/local/bin/nadir (or wherever the running binary lives), and restart
|
||||||
// the systemd unit so the new code takes effect.
|
// the systemd unit so the new code takes effect.
|
||||||
func updateCmd(args []string) error {
|
func updateCmd(args []string) error {
|
||||||
@@ -66,16 +71,25 @@ func updateCmd(args []string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Locate the binary asset and the two verification assets in the release.
|
||||||
var assetURL, assetName string
|
var assetURL, assetName string
|
||||||
|
var sumsURL, sigURL string
|
||||||
for _, a := range rel.Assets {
|
for _, a := range rel.Assets {
|
||||||
if strings.HasSuffix(a.Name, suffix) {
|
switch {
|
||||||
|
case strings.HasSuffix(a.Name, suffix):
|
||||||
assetURL, assetName = a.URL, a.Name
|
assetURL, assetName = a.URL, a.Name
|
||||||
break
|
case a.Name == "sha256sums.txt":
|
||||||
|
sumsURL = a.URL
|
||||||
|
case a.Name == "sha256sums.txt.minisig":
|
||||||
|
sigURL = a.URL
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if assetURL == "" {
|
if assetURL == "" {
|
||||||
return fmt.Errorf("no %s asset in release %s", suffix, rel.TagName)
|
return fmt.Errorf("no %s asset in release %s", suffix, rel.TagName)
|
||||||
}
|
}
|
||||||
|
if sumsURL == "" || sigURL == "" {
|
||||||
|
return fmt.Errorf("release %s is missing sha256sums.txt or sha256sums.txt.minisig — cannot verify; refusing to install an unverified binary", rel.TagName)
|
||||||
|
}
|
||||||
|
|
||||||
exe, err := os.Executable()
|
exe, err := os.Executable()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -88,6 +102,15 @@ func updateCmd(args []string) error {
|
|||||||
os.Remove(tmp)
|
os.Remove(tmp)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Verify: download checksums + signature, check minisign, check SHA-256.
|
||||||
|
fmt.Println("verifying release signature ...")
|
||||||
|
if err := verifyRelease(tmp, assetName, sumsURL, sigURL); err != nil {
|
||||||
|
os.Remove(tmp)
|
||||||
|
return fmt.Errorf("verification failed: %w", err)
|
||||||
|
}
|
||||||
|
fmt.Println("signature and checksum OK.")
|
||||||
|
|
||||||
// Atomic on the same filesystem; replaces the on-disk file without
|
// Atomic on the same filesystem; replaces the on-disk file without
|
||||||
// disturbing the still-running process (its inode stays alive).
|
// disturbing the still-running process (its inode stays alive).
|
||||||
if err := os.Rename(tmp, exe); err != nil {
|
if err := os.Rename(tmp, exe); err != nil {
|
||||||
@@ -103,6 +126,113 @@ func updateCmd(args []string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// verifyRelease downloads sha256sums.txt + its minisig from the release,
|
||||||
|
// verifies the signature against the embedded public key, then checks the
|
||||||
|
// downloaded binary's SHA-256 against the matching line in the checksums file.
|
||||||
|
func verifyRelease(binaryPath, assetName, sumsURL, sigURL string) error {
|
||||||
|
// Parse the embedded public key. The placeholder file will fail here
|
||||||
|
// (no valid base64 line), which is the desired behavior: updates are
|
||||||
|
// disabled until a real key is committed.
|
||||||
|
pubKey, err := minisign.DecodePublicKey(nadir.ReleasePublicKey)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("embedded minisign public key is invalid (is minisign.pub still the placeholder?): %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Download the checksums file and its signature.
|
||||||
|
sumsBody, err := downloadBytes(sumsURL)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("download sha256sums.txt: %w", err)
|
||||||
|
}
|
||||||
|
sigBody, err := downloadBytes(sigURL)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("download sha256sums.txt.minisig: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify the minisign signature on the checksums file.
|
||||||
|
sig, err := minisign.DecodeSignature(string(sigBody))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("decode minisig: %w", err)
|
||||||
|
}
|
||||||
|
ok, err := pubKey.Verify(sumsBody, sig)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("minisign verify: %w", err)
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("minisign signature is not valid for this sha256sums.txt")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find the expected hash for our binary in the signed checksums file.
|
||||||
|
expectedHash, err := findChecksum(string(sumsBody), assetName)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash the downloaded binary and compare.
|
||||||
|
actualHash, err := sha256File(binaryPath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("hash downloaded binary: %w", err)
|
||||||
|
}
|
||||||
|
if actualHash != expectedHash {
|
||||||
|
return fmt.Errorf("SHA-256 mismatch for %s: expected %s, got %s", assetName, expectedHash, actualHash)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// findChecksum parses a sha256sums.txt body (one "hash filename\n" per line)
|
||||||
|
// and returns the hex hash for the named asset.
|
||||||
|
func findChecksum(sums, assetName string) (string, error) {
|
||||||
|
for _, line := range strings.Split(sums, "\n") {
|
||||||
|
line = strings.TrimSpace(line)
|
||||||
|
if line == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Standard sha256sum output: "<hex> <filename>" (two spaces).
|
||||||
|
parts := strings.SplitN(line, " ", 2)
|
||||||
|
if len(parts) != 2 {
|
||||||
|
// Also accept single-space separation.
|
||||||
|
parts = strings.SplitN(line, " ", 2)
|
||||||
|
}
|
||||||
|
if len(parts) == 2 && strings.TrimSpace(parts[1]) == assetName {
|
||||||
|
h := strings.TrimSpace(parts[0])
|
||||||
|
if len(h) != 64 {
|
||||||
|
return "", fmt.Errorf("sha256sums.txt: invalid hash length for %s: %q", assetName, h)
|
||||||
|
}
|
||||||
|
return strings.ToLower(h), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("sha256sums.txt does not contain a hash for %s", assetName)
|
||||||
|
}
|
||||||
|
|
||||||
|
// sha256File returns the lowercase hex SHA-256 of the file at path.
|
||||||
|
func sha256File(path string) (string, error) {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
h := sha256.New()
|
||||||
|
if _, err := io.Copy(h, f); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(h.Sum(nil)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// downloadBytes fetches a URL and returns its body as a byte slice (for small
|
||||||
|
// files like sha256sums.txt and .minisig).
|
||||||
|
func downloadBytes(srcURL string) ([]byte, error) {
|
||||||
|
c := &http.Client{Timeout: 30 * time.Second}
|
||||||
|
resp, err := c.Get(srcURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("GET %s: %s", srcURL, resp.Status)
|
||||||
|
}
|
||||||
|
// Cap read to 1 MB — sha256sums.txt and .minisig are tiny.
|
||||||
|
return io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||||
|
}
|
||||||
|
|
||||||
type giteaRelease struct {
|
type giteaRelease struct {
|
||||||
TagName string `json:"tag_name"`
|
TagName string `json:"tag_name"`
|
||||||
Assets []struct {
|
Assets []struct {
|
||||||
@@ -136,6 +266,9 @@ func releaseAPIURL(repoURL string) (string, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("release_repo: %w", err)
|
return "", fmt.Errorf("release_repo: %w", err)
|
||||||
}
|
}
|
||||||
|
if u.Scheme != "https" {
|
||||||
|
return "", fmt.Errorf("release_repo must use https:// (got %q) — auto-update downloads and executes the binary, plaintext would let any on-path attacker replace it", repoURL)
|
||||||
|
}
|
||||||
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
|
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
|
||||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||||
return "", fmt.Errorf("release_repo must look like https://host/owner/repo, got %q", repoURL)
|
return "", fmt.Errorf("release_repo must look like https://host/owner/repo, got %q", repoURL)
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestReleaseAPIURL pins the contract that downstream code (the updater and
|
||||||
|
// /install.sh) relies on: only https://host/owner/repo produces an API URL,
|
||||||
|
// everything else errors. Plain HTTP must be rejected — M7 makes auto-update
|
||||||
|
// only trust TLS-protected release feeds, since the binary it downloads is
|
||||||
|
// exec'd as root.
|
||||||
|
func TestReleaseAPIURL(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
in string
|
||||||
|
want string
|
||||||
|
wantErr string // substring expected in the error message; "" means success
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "valid https repo",
|
||||||
|
in: "https://tea.example.com/owner/repo",
|
||||||
|
want: "https://tea.example.com/api/v1/repos/owner/repo/releases/latest",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "http rejected",
|
||||||
|
in: "http://tea.example.com/owner/repo",
|
||||||
|
wantErr: "https",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "ssh scheme rejected",
|
||||||
|
in: "ssh://tea.example.com/owner/repo",
|
||||||
|
wantErr: "https",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing repo segment",
|
||||||
|
in: "https://tea.example.com/owner",
|
||||||
|
wantErr: "owner/repo",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "extra path segments",
|
||||||
|
in: "https://tea.example.com/owner/repo/extra",
|
||||||
|
wantErr: "owner/repo",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty",
|
||||||
|
in: "",
|
||||||
|
wantErr: "https",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got, err := releaseAPIURL(tt.in)
|
||||||
|
if tt.wantErr == "" {
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("got %q, want %q", got, tt.want)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("expected error containing %q, got nil (result %q)", tt.wantErr, got)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||||
|
t.Errorf("error %q does not contain %q", err.Error(), tt.wantErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,17 +9,18 @@ require github.com/danielgtaylor/huma/v2 v2.38.0
|
|||||||
require (
|
require (
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
modernc.org/sqlite v1.52.0
|
modernc.org/sqlite v1.52.0
|
||||||
github.com/coder/websocket v1.8.15
|
|
||||||
github.com/creack/pty v1.1.24
|
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
aead.dev/minisign v0.3.0
|
||||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||||
github.com/google/uuid v1.6.0 // 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 // indirect
|
||||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
golang.org/x/sys v0.43.0 // indirect
|
golang.org/x/crypto v0.52.0 // indirect
|
||||||
|
golang.org/x/sys v0.45.0 // indirect
|
||||||
modernc.org/libc v1.72.3 // indirect
|
modernc.org/libc v1.72.3 // indirect
|
||||||
modernc.org/mathutil v1.7.1 // indirect
|
modernc.org/mathutil v1.7.1 // indirect
|
||||||
modernc.org/memory v1.11.0 // indirect
|
modernc.org/memory v1.11.0 // indirect
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
|
aead.dev/minisign v0.3.0 h1:8Xafzy5PEVZqYDNP60yJHARlW1eOQtsKNp/Ph2c0vRA=
|
||||||
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
aead.dev/minisign v0.3.0/go.mod h1:NLvG3Uoq3skkRMDuc3YHpWUTMTrSExqm+Ij73W13F6Y=
|
||||||
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 h1:fb0WZCatnaiHLphMQDDWDjygNxfMkX/ENma3QsRl7vY=
|
||||||
github.com/danielgtaylor/huma/v2 v2.38.0/go.mod h1:k9hwjlgWFt1t2jsmQGlsgXAG2FBTZa4kkjV581qAtfo=
|
github.com/danielgtaylor/huma/v2 v2.38.0/go.mod h1:k9hwjlgWFt1t2jsmQGlsgXAG2FBTZa4kkjV581qAtfo=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
@@ -16,6 +14,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
|||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||||
|
github.com/jedisct1/go-minisign v0.0.0-20260527172527-a09352b57a22 h1:C68TAi+k12EKJCAmsdaERzQ22ZxVE6n+CuB3kOkhQ7c=
|
||||||
|
github.com/jedisct1/go-minisign v0.0.0-20260527172527-a09352b57a22/go.mod h1:vYVVh81Lqe/TP0sPLjiNYcX9Hxy/YSfkUx96lYJeyKo=
|
||||||
github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs=
|
github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs=
|
||||||
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||||
github.com/msteinert/pam v1.2.0 h1:mYfjlvN2KYs2Pb9G6nb/1f/nPfAttT/Jee5Sq9r3bGE=
|
github.com/msteinert/pam v1.2.0 h1:mYfjlvN2KYs2Pb9G6nb/1f/nPfAttT/Jee5Sq9r3bGE=
|
||||||
@@ -30,14 +30,16 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
|
|||||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||||
|
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
|
||||||
|
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
|
||||||
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
|
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
|
||||||
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
|
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
|
||||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
|
||||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=
|
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
||||||
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
|
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
||||||
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
||||||
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
|
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
|
|||||||
@@ -60,6 +60,40 @@ do_install() {
|
|||||||
|
|
||||||
echo "downloading $asset_url ..."
|
echo "downloading $asset_url ..."
|
||||||
curl -f --progress-bar -L "$asset_url" -o /usr/local/bin/nadir.tmp
|
curl -f --progress-bar -L "$asset_url" -o /usr/local/bin/nadir.tmp
|
||||||
|
|
||||||
|
asset_name=$(basename "$asset_url")
|
||||||
|
|
||||||
|
# Verify SHA-256: download the checksums file published alongside the binary
|
||||||
|
# and confirm the hash matches. This catches CDN corruption and (together with
|
||||||
|
# the HTTPS transport) makes tampered binaries detectable.
|
||||||
|
sums_url="$host/api/v1/repos/$path/releases/latest"
|
||||||
|
sums_asset_url=$(curl -fsSL "$sums_url" \
|
||||||
|
| grep -o '"browser_download_url":"[^"]*sha256sums\.txt"' \
|
||||||
|
| head -n1 \
|
||||||
|
| cut -d'"' -f4)
|
||||||
|
|
||||||
|
if [ -n "$sums_asset_url" ]; then
|
||||||
|
echo "verifying checksum ..."
|
||||||
|
curl -fsSL "$sums_asset_url" -o /tmp/nadir-sha256sums.txt
|
||||||
|
# Extract the expected hash for our asset and compare.
|
||||||
|
expected=$(grep "$asset_name" /tmp/nadir-sha256sums.txt | awk '{print $1}')
|
||||||
|
actual=$(sha256sum /usr/local/bin/nadir.tmp | awk '{print $1}')
|
||||||
|
rm -f /tmp/nadir-sha256sums.txt
|
||||||
|
if [ -z "$expected" ]; then
|
||||||
|
echo "warning: sha256sums.txt does not contain a hash for $asset_name" >&2
|
||||||
|
echo "proceeding without verification" >&2
|
||||||
|
elif [ "$expected" != "$actual" ]; then
|
||||||
|
echo "SHA-256 MISMATCH: expected $expected, got $actual" >&2
|
||||||
|
echo "the downloaded binary may be corrupted or tampered with — aborting" >&2
|
||||||
|
rm -f /usr/local/bin/nadir.tmp
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
echo "checksum OK ($actual)"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "warning: no sha256sums.txt in release — skipping verification" >&2
|
||||||
|
fi
|
||||||
|
|
||||||
mv /usr/local/bin/nadir.tmp /usr/local/bin/nadir
|
mv /usr/local/bin/nadir.tmp /usr/local/bin/nadir
|
||||||
chmod +x /usr/local/bin/nadir
|
chmod +x /usr/local/bin/nadir
|
||||||
|
|
||||||
|
|||||||
+23
-11
@@ -3,6 +3,7 @@ package auth
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"regexp"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"nadir/internal/auditlog"
|
"nadir/internal/auditlog"
|
||||||
@@ -10,6 +11,11 @@ import (
|
|||||||
"github.com/danielgtaylor/huma/v2"
|
"github.com/danielgtaylor/huma/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 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
|
||||||
|
// 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
|
// authenticator verifies a username/password (PAM in production). It's a field
|
||||||
// of the login handler rather than a package global so tests can inject a stub
|
// of the login handler rather than a package global so tests can inject a stub
|
||||||
// without mutating shared state.
|
// without mutating shared state.
|
||||||
@@ -37,8 +43,9 @@ type LoginOutput struct {
|
|||||||
// development over plain HTTP, where a Secure cookie would never be sent back.
|
// 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) {
|
func RegisterLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store, secure bool) {
|
||||||
// loginThrottle blunts brute force: 5 failures for a username+source IP
|
// loginThrottle blunts brute force: 5 failures for a username+source IP
|
||||||
// trigger a one-minute cooldown. See throttle.go for the ceiling/upgrade path.
|
// trigger a one-minute cooldown. Persisted in SQLite so cooldowns survive
|
||||||
registerLogin(api, sessions, auditor, secure, Authenticate, newFailLimiter(5, time.Minute))
|
// 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) {
|
func registerLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store, secure bool, authenticate authenticator, throttle *failLimiter) {
|
||||||
@@ -53,6 +60,11 @@ func registerLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store
|
|||||||
Tags: []string{"Authentication"},
|
Tags: []string{"Authentication"},
|
||||||
Errors: []int{401, 429},
|
Errors: []int{401, 429},
|
||||||
}, func(ctx context.Context, in *LoginInput) (*LoginOutput, error) {
|
}, func(ctx context.Context, in *LoginInput) (*LoginOutput, error) {
|
||||||
|
// Reject malformed usernames at the trust boundary so PAM, su, and the
|
||||||
|
// audit log never see flag-like or shell-metacharacter input.
|
||||||
|
if !loginNameRe.MatchString(in.Body.Username) {
|
||||||
|
return nil, huma.Error401Unauthorized("invalid credentials")
|
||||||
|
}
|
||||||
// Throttle brute force: too many recent failures for this account/source
|
// Throttle brute force: too many recent failures for this account/source
|
||||||
// put it in a short cooldown before the password is even checked.
|
// put it in a short cooldown before the password is even checked.
|
||||||
throttleKey := in.Body.Username + "|" + ClientIP(ctx)
|
throttleKey := in.Body.Username + "|" + ClientIP(ctx)
|
||||||
@@ -74,15 +86,15 @@ func registerLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store
|
|||||||
return nil, huma.Error500InternalServerError("could not create session", err)
|
return nil, huma.Error500InternalServerError("could not create session", err)
|
||||||
}
|
}
|
||||||
out := &LoginOutput{
|
out := &LoginOutput{
|
||||||
SetCookie: http.Cookie{
|
SetCookie: http.Cookie{
|
||||||
Name: "nadir_session_id",
|
Name: "nadir_session_id",
|
||||||
Value: sessionID,
|
Value: sessionID,
|
||||||
Path: "/",
|
Path: "/",
|
||||||
HttpOnly: true,
|
HttpOnly: true,
|
||||||
Secure: secure,
|
Secure: secure,
|
||||||
SameSite: http.SameSiteStrictMode,
|
SameSite: http.SameSiteStrictMode,
|
||||||
Expires: time.Now().Add(24 * time.Hour),
|
MaxAge: 86400,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
out.Body.Status = "logged in"
|
out.Body.Status = "logged in"
|
||||||
return out, nil
|
return out, nil
|
||||||
|
|||||||
+78
-82
@@ -68,110 +68,106 @@ func TestLoginLogoutThrottling(t *testing.T) {
|
|||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
|
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 {
|
authMock := func(username, password string) error {
|
||||||
if password == "correct" {
|
if password == "correct" {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return errors.New("pam error")
|
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)
|
RegisterLogout(api, sessions, false)
|
||||||
|
|
||||||
// 1. Test failed login
|
t.Run("failed login returns 401", func(t *testing.T) {
|
||||||
resp := api.Post("/api/login", struct {
|
resp := api.Post("/api/login", struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
}{
|
}{
|
||||||
Username: "admin",
|
Username: "admin",
|
||||||
Password: "wrong",
|
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
|
var sessionID string
|
||||||
parts := strings.SplitSeq(cookieHeader, ";")
|
t.Run("successful login returns session cookie", func(t *testing.T) {
|
||||||
for part := range parts {
|
resp := api.Post("/api/login", struct {
|
||||||
part = strings.TrimSpace(part)
|
Username string `json:"username"`
|
||||||
if after, ok := strings.CutPrefix(part, "nadir_session_id="); ok {
|
Password string `json:"password"`
|
||||||
sessionID = after
|
}{
|
||||||
break
|
Username: "admin",
|
||||||
|
Password: "correct",
|
||||||
|
})
|
||||||
|
if resp.Code != http.StatusOK {
|
||||||
|
t.Fatalf("got code %d, want %d", resp.Code, http.StatusOK)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if sessionID == "" {
|
cookieHeader := resp.Header().Get("Set-Cookie")
|
||||||
t.Fatal("nadir_session_id cookie not found")
|
if !strings.Contains(cookieHeader, "nadir_session_id=") {
|
||||||
}
|
t.Fatalf("Set-Cookie header missing nadir_session_id: %q", cookieHeader)
|
||||||
|
}
|
||||||
|
|
||||||
_, ok := sessions.GetByToken(sessionID)
|
parts := strings.SplitSeq(cookieHeader, ";")
|
||||||
if !ok {
|
for part := range parts {
|
||||||
t.Fatal("session not found in session store")
|
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
|
t.Run("logout invalidates session", func(t *testing.T) {
|
||||||
resp = api.Post("/api/logout", "Cookie: nadir_session_id="+sessionID, struct{}{})
|
resp := api.Post("/api/logout", "Cookie: nadir_session_id="+sessionID, struct{}{})
|
||||||
if resp.Code != http.StatusOK {
|
if resp.Code != http.StatusOK {
|
||||||
t.Errorf("logout failed: got code %d, want %d", 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)
|
t.Run("throttling blocks after 3 failures", func(t *testing.T) {
|
||||||
if ok {
|
for range 3 {
|
||||||
t.Fatal("session still valid after logout")
|
api.Post("/api/login", struct {
|
||||||
}
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
// 4. Test throttling (the handler was registered with a 3-failure limiter).
|
}{
|
||||||
for range 3 {
|
Username: "throttled-user",
|
||||||
api.Post("/api/login", struct {
|
Password: "wrong",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
resp := api.Post("/api/login", struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
}{
|
}{
|
||||||
Username: "throttled-user",
|
Username: "throttled-user",
|
||||||
Password: "wrong",
|
Password: "correct",
|
||||||
})
|
})
|
||||||
}
|
if resp.Code != http.StatusTooManyRequests {
|
||||||
|
t.Errorf("got code %d, want %d", resp.Code, http.StatusTooManyRequests)
|
||||||
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("throttled login: got code %d, want %d", resp.Code, http.StatusTooManyRequests)
|
|
||||||
}
|
|
||||||
|
|
||||||
time.Sleep(600 * time.Millisecond)
|
t.Run("throttle reset allows login", func(t *testing.T) {
|
||||||
|
throttle.reset("throttled-user|")
|
||||||
resp = api.Post("/api/login", struct {
|
resp := api.Post("/api/login", struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
}{
|
}{
|
||||||
Username: "throttled-user",
|
Username: "throttled-user",
|
||||||
Password: "correct",
|
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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -12,7 +13,7 @@ import (
|
|||||||
_ "modernc.org/sqlite"
|
_ "modernc.org/sqlite"
|
||||||
)
|
)
|
||||||
|
|
||||||
const sessionTTL = 24 * time.Hour
|
var sessionTTL = 24 * time.Hour
|
||||||
|
|
||||||
type Session struct {
|
type Session struct {
|
||||||
Username string
|
Username string
|
||||||
@@ -45,6 +46,17 @@ func NewSessionStore(path string) (*SessionStore, error) {
|
|||||||
)`); err != nil {
|
)`); err != nil {
|
||||||
return nil, fmt.Errorf("create sessions table: %w", err)
|
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
|
return &SessionStore{db: db}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,7 +69,7 @@ func (s *SessionStore) Create(username string) (string, error) {
|
|||||||
expires := time.Now().Add(sessionTTL)
|
expires := time.Now().Add(sessionTTL)
|
||||||
if _, err := s.db.Exec(
|
if _, err := s.db.Exec(
|
||||||
`INSERT INTO sessions (token, username, expires_at) VALUES (?, ?, ?)`,
|
`INSERT INTO sessions (token, username, expires_at) VALUES (?, ?, ?)`,
|
||||||
token, username, expires.Unix(),
|
hashSessionToken(token), username, expires.Unix(),
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@@ -67,26 +79,75 @@ func (s *SessionStore) Create(username string) (string, error) {
|
|||||||
// Delete removes a session, invalidating it immediately (logout). Deleting an
|
// Delete removes a session, invalidating it immediately (logout). Deleting an
|
||||||
// unknown token is a no-op.
|
// unknown token is a no-op.
|
||||||
func (s *SessionStore) Delete(token string) error {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *SessionStore) GetByToken(token string) (Session, bool) {
|
func (s *SessionStore) GetByToken(token string) (Session, bool) {
|
||||||
var username string
|
var username string
|
||||||
var expires int64
|
var expires int64
|
||||||
|
h := hashSessionToken(token)
|
||||||
err := s.db.QueryRow(
|
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)
|
).Scan(&username, &expires)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Session{}, false
|
return Session{}, false
|
||||||
}
|
}
|
||||||
if time.Now().Unix() > expires {
|
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{}, false
|
||||||
}
|
}
|
||||||
return Session{Username: username}, true
|
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 {
|
func randomToken() string {
|
||||||
b := make([]byte, 32)
|
b := make([]byte, 32)
|
||||||
rand.Read(b) // never fails; rand.Read panics internally on misconfigured platforms.
|
rand.Read(b) // never fails; rand.Read panics internally on misconfigured platforms.
|
||||||
|
|||||||
@@ -34,22 +34,21 @@ func TestExpiredSessionRejected(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
// Write a row that expired an hour ago, bypassing Create's TTL.
|
// Create a session with an already-expired TTL (-2s ensures the Unix
|
||||||
_, err = store.db.Exec(
|
// second-rounded timestamp is safely in the past).
|
||||||
`INSERT INTO sessions (token, username, expires_at) VALUES (?, ?, ?)`,
|
oldTTL := sessionTTL
|
||||||
"stale", "urania", time.Now().Add(-time.Hour).Unix(),
|
sessionTTL = -2 * time.Second
|
||||||
)
|
token, err := store.Create("urania")
|
||||||
|
sessionTTL = oldTTL
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if _, ok := store.GetByToken("stale"); ok {
|
if _, ok := store.GetByToken(token); ok {
|
||||||
t.Fatal("expired session was accepted")
|
t.Fatal("expired session was accepted")
|
||||||
}
|
}
|
||||||
// Lazy cleanup should have deleted the row.
|
// Lazy cleanup should have deleted the row.
|
||||||
var n int
|
if _, ok := store.GetByToken(token); ok {
|
||||||
store.db.QueryRow(`SELECT count(*) FROM sessions WHERE token = ?`, "stale").Scan(&n)
|
t.Fatal("expired session still in store")
|
||||||
if n != 0 {
|
|
||||||
t.Fatalf("expired row not cleaned up: %d rows remain", n)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ type failLimiter struct {
|
|||||||
attempts map[string]*attemptState
|
attempts map[string]*attemptState
|
||||||
max int
|
max int
|
||||||
window time.Duration
|
window time.Duration
|
||||||
|
sync func(key string, s *attemptState) // optional: persist to DB
|
||||||
}
|
}
|
||||||
|
|
||||||
type attemptState struct {
|
type attemptState struct {
|
||||||
@@ -32,8 +33,8 @@ type attemptState struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// maxTrackedKeys bounds memory: an attacker rotating username/IP can't grow the
|
// 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
|
// map without limit. When exceeded we fail closed instead of wiping state, so
|
||||||
// that briefly forgets cooldowns, acceptable for a single-node panel.
|
// existing cooldowns are preserved.
|
||||||
const maxTrackedKeys = 10000
|
const maxTrackedKeys = 10000
|
||||||
|
|
||||||
func newFailLimiter(max int, window time.Duration) *failLimiter {
|
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.
|
// 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) {
|
func (l *failLimiter) fail(key string) {
|
||||||
l.mu.Lock()
|
l.mu.Lock()
|
||||||
defer l.mu.Unlock()
|
defer l.mu.Unlock()
|
||||||
if len(l.attempts) > maxTrackedKeys {
|
if len(l.attempts) >= maxTrackedKeys {
|
||||||
l.attempts = map[string]*attemptState{}
|
return
|
||||||
}
|
}
|
||||||
s := l.attempts[key]
|
s := l.attempts[key]
|
||||||
if s == nil {
|
if s == nil {
|
||||||
@@ -63,7 +66,10 @@ func (l *failLimiter) fail(key string) {
|
|||||||
s.count++
|
s.count++
|
||||||
if s.count >= l.max {
|
if s.count >= l.max {
|
||||||
s.until = time.Now().Add(l.window)
|
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()
|
l.mu.Lock()
|
||||||
defer l.mu.Unlock()
|
defer l.mu.Unlock()
|
||||||
delete(l.attempts, key)
|
delete(l.attempts, key)
|
||||||
|
if l.sync != nil {
|
||||||
|
l.sync(key, nil)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type ctxKey int
|
type ctxKey int
|
||||||
|
|||||||
@@ -56,6 +56,9 @@ func NewTokenStore(path string) (*TokenStore, error) {
|
|||||||
)`); err != nil {
|
)`); err != nil {
|
||||||
return nil, fmt.Errorf("create tokens table: %w", err)
|
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
|
return &TokenStore{db: db}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ func TestTokenStore(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if len(raw) < len(tokenPrefix)+32 || raw[:len(tokenPrefix)] != tokenPrefix {
|
if len(raw) < 36 || raw[:4] != "nad_" {
|
||||||
t.Fatalf("token %q lacks %q prefix or is too short", raw, tokenPrefix)
|
t.Fatalf("token %q lacks %q prefix or is too short", raw, "nad_")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Round-trip: the minted secret resolves to its name.
|
// 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)
|
t.Errorf("Lookup(valid) = %q,%v; want dash,true", name, ok)
|
||||||
}
|
}
|
||||||
// A wrong secret (and a non-prefixed one) must not resolve.
|
// 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")
|
t.Error("Lookup(wrong) succeeded")
|
||||||
}
|
}
|
||||||
if _, ok := store.Lookup("no-prefix"); ok {
|
if _, ok := store.Lookup("no-prefix"); ok {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -68,10 +69,10 @@ type Server struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SecureCookie reports whether the session cookie should carry the Secure
|
// 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 {
|
func (f *File) SecureCookie() bool {
|
||||||
if f.Server.SecureTLS == nil {
|
if f.Server.SecureTLS == nil {
|
||||||
return true
|
return false
|
||||||
}
|
}
|
||||||
return *f.Server.SecureTLS
|
return *f.Server.SecureTLS
|
||||||
}
|
}
|
||||||
@@ -108,6 +109,32 @@ func Load(path string) (*File, error) {
|
|||||||
if err := yaml.Unmarshal(data, &f); err != nil {
|
if err := yaml.Unmarshal(data, &f); err != nil {
|
||||||
return nil, fmt.Errorf("parse config %s: %w", path, err)
|
return nil, fmt.Errorf("parse config %s: %w", path, err)
|
||||||
}
|
}
|
||||||
|
// 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)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("server.release_repo: %w", err)
|
||||||
|
}
|
||||||
|
if u.Scheme != "https" {
|
||||||
|
return nil, fmt.Errorf("server.release_repo must use https:// (got %q)", f.Server.ReleaseRepo)
|
||||||
|
}
|
||||||
|
if u.Host == "" {
|
||||||
|
return nil, fmt.Errorf("server.release_repo missing host: %q", f.Server.ReleaseRepo)
|
||||||
|
}
|
||||||
|
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
|
||||||
|
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
|
return &f, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,13 +30,13 @@ func mods() []module.Module {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSecureCookieDefaultsTrue(t *testing.T) {
|
func TestSecureCookieDefaultsFalse(t *testing.T) {
|
||||||
if !(&File{}).SecureCookie() {
|
if (&File{}).SecureCookie() {
|
||||||
t.Error("omitted secure_tls should default to true")
|
t.Error("omitted secure_tls should default to false")
|
||||||
}
|
}
|
||||||
no := false
|
yes := true
|
||||||
if (&File{Server: Server{SecureTLS: &no}}).SecureCookie() {
|
if !(&File{Server: Server{SecureTLS: &yes}}).SecureCookie() {
|
||||||
t.Error("secure_tls: false should disable the Secure flag")
|
t.Error("secure_tls: true should enable the Secure flag")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,33 +1,13 @@
|
|||||||
package audit
|
package meta
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"nadir/internal/auditlog"
|
"nadir/internal/auditlog"
|
||||||
"nadir/internal/rbac"
|
|
||||||
|
|
||||||
"github.com/danielgtaylor/huma/v2"
|
"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 {
|
type AuditListInput struct {
|
||||||
Limit int `query:"limit" default:"200" minimum:"1" maximum:"10000" doc:"Max entries to return, newest first"`
|
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{
|
huma.Register(api, huma.Operation{
|
||||||
OperationID: "audit-list",
|
OperationID: "audit-list",
|
||||||
Method: "GET",
|
Method: "GET",
|
||||||
@@ -46,11 +30,11 @@ func (m *Module) Register(api huma.API) {
|
|||||||
Summary: "List recorded actions",
|
Summary: "List recorded actions",
|
||||||
Description: "Returns the audit trail of privileged write operations " +
|
Description: "Returns the audit trail of privileged write operations " +
|
||||||
"(who, what, when, result), newest first.",
|
"(who, what, when, result), newest first.",
|
||||||
Tags: []string{"Audit"},
|
Tags: []string{"Meta", "Audit"},
|
||||||
Metadata: map[string]any{"module": ModuleID, "permission": "read"},
|
Metadata: map[string]any{"module": "audit", "permission": "read"},
|
||||||
Errors: []int{401, 403, 500},
|
Errors: []int{401, 403, 500},
|
||||||
}, func(ctx context.Context, in *AuditListInput) (*AuditListOutput, error) {
|
}, func(ctx context.Context, in *AuditListInput) (*AuditListOutput, error) {
|
||||||
entries, err := m.store.List(in.Limit)
|
entries, err := store.List(in.Limit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("read audit log failed", err)
|
return nil, huma.Error500InternalServerError("read audit log failed", err)
|
||||||
}
|
}
|
||||||
@@ -12,19 +12,18 @@ import (
|
|||||||
"github.com/danielgtaylor/huma/v2"
|
"github.com/danielgtaylor/huma/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ConfigPath is set at startup so the update handler can re-load config and
|
// RegisterUpdate wires POST /api/update. It runs the equivalent of
|
||||||
// surface release_repo / parse errors to the caller instead of only stderr.
|
|
||||||
var ConfigPath string
|
|
||||||
|
|
||||||
// RegisterUpdate wires POST /api/meta/update. It runs the equivalent of
|
|
||||||
// `sudo nadir update` in a detached session and returns 202 immediately; the
|
// `sudo nadir update` in a detached session and returns 202 immediately; the
|
||||||
// systemctl restart that ends the updater drops in-flight connections, so the
|
// systemctl restart that ends the updater drops in-flight connections, so the
|
||||||
// caller should poll /api/health to confirm the new version is up.
|
// caller should poll /api/health to confirm the new version is up.
|
||||||
//
|
//
|
||||||
|
// configPath is re-read by the handler so a missing release_repo (or any other
|
||||||
|
// config error) surfaces as 4xx/5xx to the caller, not as stderr only.
|
||||||
|
//
|
||||||
// Authorization: requires (meta, root). Only roles with a wildcard grant
|
// Authorization: requires (meta, root). Only roles with a wildcard grant
|
||||||
// (the default admin role) match, since "meta" isn't a real module with a
|
// (the default admin role) match, since "meta" isn't a real module with a
|
||||||
// declared permission vocabulary.
|
// declared permission vocabulary.
|
||||||
func RegisterUpdate(api huma.API) {
|
func RegisterUpdate(api huma.API, configPath string) {
|
||||||
huma.Register(api, huma.Operation{
|
huma.Register(api, huma.Operation{
|
||||||
OperationID: "meta-update",
|
OperationID: "meta-update",
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
@@ -36,13 +35,13 @@ func RegisterUpdate(api huma.API) {
|
|||||||
Errors: []int{400, 401, 403, 500},
|
Errors: []int{400, 401, 403, 500},
|
||||||
DefaultStatus: 202,
|
DefaultStatus: 202,
|
||||||
}, func(ctx context.Context, _ *struct{}) (*oscmd.StatusOutput, error) {
|
}, func(ctx context.Context, _ *struct{}) (*oscmd.StatusOutput, error) {
|
||||||
if ConfigPath != "" {
|
if configPath != "" {
|
||||||
cfg, err := config.Load(ConfigPath)
|
cfg, err := config.Load(configPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("config load failed", err)
|
return nil, huma.Error500InternalServerError("config load failed", err)
|
||||||
}
|
}
|
||||||
if cfg.Server.ReleaseRepo == "" {
|
if cfg.Server.ReleaseRepo == "" {
|
||||||
return nil, huma.Error400BadRequest("server.release_repo not set in " + ConfigPath)
|
return nil, huma.Error400BadRequest("server.release_repo not set in " + configPath)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
exe, err := os.Executable()
|
exe, err := os.Executable()
|
||||||
|
|||||||
+26
-7
@@ -15,6 +15,7 @@ import (
|
|||||||
// itself.
|
// itself.
|
||||||
type WhoamiInput struct {
|
type WhoamiInput struct {
|
||||||
SessionID string `cookie:"nadir_session_id"`
|
SessionID string `cookie:"nadir_session_id"`
|
||||||
|
Auth string `header:"Authorization"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// WhoamiBody reports who the caller is and, per module, which permissions they
|
// 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
|
// RegisterWhoami adds the current-user endpoint. It resolves the caller's
|
||||||
// concrete grants by asking the RBAC store about each module's permissions,
|
// concrete grants by asking the RBAC store about each module's permissions,
|
||||||
// so "*" wildcards in roles are expanded for free.
|
// 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{
|
huma.Register(api, huma.Operation{
|
||||||
OperationID: "whoami",
|
OperationID: "whoami",
|
||||||
Method: "GET",
|
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 " +
|
"permissions the caller holds (wildcards resolved). Pair with " +
|
||||||
"/api/_modules to render the full permission matrix.",
|
"/api/_modules to render the full permission matrix.",
|
||||||
Tags: []string{"Meta"},
|
Tags: []string{"Meta"},
|
||||||
Errors: []int{401},
|
Errors: []int{401, 429},
|
||||||
}, func(ctx context.Context, in *WhoamiInput) (*WhoamiOutput, error) {
|
}, func(ctx context.Context, in *WhoamiInput) (*WhoamiOutput, error) {
|
||||||
sess, ok := sessions.GetByToken(in.SessionID)
|
var username string
|
||||||
if !ok {
|
|
||||||
return nil, huma.Error401Unauthorized("unauthorized")
|
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)
|
held := make(map[string][]string)
|
||||||
for _, m := range mods {
|
for _, m := range mods {
|
||||||
var perms []string
|
var perms []string
|
||||||
for _, p := range m.Permissions() {
|
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))
|
perms = append(perms, string(p))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -61,7 +79,8 @@ func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC,
|
|||||||
}
|
}
|
||||||
|
|
||||||
out := &WhoamiOutput{}
|
out := &WhoamiOutput{}
|
||||||
out.Body = WhoamiBody{Username: sess.Username, Permissions: held}
|
out.Body = WhoamiBody{Username: username, Permissions: held}
|
||||||
return out, nil
|
return out, nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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"])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -70,7 +70,7 @@ func registerGroups(api huma.API) {
|
|||||||
}, func(ctx context.Context, _ *struct{}) (*ListGroupsOutput, error) {
|
}, func(ctx context.Context, _ *struct{}) (*ListGroupsOutput, error) {
|
||||||
list, err := listGroups()
|
list, err := listGroups()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
|
return nil, huma.Error500InternalServerError("group lookup failed", err)
|
||||||
}
|
}
|
||||||
out := &ListGroupsOutput{}
|
out := &ListGroupsOutput{}
|
||||||
out.Body.Groups = list
|
out.Body.Groups = list
|
||||||
@@ -92,7 +92,7 @@ func registerGroups(api huma.API) {
|
|||||||
}
|
}
|
||||||
g, ok, err := lookupGroup(in.Group)
|
g, ok, err := lookupGroup(in.Group)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
|
return nil, huma.Error500InternalServerError("group lookup failed", err)
|
||||||
}
|
}
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, huma.Error404NotFound("group not found: " + in.Group)
|
return nil, huma.Error404NotFound("group not found: " + in.Group)
|
||||||
@@ -114,7 +114,7 @@ func registerGroups(api huma.API) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if _, ok, err := lookupGroup(in.Body.Name); err != nil {
|
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 {
|
} else if ok {
|
||||||
return nil, huma.Error409Conflict("group already exists: " + in.Body.Name)
|
return nil, huma.Error409Conflict("group already exists: " + in.Body.Name)
|
||||||
}
|
}
|
||||||
@@ -154,7 +154,7 @@ func registerGroups(api huma.API) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if _, ok, err := lookupGroup(in.Group); err != nil {
|
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 {
|
} else if !ok {
|
||||||
return nil, huma.Error404NotFound("group not found: " + in.Group)
|
return nil, huma.Error404NotFound("group not found: " + in.Group)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,14 +38,30 @@ short:x:5
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestValidateGroupName(t *testing.T) {
|
func TestValidateGroupName(t *testing.T) {
|
||||||
for _, n := range []string{"wheel", "_svc", "dev-team", "g1"} {
|
for _, tt := range []struct {
|
||||||
if err := validateGroupName(n); err != nil {
|
name string
|
||||||
t.Errorf("validateGroupName(%q) = %v, want nil", n, err)
|
value string
|
||||||
}
|
valid bool
|
||||||
}
|
}{
|
||||||
for _, n := range []string{"", "-x", "Wheel", "a,b", "foo;rm", "1grp"} {
|
{name: "wheel", value: "wheel", valid: true},
|
||||||
if err := validateGroupName(n); err == nil {
|
{name: "underscore prefix", value: "_svc", valid: true},
|
||||||
t.Errorf("validateGroupName(%q) = nil, want error", n)
|
{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)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,17 +49,31 @@ func TestValidateIfaceConfig(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestValidateIface(t *testing.T) {
|
func TestValidateIface(t *testing.T) {
|
||||||
valid := []string{"eth0", "enp3s0", "wlan0", "br-lan", "veth1234567", "docker0"}
|
for _, tt := range []struct {
|
||||||
for _, name := range valid {
|
name string
|
||||||
if err := validateIface(name); err != nil {
|
value string
|
||||||
t.Errorf("validateIface(%q) unexpected error: %v", name, err)
|
valid bool
|
||||||
}
|
}{
|
||||||
}
|
{name: "eth0", value: "eth0", valid: true},
|
||||||
|
{name: "enp3s0", value: "enp3s0", valid: true},
|
||||||
invalid := []string{"", "-eth0", "/dev/net", "a b", "name_that_is_way_too_long_for_linux"}
|
{name: "wlan0", value: "wlan0", valid: true},
|
||||||
for _, name := range invalid {
|
{name: "bridge", value: "br-lan", valid: true},
|
||||||
if err := validateIface(name); err == nil {
|
{name: "veth", value: "veth1234567", valid: true},
|
||||||
t.Errorf("validateIface(%q) expected error", name)
|
{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)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"nadir/internal/oscmd"
|
"nadir/internal/oscmd"
|
||||||
|
|
||||||
@@ -18,6 +19,10 @@ import (
|
|||||||
|
|
||||||
var hostsFile = "/etc/hosts"
|
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
|
// 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.
|
// 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._-]*$`)
|
var hostnameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`)
|
||||||
@@ -156,9 +161,26 @@ func renderHostLine(ip string, hostnames []string) string {
|
|||||||
|
|
||||||
// --- writes ------------------------------------------------------------------
|
// --- 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
|
// upsertHost replaces the line for ip (matched on the address field) or appends
|
||||||
// a new one, preserving every other line.
|
// a new one, preserving every other line.
|
||||||
func upsertHost(ip string, hostnames []string) error {
|
func upsertHost(ip string, hostnames []string) error {
|
||||||
|
hostsMu.Lock()
|
||||||
|
defer hostsMu.Unlock()
|
||||||
|
|
||||||
data, err := os.ReadFile(hostsFile)
|
data, err := os.ReadFile(hostsFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -174,7 +196,6 @@ func upsertHost(ip string, hostnames []string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !replaced {
|
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]) == "" {
|
if n := len(lines); n > 0 && strings.TrimSpace(lines[n-1]) == "" {
|
||||||
lines[n-1] = newLine
|
lines[n-1] = newLine
|
||||||
} else {
|
} else {
|
||||||
@@ -182,11 +203,14 @@ func upsertHost(ip string, hostnames []string) error {
|
|||||||
}
|
}
|
||||||
lines = append(lines, "")
|
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.
|
// deleteHost removes every line mapping ip and reports whether any were removed.
|
||||||
func deleteHost(ip string) (bool, error) {
|
func deleteHost(ip string) (bool, error) {
|
||||||
|
hostsMu.Lock()
|
||||||
|
defer hostsMu.Unlock()
|
||||||
|
|
||||||
data, err := os.ReadFile(hostsFile)
|
data, err := os.ReadFile(hostsFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
@@ -204,5 +228,5 @@ func deleteHost(ip string) (bool, error) {
|
|||||||
if !removed {
|
if !removed {
|
||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
return true, os.WriteFile(hostsFile, []byte(strings.Join(kept, "\n")), 0644)
|
return true, writeHostsAtomically(strings.Join(kept, "\n"))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ func (m *Module) Permissions() []rbac.Permission {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (m *Module) Register(api huma.API) {
|
func (m *Module) Register(api huma.API) {
|
||||||
registerReads(api)
|
registerReads(api, m)
|
||||||
registerWrites(api, m)
|
registerWrites(api, m)
|
||||||
registerHosts(api)
|
registerHosts(api)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
|
||||||
|
|
||||||
"nadir/internal/oscmd"
|
"nadir/internal/oscmd"
|
||||||
|
|
||||||
@@ -87,6 +86,30 @@ func TestNetworkingHandlers(t *testing.T) {
|
|||||||
t.Errorf("list interfaces: got %d, want %d", resp.Code, http.StatusOK)
|
t.Errorf("list interfaces: got %d, want %d", resp.Code, http.StatusOK)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 1b. Test GET /api/networking/interfaces/{name} (used by edit-form prefill).
|
||||||
|
// Asserts the backend's Snapshot output is returned verbatim as the body, so
|
||||||
|
// the same shape can feed straight into PUT.
|
||||||
|
resp = api.Get("/api/networking/interfaces/eth0")
|
||||||
|
if resp.Code != http.StatusOK {
|
||||||
|
t.Errorf("get interface: got %d, want %d", resp.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
var ifaceRes GetInterfaceConfigOutput
|
||||||
|
if err := json.Unmarshal(resp.Body.Bytes(), &ifaceRes.Body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ifaceRes.Body.Method != "dhcp" || ifaceRes.Body.Address != "192.168.1.10/24" {
|
||||||
|
t.Errorf("get interface: got %+v, want snapshot result", ifaceRes.Body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same endpoint with no backend should return 501.
|
||||||
|
noBackend := &Module{}
|
||||||
|
noBackendMux := http.NewServeMux()
|
||||||
|
noBackendAPI := humatest.Wrap(t, humago.New(noBackendMux, huma.DefaultConfig("Test", "1.0.0")))
|
||||||
|
noBackend.Register(noBackendAPI)
|
||||||
|
if got := noBackendAPI.Get("/api/networking/interfaces/eth0").Code; got != http.StatusNotImplemented {
|
||||||
|
t.Errorf("get interface without backend: got %d, want 501", got)
|
||||||
|
}
|
||||||
|
|
||||||
// 2. Test GET /api/networking/routes
|
// 2. Test GET /api/networking/routes
|
||||||
resp = api.Get("/api/networking/routes")
|
resp = api.Get("/api/networking/routes")
|
||||||
if resp.Code != http.StatusOK {
|
if resp.Code != http.StatusOK {
|
||||||
@@ -144,14 +167,18 @@ func TestNetworkingHandlers(t *testing.T) {
|
|||||||
t.Errorf("pending change should be cleared: got %d, want %d", resp.Code, http.StatusNotFound)
|
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
|
applyPayload.RollbackSeconds = 1
|
||||||
resp = api.Put("/api/networking/interfaces/eth0", applyPayload)
|
resp = api.Put("/api/networking/interfaces/eth0", applyPayload)
|
||||||
if resp.Code != http.StatusOK {
|
if resp.Code != http.StatusOK {
|
||||||
t.Errorf("apply config again: got %d, want %d", resp.Code, http.StatusOK)
|
t.Errorf("apply config again: got %d, want %d", resp.Code, http.StatusOK)
|
||||||
}
|
}
|
||||||
|
if m.pending == nil {
|
||||||
time.Sleep(1200 * time.Millisecond)
|
t.Fatal("expected pending change after apply")
|
||||||
|
}
|
||||||
|
if err := m.rollbackNow("eth0"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
resp = api.Get("/api/networking/pending")
|
resp = api.Get("/api/networking/pending")
|
||||||
if resp.Code != http.StatusNotFound {
|
if resp.Code != http.StatusNotFound {
|
||||||
@@ -388,3 +415,69 @@ func TestBackendImplementations(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGetInterfaceConfigAugment(t *testing.T) {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
|
||||||
|
|
||||||
|
be := &mockBackend{
|
||||||
|
name: "mockbe",
|
||||||
|
snapshotResult: IfaceConfig{
|
||||||
|
Method: "dhcp",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
m := &Module{be: be}
|
||||||
|
m.Register(api)
|
||||||
|
|
||||||
|
tempResolv := filepath.Join(t.TempDir(), "resolv.conf")
|
||||||
|
if err := os.WriteFile(tempResolv, []byte("nameserver 1.1.1.1\nnameserver 8.8.8.8\n"), 0644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
oldResolv := resolvConf
|
||||||
|
resolvConf = tempResolv
|
||||||
|
defer func() { resolvConf = oldResolv }()
|
||||||
|
|
||||||
|
oscmd.SetMock("ip", func(args []string) oscmd.MockCommand {
|
||||||
|
argStr := strings.Join(args, " ")
|
||||||
|
if strings.Contains(argStr, "addr show") {
|
||||||
|
out := `[{"ifname": "eth0", "operstate": "UP", "address": "aa:bb:cc:dd:ee:ff", "mtu": 1500, "addr_info": [{"family": "inet", "local": "192.168.1.10", "prefixlen": 24}, {"family": "inet6", "local": "2001:db8::10", "prefixlen": 64}]}]`
|
||||||
|
return oscmd.MockCommand{Stdout: out, ExitCode: 0}
|
||||||
|
}
|
||||||
|
if strings.Contains(argStr, "route show") && !strings.Contains(argStr, "-6") {
|
||||||
|
out := `[{"dst": "default", "gateway": "192.168.1.1", "dev": "eth0"}]`
|
||||||
|
return oscmd.MockCommand{Stdout: out, ExitCode: 0}
|
||||||
|
}
|
||||||
|
if strings.Contains(argStr, "-6") && strings.Contains(argStr, "route show") {
|
||||||
|
out := `[{"dst": "default", "gateway": "2001:db8::1", "dev": "eth0"}]`
|
||||||
|
return oscmd.MockCommand{Stdout: out, ExitCode: 0}
|
||||||
|
}
|
||||||
|
return oscmd.MockCommand{ExitCode: 1}
|
||||||
|
})
|
||||||
|
defer oscmd.ClearMocks()
|
||||||
|
|
||||||
|
resp := api.Get("/api/networking/interfaces/eth0")
|
||||||
|
if resp.Code != http.StatusOK {
|
||||||
|
t.Errorf("get interface: got %d, want %d", resp.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
var ifaceRes GetInterfaceConfigOutput
|
||||||
|
if err := json.Unmarshal(resp.Body.Bytes(), &ifaceRes.Body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if ifaceRes.Body.Method != "dhcp" {
|
||||||
|
t.Errorf("expected Method to be dhcp, got %s", ifaceRes.Body.Method)
|
||||||
|
}
|
||||||
|
if ifaceRes.Body.Address != "192.168.1.10" || ifaceRes.Body.Prefix != 24 {
|
||||||
|
t.Errorf("expected augmented Address 192.168.1.10/24, got %s/%d", ifaceRes.Body.Address, ifaceRes.Body.Prefix)
|
||||||
|
}
|
||||||
|
if ifaceRes.Body.Gateway != "192.168.1.1" {
|
||||||
|
t.Errorf("expected augmented Gateway 192.168.1.1, got %s", ifaceRes.Body.Gateway)
|
||||||
|
}
|
||||||
|
if len(ifaceRes.Body.DNS) != 2 || ifaceRes.Body.DNS[0] != "1.1.1.1" || ifaceRes.Body.DNS[1] != "8.8.8.8" {
|
||||||
|
t.Errorf("expected augmented DNS [1.1.1.1, 8.8.8.8], got %v", ifaceRes.Body.DNS)
|
||||||
|
}
|
||||||
|
if ifaceRes.Body.IPv6 == nil || ifaceRes.Body.IPv6.Method != "auto" || ifaceRes.Body.IPv6.Address != "2001:db8::10" || ifaceRes.Body.IPv6.Prefix != 64 || ifaceRes.Body.IPv6.Gateway != "2001:db8::1" {
|
||||||
|
t.Errorf("expected augmented IPv6, got %+v", ifaceRes.Body.IPv6)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -46,11 +46,19 @@ func (b *nmcliBackend) Snapshot(ctx context.Context, iface string) (IfaceConfig,
|
|||||||
return IfaceConfig{Method: "dhcp"}, nil
|
return IfaceConfig{Method: "dhcp"}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// nmcli's `con show <NAME>` parser does NOT honor `--` as an end-of-options
|
||||||
|
// separator; passing it makes nmcli look for a connection literally named
|
||||||
|
// "--" and fail. `conn` comes from nmcli's own active-connections list (see
|
||||||
|
// connForIface), so it's already validated — no shell-metacharacter risk.
|
||||||
|
// Same applies to con up / con down / con modify below.
|
||||||
out, err := oscmd.RunContext(ctx, "nmcli", "-t", "-f",
|
out, err := oscmd.RunContext(ctx, "nmcli", "-t", "-f",
|
||||||
"ipv4.method,ipv4.addresses,ipv4.gateway,ipv4.dns,ipv4.routes,ipv6.method,ipv6.addresses,ipv6.gateway",
|
"ipv4.method,ipv4.addresses,ipv4.gateway,ipv4.dns,ipv4.routes,ipv6.method,ipv6.addresses,ipv6.gateway",
|
||||||
"con", "show", "--", conn)
|
"con", "show", conn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return IfaceConfig{}, fmt.Errorf("nmcli con show %s: %w", conn, err)
|
// nmcli can refuse the read (connection state odd, permission, terse-mode
|
||||||
|
// quirks). Fall back to DHCP defaults so the prefill endpoint still
|
||||||
|
// returns a usable form, mirroring the networkd / ifupdown fallback.
|
||||||
|
return IfaceConfig{Method: "dhcp"}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return parseNmcliSnapshot(out), nil
|
return parseNmcliSnapshot(out), nil
|
||||||
@@ -159,9 +167,9 @@ func (b *nmcliBackend) Apply(ctx context.Context, iface string, cfg IfaceConfig)
|
|||||||
return fmt.Errorf("cannot apply: %w", err)
|
return fmt.Errorf("cannot apply: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build the nmcli con modify arguments. Note: conn is safe to place after
|
// conn comes from nmcli's own active list (connForIface), not user input.
|
||||||
// -- since it comes from nmcli output, not directly from the user.
|
// nmcli's con subcommands don't honor "--" as an end-of-options separator.
|
||||||
args := []string{"con", "modify", "--", conn}
|
args := []string{"con", "modify", conn}
|
||||||
|
|
||||||
switch cfg.Method {
|
switch cfg.Method {
|
||||||
case "static":
|
case "static":
|
||||||
@@ -222,7 +230,7 @@ func (b *nmcliBackend) Apply(ctx context.Context, iface string, cfg IfaceConfig)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Bring the connection up to apply changes.
|
// Bring the connection up to apply changes.
|
||||||
if _, err := oscmd.RunContext(ctx, "nmcli", "con", "up", "--", conn); err != nil {
|
if _, err := oscmd.RunContext(ctx, "nmcli", "con", "up", conn); err != nil {
|
||||||
return fmt.Errorf("nmcli con up: %w", err)
|
return fmt.Errorf("nmcli con up: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@@ -235,7 +243,7 @@ func (b *nmcliBackend) SetLinkUp(ctx context.Context, iface string) error {
|
|||||||
_, err = oscmd.RunContext(ctx, "ip", "link", "set", "--", iface, "up")
|
_, err = oscmd.RunContext(ctx, "ip", "link", "set", "--", iface, "up")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, err = oscmd.RunContext(ctx, "nmcli", "con", "up", "--", conn)
|
_, err = oscmd.RunContext(ctx, "nmcli", "con", "up", conn)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,7 +253,7 @@ func (b *nmcliBackend) SetLinkDown(ctx context.Context, iface string) error {
|
|||||||
_, err = oscmd.RunContext(ctx, "ip", "link", "set", "--", iface, "down")
|
_, err = oscmd.RunContext(ctx, "ip", "link", "set", "--", iface, "down")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, err = oscmd.RunContext(ctx, "nmcli", "con", "down", "--", conn)
|
_, err = oscmd.RunContext(ctx, "nmcli", "con", "down", conn)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package networking
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -53,7 +55,48 @@ type DNSOutput struct {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func registerReads(api huma.API) {
|
// GetInterfaceConfigInput carries the path param; matches the PUT endpoint's
|
||||||
|
// IfacePathInput so the frontend can use the same path for both verbs.
|
||||||
|
type GetInterfaceConfigInput struct {
|
||||||
|
Name string `path:"name" example:"eth0" doc:"Interface name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetInterfaceConfigOutput returns the same IfaceConfig shape that PUT
|
||||||
|
// accepts, so the form can be pre-filled directly from this response.
|
||||||
|
type GetInterfaceConfigOutput struct {
|
||||||
|
Body IfaceConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func registerReads(api huma.API, m *Module) {
|
||||||
|
huma.Register(api, huma.Operation{
|
||||||
|
OperationID: "networking-get-interface",
|
||||||
|
Method: "GET",
|
||||||
|
Path: "/api/networking/interfaces/{name}",
|
||||||
|
Summary: "Get an interface's current configuration",
|
||||||
|
Description: "Returns the IfaceConfig the backend currently has for this " +
|
||||||
|
"interface (method, address/prefix, gateway, DNS, IPv6). Same schema as " +
|
||||||
|
"PUT /api/networking/interfaces/{name}, so the frontend can prefill an " +
|
||||||
|
"edit form from this response directly. Returns 501 when no backend was " +
|
||||||
|
"detected (nmcli / networkd / ifupdown).",
|
||||||
|
Tags: []string{tagNetworking},
|
||||||
|
Metadata: op("read"),
|
||||||
|
Errors: readErrors,
|
||||||
|
}, func(ctx context.Context, in *GetInterfaceConfigInput) (*GetInterfaceConfigOutput, error) {
|
||||||
|
if m.be == nil {
|
||||||
|
return nil, huma.Error501NotImplemented("", errNoBackend)
|
||||||
|
}
|
||||||
|
if err := validateIface(in.Name); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cfg, err := m.be.Snapshot(ctx, in.Name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, huma.Error500InternalServerError("snapshot failed", err)
|
||||||
|
}
|
||||||
|
augmentWithLiveState(ctx, in.Name, &cfg)
|
||||||
|
return &GetInterfaceConfigOutput{Body: cfg}, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
huma.Register(api, huma.Operation{
|
huma.Register(api, huma.Operation{
|
||||||
OperationID: "networking-list-interfaces",
|
OperationID: "networking-list-interfaces",
|
||||||
Method: "GET",
|
Method: "GET",
|
||||||
@@ -114,7 +157,7 @@ func registerReads(api huma.API) {
|
|||||||
}, func(ctx context.Context, _ *struct{}) (*DNSOutput, error) {
|
}, func(ctx context.Context, _ *struct{}) (*DNSOutput, error) {
|
||||||
data, err := os.ReadFile(resolvConf)
|
data, err := os.ReadFile(resolvConf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("read resolv.conf failed", err)
|
return nil, huma.Error500InternalServerError("DNS config lookup failed", err)
|
||||||
}
|
}
|
||||||
res := &DNSOutput{}
|
res := &DNSOutput{}
|
||||||
res.Body.Servers = parseResolv(string(data))
|
res.Body.Servers = parseResolv(string(data))
|
||||||
@@ -209,3 +252,113 @@ func parseResolv(text string) []string {
|
|||||||
}
|
}
|
||||||
return servers
|
return servers
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getLiveInterface(ctx context.Context, iface string) (*Interface, error) {
|
||||||
|
out, err := oscmd.RunContext(ctx, "ip", "-j", "addr", "show", "--", iface)
|
||||||
|
if err != nil {
|
||||||
|
out, err = oscmd.RunContext(ctx, "ip", "-j", "addr")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ifaces, err := parseInterfaces(out)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for i := range ifaces {
|
||||||
|
if ifaces[i].Name == iface {
|
||||||
|
return &ifaces[i], nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("interface %s not found in ip addr output", iface)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getLiveGateway(ctx context.Context, iface string) string {
|
||||||
|
routeOut, err := oscmd.RunContext(ctx, "ip", "-j", "route", "show", "dev", "--", iface)
|
||||||
|
if err != nil {
|
||||||
|
routeOut, err = oscmd.RunContext(ctx, "ip", "-j", "route")
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
routes, err := parseRoutes(routeOut)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
for _, r := range routes {
|
||||||
|
if r.Destination == "default" && (r.Interface == iface || r.Interface == "") && r.Gateway != "" {
|
||||||
|
return r.Gateway
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func getLiveIPv6Gateway(ctx context.Context, iface string) string {
|
||||||
|
routeOut, err := oscmd.RunContext(ctx, "ip", "-6", "-j", "route", "show", "dev", "--", iface)
|
||||||
|
if err != nil {
|
||||||
|
routeOut, err = oscmd.RunContext(ctx, "ip", "-6", "-j", "route")
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
routes, err := parseRoutes(routeOut)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
for _, r := range routes {
|
||||||
|
if r.Destination == "default" && (r.Interface == iface || r.Interface == "") && r.Gateway != "" {
|
||||||
|
return r.Gateway
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func augmentWithLiveState(ctx context.Context, iface string, cfg *IfaceConfig) {
|
||||||
|
liveIface, err := getLiveInterface(ctx, iface)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prefill IPv4 address and prefix if empty
|
||||||
|
if cfg.Address == "" && len(liveIface.IPv4) > 0 {
|
||||||
|
addr, prefix := splitCIDR(liveIface.IPv4[0])
|
||||||
|
if addr != "" {
|
||||||
|
cfg.Address = addr
|
||||||
|
cfg.Prefix = prefix
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prefill Gateway if empty
|
||||||
|
if cfg.Gateway == "" {
|
||||||
|
cfg.Gateway = getLiveGateway(ctx, iface)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prefill DNS if empty
|
||||||
|
if len(cfg.DNS) == 0 {
|
||||||
|
if data, err := os.ReadFile(resolvConf); err == nil {
|
||||||
|
cfg.DNS = parseResolv(string(data))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prefill IPv6 if present and method is not ignore
|
||||||
|
if cfg.IPv6 == nil {
|
||||||
|
cfg.IPv6 = &IPv6Config{Method: "auto"}
|
||||||
|
}
|
||||||
|
if cfg.IPv6.Method != "ignore" {
|
||||||
|
// Capture first global IPv6 if address is empty
|
||||||
|
if cfg.IPv6.Address == "" {
|
||||||
|
for _, c := range liveIface.IPv6 {
|
||||||
|
addr, prefix := splitCIDR(c)
|
||||||
|
if ip, err := netip.ParseAddr(addr); err == nil && !ip.IsLinkLocalUnicast() {
|
||||||
|
cfg.IPv6.Address = addr
|
||||||
|
cfg.IPv6.Prefix = prefix
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Capture IPv6 default gateway if empty
|
||||||
|
if cfg.IPv6.Gateway == "" {
|
||||||
|
cfg.IPv6.Gateway = getLiveIPv6Gateway(ctx, iface)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
const defaultRollbackSeconds = 60
|
const defaultRollbackSeconds = 120
|
||||||
|
|
||||||
// errAlreadyPending is returned when another change is awaiting confirmation.
|
// errAlreadyPending is returned when another change is awaiting confirmation.
|
||||||
// The write handlers map this to 409 Conflict.
|
// 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
|
// revert even if the server is otherwise idle — the whole point is protecting
|
||||||
// against being locked out of a remote box.
|
// against being locked out of a remote box.
|
||||||
pc.Timer = time.AfterFunc(dur, func() {
|
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()
|
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 {
|
if m.pending != pc {
|
||||||
|
m.mu.Unlock()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
iface := pc.Iface
|
||||||
|
revert := pc.revert
|
||||||
|
m.mu.Unlock()
|
||||||
|
|
||||||
log.Printf("networking: rollback timer expired for %s — reverting", iface)
|
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)
|
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
|
m.pending = pc
|
||||||
|
|||||||
@@ -65,6 +65,10 @@ type RemoveInput struct {
|
|||||||
Name string `path:"name" example:"htop" doc:"Package to remove"`
|
Name string `path:"name" example:"htop" doc:"Package to remove"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type UpgradeOneInput struct {
|
||||||
|
Name string `path:"name" example:"htop" doc:"Package to upgrade"`
|
||||||
|
}
|
||||||
|
|
||||||
// SSE event types for streaming package operations.
|
// SSE event types for streaming package operations.
|
||||||
type PkgOutputEvent struct {
|
type PkgOutputEvent struct {
|
||||||
Line string `json:"line" doc:"One line of the package manager's terminal output"`
|
Line string `json:"line" doc:"One line of the package manager's terminal output"`
|
||||||
@@ -79,6 +83,11 @@ type PkgDoneEvent struct {
|
|||||||
Error string `json:"error,omitempty" doc:"Exit error when it failed"`
|
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
|
// pkgEvents maps SSE event names to their payload types for the streaming
|
||||||
// install/remove/upgrade operations.
|
// install/remove/upgrade operations.
|
||||||
var pkgEvents = map[string]any{
|
var pkgEvents = map[string]any{
|
||||||
@@ -162,6 +171,25 @@ func registerPackages(api huma.API, pm manager) {
|
|||||||
bin, args := pm.upgradeArgs()
|
bin, args := pm.upgradeArgs()
|
||||||
streamOp(ctx, send, bin, args)
|
streamOp(ctx, send, bin, args)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
sse.Register(api, huma.Operation{
|
||||||
|
OperationID: "packages-upgrade-one",
|
||||||
|
Method: "POST",
|
||||||
|
Path: "/api/packages/upgrade/{name}",
|
||||||
|
Summary: "Upgrade a single package (streamed)",
|
||||||
|
Description: "Upgrades the named package to its latest version, streaming the " +
|
||||||
|
"package manager's output live. apt uses `install --only-upgrade` so the " +
|
||||||
|
"package must already be installed; dnf/pacman handle this natively.",
|
||||||
|
Tags: []string{tagPackages},
|
||||||
|
Metadata: op("write"),
|
||||||
|
}, pkgEvents, func(ctx context.Context, in *UpgradeOneInput, send sse.Sender) {
|
||||||
|
if validateName(in.Name) != nil {
|
||||||
|
send.Data(PkgErrorEvent{Message: "invalid package name: " + in.Name})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
bin, args := pm.upgradeOneArgs(in.Name)
|
||||||
|
streamOp(ctx, send, bin, args)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// streamOp runs a package write and streams its combined output to the client.
|
// streamOp runs a package write and streams its combined output to the client.
|
||||||
@@ -170,6 +198,13 @@ func streamOp(ctx context.Context, send sse.Sender, bin string, args []string) {
|
|||||||
send.Data(PkgErrorEvent{Message: "no supported package manager found"})
|
send.Data(PkgErrorEvent{Message: "no supported package manager found"})
|
||||||
return
|
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.
|
// DEBIAN_FRONTEND keeps apt from blocking on an interactive prompt.
|
||||||
lines, errc, err := oscmd.RunStreamCombined(ctx, []string{"DEBIAN_FRONTEND=noninteractive"}, bin, args...)
|
lines, errc, err := oscmd.RunStreamCombined(ctx, []string{"DEBIAN_FRONTEND=noninteractive"}, bin, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -260,11 +295,11 @@ func result(pm manager, pkgs []Package) *ListOutput {
|
|||||||
func (m manager) installArgs(name string) (string, []string) {
|
func (m manager) installArgs(name string) (string, []string) {
|
||||||
switch m.name {
|
switch m.name {
|
||||||
case "dnf":
|
case "dnf":
|
||||||
return "dnf", []string{"install", "-y", "--", name}
|
return "dnf", []string{"install", "-y", name}
|
||||||
case "apt":
|
case "apt":
|
||||||
return "apt-get", []string{"install", "-y", "--", name}
|
return "apt-get", []string{"install", "-y", name}
|
||||||
case "pacman":
|
case "pacman":
|
||||||
return "pacman", []string{"-S", "--noconfirm", "--", name}
|
return "pacman", []string{"-S", "--noconfirm", name}
|
||||||
}
|
}
|
||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
@@ -272,11 +307,11 @@ func (m manager) installArgs(name string) (string, []string) {
|
|||||||
func (m manager) removeArgs(name string) (string, []string) {
|
func (m manager) removeArgs(name string) (string, []string) {
|
||||||
switch m.name {
|
switch m.name {
|
||||||
case "dnf":
|
case "dnf":
|
||||||
return "dnf", []string{"remove", "-y", "--", name}
|
return "dnf", []string{"remove", "-y", name}
|
||||||
case "apt":
|
case "apt":
|
||||||
return "apt-get", []string{"remove", "-y", "--", name}
|
return "apt-get", []string{"remove", "-y", name}
|
||||||
case "pacman":
|
case "pacman":
|
||||||
return "pacman", []string{"-R", "--noconfirm", "--", name}
|
return "pacman", []string{"-R", "--noconfirm", name}
|
||||||
}
|
}
|
||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
@@ -293,6 +328,21 @@ func (m manager) upgradeArgs() (string, []string) {
|
|||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// upgradeOneArgs upgrades a single package to its latest version. apt's
|
||||||
|
// `install --only-upgrade` is the safe variant (won't install if absent);
|
||||||
|
// pacman -S re-syncs to latest; dnf upgrade is naturally scoped by name.
|
||||||
|
func (m manager) upgradeOneArgs(name string) (string, []string) {
|
||||||
|
switch m.name {
|
||||||
|
case "dnf":
|
||||||
|
return "dnf", []string{"upgrade", "-y", name}
|
||||||
|
case "apt":
|
||||||
|
return "apt-get", []string{"install", "--only-upgrade", "-y", name}
|
||||||
|
case "pacman":
|
||||||
|
return "pacman", []string{"-S", "--noconfirm", name}
|
||||||
|
}
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
// --- parsers (pure, tested) --------------------------------------------------
|
// --- parsers (pure, tested) --------------------------------------------------
|
||||||
|
|
||||||
// parseTabbed reads "name\tversion" lines (dpkg-query / rpm output).
|
// parseTabbed reads "name\tversion" lines (dpkg-query / rpm output).
|
||||||
|
|||||||
@@ -54,27 +54,50 @@ func TestParsePacmanUpdates(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStripArch(t *testing.T) {
|
func TestStripArch(t *testing.T) {
|
||||||
cases := map[string]string{
|
tests := []struct {
|
||||||
"code.x86_64": "code",
|
name string
|
||||||
"python3.11.noarch": "python3.11", // arch is only the final segment
|
in string
|
||||||
"noarchhere": "noarchhere",
|
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 {
|
for _, tt := range tests {
|
||||||
if got := stripArch(in); got != want {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
t.Errorf("stripArch(%q) = %q, want %q", in, got, want)
|
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) {
|
func TestValidateName(t *testing.T) {
|
||||||
for _, n := range []string{"htop", "openssh-server", "lib32-glibc", "g++", "python3.11"} {
|
for _, tt := range []struct {
|
||||||
if err := validateName(n); err != nil {
|
name string
|
||||||
t.Errorf("validateName(%q) = %v, want nil", n, err)
|
value string
|
||||||
}
|
valid bool
|
||||||
}
|
}{
|
||||||
for _, n := range []string{"", "-rf", "foo;rm", "foo bar", "pkg=1.0", "a/b"} {
|
{name: "htop", value: "htop", valid: true},
|
||||||
if err := validateName(n); err == nil {
|
{name: "openssh-server", value: "openssh-server", valid: true},
|
||||||
t.Errorf("validateName(%q) = nil, want error", n)
|
{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)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,10 @@ const (
|
|||||||
maxLogLines = 10000
|
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
|
// 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,
|
// journalctl's JSON; for the file source only Message is set (the raw line,
|
||||||
// which usually carries its own embedded timestamp).
|
// which usually carries its own embedded timestamp).
|
||||||
@@ -128,6 +132,14 @@ func registerLogs(api huma.API, logFiles map[string][]string) {
|
|||||||
return
|
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 cmd string
|
||||||
var args []string
|
var args []string
|
||||||
if in.Source == "file" {
|
if in.Source == "file" {
|
||||||
|
|||||||
@@ -48,49 +48,74 @@ func TestResolveLogPath(t *testing.T) {
|
|||||||
"nginx.service": {"/var/log/nginx/access.log", "/var/log/nginx/error.log"},
|
"nginx.service": {"/var/log/nginx/access.log", "/var/log/nginx/error.log"},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Allowlisted path resolves whether the caller uses the bare or .service
|
t.Run("allowlisted path via bare name", func(t *testing.T) {
|
||||||
// form, regardless of which form the config key used.
|
p, err := resolveLogPath(allow, "nginx", "/var/log/nginx/error.log")
|
||||||
for _, unit := range []string{"nginx.service", "nginx"} {
|
if err != nil || p != "/var/log/nginx/error.log" {
|
||||||
if p, err := resolveLogPath(allow, unit, "/var/log/nginx/error.log"); err != nil || p != "/var/log/nginx/error.log" {
|
t.Errorf("got %q, %v", p, err)
|
||||||
t.Errorf("allowlisted path for %q: got %q, %v", unit, 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),
|
for _, tt := range []struct {
|
||||||
// listed path but wrong unit, and unit with no allowlist at all.
|
name string
|
||||||
bad := []struct{ unit, path string }{
|
unit string
|
||||||
{"nginx.service", ""},
|
path string
|
||||||
{"nginx.service", "/etc/shadow"},
|
}{
|
||||||
{"nginx.service", "/var/log/nginx/access.log/../../../etc/shadow"},
|
{name: "empty path", unit: "nginx.service", path: ""},
|
||||||
{"sshd.service", "/var/log/nginx/error.log"},
|
{name: "non-allowlisted path", unit: "nginx.service", path: "/etc/shadow"},
|
||||||
{"unknown.service", "/var/log/nginx/error.log"},
|
{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"},
|
||||||
for _, b := range bad {
|
{name: "unknown unit", unit: "unknown.service", path: "/var/log/nginx/error.log"},
|
||||||
if _, err := resolveLogPath(allow, b.unit, b.path); err == nil {
|
} {
|
||||||
t.Errorf("resolveLogPath(%q, %q) = nil error, want rejection", b.unit, b.path)
|
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) {
|
func TestJournalUnit(t *testing.T) {
|
||||||
cases := map[string]string{
|
tests := []struct {
|
||||||
"docker.service": "docker",
|
name string
|
||||||
"docker": "docker",
|
in string
|
||||||
"sshd.service": "sshd",
|
want string
|
||||||
"foo.socket": "foo.socket", // only .service is stripped
|
}{
|
||||||
|
{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 {
|
for _, tt := range tests {
|
||||||
if got := journalUnit(in); got != want {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
t.Errorf("journalUnit(%q) = %q, want %q", in, got, want)
|
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) {
|
func TestClampLines(t *testing.T) {
|
||||||
cases := map[int]int{0: defaultLogLines, -5: defaultLogLines, 50: 50, 999999: maxLogLines}
|
tests := []struct {
|
||||||
for in, want := range cases {
|
name string
|
||||||
if got := clampLines(in); got != want {
|
in int
|
||||||
t.Errorf("clampLines(%d) = %d, want %d", in, got, want)
|
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)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,12 @@ import (
|
|||||||
"github.com/danielgtaylor/huma/v2"
|
"github.com/danielgtaylor/huma/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// selfUnit is nadir's own systemd unit name. Acting on it via the normal
|
||||||
|
// synchronous path would have systemd SIGTERM the very process serving the
|
||||||
|
// request, so the client sees a dropped connection / 500 even though the
|
||||||
|
// action succeeded. We detach those calls into a Setsid subprocess instead.
|
||||||
|
const selfUnit = "nadir"
|
||||||
|
|
||||||
const tagServices = "Services"
|
const tagServices = "Services"
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -136,6 +142,9 @@ func registerServices(api huma.API) {
|
|||||||
if err := ensureExists(in.Unit); err != nil {
|
if err := ensureExists(in.Unit); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if isSelf(in.Unit) {
|
||||||
|
return runDetached(c.action, in.Unit)
|
||||||
|
}
|
||||||
if _, err := oscmd.Run("systemctl", c.action, "--", in.Unit); err != nil {
|
if _, err := oscmd.Run("systemctl", c.action, "--", in.Unit); err != nil {
|
||||||
return nil, huma.Error500InternalServerError("systemctl "+c.action+" failed", err)
|
return nil, huma.Error500InternalServerError("systemctl "+c.action+" failed", err)
|
||||||
}
|
}
|
||||||
@@ -144,6 +153,24 @@ func registerServices(api huma.API) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// isSelf reports whether unit names nadir's own service, with or without the
|
||||||
|
// .service suffix.
|
||||||
|
func isSelf(unit string) bool {
|
||||||
|
return unit == selfUnit || unit == selfUnit+".service"
|
||||||
|
}
|
||||||
|
|
||||||
|
// runDetached fires systemctl in a new session so a "systemctl restart nadir"
|
||||||
|
// (or stop) doesn't kill its own caller before the HTTP response is written.
|
||||||
|
// 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) {
|
||||||
|
out, err := oscmd.RunDetached("systemctl", action, "--", unit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, huma.Error500InternalServerError("could not start detached systemctl", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
// validateUnit guards against empty, flag-like, or malformed unit names.
|
// validateUnit guards against empty, flag-like, or malformed unit names.
|
||||||
func validateUnit(unit string) error {
|
func validateUnit(unit string) error {
|
||||||
if unit == "" || strings.HasPrefix(unit, "-") || !unitNameRe.MatchString(unit) {
|
if unit == "" || strings.HasPrefix(unit, "-") || !unitNameRe.MatchString(unit) {
|
||||||
|
|||||||
@@ -3,19 +3,58 @@ package services
|
|||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
func TestValidateUnit(t *testing.T) {
|
func TestValidateUnit(t *testing.T) {
|
||||||
valid := []string{"sshd.service", "getty@tty1.service", "foo.bar:baz-1.service", "a_b.timer"}
|
for _, tt := range []struct {
|
||||||
for _, u := range valid {
|
name string
|
||||||
if err := validateUnit(u); err != nil {
|
value string
|
||||||
t.Errorf("validateUnit(%q) = %v, want nil", u, err)
|
valid bool
|
||||||
}
|
}{
|
||||||
}
|
{name: "sshd.service", value: "sshd.service", valid: true},
|
||||||
|
{name: "template", value: "getty@tty1.service", valid: true},
|
||||||
// Empty, flag-injection, and anything with shell/path metacharacters must
|
{name: "dots and colons", value: "foo.bar:baz-1.service", valid: true},
|
||||||
// be rejected before reaching systemctl.
|
{name: "timer", value: "a_b.timer", valid: true},
|
||||||
invalid := []string{"", "-rf", "--now", "a b", "foo;rm -rf /", "a/b", "naughty$()", "x|y"}
|
{name: "empty", value: "", valid: false},
|
||||||
for _, u := range invalid {
|
{name: "flag injection", value: "-rf", valid: false},
|
||||||
if err := validateUnit(u); err == nil {
|
{name: "double dash", value: "--now", valid: false},
|
||||||
t.Errorf("validateUnit(%q) = nil, want error", u)
|
{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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestIsSelf pins the dispatch that detaches stop/restart-of-self into a
|
||||||
|
// Setsid subprocess. Both "nadir" and "nadir.service" must match; anything
|
||||||
|
// else (including substrings) must not, or unrelated services would also get
|
||||||
|
// detached and bypass the synchronous error path.
|
||||||
|
func TestIsSelf(t *testing.T) {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"nadir/internal/mounts"
|
"nadir/internal/mounts"
|
||||||
"nadir/internal/oscmd"
|
"nadir/internal/oscmd"
|
||||||
@@ -16,6 +17,10 @@ import (
|
|||||||
// fstabFile is a var so tests can point it at a fixture.
|
// fstabFile is a var so tests can point it at a fixture.
|
||||||
var fstabFile = "/etc/fstab"
|
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
|
// FstabEntry is one /etc/fstab line. Dump and Pass are the last two numeric
|
||||||
// fields (fs_freq and fs_passno).
|
// fields (fs_freq and fs_passno).
|
||||||
type FstabEntry struct {
|
type FstabEntry struct {
|
||||||
@@ -67,7 +72,7 @@ func registerStorage(api huma.API) {
|
|||||||
}, func(ctx context.Context, _ *struct{}) (*ListMountsOutput, error) {
|
}, func(ctx context.Context, _ *struct{}) (*ListMountsOutput, error) {
|
||||||
entries, err := mounts.Proc()
|
entries, err := mounts.Proc()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("read mounts failed", err)
|
return nil, huma.Error500InternalServerError("mount table lookup failed", err)
|
||||||
}
|
}
|
||||||
res := &ListMountsOutput{}
|
res := &ListMountsOutput{}
|
||||||
res.Body.Mounts = entries
|
res.Body.Mounts = entries
|
||||||
@@ -86,7 +91,7 @@ func registerStorage(api huma.API) {
|
|||||||
}, func(ctx context.Context, _ *struct{}) (*ListFstabOutput, error) {
|
}, func(ctx context.Context, _ *struct{}) (*ListFstabOutput, error) {
|
||||||
data, err := os.ReadFile(fstabFile)
|
data, err := os.ReadFile(fstabFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("read fstab failed", err)
|
return nil, huma.Error500InternalServerError("fstab lookup failed", err)
|
||||||
}
|
}
|
||||||
res := &ListFstabOutput{}
|
res := &ListFstabOutput{}
|
||||||
res.Body.Entries = parseFstab(string(data))
|
res.Body.Entries = parseFstab(string(data))
|
||||||
@@ -121,7 +126,7 @@ func registerStorage(api huma.API) {
|
|||||||
|
|
||||||
existing, err := readFstab()
|
existing, err := readFstab()
|
||||||
if err != nil {
|
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 {
|
if findEntry(existing, e.Mountpoint) != nil {
|
||||||
return nil, huma.Error409Conflict("an fstab entry already exists for " + e.Mountpoint)
|
return nil, huma.Error409Conflict("an fstab entry already exists for " + e.Mountpoint)
|
||||||
@@ -158,13 +163,13 @@ func registerStorage(api huma.API) {
|
|||||||
|
|
||||||
entries, err := readFstab()
|
entries, err := readFstab()
|
||||||
if err != nil {
|
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
|
inFstab := findEntry(entries, in.Mountpoint) != nil
|
||||||
|
|
||||||
mounted, err := isMounted(in.Mountpoint)
|
mounted, err := isMounted(in.Mountpoint)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("read mounts failed", err)
|
return nil, huma.Error500InternalServerError("mount table lookup failed", err)
|
||||||
}
|
}
|
||||||
if !inFstab && !mounted {
|
if !inFstab && !mounted {
|
||||||
return nil, huma.Error404NotFound("no mount or fstab entry for " + in.Mountpoint)
|
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)
|
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.
|
// appendFstabLine adds one entry, leaving every existing line untouched.
|
||||||
func appendFstabLine(e FstabEntry) error {
|
func appendFstabLine(e FstabEntry) error {
|
||||||
|
fstabMu.Lock()
|
||||||
|
defer fstabMu.Unlock()
|
||||||
|
|
||||||
data, err := os.ReadFile(fstabFile)
|
data, err := os.ReadFile(fstabFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -242,12 +264,15 @@ func appendFstabLine(e FstabEntry) error {
|
|||||||
content += "\n"
|
content += "\n"
|
||||||
}
|
}
|
||||||
content += renderFstabLine(e) + "\n"
|
content += renderFstabLine(e) + "\n"
|
||||||
return os.WriteFile(fstabFile, []byte(content), 0644)
|
return writeFstabAtomically(content)
|
||||||
}
|
}
|
||||||
|
|
||||||
// removeFstabLines drops every line mapping mountpoint, preserving comments and
|
// removeFstabLines drops every line mapping mountpoint, preserving comments and
|
||||||
// other entries. Reports whether anything was removed.
|
// other entries. Reports whether anything was removed.
|
||||||
func removeFstabLines(mountpoint string) (bool, error) {
|
func removeFstabLines(mountpoint string) (bool, error) {
|
||||||
|
fstabMu.Lock()
|
||||||
|
defer fstabMu.Unlock()
|
||||||
|
|
||||||
data, err := os.ReadFile(fstabFile)
|
data, err := os.ReadFile(fstabFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
@@ -268,7 +293,7 @@ func removeFstabLines(mountpoint string) (bool, error) {
|
|||||||
if !removed {
|
if !removed {
|
||||||
return false, nil
|
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 {
|
func findEntry(entries []FstabEntry, mountpoint string) *FstabEntry {
|
||||||
|
|||||||
@@ -79,23 +79,27 @@ func mustReadFstab(t *testing.T) []FstabEntry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestValidateEntry(t *testing.T) {
|
func TestValidateEntry(t *testing.T) {
|
||||||
ok := FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/data", FSType: "ext4", Options: "defaults"}
|
for _, tt := range []struct {
|
||||||
if err := validateEntry(ok); err != nil {
|
name string
|
||||||
t.Errorf("valid entry rejected: %v", err)
|
entry FstabEntry
|
||||||
}
|
valid bool
|
||||||
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)
|
{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},
|
||||||
bad := []FstabEntry{
|
{name: "shell metachar in device", entry: FstabEntry{Device: "/dev/sdb1; rm -rf /", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults"}, valid: false},
|
||||||
{Device: "/dev/sdb1; rm -rf /", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults"}, // shell metachars
|
{name: "relative mountpoint", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "../etc", FSType: "ext4", Options: "defaults"}, valid: false},
|
||||||
{Device: "/dev/sdb1", Mountpoint: "../etc", FSType: "ext4", Options: "defaults"}, // not absolute
|
{name: "traversal in mountpoint", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/../../etc", FSType: "ext4", Options: "defaults"}, valid: false},
|
||||||
{Device: "/dev/sdb1", Mountpoint: "/mnt/../../etc", FSType: "ext4", Options: "defaults"}, // traversal
|
{name: "bad fstype", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4!", Options: "defaults"}, valid: false},
|
||||||
{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4!", Options: "defaults"}, // bad fstype
|
{name: "bad options", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults; reboot"}, valid: false},
|
||||||
{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults; reboot"}, // bad options
|
} {
|
||||||
}
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
for i, e := range bad {
|
err := validateEntry(tt.entry)
|
||||||
if err := validateEntry(e); err == nil {
|
if tt.valid && err != nil {
|
||||||
t.Errorf("bad entry %d accepted: %+v", i, e)
|
t.Errorf("valid entry rejected: %v", err)
|
||||||
}
|
}
|
||||||
|
if !tt.valid && err == nil {
|
||||||
|
t.Errorf("bad entry accepted: %+v", tt.entry)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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 0–100", 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package system
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"nadir/internal/oscmd"
|
"nadir/internal/oscmd"
|
||||||
@@ -9,6 +10,11 @@ import (
|
|||||||
"github.com/danielgtaylor/huma/v2"
|
"github.com/danielgtaylor/huma/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// hostnameRe matches RFC-1123 labels joined by dots, max 253 chars total. Anchored
|
||||||
|
// so a leading "-" can't be read as a hostnamectl flag and shell metacharacters
|
||||||
|
// can't survive — same pattern the other modules use (CLAUDE.md §5).
|
||||||
|
var hostnameRe = regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9-]{0,62})(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,62}))*$`)
|
||||||
|
|
||||||
type HostnameBody struct {
|
type HostnameBody struct {
|
||||||
Hostname string `json:"hostname" example:"server01" doc:"System hostname"`
|
Hostname string `json:"hostname" example:"server01" doc:"System hostname"`
|
||||||
}
|
}
|
||||||
@@ -49,7 +55,10 @@ func registerHostname(api huma.API) {
|
|||||||
if name == "" {
|
if name == "" {
|
||||||
return nil, huma.Error400BadRequest("empty hostname")
|
return nil, huma.Error400BadRequest("empty hostname")
|
||||||
}
|
}
|
||||||
if _, err := oscmd.Run("hostnamectl", "set-hostname", name); err != nil {
|
if len(name) > 253 || !hostnameRe.MatchString(name) {
|
||||||
|
return nil, huma.Error400BadRequest("invalid hostname: " + name)
|
||||||
|
}
|
||||||
|
if _, err := oscmd.Run("hostnamectl", "set-hostname", "--", name); err != nil {
|
||||||
return nil, huma.Error500InternalServerError("hostnamectl failed", err)
|
return nil, huma.Error500InternalServerError("hostnamectl failed", err)
|
||||||
}
|
}
|
||||||
return oscmd.OK(), nil
|
return oscmd.OK(), nil
|
||||||
|
|||||||
@@ -2,25 +2,16 @@ package system
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"math"
|
|
||||||
"net"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
|
||||||
"syscall"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"nadir/internal/mounts"
|
|
||||||
"nadir/internal/oscmd"
|
|
||||||
|
|
||||||
"github.com/danielgtaylor/huma/v2"
|
"github.com/danielgtaylor/huma/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SystemInfoBody is the dashboard overview: OS identity plus live CPU, memory,
|
// 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
|
// 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.
|
// value or empty list rather than failing the whole call.
|
||||||
type SystemInfoBody struct {
|
type SystemInfoBody struct {
|
||||||
@@ -33,71 +24,12 @@ type SystemInfoBody struct {
|
|||||||
Disks []DiskInfo `json:"disks" doc:"Mounted block-device filesystems"`
|
Disks []DiskInfo `json:"disks" doc:"Mounted block-device filesystems"`
|
||||||
NetworkInterfaces []NetInterface `json:"network_interfaces" doc:"Network interfaces and their addresses"`
|
NetworkInterfaces []NetInterface `json:"network_interfaces" doc:"Network interfaces and their addresses"`
|
||||||
Temperatures []Temperature `json:"temperatures" doc:"Thermal sensor readings in Celsius"`
|
Temperatures []Temperature `json:"temperatures" doc:"Thermal sensor readings in Celsius"`
|
||||||
}
|
GPUs []GPUInfo `json:"gpus" doc:"Graphics processors detected via DRM sysfs"`
|
||||||
|
|
||||||
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 (0–100)"`
|
|
||||||
}
|
|
||||||
|
|
||||||
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"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type GetInfoOutput struct{ Body SystemInfoBody }
|
type GetInfoOutput struct{ Body SystemInfoBody }
|
||||||
|
|
||||||
func registerInfo(api huma.API) {
|
func registerInfo(api huma.API, sampler *Sampler) {
|
||||||
startCPUSampler()
|
|
||||||
huma.Register(api, huma.Operation{
|
huma.Register(api, huma.Operation{
|
||||||
OperationID: "system-get-info",
|
OperationID: "system-get-info",
|
||||||
Method: "GET",
|
Method: "GET",
|
||||||
@@ -105,9 +37,9 @@ func registerInfo(api huma.API) {
|
|||||||
Summary: "Get system information",
|
Summary: "Get system information",
|
||||||
Description: "Returns an overview for a dashboard: OS/kernel identity, CPU, " +
|
Description: "Returns an overview for a dashboard: OS/kernel identity, CPU, " +
|
||||||
"memory and swap, mounted disks, load averages, uptime, network " +
|
"memory and swap, mounted disks, load averages, uptime, network " +
|
||||||
"interfaces, and temperatures. All values come from cheap local reads " +
|
"interfaces, temperatures, and GPU information. All values come from cheap " +
|
||||||
"(/proc, /sys, syscalls) with no D-Bus dependency; each section is " +
|
"local reads (/proc, /sys, syscalls) with no D-Bus dependency; each " +
|
||||||
"best-effort.",
|
"section is best-effort.",
|
||||||
Tags: []string{tagSystem},
|
Tags: []string{tagSystem},
|
||||||
Metadata: op("read"),
|
Metadata: op("read"),
|
||||||
Errors: readErrors,
|
Errors: readErrors,
|
||||||
@@ -117,298 +49,17 @@ func registerInfo(api huma.API) {
|
|||||||
OS: osInfo(),
|
OS: osInfo(),
|
||||||
CPU: cpuInfo(),
|
CPU: cpuInfo(),
|
||||||
Memory: memInfo(),
|
Memory: memInfo(),
|
||||||
Load: loadInfo(),
|
Load: loadInfo(sampler),
|
||||||
UptimeSec: uptime,
|
UptimeSec: uptime,
|
||||||
BootTime: boot.Format(time.RFC3339),
|
BootTime: boot.Format(time.RFC3339),
|
||||||
Disks: diskInfo(),
|
Disks: diskInfo(),
|
||||||
NetworkInterfaces: netInfo(),
|
NetworkInterfaces: netInfo(),
|
||||||
Temperatures: tempInfo(),
|
Temperatures: tempInfo(),
|
||||||
|
GPUs: gpuInfo(),
|
||||||
}}, nil
|
}}, 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.
|
|
||||||
if mhz := cpuinfoMaxMHz(string(data)); 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
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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.
|
// uptimeAndBoot reads /proc/uptime (seconds since boot) and derives boot time.
|
||||||
// On any read error it returns zero values rather than failing the request.
|
// On any read error it returns zero values rather than failing the request.
|
||||||
func uptimeAndBoot() (int64, time.Time) {
|
func uptimeAndBoot() (int64, time.Time) {
|
||||||
@@ -427,127 +78,3 @@ func uptimeAndBoot() (int64, time.Time) {
|
|||||||
boot := time.Now().Add(-time.Duration(secs * float64(time.Second))).UTC()
|
boot := time.Now().Add(-time.Duration(secs * float64(time.Second))).UTC()
|
||||||
return int64(secs), boot
|
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 {
|
|
||||||
// Only real block devices; skip pseudo filesystems and snap's squashfs
|
|
||||||
// loop mounts that would otherwise clutter the list.
|
|
||||||
if !strings.HasPrefix(e.Device, "/dev/") || e.FSType == "squashfs" || 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
|
|
||||||
}
|
|
||||||
|
|
||||||
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))
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -6,6 +6,106 @@ import (
|
|||||||
"testing"
|
"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) {
|
func TestReadHwmonTemps(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
// k10temp: CPU, labelled Tctl.
|
// 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) {
|
func write(t *testing.T, root, chip, file, val string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
dir := filepath.Join(root, chip)
|
dir := filepath.Join(root, chip)
|
||||||
|
|||||||
@@ -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 (0–100)"`
|
||||||
|
}
|
||||||
|
|
||||||
|
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)}
|
||||||
|
}
|
||||||
@@ -2,6 +2,10 @@ package system
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"regexp"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -12,6 +16,7 @@ import (
|
|||||||
|
|
||||||
type LocaleStatusBody struct {
|
type LocaleStatusBody struct {
|
||||||
Lang string `json:"lang" example:"it_IT.UTF-8" doc:"System locale (LANG)"`
|
Lang string `json:"lang" example:"it_IT.UTF-8" doc:"System locale (LANG)"`
|
||||||
|
Language string `json:"language" example:"en_US:" doc:"Fallback language list (LANGUAGE)"`
|
||||||
VCKeymap string `json:"vc_keymap" example:"it" doc:"Virtual console keymap"`
|
VCKeymap string `json:"vc_keymap" example:"it" doc:"Virtual console keymap"`
|
||||||
X11Layout string `json:"x11_layout" example:"it" doc:"X11 keyboard layout"`
|
X11Layout string `json:"x11_layout" example:"it" doc:"X11 keyboard layout"`
|
||||||
}
|
}
|
||||||
@@ -27,12 +32,14 @@ type LocalesOutput struct {
|
|||||||
type KeymapsOutput struct {
|
type KeymapsOutput struct {
|
||||||
Body struct {
|
Body struct {
|
||||||
Keymaps []string `json:"keymaps" doc:"Available virtual console keymaps"`
|
Keymaps []string `json:"keymaps" doc:"Available virtual console keymaps"`
|
||||||
|
Reason string `json:"reason,omitempty" doc:"When keymaps is empty, why: e.g. \"kbd not installed on this server\""`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type SetLocaleInput struct {
|
type SetLocaleInput struct {
|
||||||
Body struct {
|
Body struct {
|
||||||
Lang string `json:"lang" example:"it_IT.UTF-8" doc:"Locale to set as LANG"`
|
Lang string `json:"lang" example:"it_IT.UTF-8" doc:"Locale to set as LANG"`
|
||||||
|
Language *string `json:"language,omitempty" example:"en_US:" doc:"Fallback language list (LANGUAGE)"`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,6 +49,20 @@ type SetKeymapInput struct {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type GenerateLocaleInput struct {
|
||||||
|
Body struct {
|
||||||
|
Locale string `json:"locale" example:"fr_FR.UTF-8" doc:"Locale to generate (e.g. fr_FR.UTF-8)"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// localeRe validates a locale identifier: language_TERRITORY with an optional
|
||||||
|
// .charmap suffix (e.g. fr_FR, fr_FR.UTF-8, en_US.ISO-8859-1).
|
||||||
|
var localeRe = regexp.MustCompile(`^[a-z]{2,3}_[A-Z]{2}(\.[A-Za-z0-9_-]+)?$`)
|
||||||
|
|
||||||
|
// languageRe validates the LANGUAGE fallback list: colon-separated locale names
|
||||||
|
// like "en_US:de_DE". Anchored so a leading "-" can't survive into argv.
|
||||||
|
var languageRe = regexp.MustCompile(`^[a-zA-Z0-9_.:-]*$`)
|
||||||
|
|
||||||
func localeStatus() (LocaleStatusBody, error) {
|
func localeStatus() (LocaleStatusBody, error) {
|
||||||
lines, err := oscmd.RunLines("localectl", "status")
|
lines, err := oscmd.RunLines("localectl", "status")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -49,21 +70,28 @@ func localeStatus() (LocaleStatusBody, error) {
|
|||||||
}
|
}
|
||||||
var b LocaleStatusBody
|
var b LocaleStatusBody
|
||||||
for _, line := range lines {
|
for _, line := range lines {
|
||||||
label, val, ok := strings.Cut(line, ":")
|
trimmed := strings.TrimSpace(line)
|
||||||
if !ok {
|
if strings.HasPrefix(trimmed, "VC Keymap:") {
|
||||||
|
b.VCKeymap = strings.TrimSpace(strings.TrimPrefix(trimmed, "VC Keymap:"))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
switch strings.TrimSpace(label) {
|
if strings.HasPrefix(trimmed, "X11 Layout:") {
|
||||||
case "System Locale":
|
b.X11Layout = strings.TrimSpace(strings.TrimPrefix(trimmed, "X11 Layout:"))
|
||||||
for kv := range strings.FieldsSeq(val) {
|
continue
|
||||||
if k, v, ok := strings.Cut(kv, "="); ok && k == "LANG" {
|
}
|
||||||
|
// Parse k=v fields on any other line (like System Locale block).
|
||||||
|
parts := strings.Fields(trimmed)
|
||||||
|
for _, part := range parts {
|
||||||
|
part = strings.TrimPrefix(part, "System Locale:")
|
||||||
|
part = strings.TrimSpace(part)
|
||||||
|
if k, v, ok := strings.Cut(part, "="); ok {
|
||||||
|
switch k {
|
||||||
|
case "LANG":
|
||||||
b.Lang = v
|
b.Lang = v
|
||||||
|
case "LANGUAGE":
|
||||||
|
b.Language = v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case "VC Keymap":
|
|
||||||
b.VCKeymap = strings.TrimSpace(val)
|
|
||||||
case "X11 Layout":
|
|
||||||
b.X11Layout = strings.TrimSpace(val)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return b, nil
|
return b, nil
|
||||||
@@ -130,7 +158,17 @@ func registerLocale(api huma.API) {
|
|||||||
if !slices.Contains(locales, lang) {
|
if !slices.Contains(locales, lang) {
|
||||||
return nil, huma.Error400BadRequest("unknown locale: " + lang)
|
return nil, huma.Error400BadRequest("unknown locale: " + lang)
|
||||||
}
|
}
|
||||||
if _, err := oscmd.Run("localectl", "set-locale", "LANG="+lang); err != nil {
|
|
||||||
|
args := []string{"set-locale", "LANG=" + lang}
|
||||||
|
if in.Body.Language != nil {
|
||||||
|
langVal := strings.TrimSpace(*in.Body.Language)
|
||||||
|
if !languageRe.MatchString(langVal) {
|
||||||
|
return nil, huma.Error400BadRequest("invalid language format: " + langVal)
|
||||||
|
}
|
||||||
|
args = append(args, "LANGUAGE="+langVal)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := oscmd.Run("localectl", args...); err != nil {
|
||||||
return nil, huma.Error500InternalServerError("set-locale failed", err)
|
return nil, huma.Error500InternalServerError("set-locale failed", err)
|
||||||
}
|
}
|
||||||
return oscmd.OK(), nil
|
return oscmd.OK(), nil
|
||||||
@@ -146,12 +184,15 @@ func registerLocale(api huma.API) {
|
|||||||
Metadata: op("read"),
|
Metadata: op("read"),
|
||||||
Errors: readErrors,
|
Errors: readErrors,
|
||||||
}, func(ctx context.Context, _ *struct{}) (*KeymapsOutput, error) {
|
}, func(ctx context.Context, _ *struct{}) (*KeymapsOutput, error) {
|
||||||
|
// ponytail: minimal servers ship without kbd / /usr/share/keymaps, so
|
||||||
|
// localectl errors instead of returning empty. Surface that as a `reason`
|
||||||
|
// the frontend can display ("kbd not installed") instead of an opaque N/A.
|
||||||
keymaps, err := oscmd.RunLines("localectl", "list-keymaps")
|
keymaps, err := oscmd.RunLines("localectl", "list-keymaps")
|
||||||
if err != nil {
|
|
||||||
return nil, huma.Error500InternalServerError("localectl failed", err)
|
|
||||||
}
|
|
||||||
out := &KeymapsOutput{}
|
out := &KeymapsOutput{}
|
||||||
out.Body.Keymaps = keymaps
|
out.Body.Keymaps = keymaps
|
||||||
|
if err != nil || len(keymaps) == 0 {
|
||||||
|
out.Body.Reason = "kbd is not installed on this server (install the kbd / console-data package to enable keymap selection)"
|
||||||
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -171,10 +212,9 @@ func registerLocale(api huma.API) {
|
|||||||
if km == "" {
|
if km == "" {
|
||||||
return nil, huma.Error400BadRequest("empty keymap")
|
return nil, huma.Error400BadRequest("empty keymap")
|
||||||
}
|
}
|
||||||
keymaps, err := oscmd.RunLines("localectl", "list-keymaps")
|
// list-keymaps failure means no keymap allowlist on this host (kbd absent);
|
||||||
if err != nil {
|
// fall through to unknown-keymap 400 instead of 500.
|
||||||
return nil, huma.Error500InternalServerError("localectl failed", err)
|
keymaps, _ := oscmd.RunLines("localectl", "list-keymaps")
|
||||||
}
|
|
||||||
if !slices.Contains(keymaps, km) {
|
if !slices.Contains(keymaps, km) {
|
||||||
return nil, huma.Error400BadRequest("unknown keymap: " + km)
|
return nil, huma.Error400BadRequest("unknown keymap: " + km)
|
||||||
}
|
}
|
||||||
@@ -183,4 +223,124 @@ func registerLocale(api huma.API) {
|
|||||||
}
|
}
|
||||||
return oscmd.OK(), nil
|
return oscmd.OK(), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
huma.Register(api, huma.Operation{
|
||||||
|
OperationID: "system-generate-locale",
|
||||||
|
Method: "POST",
|
||||||
|
Path: "/api/system/locale/generate",
|
||||||
|
Summary: "Generate (install) a new locale",
|
||||||
|
Description: "Generates a locale so it becomes available for use with set-locale. " +
|
||||||
|
"On Debian/Ubuntu/Arch this uncomments the entry in /etc/locale.gen and runs " +
|
||||||
|
"locale-gen; on RHEL/Fedora it uses localedef. Idempotent: if the locale is " +
|
||||||
|
"already generated, returns 200 immediately.",
|
||||||
|
Tags: []string{tagSystem},
|
||||||
|
Metadata: op("write"),
|
||||||
|
Errors: []int{400, 401, 403, 500, 501},
|
||||||
|
}, func(ctx context.Context, in *GenerateLocaleInput) (*oscmd.StatusOutput, error) {
|
||||||
|
locale := strings.TrimSpace(in.Body.Locale)
|
||||||
|
if locale == "" {
|
||||||
|
return nil, huma.Error400BadRequest("empty locale")
|
||||||
|
}
|
||||||
|
if !localeRe.MatchString(locale) {
|
||||||
|
return nil, huma.Error400BadRequest("invalid locale format: "+locale,
|
||||||
|
fmt.Errorf("expected language_TERRITORY[.charmap], e.g. fr_FR.UTF-8"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Idempotency: already generated → success.
|
||||||
|
existing, err := oscmd.RunLines("localectl", "list-locales")
|
||||||
|
if err != nil {
|
||||||
|
return nil, huma.Error500InternalServerError("localectl failed", err)
|
||||||
|
}
|
||||||
|
if slices.Contains(existing, locale) {
|
||||||
|
return oscmd.OK(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detect which generation path the host supports.
|
||||||
|
localeGenFile := "/etc/locale.gen"
|
||||||
|
_, hasFile := os.Stat(localeGenFile)
|
||||||
|
_, hasLocaleGen := exec.LookPath("locale-gen")
|
||||||
|
_, hasLocaledef := exec.LookPath("localedef")
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case hasFile == nil && hasLocaleGen == nil:
|
||||||
|
if err := enableLocaleGen(localeGenFile, locale); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
case hasLocaledef == nil:
|
||||||
|
if err := generateLocaledef(locale); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return nil, huma.Error501NotImplemented(
|
||||||
|
"locale generation not supported on this host (no locale-gen or localedef found)")
|
||||||
|
}
|
||||||
|
return oscmd.OK(), nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// enableLocaleGen uncomments the locale in /etc/locale.gen and runs locale-gen.
|
||||||
|
// This is the Debian/Ubuntu/Arch path.
|
||||||
|
func enableLocaleGen(path, locale string) error {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return huma.Error500InternalServerError("reading locale.gen failed", err)
|
||||||
|
}
|
||||||
|
newContent, found := uncommentLocaleGen(string(data), locale)
|
||||||
|
if !found {
|
||||||
|
return huma.Error400BadRequest("locale not available for generation: " + locale)
|
||||||
|
}
|
||||||
|
// Write atomically: a crash mid-write would leave /etc/locale.gen truncated
|
||||||
|
// and break every subsequent locale-gen on the host.
|
||||||
|
tmp := path + ".nadir.tmp"
|
||||||
|
if err := os.WriteFile(tmp, []byte(newContent), 0644); err != nil {
|
||||||
|
return huma.Error500InternalServerError("writing locale.gen failed", err)
|
||||||
|
}
|
||||||
|
if err := os.Rename(tmp, path); err != nil {
|
||||||
|
os.Remove(tmp)
|
||||||
|
return huma.Error500InternalServerError("replacing locale.gen failed", err)
|
||||||
|
}
|
||||||
|
if _, err := oscmd.Run("locale-gen"); err != nil {
|
||||||
|
return huma.Error500InternalServerError("locale-gen failed", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// uncommentLocaleGen finds a commented-out line for the given locale in a
|
||||||
|
// locale.gen file and uncomments it. Returns the modified content and whether
|
||||||
|
// a matching line was found. Pure function for testability.
|
||||||
|
func uncommentLocaleGen(content, locale string) (string, bool) {
|
||||||
|
lines := strings.Split(content, "\n")
|
||||||
|
found := false
|
||||||
|
for i, line := range lines {
|
||||||
|
trimmed := strings.TrimSpace(line)
|
||||||
|
// Match lines like "# fr_FR.UTF-8 UTF-8" or "#fr_FR.UTF-8 UTF-8".
|
||||||
|
if !strings.HasPrefix(trimmed, "#") {
|
||||||
|
// Also check if already uncommented (idempotent at the file level).
|
||||||
|
if strings.HasPrefix(trimmed, locale+" ") || trimmed == locale {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
uncommented := strings.TrimSpace(strings.TrimPrefix(trimmed, "#"))
|
||||||
|
if strings.HasPrefix(uncommented, locale+" ") || uncommented == locale {
|
||||||
|
lines[i] = uncommented
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n"), found
|
||||||
|
}
|
||||||
|
|
||||||
|
// generateLocaledef generates a locale using localedef. This is the RHEL/Fedora
|
||||||
|
// path where there is no /etc/locale.gen.
|
||||||
|
func generateLocaledef(locale string) error {
|
||||||
|
// Parse "fr_FR.UTF-8" into language_territory="fr_FR" and charmap="UTF-8".
|
||||||
|
// If there is no dot, default to UTF-8 (the common case on modern systems).
|
||||||
|
langTerritory, charmap, _ := strings.Cut(locale, ".")
|
||||||
|
if charmap == "" {
|
||||||
|
charmap = "UTF-8"
|
||||||
|
}
|
||||||
|
if _, err := oscmd.Run("localedef", "-i", langTerritory, "-f", charmap, locale); err != nil {
|
||||||
|
return huma.Error500InternalServerError("localedef failed", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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"],
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
package system
|
package system
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
"nadir/internal/rbac"
|
"nadir/internal/rbac"
|
||||||
|
|
||||||
"github.com/danielgtaylor/huma/v2"
|
"github.com/danielgtaylor/huma/v2"
|
||||||
@@ -8,9 +11,15 @@ import (
|
|||||||
|
|
||||||
const ModuleID = "system"
|
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 }
|
func (m *Module) ID() string { return ModuleID }
|
||||||
|
|
||||||
@@ -19,7 +28,8 @@ func (m *Module) Permissions() []rbac.Permission {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (m *Module) Register(api huma.API) {
|
func (m *Module) Register(api huma.API) {
|
||||||
registerInfo(api)
|
m.sampler.Start(context.Background())
|
||||||
|
registerInfo(api, m.sampler)
|
||||||
registerHostname(api)
|
registerHostname(api)
|
||||||
registerTimedate(api)
|
registerTimedate(api)
|
||||||
registerLocale(api)
|
registerLocale(api)
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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 ""
|
||||||
|
}
|
||||||
@@ -3,16 +3,34 @@ package system
|
|||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
func TestWhenRe(t *testing.T) {
|
func TestWhenRe(t *testing.T) {
|
||||||
valid := []string{"now", "+0", "+5", "+120", "0:00", "9:30", "23:59", "07:05"}
|
for _, tt := range []struct {
|
||||||
for _, w := range valid {
|
name string
|
||||||
if !whenRe.MatchString(w) {
|
value string
|
||||||
t.Errorf("whenRe.MatchString(%q) = false, want true", w)
|
want bool
|
||||||
}
|
}{
|
||||||
}
|
{name: "now", value: "now", want: true},
|
||||||
invalid := []string{"", "-r", "-h", "--help", "24:00", "9:60", "+5; reboot", "now ", "5", "1:2"}
|
{name: "plus zero", value: "+0", want: true},
|
||||||
for _, w := range invalid {
|
{name: "plus five", value: "+5", want: true},
|
||||||
if whenRe.MatchString(w) {
|
{name: "plus 120", value: "+120", want: true},
|
||||||
t.Errorf("whenRe.MatchString(%q) = true, want false", w)
|
{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)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"nadir/internal/oscmd"
|
"nadir/internal/oscmd"
|
||||||
@@ -21,7 +22,7 @@ func TestSystemHandlers(t *testing.T) {
|
|||||||
registerTimedate(api)
|
registerTimedate(api)
|
||||||
registerLocale(api)
|
registerLocale(api)
|
||||||
registerPower(api)
|
registerPower(api)
|
||||||
registerInfo(api)
|
registerInfo(api, NewSampler("/proc/stat", 0))
|
||||||
|
|
||||||
// Mock uname for GET /api/system/info
|
// Mock uname for GET /api/system/info
|
||||||
oscmd.SetMock("uname", func(args []string) oscmd.MockCommand {
|
oscmd.SetMock("uname", func(args []string) oscmd.MockCommand {
|
||||||
@@ -33,6 +34,14 @@ func TestSystemHandlers(t *testing.T) {
|
|||||||
}
|
}
|
||||||
return oscmd.MockCommand{ExitCode: 1}
|
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()
|
defer oscmd.ClearMocks()
|
||||||
|
|
||||||
// 1. Test GET /api/system/info
|
// 1. Test GET /api/system/info
|
||||||
@@ -46,7 +55,7 @@ func TestSystemHandlers(t *testing.T) {
|
|||||||
if reflect.DeepEqual(args, []string{"hostname"}) {
|
if reflect.DeepEqual(args, []string{"hostname"}) {
|
||||||
return oscmd.MockCommand{Stdout: "server01\n", ExitCode: 0}
|
return oscmd.MockCommand{Stdout: "server01\n", ExitCode: 0}
|
||||||
}
|
}
|
||||||
if reflect.DeepEqual(args, []string{"set-hostname", "server02"}) {
|
if reflect.DeepEqual(args, []string{"set-hostname", "--", "server02"}) {
|
||||||
return oscmd.MockCommand{ExitCode: 0}
|
return oscmd.MockCommand{ExitCode: 0}
|
||||||
}
|
}
|
||||||
return oscmd.MockCommand{ExitCode: 1}
|
return oscmd.MockCommand{ExitCode: 1}
|
||||||
@@ -141,7 +150,7 @@ func TestSystemHandlers(t *testing.T) {
|
|||||||
// 4. Test GET & POST /api/system/locale
|
// 4. Test GET & POST /api/system/locale
|
||||||
oscmd.SetMock("localectl", func(args []string) oscmd.MockCommand {
|
oscmd.SetMock("localectl", func(args []string) oscmd.MockCommand {
|
||||||
if reflect.DeepEqual(args, []string{"status"}) {
|
if reflect.DeepEqual(args, []string{"status"}) {
|
||||||
statusOut := " System Locale: LANG=it_IT.UTF-8\n VC Keymap: it\n X11 Layout: it\n"
|
statusOut := " System Locale: LANG=it_IT.UTF-8\n LANGUAGE=en_US:\n VC Keymap: it\n X11 Layout: it\n"
|
||||||
return oscmd.MockCommand{Stdout: statusOut, ExitCode: 0}
|
return oscmd.MockCommand{Stdout: statusOut, ExitCode: 0}
|
||||||
}
|
}
|
||||||
if reflect.DeepEqual(args, []string{"list-locales"}) {
|
if reflect.DeepEqual(args, []string{"list-locales"}) {
|
||||||
@@ -150,6 +159,9 @@ func TestSystemHandlers(t *testing.T) {
|
|||||||
if reflect.DeepEqual(args, []string{"set-locale", "LANG=it_IT.UTF-8"}) {
|
if reflect.DeepEqual(args, []string{"set-locale", "LANG=it_IT.UTF-8"}) {
|
||||||
return oscmd.MockCommand{ExitCode: 0}
|
return oscmd.MockCommand{ExitCode: 0}
|
||||||
}
|
}
|
||||||
|
if reflect.DeepEqual(args, []string{"set-locale", "LANG=it_IT.UTF-8", "LANGUAGE=en_US:"}) {
|
||||||
|
return oscmd.MockCommand{ExitCode: 0}
|
||||||
|
}
|
||||||
if reflect.DeepEqual(args, []string{"list-keymaps"}) {
|
if reflect.DeepEqual(args, []string{"list-keymaps"}) {
|
||||||
return oscmd.MockCommand{Stdout: "it\nus\n", ExitCode: 0}
|
return oscmd.MockCommand{Stdout: "it\nus\n", ExitCode: 0}
|
||||||
}
|
}
|
||||||
@@ -167,7 +179,7 @@ func TestSystemHandlers(t *testing.T) {
|
|||||||
if err := json.Unmarshal(resp.Body.Bytes(), &localeRes.Body); err != nil {
|
if err := json.Unmarshal(resp.Body.Bytes(), &localeRes.Body); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if localeRes.Body.Lang != "it_IT.UTF-8" || localeRes.Body.VCKeymap != "it" {
|
if localeRes.Body.Lang != "it_IT.UTF-8" || localeRes.Body.Language != "en_US:" || localeRes.Body.VCKeymap != "it" {
|
||||||
t.Errorf("got locale status: %+v", localeRes.Body)
|
t.Errorf("got locale status: %+v", localeRes.Body)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,6 +197,17 @@ func TestSystemHandlers(t *testing.T) {
|
|||||||
t.Errorf("set locale: got %d, want %d", resp.Code, http.StatusOK)
|
t.Errorf("set locale: got %d, want %d", resp.Code, http.StatusOK)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
resp = api.Post("/api/system/locale", struct {
|
||||||
|
Lang string `json:"lang"`
|
||||||
|
Language string `json:"language"`
|
||||||
|
}{
|
||||||
|
Lang: "it_IT.UTF-8",
|
||||||
|
Language: "en_US:",
|
||||||
|
})
|
||||||
|
if resp.Code != http.StatusOK {
|
||||||
|
t.Errorf("set locale with language: got %d, want %d", resp.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
resp = api.Get("/api/system/keymaps")
|
resp = api.Get("/api/system/keymaps")
|
||||||
if resp.Code != http.StatusOK {
|
if resp.Code != http.StatusOK {
|
||||||
t.Errorf("list keymaps: got %d, want %d", resp.Code, http.StatusOK)
|
t.Errorf("list keymaps: got %d, want %d", resp.Code, http.StatusOK)
|
||||||
@@ -199,6 +222,37 @@ func TestSystemHandlers(t *testing.T) {
|
|||||||
t.Errorf("set keymap: got %d, want %d", resp.Code, http.StatusOK)
|
t.Errorf("set keymap: got %d, want %d", resp.Code, http.StatusOK)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 4b. Test POST /api/system/locale/generate (validation & idempotent)
|
||||||
|
// Empty locale → 422 (huma validates non-empty before handler runs)
|
||||||
|
resp = api.Post("/api/system/locale/generate", struct {
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
}{
|
||||||
|
Locale: "",
|
||||||
|
})
|
||||||
|
if resp.Code != http.StatusBadRequest && resp.Code != http.StatusUnprocessableEntity {
|
||||||
|
t.Errorf("generate empty locale: got %d, want 400 or 422", resp.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invalid format → 400
|
||||||
|
resp = api.Post("/api/system/locale/generate", struct {
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
}{
|
||||||
|
Locale: "not-a-locale!!",
|
||||||
|
})
|
||||||
|
if resp.Code != http.StatusBadRequest {
|
||||||
|
t.Errorf("generate invalid locale: got %d, want %d", resp.Code, http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Already generated (it_IT.UTF-8 is in list-locales mock) → 200 (idempotent)
|
||||||
|
resp = api.Post("/api/system/locale/generate", struct {
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
}{
|
||||||
|
Locale: "it_IT.UTF-8",
|
||||||
|
})
|
||||||
|
if resp.Code != http.StatusOK {
|
||||||
|
t.Errorf("generate existing locale (idempotent): got %d, want %d", resp.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
// 5. Test POST /api/system/reboot and /api/system/poweroff
|
// 5. Test POST /api/system/reboot and /api/system/poweroff
|
||||||
oscmd.SetMock("shutdown", func(args []string) oscmd.MockCommand {
|
oscmd.SetMock("shutdown", func(args []string) oscmd.MockCommand {
|
||||||
if reflect.DeepEqual(args, []string{"-r", "now"}) || reflect.DeepEqual(args, []string{"-h", "now"}) {
|
if reflect.DeepEqual(args, []string{"-r", "now"}) || reflect.DeepEqual(args, []string{"-h", "now"}) {
|
||||||
@@ -225,3 +279,58 @@ func TestSystemHandlers(t *testing.T) {
|
|||||||
t.Errorf("poweroff: got %d, want %d", resp.Code, http.StatusOK)
|
t.Errorf("poweroff: got %d, want %d", resp.Code, http.StatusOK)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestUncommentLocaleGen(t *testing.T) {
|
||||||
|
const sampleLocaleGen = `# This file lists locales that you wish to have built.
|
||||||
|
#
|
||||||
|
# en_US.UTF-8 UTF-8
|
||||||
|
# fr_FR.UTF-8 UTF-8
|
||||||
|
# de_DE.UTF-8 UTF-8
|
||||||
|
it_IT.UTF-8 UTF-8
|
||||||
|
`
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
locale string
|
||||||
|
wantFound bool
|
||||||
|
wantSubstr string // substring that should appear uncommented
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "uncomment commented locale",
|
||||||
|
locale: "fr_FR.UTF-8",
|
||||||
|
wantFound: true,
|
||||||
|
wantSubstr: "\nfr_FR.UTF-8 UTF-8\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "already uncommented",
|
||||||
|
locale: "it_IT.UTF-8",
|
||||||
|
wantFound: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "locale not in file",
|
||||||
|
locale: "ja_JP.UTF-8",
|
||||||
|
wantFound: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
result, found := uncommentLocaleGen(sampleLocaleGen, tt.locale)
|
||||||
|
if found != tt.wantFound {
|
||||||
|
t.Errorf("found = %v, want %v", found, tt.wantFound)
|
||||||
|
}
|
||||||
|
if tt.wantSubstr != "" && !contains(result, tt.wantSubstr) {
|
||||||
|
t.Errorf("result does not contain %q:\n%s", tt.wantSubstr, result)
|
||||||
|
}
|
||||||
|
// The commented versions of OTHER locales should remain commented.
|
||||||
|
if tt.locale == "fr_FR.UTF-8" && !contains(result, "# en_US.UTF-8 UTF-8") {
|
||||||
|
t.Errorf("other locales should stay commented:\n%s", result)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func contains(s, substr string) bool {
|
||||||
|
return len(s) >= len(substr) && (s == substr || len(substr) == 0 ||
|
||||||
|
(len(s) > 0 && strings.Contains(s, substr)))
|
||||||
|
}
|
||||||
|
|||||||
@@ -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))
|
||||||
|
}
|
||||||
@@ -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
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -8,9 +8,17 @@ import (
|
|||||||
|
|
||||||
const ModuleID = "users"
|
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 }
|
func (m *Module) ID() string { return ModuleID }
|
||||||
|
|
||||||
@@ -21,7 +29,7 @@ func (m *Module) Permissions() []rbac.Permission {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (m *Module) Register(api huma.API) {
|
func (m *Module) Register(api huma.API) {
|
||||||
registerUsers(api)
|
registerUsers(api, m.sessions)
|
||||||
}
|
}
|
||||||
|
|
||||||
func op(permission string) map[string]any {
|
func op(permission string) map[string]any {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package users
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
"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{
|
huma.Register(api, huma.Operation{
|
||||||
OperationID: "users-list",
|
OperationID: "users-list",
|
||||||
Method: "GET",
|
Method: "GET",
|
||||||
@@ -105,7 +106,7 @@ func registerUsers(api huma.API) {
|
|||||||
}, func(ctx context.Context, _ *struct{}) (*ListUsersOutput, error) {
|
}, func(ctx context.Context, _ *struct{}) (*ListUsersOutput, error) {
|
||||||
list, err := listUsers()
|
list, err := listUsers()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||||
}
|
}
|
||||||
out := &ListUsersOutput{}
|
out := &ListUsersOutput{}
|
||||||
out.Body.Users = list
|
out.Body.Users = list
|
||||||
@@ -127,7 +128,7 @@ func registerUsers(api huma.API) {
|
|||||||
}
|
}
|
||||||
u, ok, err := lookupUser(in.Username)
|
u, ok, err := lookupUser(in.Username)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||||
}
|
}
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, huma.Error404NotFound("user not found: " + in.Username)
|
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")
|
return nil, huma.Error400BadRequest("home must be an absolute path")
|
||||||
}
|
}
|
||||||
if _, ok, err := lookupUser(in.Body.Username); err != nil {
|
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 {
|
} else if ok {
|
||||||
return nil, huma.Error409Conflict("user already exists: " + in.Body.Username)
|
return nil, huma.Error409Conflict("user already exists: " + in.Body.Username)
|
||||||
}
|
}
|
||||||
@@ -212,7 +213,7 @@ func registerUsers(api huma.API) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if _, ok, err := lookupUser(in.Username); err != nil {
|
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 {
|
} else if !ok {
|
||||||
return nil, huma.Error404NotFound("user not found: " + in.Username)
|
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")
|
return nil, huma.Error400BadRequest("password may not contain newlines")
|
||||||
}
|
}
|
||||||
if _, ok, err := lookupUser(in.Username); err != nil {
|
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 {
|
} else if !ok {
|
||||||
return nil, huma.Error404NotFound("user not found: " + in.Username)
|
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 {
|
if _, err := oscmd.RunStdin(in.Username+":"+in.Body.Password+"\n", "chpasswd"); err != nil {
|
||||||
return nil, huma.Error500InternalServerError("chpasswd failed", err)
|
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
|
return oscmd.OK(), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -290,7 +296,7 @@ func registerUsers(api huma.API) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, ok, err := lookupUser(in.Username); err != nil {
|
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 {
|
} else if !ok {
|
||||||
return nil, huma.Error404NotFound("user not found: " + in.Username)
|
return nil, huma.Error404NotFound("user not found: " + in.Username)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ func TestUsersHandlers(t *testing.T) {
|
|||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
|
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
|
||||||
registerUsers(api)
|
registerUsers(api, nil)
|
||||||
|
|
||||||
// 1. Test GET /api/users
|
// 1. Test GET /api/users
|
||||||
resp := api.Get("/api/users")
|
resp := api.Get("/api/users")
|
||||||
|
|||||||
@@ -28,26 +28,34 @@ short:x:2:2
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestValidateUsername(t *testing.T) {
|
func TestValidateUsername(t *testing.T) {
|
||||||
valid := []string{"alice", "_svc", "user-1", "a", "machine$", "abc_def"}
|
for _, n := range []struct {
|
||||||
for _, n := range valid {
|
name string
|
||||||
if err := validateUsername(n); err != nil {
|
value string
|
||||||
t.Errorf("validateUsername(%q) = %v, want nil", n, err)
|
valid bool
|
||||||
}
|
}{
|
||||||
}
|
{name: "alice", value: "alice", valid: true},
|
||||||
|
{name: "underscore prefix", value: "_svc", valid: true},
|
||||||
invalid := []string{
|
{name: "hyphen", value: "user-1", valid: true},
|
||||||
"", // empty
|
{name: "single char", value: "a", valid: true},
|
||||||
"-rf", // leading dash (flag injection)
|
{name: "dollar suffix", value: "machine$", valid: true},
|
||||||
"Alice", // uppercase
|
{name: "underscore", value: "abc_def", valid: true},
|
||||||
"1user", // leading digit
|
{name: "empty", value: "", valid: false},
|
||||||
"a b", // space
|
{name: "leading dash", value: "-rf", valid: false},
|
||||||
"foo;rm", // shell metachar
|
{name: "uppercase", value: "Alice", valid: false},
|
||||||
"root:x", // colon (passwd separator)
|
{name: "leading digit", value: "1user", valid: false},
|
||||||
"waytoolongusernamethatexceedsthirtytwochars", // >32
|
{name: "space", value: "a b", valid: false},
|
||||||
}
|
{name: "shell metachar", value: "foo;rm", valid: false},
|
||||||
for _, n := range invalid {
|
{name: "colon", value: "root:x", valid: false},
|
||||||
if err := validateUsername(n); err == nil {
|
{name: "too long", value: "waytoolongusernamethatexceedsthirtytwochars", valid: false},
|
||||||
t.Errorf("validateUsername(%q) = nil, want error", n)
|
} {
|
||||||
}
|
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)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,16 +25,22 @@ func TestParseProc(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestUnescape(t *testing.T) {
|
func TestUnescape(t *testing.T) {
|
||||||
cases := map[string]string{
|
tests := []struct {
|
||||||
`/mnt/my\040disk`: "/mnt/my disk",
|
name string
|
||||||
`/no/escapes`: "/no/escapes",
|
in string
|
||||||
`tab\011here`: "tab\there",
|
want string
|
||||||
`back\134slash`: `back\slash`,
|
}{
|
||||||
|
{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 {
|
for _, tt := range tests {
|
||||||
if got := Unescape(in); got != want {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
t.Errorf("Unescape(%q) = %q, want %q", in, got, want)
|
if got := Unescape(tt.in); got != tt.want {
|
||||||
}
|
t.Errorf("Unescape(%q) = %q, want %q", tt.in, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,14 +14,12 @@ import (
|
|||||||
"nadir/internal/auth"
|
"nadir/internal/auth"
|
||||||
"nadir/internal/meta"
|
"nadir/internal/meta"
|
||||||
"nadir/internal/module"
|
"nadir/internal/module"
|
||||||
"nadir/internal/modules/audit"
|
|
||||||
"nadir/internal/modules/groups"
|
"nadir/internal/modules/groups"
|
||||||
"nadir/internal/modules/networking"
|
"nadir/internal/modules/networking"
|
||||||
"nadir/internal/modules/packages"
|
"nadir/internal/modules/packages"
|
||||||
"nadir/internal/modules/services"
|
"nadir/internal/modules/services"
|
||||||
"nadir/internal/modules/storage"
|
"nadir/internal/modules/storage"
|
||||||
"nadir/internal/modules/system"
|
"nadir/internal/modules/system"
|
||||||
"nadir/internal/modules/terminal"
|
|
||||||
"nadir/internal/modules/users"
|
"nadir/internal/modules/users"
|
||||||
"nadir/internal/rbac"
|
"nadir/internal/rbac"
|
||||||
|
|
||||||
@@ -29,6 +27,12 @@ import (
|
|||||||
"github.com/danielgtaylor/huma/v2/adapters/humago"
|
"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) {
|
func TestOpenAPISchemaNoCollisions(t *testing.T) {
|
||||||
auditStore, err := auditlog.New(filepath.Join(t.TempDir(), "audit.db"))
|
auditStore, err := auditlog.New(filepath.Join(t.TempDir(), "audit.db"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -44,13 +48,12 @@ func TestOpenAPISchemaNoCollisions(t *testing.T) {
|
|||||||
mods := []module.Module{
|
mods := []module.Module{
|
||||||
system.New(),
|
system.New(),
|
||||||
services.New(nil),
|
services.New(nil),
|
||||||
users.New(),
|
users.New(nil),
|
||||||
groups.New(),
|
groups.New(),
|
||||||
packages.New(),
|
packages.New(),
|
||||||
networking.New(),
|
networking.New(),
|
||||||
storage.New(),
|
storage.New(),
|
||||||
audit.New(auditStore),
|
auditModule{},
|
||||||
terminal.New(sessions),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
@@ -60,7 +63,8 @@ func TestOpenAPISchemaNoCollisions(t *testing.T) {
|
|||||||
}
|
}
|
||||||
meta.Register(api, mods)
|
meta.Register(api, mods)
|
||||||
meta.RegisterHealth(api, sessions)
|
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.RegisterLogin(api, sessions, auditStore, true)
|
||||||
auth.RegisterLogout(api, sessions, true)
|
auth.RegisterLogout(api, sessions, true)
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
"os/exec"
|
"os/exec"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -276,6 +277,23 @@ func ParseKV(lines []string) map[string]string {
|
|||||||
return m
|
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
|
// StatusOutput is the shared response for write operations that just report
|
||||||
// success. Reusing one type means all such endpoints share a single OpenAPI
|
// success. Reusing one type means all such endpoints share a single OpenAPI
|
||||||
// schema.
|
// schema.
|
||||||
|
|||||||
@@ -41,8 +41,6 @@ func TestRbacMiddleware(t *testing.T) {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
r.AssignRole("alice", "test-role")
|
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")
|
r.AssignRole("dash", "test-role")
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
@@ -76,81 +74,91 @@ func TestRbacMiddleware(t *testing.T) {
|
|||||||
return &struct{ Body string }{Body: "gated-write"}, nil
|
return &struct{ Body string }{Body: "gated-write"}, nil
|
||||||
})
|
})
|
||||||
|
|
||||||
// 1. Test public route
|
t.Run("public route", func(t *testing.T) {
|
||||||
resp := api.Get("/public")
|
resp := api.Get("/public")
|
||||||
if resp.Code != http.StatusOK {
|
if resp.Code != http.StatusOK {
|
||||||
t.Errorf("public GET: got status %d, want %d", resp.Code, http.StatusOK)
|
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
|
||||||
// 2. Test gated route without cookie -> 401 Unauthorized
|
t.Run("no auth returns 401", func(t *testing.T) {
|
||||||
resp = api.Get("/gated-read")
|
resp := api.Get("/gated-read")
|
||||||
if resp.Code != http.StatusUnauthorized {
|
if resp.Code != http.StatusUnauthorized {
|
||||||
t.Errorf("gated GET no cookie: got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
|
||||||
// 3. Test gated route with invalid cookie -> 401 Unauthorized
|
t.Run("invalid cookie returns 401", func(t *testing.T) {
|
||||||
resp = api.Get("/gated-read", "Cookie: nadir_session_id=invalid")
|
resp := api.Get("/gated-read", "Cookie: nadir_session_id=invalid")
|
||||||
if resp.Code != http.StatusUnauthorized {
|
if resp.Code != http.StatusUnauthorized {
|
||||||
t.Errorf("gated GET invalid cookie: got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
|
||||||
// Create valid session
|
var aliceToken string
|
||||||
token, err := sessions.Create("alice")
|
t.Run("valid session returns 200", func(t *testing.T) {
|
||||||
if err != nil {
|
var err error
|
||||||
t.Fatal(err)
|
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
|
t.Run("csrf mismatched origin returns 403", func(t *testing.T) {
|
||||||
resp = api.Get("/gated-read", "Cookie: nadir_session_id="+token)
|
resp := api.Post("/gated-write", "Cookie: nadir_session_id="+aliceToken, "Origin: http://evil.com", "Host: example.com", struct{}{})
|
||||||
if resp.Code != http.StatusOK {
|
if resp.Code != http.StatusForbidden {
|
||||||
t.Errorf("gated GET valid cookie: got status %d, want %d", resp.Code, http.StatusOK)
|
t.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
|
||||||
// 5. Test CSRF violation: POST with mismatched Origin header -> 403 Forbidden
|
t.Run("csrf matching origin returns 200", func(t *testing.T) {
|
||||||
resp = api.Post("/gated-write", "Cookie: nadir_session_id="+token, "Origin: http://evil.com", "Host: example.com", struct{}{})
|
resp := api.Post("/gated-write", "Cookie: nadir_session_id="+aliceToken, "Origin: http://example.com", "Host: example.com", struct{}{})
|
||||||
if resp.Code != http.StatusForbidden {
|
if resp.Code != http.StatusOK {
|
||||||
t.Errorf("CSRF mismatched Origin: got status %d, want %d", resp.Code, http.StatusForbidden)
|
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
|
||||||
// 6. Test CSRF success: POST with matching Origin header -> 200 OK
|
t.Run("unauthorized user returns 403", func(t *testing.T) {
|
||||||
resp = api.Post("/gated-write", "Cookie: nadir_session_id="+token, "Origin: http://example.com", "Host: example.com", struct{}{})
|
bobToken, err := sessions.Create("bob")
|
||||||
if resp.Code != http.StatusOK {
|
if err != nil {
|
||||||
t.Errorf("CSRF matching Origin: got status %d, want %d", resp.Code, http.StatusOK)
|
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
|
t.Run("valid bearer token returns 200", func(t *testing.T) {
|
||||||
tokenBob, err := sessions.Create("bob")
|
rawToken, err := tokenStore.Create("dash")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
resp = api.Get("/gated-read", "Cookie: nadir_session_id="+tokenBob)
|
resp := api.Get("/gated-read", "Authorization: Bearer "+rawToken)
|
||||||
if resp.Code != http.StatusForbidden {
|
if resp.Code != http.StatusOK {
|
||||||
t.Errorf("bob unauthorized GET: got status %d, want %d", resp.Code, http.StatusForbidden)
|
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
|
||||||
// 8. Bearer token for an assigned name -> 200 OK
|
t.Run("bogus bearer token returns 401", func(t *testing.T) {
|
||||||
rawToken, err := tokenStore.Create("dash")
|
resp := api.Get("/gated-read", "Authorization: Bearer nad_deadbeef")
|
||||||
if err != nil {
|
if resp.Code != http.StatusUnauthorized {
|
||||||
t.Fatal(err)
|
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||||
}
|
}
|
||||||
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)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 9. Bogus bearer token -> 401 Unauthorized
|
t.Run("unassigned bearer token returns 403", func(t *testing.T) {
|
||||||
resp = api.Get("/gated-read", "Authorization: Bearer nad_deadbeef")
|
rawUnassigned, err := tokenStore.Create("orphan")
|
||||||
if resp.Code != http.StatusUnauthorized {
|
if err != nil {
|
||||||
t.Errorf("bogus bearer GET: got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
resp := api.Get("/gated-read", "Authorization: Bearer "+rawUnassigned)
|
||||||
// 10. Bearer token with no role assignment -> 403 Forbidden
|
if resp.Code != http.StatusForbidden {
|
||||||
rawUnassigned, err := tokenStore.Create("orphan")
|
t.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
untrusted comment: minisign public key: 702ABD7F45200669
|
||||||
|
RWRpBiBFf70qcEXS0cOS+8tZ1hpoLj9mX0V5OiE8qYIIZsetU8hNA4Ou
|
||||||
Binary file not shown.
Executable
BIN
Binary file not shown.
@@ -0,0 +1,54 @@
|
|||||||
|
// Command sign-checksums is a CI helper that signs a file using minisign.
|
||||||
|
//
|
||||||
|
// The minisign CLI reads passwords from /dev/tty, which doesn't exist in CI
|
||||||
|
// runners. This program uses the library directly: password and encrypted
|
||||||
|
// secret key come from environment variables, no terminal required.
|
||||||
|
//
|
||||||
|
// Usage (in CI):
|
||||||
|
//
|
||||||
|
// MINISIGN_SECRET_KEY=... MINISIGN_PASSWORD=... go run ./tools/sign-checksums dist/sha256sums.txt
|
||||||
|
//
|
||||||
|
// Produces dist/sha256sums.txt.minisig alongside the input.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"aead.dev/minisign"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if len(os.Args) != 2 {
|
||||||
|
fmt.Fprintf(os.Stderr, "usage: sign-checksums <file>\n")
|
||||||
|
os.Exit(2)
|
||||||
|
}
|
||||||
|
filePath := os.Args[1]
|
||||||
|
|
||||||
|
password := os.Getenv("MINISIGN_PASSWORD")
|
||||||
|
keyBytes := []byte(os.Getenv("MINISIGN_SECRET_KEY"))
|
||||||
|
if len(keyBytes) == 0 {
|
||||||
|
fmt.Fprintln(os.Stderr, "MINISIGN_SECRET_KEY is not set")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
key, err := minisign.DecryptKey(password, keyBytes)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "decrypt key: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
message, err := os.ReadFile(filePath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "read %s: %v\n", filePath, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
sig := minisign.Sign(key, message)
|
||||||
|
sigPath := filePath + ".minisig"
|
||||||
|
if err := os.WriteFile(sigPath, sig, 0644); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "write %s: %v\n", sigPath, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fmt.Printf("signed %s -> %s\n", filePath, sigPath)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user