9 Commits

Author SHA1 Message Date
urania 54108c263f fix: remove terminal module and implement concurrent log stream limiting
build-and-release / release (push) Successful in 2m39s
2026-06-24 17:29:45 +02:00
urania 37e5b97507 fix: crt
build-and-release / release (push) Successful in 2m38s
2026-06-23 19:47:19 +02:00
urania 63c9a272b5 feat: add configurable TLS/proxy installation options for the systemd service
build-and-release / release (push) Successful in 2m34s
2026-06-23 19:13:34 +02:00
urania 411f7fd6d9 feat: persistent TLS cert and token auto-generation during install 2026-06-23 19:05:26 +02:00
urania 8fc4b236ac fix: whomai with bearer
build-and-release / release (push) Successful in 2m39s
2026-06-23 18:02:52 +02:00
urania 37f03816e1 fix: networking/interfaces
build-and-release / release (push) Successful in 2m29s
2026-06-23 17:40:44 +02:00
urania 541260e65e fix: networking/interfaces
build-and-release / release (push) Has been cancelled
2026-06-23 17:40:17 +02:00
urania c4180bada1 fix: networking / services / and testing
build-and-release / release (push) Successful in 2m40s
2026-06-23 17:16:01 +02:00
urania 088880f584 fix: updates
build-and-release / release (push) Successful in 2m39s
2026-06-23 14:27:06 +02:00
45 changed files with 1501 additions and 822 deletions
-2
View File
@@ -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
+76 -23
View File
@@ -31,7 +31,6 @@ import (
"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"
@@ -63,6 +62,12 @@ 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 { if *showVersion {
@@ -81,7 +86,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)
} }
@@ -96,7 +101,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")))
@@ -200,13 +205,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), audit.New(auditStore),
terminal.New(sessions),
} }
roles := rbac.New() roles := rbac.New()
@@ -230,6 +234,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 {
@@ -238,7 +244,7 @@ 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.RegisterUpdate(api, configPath) meta.RegisterUpdate(api, configPath)
auth.RegisterLogin(api, sessions, auditStore, cfg.SecureCookie()) auth.RegisterLogin(api, sessions, auditStore, cfg.SecureCookie())
@@ -271,18 +277,18 @@ 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 // /docs needs to execute the Scalar bundle, so loosen the strict CSP set
// by secHeaders for this one page: allow scripts/styles from the jsdelivr // by secHeaders for this one page: allow scripts/styles from the pinned
// CDN plus inline (Scalar uses inline <script> + inline styles). The CDN // jsdelivr CDN version + inline (Scalar uses inline <script> + inline styles).
// host is the supply-chain trust boundary; pinning a version + SRI here // unsafe-eval is removed Scalar does not need it. The CDN host is the
// is the follow-up (M5 partial). // supply-chain trust boundary; SRI pinning would close the remaining gap.
w.Header().Set("Content-Security-Policy", w.Header().Set("Content-Security-Policy",
"default-src 'self'; "+ "default-src 'self'; "+
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+ "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+ "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
"img-src 'self' data: https:; "+ "img-src 'self' data: https:; "+
"connect-src 'self'; "+ "connect-src 'self'; "+
"font-src 'self' data: https://cdn.jsdelivr.net") "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">
@@ -297,7 +303,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: secHeaders(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
@@ -307,14 +313,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)
} }
@@ -325,8 +331,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() {
@@ -354,6 +371,40 @@ func runServer() {
} }
} }
// bodySizeLimit rejects requests with a body larger than 1 MB, preventing
// OOM from arbitrarily large JSON payloads. Wraps the entire mux so it
// covers both Huma-registered routes and raw mux handlers (/docs, /install.sh).
func bodySizeLimit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
next.ServeHTTP(w, r)
})
}
// requestTimeout cancels slow requests via context deadline. SSE endpoints
// (package streams, log following) are exempt because they keep the
// connection open indefinitely.
func requestTimeout(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if isSSEEndpoint(r) {
next.ServeHTTP(w, r)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// isSSEEndpoint identifies routes that stream data indefinitely and must
// not have a context deadline.
func isSSEEndpoint(r *http.Request) bool {
if strings.HasPrefix(r.URL.Path, "/api/packages") {
return r.Method == "POST" || r.Method == "DELETE"
}
return r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/logs/stream")
}
// secHeaders sets defensive response headers on every HTTP response. The // secHeaders sets defensive response headers on every HTTP response. The
// default Content-Security-Policy denies everything (`default-src 'none'`) — // default Content-Security-Policy denies everything (`default-src 'none'`) —
// correct for the JSON API and the tiny landing/favicon endpoints. /docs // correct for the JSON API and the tiny landing/favicon endpoints. /docs
@@ -371,6 +422,8 @@ func secHeaders(next http.Handler) http.Handler {
h.Set("Referrer-Policy", "no-referrer") h.Set("Referrer-Policy", "no-referrer")
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
h.Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'") 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) next.ServeHTTP(w, r)
}) })
} }
+143 -27
View File
@@ -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).
`) `)
+53 -22
View File
@@ -4,44 +4,33 @@ import (
"crypto/ecdsa" "crypto/ecdsa"
"crypto/elliptic" "crypto/elliptic"
"crypto/rand" "crypto/rand"
"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) {
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 := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
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,
@@ -49,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
} }
-2
View File
@@ -7,8 +7,6 @@ require github.com/msteinert/pam v1.2.0
require github.com/danielgtaylor/huma/v2 v2.38.0 require github.com/danielgtaylor/huma/v2 v2.38.0
require ( require (
github.com/coder/websocket v1.8.15
github.com/creack/pty v1.1.24
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
) )
-4
View File
@@ -1,9 +1,5 @@
aead.dev/minisign v0.3.0 h1:8Xafzy5PEVZqYDNP60yJHARlW1eOQtsKNp/Ph2c0vRA= aead.dev/minisign v0.3.0 h1:8Xafzy5PEVZqYDNP60yJHARlW1eOQtsKNp/Ph2c0vRA=
aead.dev/minisign v0.3.0/go.mod h1:NLvG3Uoq3skkRMDuc3YHpWUTMTrSExqm+Ij73W13F6Y= aead.dev/minisign v0.3.0/go.mod h1:NLvG3Uoq3skkRMDuc3YHpWUTMTrSExqm+Ij73W13F6Y=
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/danielgtaylor/huma/v2 v2.38.0 h1:fb0WZCatnaiHLphMQDDWDjygNxfMkX/ENma3QsRl7vY= github.com/danielgtaylor/huma/v2 v2.38.0 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=
+13 -12
View File
@@ -13,7 +13,7 @@ import (
// loginNameRe is the useradd default NAME_REGEX. Validating at this trust // 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 // boundary keeps a flag-like name (e.g. "-c", "--help") from reaching `su` in
// the terminal handler or showing up verbatim in audit logs / throttle keys. // showing up verbatim in audit logs / throttle keys.
var loginNameRe = regexp.MustCompile(`^[a-z_][a-z0-9_-]{0,31}\$?$`) 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
@@ -43,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) {
@@ -85,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
View File
@@ -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)
}
} }
+72
View File
@@ -0,0 +1,72 @@
package auth
import (
"net/http"
"sync"
"time"
"github.com/danielgtaylor/huma/v2"
)
// RateLimiter provides per-IP rate limiting for authenticated API endpoints,
// complementing the login-specific failLimiter with a broader cap on all
// requests. The window aligns to wall-clock intervals so all IPs share the
// same boundary.
type RateLimiter struct {
mu sync.Mutex
buckets map[string]*tokenBucket
limit int
interval time.Duration
}
type tokenBucket struct {
count int
windowEnd time.Time
}
const maxRateLimitKeys = 10000
func NewRateLimiter(limit int, interval time.Duration) *RateLimiter {
return &RateLimiter{
buckets: map[string]*tokenBucket{},
limit: limit,
interval: interval,
}
}
// Allow reports whether ip may make a request now. Returns false when the
// limit is exceeded OR the map is full (fail-closed).
func (l *RateLimiter) Allow(ip string) bool {
l.mu.Lock()
defer l.mu.Unlock()
now := time.Now()
b, ok := l.buckets[ip]
if !ok || now.After(b.windowEnd) {
if len(l.buckets) >= maxRateLimitKeys {
return false
}
l.buckets[ip] = &tokenBucket{count: 1, windowEnd: now.Add(l.interval)}
return true
}
if b.count >= l.limit {
return false
}
b.count++
return true
}
// RateLimitMiddleware returns Huma middleware that rejects requests exceeding
// the per-IP rate limit with 429 Too Many Requests. It runs before the RBAC
// check so abusive IPs are dropped early. The IP is read from the context set
// by WithClientIP; if absent the request passes through unthrottled.
func RateLimitMiddleware(api huma.API, rl *RateLimiter) func(huma.Context, func(huma.Context)) {
return func(ctx huma.Context, next func(huma.Context)) {
ip := ClientIP(ctx.Context())
if ip != "" && !rl.Allow(ip) {
huma.WriteErr(api, ctx, http.StatusTooManyRequests, "rate limit exceeded, try again later")
return
}
next(ctx)
}
}
+66 -5
View File
@@ -2,6 +2,7 @@ package auth
import ( 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.
+9 -10
View File
@@ -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)
} }
} }
+14 -5
View File
@@ -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
+3
View File
@@ -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
} }
+3 -3
View File
@@ -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 {
+11 -6
View File
@@ -69,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
} }
@@ -109,10 +109,10 @@ 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 downloaded over the wire and (for /api/update) // release_repo, when set, is substituted into shell scripts and downloaded
// executed. Validate shape + scheme once here so /install.sh and the updater // over the wire. Validate shape + scheme + shell-safety once here so
// can use the string directly. Trim any trailing slash so downstream string // /install.sh and the updater can use the string directly. Trim any trailing
// concatenation produces a clean URL. // slash so downstream string concatenation produces a clean URL.
if f.Server.ReleaseRepo != "" { if f.Server.ReleaseRepo != "" {
f.Server.ReleaseRepo = strings.TrimRight(f.Server.ReleaseRepo, "/") f.Server.ReleaseRepo = strings.TrimRight(f.Server.ReleaseRepo, "/")
u, err := url.Parse(f.Server.ReleaseRepo) u, err := url.Parse(f.Server.ReleaseRepo)
@@ -129,6 +129,11 @@ func Load(path string) (*File, error) {
if len(parts) != 2 || parts[0] == "" || parts[1] == "" { 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) 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
} }
+6 -6
View File
@@ -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")
} }
} }
+26 -7
View File
@@ -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
}) })
} }
+115
View File
@@ -0,0 +1,115 @@
package meta
import (
"encoding/json"
"net/http"
"path/filepath"
"slices"
"testing"
"nadir/internal/auth"
"nadir/internal/module"
"nadir/internal/rbac"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
"github.com/danielgtaylor/huma/v2/humatest"
)
type dummyModule struct {
id string
perms []rbac.Permission
}
func (m *dummyModule) ID() string { return m.id }
func (m *dummyModule) Name() string { return m.id }
func (m *dummyModule) Permissions() []rbac.Permission { return m.perms }
func (m *dummyModule) Register(api huma.API) {}
func TestWhoami(t *testing.T) {
tempDir := t.TempDir()
sessions, err := auth.NewSessionStore(filepath.Join(tempDir, "sessions.db"))
if err != nil {
t.Fatal(err)
}
tokenStore, err := auth.NewTokenStore(filepath.Join(tempDir, "tokens.db"))
if err != nil {
t.Fatal(err)
}
defer tokenStore.Close()
tokenAuth := auth.NewTokenAuth(tokenStore)
roles := rbac.New()
roles.DefineRole(rbac.Role{
Name: "admin-role",
ModuleGrants: map[string][]rbac.Permission{
"system": {rbac.Read},
},
})
roles.AssignRole("admin", "admin-role")
mods := []module.Module{
&dummyModule{
id: "system",
perms: []rbac.Permission{rbac.Read, rbac.Write},
},
}
mux := http.NewServeMux()
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
RegisterWhoami(api, sessions, tokenAuth, roles, mods)
// 1. Unauthorized request (no token, no session)
resp := api.Get("/api/whoami")
if resp.Code != http.StatusUnauthorized {
t.Errorf("expected 401, got %d", resp.Code)
}
// 2. Cookie session request
sessToken, err := sessions.Create("admin")
if err != nil {
t.Fatal(err)
}
resp = api.Get("/api/whoami", "Cookie: nadir_session_id="+sessToken)
if resp.Code != http.StatusOK {
t.Errorf("expected 200, got %d", resp.Code)
}
var body WhoamiBody
if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.Username != "admin" {
t.Errorf("expected username admin, got %q", body.Username)
}
if !slices.Contains(body.Permissions["system"], "read") {
t.Errorf("expected system read permission, got %v", body.Permissions["system"])
}
// 3. Token request
bearerToken, err := tokenStore.Create("api-user")
if err != nil {
t.Fatal(err)
}
roles.DefineRole(rbac.Role{
Name: "api-role",
ModuleGrants: map[string][]rbac.Permission{
"system": {rbac.Write},
},
})
roles.AssignRole("api-user", "api-role")
resp = api.Get("/api/whoami", "Authorization: Bearer "+bearerToken)
if resp.Code != http.StatusOK {
t.Errorf("expected 200, got %d", resp.Code)
}
if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.Username != "api-user" {
t.Errorf("expected username api-user, got %q", body.Username)
}
if !slices.Contains(body.Permissions["system"], "write") {
t.Errorf("expected system write permission, got %v", body.Permissions["system"])
}
}
+4 -4
View File
@@ -70,7 +70,7 @@ func registerGroups(api huma.API) {
}, func(ctx context.Context, _ *struct{}) (*ListGroupsOutput, error) { }, 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)
} }
+25 -9
View File
@@ -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)
}
})
} }
} }
+26 -12
View File
@@ -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)
}
})
} }
} }
+27 -3
View File
@@ -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"))
} }
+1 -1
View File
@@ -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)
}
}
+16 -8
View File
@@ -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
} }
+155 -2
View File
@@ -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)
}
}
}
+14 -6
View File
@@ -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
+21 -9
View File
@@ -83,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{
@@ -193,6 +198,13 @@ func streamOp(ctx context.Context, send sse.Sender, bin string, args []string) {
send.Data(PkgErrorEvent{Message: "no supported package manager found"}) 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 {
@@ -283,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
} }
@@ -295,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
} }
@@ -322,11 +334,11 @@ func (m manager) upgradeArgs() (string, []string) {
func (m manager) upgradeOneArgs(name string) (string, []string) { func (m manager) upgradeOneArgs(name string) (string, []string) {
switch m.name { switch m.name {
case "dnf": case "dnf":
return "dnf", []string{"upgrade", "-y", "--", name} return "dnf", []string{"upgrade", "-y", name}
case "apt": case "apt":
return "apt-get", []string{"install", "--only-upgrade", "-y", "--", name} return "apt-get", []string{"install", "--only-upgrade", "-y", name}
case "pacman": case "pacman":
return "pacman", []string{"-S", "--noconfirm", "--", name} return "pacman", []string{"-S", "--noconfirm", name}
} }
return "", nil return "", nil
} }
+40 -17
View File
@@ -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)
}
})
} }
} }
+12
View File
@@ -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" {
+58 -33
View File
@@ -48,49 +48,74 @@ func TestResolveLogPath(t *testing.T) {
"nginx.service": {"/var/log/nginx/access.log", "/var/log/nginx/error.log"}, "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)
}
})
} }
} }
+32
View File
@@ -3,14 +3,22 @@ package services
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"os/exec"
"regexp" "regexp"
"strings" "strings"
"syscall"
"nadir/internal/oscmd" "nadir/internal/oscmd"
"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 +144,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 +155,27 @@ 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) {
cmd := exec.Command("systemctl", action, "--", unit)
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
if err := cmd.Start(); err != nil {
return nil, huma.Error500InternalServerError("could not start detached systemctl", err)
}
// Reap in the background so the child doesn't become a zombie.
go cmd.Wait()
return oscmd.OK(), nil
}
// 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) {
+53 -14
View File
@@ -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)
}
})
} }
} }
+32 -7
View File
@@ -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 {
+22 -18
View File
@@ -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)
}
})
} }
} }
+29 -11
View File
@@ -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)
}
})
} }
} }
-209
View File
@@ -1,209 +0,0 @@
package terminal
import (
"context"
"encoding/json"
"net/http"
"os/exec"
"strings"
"sync/atomic"
"time"
"nadir/internal/auth"
"nadir/internal/module"
"nadir/internal/rbac"
"github.com/coder/websocket"
"github.com/creack/pty"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
)
// tagTerminal is the OpenAPI tag for this module (registered in server.go),
// keeping tags 1:1 with modules per the project convention.
const tagTerminal = "Terminal"
const (
// maxTerminals caps concurrent shells so a buggy frontend or careless admin
// can't pile up PTYs (guideline: limit everything). Raise if it's ever a real
// limit in practice.
maxTerminals = 10
// idleTimeout closes a session after this long with no I/O in either
// direction, reclaiming abandoned shells.
idleTimeout = 15 * time.Minute
)
// terminalSem is the concurrency limiter; a slot is held for the life of a session.
var terminalSem = make(chan struct{}, maxTerminals)
type terminalModule struct {
sessions *auth.SessionStore
}
// New creates a new Terminal module that allows interactive shell access.
func New(sessions *auth.SessionStore) module.Module {
return &terminalModule{sessions: sessions}
}
func (m *terminalModule) ID() string { return "terminal" }
func (m *terminalModule) Permissions() []rbac.Permission {
return []rbac.Permission{rbac.Root}
}
type TerminalInput struct {
Ctx huma.Context `json:"-"`
}
// Resolve extracts the huma.Context into the input struct.
func (i *TerminalInput) Resolve(ctx huma.Context) []error {
i.Ctx = ctx
return nil
}
type resizeMessage struct {
Cols uint16 `json:"cols"`
Rows uint16 `json:"rows"`
}
func (m *terminalModule) Register(api huma.API) {
huma.Register(api, huma.Operation{
OperationID: "terminal-connect",
Method: "GET",
Path: "/api/terminal",
Summary: "Connect to an interactive terminal",
Description: "Upgrades the connection to a WebSocket and spawns a PTY shell as the logged-in user. Send JSON `{cols, rows}` text messages to resize, and raw binary/text messages for stdin. This is a raw WebSocket endpoint — it cannot be exercised from the API docs \"Try it\" panel; use a WebSocket client.",
Tags: []string{tagTerminal},
Metadata: map[string]any{"module": m.ID(), "permission": string(rbac.Root)},
Errors: []int{401, 403, 426, 500},
}, func(ctx context.Context, in *TerminalInput) (*struct{}, error) {
// The RBAC middleware already authenticated this request and enforced the
// "root" permission before we got here. We re-read the session only to get
// the username for `su`; the 401 below is the fallback for when the module
// is mounted without the middleware (e.g. in unit tests).
cookie, err := huma.ReadCookie(in.Ctx, "nadir_session_id")
if err != nil || cookie == nil {
return nil, huma.Error401Unauthorized("unauthorized")
}
sess, ok := m.sessions.GetByToken(cookie.Value)
if !ok {
return nil, huma.Error401Unauthorized("unauthorized")
}
req, res := humago.Unwrap(in.Ctx)
if req == nil || res == nil {
return nil, huma.Error500InternalServerError("missing http context")
}
// Reject plain GETs (e.g. the docs "Try it" button) with a clear 426 rather
// than letting websocket.Accept emit a raw protocol-violation error.
if !strings.EqualFold(req.Header.Get("Upgrade"), "websocket") {
return nil, huma.NewError(http.StatusUpgradeRequired,
"this endpoint requires a WebSocket connection; connect with a WebSocket client")
}
// InsecureSkipVerify is deliberately NOT set: coder/websocket then enforces
// that the Origin host matches the request Host, rejecting cross-site upgrade
// attempts. Defense-in-depth on top of the SameSite=Strict session cookie —
// important because this endpoint hands out an interactive shell.
conn, err := websocket.Accept(res, req, nil)
if err != nil {
// websocket.Accept already wrote the error response (e.g. 403 on an
// Origin mismatch). Just stop; writing again would corrupt the response.
return nil, nil
}
defer conn.CloseNow()
// Bound concurrent shells: take a slot or reject (don't pile up PTYs).
select {
case terminalSem <- struct{}{}:
defer func() { <-terminalSem }()
default:
conn.Close(websocket.StatusTryAgainLater, "too many terminal sessions")
return nil, nil
}
// Launch the user's login shell via su.
// "su - <username>" ensures we get their actual environment and shell.
cmd := exec.CommandContext(req.Context(), "su", "-", "--", sess.Username)
// Start the command with a PTY.
ptmx, err := pty.Start(cmd)
if err != nil {
conn.Close(websocket.StatusInternalError, "failed to start pty")
return nil, nil
}
defer ptmx.Close()
// lastActive is bumped by both pumps; the watchdog uses it to close idle
// sessions. Output activity (e.g. `top`) counts, so it isn't killed.
var lastActive atomic.Int64
lastActive.Store(time.Now().UnixNano())
go func() {
tick := time.NewTicker(idleTimeout / 4)
defer tick.Stop()
for {
select {
case <-req.Context().Done():
return
case <-tick.C:
if time.Since(time.Unix(0, lastActive.Load())) > idleTimeout {
conn.Close(websocket.StatusGoingAway, "idle timeout")
return
}
}
}
}()
// Pump stdout/stderr from PTY to WebSocket.
go func() {
buf := make([]byte, 8192)
for {
n, err := ptmx.Read(buf)
if err != nil {
break
}
lastActive.Store(time.Now().UnixNano())
// We write PTY output as binary messages. The frontend (e.g., xterm.js)
// can handle UTF-8 binary or text transparently.
err = conn.Write(req.Context(), websocket.MessageBinary, buf[:n])
if err != nil {
break
}
}
conn.Close(websocket.StatusNormalClosure, "")
}()
// Pump stdin and resize commands from WebSocket to PTY.
for {
typ, b, err := conn.Read(req.Context())
if err != nil {
break
}
lastActive.Store(time.Now().UnixNano())
if typ == websocket.MessageText {
var resize resizeMessage
if err := json.Unmarshal(b, &resize); err == nil && resize.Cols > 0 && resize.Rows > 0 {
// Handle resize
_ = pty.Setsize(ptmx, &pty.Winsize{
Cols: resize.Cols,
Rows: resize.Rows,
})
continue
}
}
// If not a valid resize message, or if it's MessageBinary, pass to PTY stdin.
_, _ = ptmx.Write(b)
}
// The read loop has ended (client gone or PTY closed). Tear down the shell
// and reap it: closing the PTY sends EOF, Kill covers shells that ignore it.
_ = ptmx.Close()
_ = cmd.Process.Kill()
_ = cmd.Wait()
return nil, nil
})
}
-124
View File
@@ -1,124 +0,0 @@
package terminal
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"nadir/internal/auth"
"github.com/coder/websocket"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
)
func TestTerminalConnectUnauthorized(t *testing.T) {
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
if err != nil {
t.Fatalf("session db: %v", err)
}
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
mod := New(sessions)
mod.Register(api)
srv := httptest.NewServer(mux)
defer srv.Close()
wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) + "/api/terminal"
// Try without cookie
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
_, resp, err := websocket.Dial(ctx, wsURL, nil)
if err == nil {
t.Fatal("expected error, got success")
}
if resp != nil && resp.StatusCode != http.StatusUnauthorized {
t.Errorf("expected 401, got %d", resp.StatusCode)
}
}
func TestTerminalConnectPlainGET(t *testing.T) {
// An authenticated but non-WebSocket GET (e.g. the docs "Try it" button) must
// get a clean 426 Upgrade Required, not a raw websocket protocol error.
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
if err != nil {
t.Fatalf("session db: %v", err)
}
token, err := sessions.Create("root")
if err != nil {
t.Fatalf("create session: %v", err)
}
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
New(sessions).Register(api)
srv := httptest.NewServer(mux)
defer srv.Close()
req, _ := http.NewRequest(http.MethodGet, srv.URL+"/api/terminal", nil)
req.Header.Set("Cookie", "nadir_session_id="+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("GET failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusUpgradeRequired {
t.Errorf("expected 426, got %d", resp.StatusCode)
}
}
func TestTerminalConnectAuthorized(t *testing.T) {
// Root or specific system configs might cause PTY or su to fail if run in constrained environments.
// But we expect the websocket upgrade to succeed and then maybe close with an error if PTY fails.
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
if err != nil {
t.Fatalf("session db: %v", err)
}
token, err := sessions.Create("root")
if err != nil {
t.Fatalf("create session: %v", err)
}
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
mod := New(sessions)
mod.Register(api)
srv := httptest.NewServer(mux)
defer srv.Close()
wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) + "/api/terminal"
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
opts := &websocket.DialOptions{
HTTPHeader: http.Header{},
}
opts.HTTPHeader.Set("Cookie", "nadir_session_id="+token)
conn, resp, err := websocket.Dial(ctx, wsURL, opts)
if err != nil {
// Depending on the test environment, "su" or "pty" might fail, but
// the websocket upgrade itself should succeed before it drops.
// If it fails to upgrade, that's a real error.
t.Fatalf("dial failed: %v (status %d)", err, resp.StatusCode)
}
defer conn.CloseNow()
// The connection was upgraded successfully.
// If PTY allocation failed or su failed, the server might close the connection immediately.
// We just verify the upgrade succeeded.
if resp.StatusCode != http.StatusSwitchingProtocols {
t.Errorf("expected 101, got %d", resp.StatusCode)
}
}
+11 -3
View File
@@ -8,9 +8,17 @@ import (
const ModuleID = "users" 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 {
+13 -7
View File
@@ -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)
} }
+1 -1
View File
@@ -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")
+29 -21
View File
@@ -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)
}
})
} }
} }
+15 -9
View File
@@ -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)
}
})
} }
} }
+2 -4
View File
@@ -21,7 +21,6 @@ import (
"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"
@@ -44,13 +43,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), audit.New(auditStore),
terminal.New(sessions),
} }
mux := http.NewServeMux() mux := http.NewServeMux()
@@ -60,7 +58,7 @@ 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)
auth.RegisterLogin(api, sessions, auditStore, true) auth.RegisterLogin(api, sessions, auditStore, true)
auth.RegisterLogout(api, sessions, true) auth.RegisterLogout(api, sessions, true)
+78 -70
View File
@@ -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)
}
} }