fix: remove terminal module and implement concurrent log stream limiting
build-and-release / release (push) Successful in 2m39s
build-and-release / release (push) Successful in 2m39s
This commit is contained in:
@@ -31,7 +31,6 @@ API and declares its own permission vocabulary.
|
||||
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.
|
||||
- **Audit** - Read-only trail of every privileged write (who, what, when, result).
|
||||
- **Terminal** - Interactive shell access. Upgrades connection to a WebSocket and spawns a PTY shell as the logged-in user (requires `root` permission).
|
||||
- **Meta** - Self-description for clients: `/api/_modules`, `/api/whoami`,
|
||||
`/api/health`.
|
||||
|
||||
@@ -453,7 +452,6 @@ internal/modules concrete modules:
|
||||
packages - dnf/apt/pacman install/remove/upgrade (streamed)
|
||||
audit - read-only audit trail
|
||||
networking - network interfaces, routing tables, DNS, and IP configurations
|
||||
terminal - interactive PTY shell over WebSocket
|
||||
internal/oscmd shared command runner (timeouts, stderr surfacing) + helpers
|
||||
internal/rbac roles, permissions ("*" wildcards), HTTP middleware (RBAC + CSRF)
|
||||
internal/audit SQLite-backed audit log writer
|
||||
|
||||
+67
-20
@@ -31,7 +31,6 @@ import (
|
||||
"nadir/internal/modules/services"
|
||||
"nadir/internal/modules/storage"
|
||||
"nadir/internal/modules/system"
|
||||
"nadir/internal/modules/terminal"
|
||||
"nadir/internal/modules/users"
|
||||
"nadir/internal/rbac"
|
||||
|
||||
@@ -206,13 +205,12 @@ func runServer() {
|
||||
mods := []module.Module{
|
||||
system.New(),
|
||||
services.New(cfg.LogFiles),
|
||||
users.New(),
|
||||
users.New(sessions),
|
||||
groups.New(),
|
||||
packages.New(),
|
||||
networking.New(),
|
||||
storage.New(),
|
||||
audit.New(auditStore),
|
||||
terminal.New(sessions),
|
||||
}
|
||||
|
||||
roles := rbac.New()
|
||||
@@ -236,6 +234,8 @@ func runServer() {
|
||||
humaConfig.DocsPath = ""
|
||||
|
||||
api := humago.New(mux, humaConfig)
|
||||
rateLimiter := auth.NewRateLimiter(100, time.Minute)
|
||||
api.UseMiddleware(auth.RateLimitMiddleware(api, rateLimiter))
|
||||
api.UseMiddleware(rbac.RbacMiddleware(api, sessions, tokenAuth, roles, auditStore))
|
||||
|
||||
for _, m := range mods {
|
||||
@@ -277,18 +277,18 @@ func runServer() {
|
||||
})
|
||||
|
||||
mux.HandleFunc("GET /docs", func(w http.ResponseWriter, _ *http.Request) {
|
||||
// /docs needs to execute the Scalar bundle, so loosen the strict CSP set
|
||||
// by secHeaders for this one page: allow scripts/styles from the jsdelivr
|
||||
// CDN plus inline (Scalar uses inline <script> + inline styles). The CDN
|
||||
// host is the supply-chain trust boundary; pinning a version + SRI here
|
||||
// is the follow-up (M5 partial).
|
||||
w.Header().Set("Content-Security-Policy",
|
||||
"default-src 'self'; "+
|
||||
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net; "+
|
||||
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
|
||||
"img-src 'self' data: https:; "+
|
||||
"connect-src 'self'; "+
|
||||
"font-src 'self' data: https://cdn.jsdelivr.net https://fonts.scalar.com")
|
||||
// /docs needs to execute the Scalar bundle, so loosen the strict CSP set
|
||||
// by secHeaders for this one page: allow scripts/styles from the pinned
|
||||
// jsdelivr CDN version + inline (Scalar uses inline <script> + inline styles).
|
||||
// unsafe-eval is removed Scalar does not need it. The CDN host is the
|
||||
// supply-chain trust boundary; SRI pinning would close the remaining gap.
|
||||
w.Header().Set("Content-Security-Policy",
|
||||
"default-src 'self'; "+
|
||||
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
|
||||
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
|
||||
"img-src 'self' data: https:; "+
|
||||
"connect-src 'self'; "+
|
||||
"font-src 'self' data: https://cdn.jsdelivr.net https://fonts.scalar.com")
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Write([]byte(`<!doctype html><html><head><title>API</title>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
@@ -303,7 +303,7 @@ func runServer() {
|
||||
Addr: addr,
|
||||
// WithClientIP records the source IP for the login throttle (H1); behind a
|
||||
// trusted proxy it reads X-Forwarded-For instead of the proxy's address.
|
||||
Handler: secHeaders(auth.WithClientIP(cfg.Server.TrustProxy, mux)),
|
||||
Handler: bodySizeLimit(requestTimeout(secHeaders(auth.WithClientIP(cfg.Server.TrustProxy, mux)))),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 0, // unset: SSE endpoints stream indefinitely
|
||||
@@ -313,14 +313,14 @@ func runServer() {
|
||||
// Pick how the connection is secured (see config.Server doc):
|
||||
// 1. trust_proxy - a reverse proxy terminates TLS; we serve plaintext HTTP.
|
||||
// 2. tls_cert/tls_key - we terminate TLS with the admin's PEM pair.
|
||||
// 3. neither - a fresh in-memory self-signed cert (dev only).
|
||||
// 3. neither - plain HTTP (localhost-only default).
|
||||
var serve func() error
|
||||
switch {
|
||||
case cfg.Server.TrustProxy:
|
||||
log.Printf("tls: trust_proxy set - serving plaintext HTTP, TLS terminated upstream; bind to localhost so X-Forwarded-For can't be spoofed")
|
||||
log.Printf("tls: trust_proxy set — serving plaintext HTTP, TLS terminated upstream; bind to localhost so X-Forwarded-For can't be spoofed")
|
||||
serve = srv.ListenAndServe
|
||||
default:
|
||||
cert, err := serverCert(cfg.Server.TLSCert, cfg.Server.TLSKey)
|
||||
case cfg.Server.TLSCert != "" && cfg.Server.TLSKey != "":
|
||||
cert, err := tls.LoadX509KeyPair(cfg.Server.TLSCert, cfg.Server.TLSKey)
|
||||
if err != nil {
|
||||
log.Fatalf("tls cert: %v", err)
|
||||
}
|
||||
@@ -331,8 +331,19 @@ func runServer() {
|
||||
srv.TLSConfig = &tls.Config{
|
||||
Certificates: []tls.Certificate{cert},
|
||||
MinVersion: tls.VersionTLS12,
|
||||
CipherSuites: []uint16{
|
||||
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
|
||||
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
|
||||
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
|
||||
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
|
||||
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
|
||||
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
|
||||
},
|
||||
}
|
||||
serve = func() error { return srv.ListenAndServeTLS("", "") }
|
||||
default:
|
||||
log.Printf("tls: no TLS configured — serving plain HTTP on %s", addr)
|
||||
serve = srv.ListenAndServe
|
||||
}
|
||||
|
||||
go func() {
|
||||
@@ -360,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
|
||||
// default Content-Security-Policy denies everything (`default-src 'none'`) —
|
||||
// correct for the JSON API and the tiny landing/favicon endpoints. /docs
|
||||
@@ -377,6 +422,8 @@ func secHeaders(next http.Handler) http.Handler {
|
||||
h.Set("Referrer-Policy", "no-referrer")
|
||||
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
|
||||
h.Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")
|
||||
h.Set("Cache-Control", "no-store, no-cache, must-revalidate, private")
|
||||
h.Set("Pragma", "no-cache")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -132,9 +132,9 @@ func installService(args []string) error {
|
||||
return fmt.Errorf("options --tls, --unsecure, and --trust-proxy are mutually exclusive")
|
||||
}
|
||||
|
||||
// Default to tls if nothing is specified
|
||||
isTLS := *tlsOpt || optCount == 0
|
||||
isUnsecure := *unsecureOpt
|
||||
// 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
|
||||
@@ -505,7 +505,7 @@ func fatalIf(err error) {
|
||||
|
||||
// DefaultConfigContent returns the default configuration template filled with the username.
|
||||
func DefaultConfigContent(username string) string {
|
||||
return fmt.Sprintf(configTemplateBase, "true", "# 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)
|
||||
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.
|
||||
@@ -531,8 +531,8 @@ Usage:
|
||||
nadir [run] [-d] [-f <path>] Start the server (-d / --detach: run in background)
|
||||
nadir --save-config [-f <path>] Save default configuration to path and exit
|
||||
nadir install [--tls|--unsecure|--trust-proxy] Install + enable the systemd service (starts on boot)
|
||||
(--tls: enable HTTPS with self-signed certificate, default)
|
||||
(--unsecure: serve HTTP directly)
|
||||
(--tls: enable HTTPS with self-signed certificate)
|
||||
(--unsecure: serve HTTP directly, default)
|
||||
(--trust-proxy: serve HTTP behind a reverse proxy)
|
||||
nadir uninstall [--complete] Remove the service (keeps data/config; --complete wipes all)
|
||||
nadir start|stop|restart|status Control the running service
|
||||
|
||||
+1
-46
@@ -4,60 +4,15 @@ import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"log"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// serverCert returns the TLS certificate to serve: the admin-supplied PEM pair
|
||||
// when both paths are set, otherwise a freshly generated in-memory self-signed
|
||||
// cert for local development.
|
||||
func serverCert(certPath, keyPath string) (tls.Certificate, error) {
|
||||
if certPath != "" && keyPath != "" {
|
||||
return tls.LoadX509KeyPair(certPath, keyPath)
|
||||
}
|
||||
log.Printf("tls: no tls_cert/tls_key configured - generating a self-signed certificate (dev only)")
|
||||
return generateSelfSignedCert()
|
||||
}
|
||||
|
||||
func generateSelfSignedCert() (tls.Certificate, error) {
|
||||
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
|
||||
// Random serial: a fixed serial (1) makes every generated cert collide in a
|
||||
// browser/OS trust store, so a previously-accepted cert can't be replaced.
|
||||
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
|
||||
template := x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{Organization: []string{"urania-nadir"}},
|
||||
NotBefore: time.Now(),
|
||||
NotAfter: time.Now().Add(365 * 24 * time.Hour),
|
||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true,
|
||||
DNSNames: []string{"localhost"},
|
||||
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback},
|
||||
}
|
||||
|
||||
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
return tls.Certificate{Certificate: [][]byte{derBytes}, PrivateKey: priv}, nil
|
||||
}
|
||||
|
||||
// generateAndSaveCert generates a self-signed certificate and private key,
|
||||
// and saves them as PEM files.
|
||||
func generateAndSaveCert(certPath, keyPath string, hostname string) error {
|
||||
@@ -75,7 +30,7 @@ func generateAndSaveCert(certPath, keyPath string, hostname string) error {
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{Organization: []string{"nadir-agent-tls"}},
|
||||
NotBefore: time.Now(),
|
||||
NotAfter: time.Now().Add(3650 * 24 * time.Hour), // 10 years
|
||||
NotAfter: time.Now().Add(365 * 24 * time.Hour), // 1 year
|
||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true,
|
||||
|
||||
@@ -7,8 +7,6 @@ require github.com/msteinert/pam v1.2.0
|
||||
require github.com/danielgtaylor/huma/v2 v2.38.0
|
||||
|
||||
require (
|
||||
github.com/coder/websocket v1.8.15
|
||||
github.com/creack/pty v1.1.24
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
modernc.org/sqlite v1.52.0
|
||||
)
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
aead.dev/minisign v0.3.0 h1:8Xafzy5PEVZqYDNP60yJHARlW1eOQtsKNp/Ph2c0vRA=
|
||||
aead.dev/minisign v0.3.0/go.mod h1:NLvG3Uoq3skkRMDuc3YHpWUTMTrSExqm+Ij73W13F6Y=
|
||||
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
|
||||
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
|
||||
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
|
||||
github.com/danielgtaylor/huma/v2 v2.38.0 h1:fb0WZCatnaiHLphMQDDWDjygNxfMkX/ENma3QsRl7vY=
|
||||
github.com/danielgtaylor/huma/v2 v2.38.0/go.mod h1:k9hwjlgWFt1t2jsmQGlsgXAG2FBTZa4kkjV581qAtfo=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
|
||||
+13
-12
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
// loginNameRe is the useradd default NAME_REGEX. Validating at this trust
|
||||
// boundary keeps a flag-like name (e.g. "-c", "--help") from reaching `su` in
|
||||
// the terminal handler or showing up verbatim in audit logs / throttle keys.
|
||||
// showing up verbatim in audit logs / throttle keys.
|
||||
var loginNameRe = regexp.MustCompile(`^[a-z_][a-z0-9_-]{0,31}\$?$`)
|
||||
|
||||
// authenticator verifies a username/password (PAM in production). It's a field
|
||||
@@ -43,8 +43,9 @@ type LoginOutput struct {
|
||||
// development over plain HTTP, where a Secure cookie would never be sent back.
|
||||
func RegisterLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store, secure bool) {
|
||||
// loginThrottle blunts brute force: 5 failures for a username+source IP
|
||||
// trigger a one-minute cooldown. See throttle.go for the ceiling/upgrade path.
|
||||
registerLogin(api, sessions, auditor, secure, Authenticate, newFailLimiter(5, time.Minute))
|
||||
// trigger a one-minute cooldown. Persisted in SQLite so cooldowns survive
|
||||
// process restarts.
|
||||
registerLogin(api, sessions, auditor, secure, Authenticate, sessions.NewPersistentFailLimiter(5, time.Minute))
|
||||
}
|
||||
|
||||
func registerLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store, secure bool, authenticate authenticator, throttle *failLimiter) {
|
||||
@@ -85,15 +86,15 @@ func registerLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store
|
||||
return nil, huma.Error500InternalServerError("could not create session", err)
|
||||
}
|
||||
out := &LoginOutput{
|
||||
SetCookie: http.Cookie{
|
||||
Name: "nadir_session_id",
|
||||
Value: sessionID,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Expires: time.Now().Add(24 * time.Hour),
|
||||
},
|
||||
SetCookie: http.Cookie{
|
||||
Name: "nadir_session_id",
|
||||
Value: sessionID,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
MaxAge: 86400,
|
||||
},
|
||||
}
|
||||
out.Body.Status = "logged in"
|
||||
return out, nil
|
||||
|
||||
+78
-82
@@ -68,110 +68,106 @@ func TestLoginLogoutThrottling(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
|
||||
|
||||
// Inject a stub authenticator and a short-window throttle (3 failures) at
|
||||
// registration — no package globals to mutate. The throttle keys on
|
||||
// username+IP, so the success/failure cases below and the throttle case (a
|
||||
// distinct user) don't interfere.
|
||||
authMock := func(username, password string) error {
|
||||
if password == "correct" {
|
||||
return nil
|
||||
}
|
||||
return errors.New("pam error")
|
||||
}
|
||||
registerLogin(api, sessions, auditStore, false, authMock, newFailLimiter(3, 500*time.Millisecond))
|
||||
throttle := newFailLimiter(3, 500*time.Millisecond)
|
||||
registerLogin(api, sessions, auditStore, false, authMock, throttle)
|
||||
RegisterLogout(api, sessions, false)
|
||||
|
||||
// 1. Test failed login
|
||||
resp := api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "admin",
|
||||
Password: "wrong",
|
||||
t.Run("failed login returns 401", func(t *testing.T) {
|
||||
resp := api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "admin",
|
||||
Password: "wrong",
|
||||
})
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("got code %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
})
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("failed login: got code %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
// 2. Test successful login
|
||||
resp = api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "admin",
|
||||
Password: "correct",
|
||||
})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("successful login: got code %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
cookieHeader := resp.Header().Get("Set-Cookie")
|
||||
if !strings.Contains(cookieHeader, "nadir_session_id=") {
|
||||
t.Fatalf("Set-Cookie header missing nadir_session_id: %q", cookieHeader)
|
||||
}
|
||||
|
||||
var sessionID string
|
||||
parts := strings.SplitSeq(cookieHeader, ";")
|
||||
for part := range parts {
|
||||
part = strings.TrimSpace(part)
|
||||
if after, ok := strings.CutPrefix(part, "nadir_session_id="); ok {
|
||||
sessionID = after
|
||||
break
|
||||
t.Run("successful login returns session cookie", func(t *testing.T) {
|
||||
resp := api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "admin",
|
||||
Password: "correct",
|
||||
})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Fatalf("got code %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
if sessionID == "" {
|
||||
t.Fatal("nadir_session_id cookie not found")
|
||||
}
|
||||
cookieHeader := resp.Header().Get("Set-Cookie")
|
||||
if !strings.Contains(cookieHeader, "nadir_session_id=") {
|
||||
t.Fatalf("Set-Cookie header missing nadir_session_id: %q", cookieHeader)
|
||||
}
|
||||
|
||||
_, ok := sessions.GetByToken(sessionID)
|
||||
if !ok {
|
||||
t.Fatal("session not found in session store")
|
||||
}
|
||||
parts := strings.SplitSeq(cookieHeader, ";")
|
||||
for part := range parts {
|
||||
part = strings.TrimSpace(part)
|
||||
if after, ok := strings.CutPrefix(part, "nadir_session_id="); ok {
|
||||
sessionID = after
|
||||
break
|
||||
}
|
||||
}
|
||||
if sessionID == "" {
|
||||
t.Fatal("nadir_session_id cookie not found")
|
||||
}
|
||||
if _, ok := sessions.GetByToken(sessionID); !ok {
|
||||
t.Fatal("session not found in session store")
|
||||
}
|
||||
})
|
||||
|
||||
// 3. Test logout
|
||||
resp = api.Post("/api/logout", "Cookie: nadir_session_id="+sessionID, struct{}{})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("logout failed: got code %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
t.Run("logout invalidates session", func(t *testing.T) {
|
||||
resp := api.Post("/api/logout", "Cookie: nadir_session_id="+sessionID, struct{}{})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Fatalf("logout failed: got code %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
if _, ok := sessions.GetByToken(sessionID); ok {
|
||||
t.Fatal("session still valid after logout")
|
||||
}
|
||||
})
|
||||
|
||||
_, ok = sessions.GetByToken(sessionID)
|
||||
if ok {
|
||||
t.Fatal("session still valid after logout")
|
||||
}
|
||||
|
||||
// 4. Test throttling (the handler was registered with a 3-failure limiter).
|
||||
for range 3 {
|
||||
api.Post("/api/login", struct {
|
||||
t.Run("throttling blocks after 3 failures", func(t *testing.T) {
|
||||
for range 3 {
|
||||
api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "throttled-user",
|
||||
Password: "wrong",
|
||||
})
|
||||
}
|
||||
resp := api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "throttled-user",
|
||||
Password: "wrong",
|
||||
Password: "correct",
|
||||
})
|
||||
}
|
||||
|
||||
resp = api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "throttled-user",
|
||||
Password: "correct",
|
||||
if resp.Code != http.StatusTooManyRequests {
|
||||
t.Errorf("got code %d, want %d", resp.Code, http.StatusTooManyRequests)
|
||||
}
|
||||
})
|
||||
if resp.Code != http.StatusTooManyRequests {
|
||||
t.Errorf("throttled login: got code %d, want %d", resp.Code, http.StatusTooManyRequests)
|
||||
}
|
||||
|
||||
time.Sleep(600 * time.Millisecond)
|
||||
|
||||
resp = api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "throttled-user",
|
||||
Password: "correct",
|
||||
t.Run("throttle reset allows login", func(t *testing.T) {
|
||||
throttle.reset("throttled-user|")
|
||||
resp := api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "throttled-user",
|
||||
Password: "correct",
|
||||
})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("got code %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("login after cooldown: got code %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
)
|
||||
|
||||
// RateLimiter provides per-IP rate limiting for authenticated API endpoints,
|
||||
// complementing the login-specific failLimiter with a broader cap on all
|
||||
// requests. The window aligns to wall-clock intervals so all IPs share the
|
||||
// same boundary.
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
buckets map[string]*tokenBucket
|
||||
limit int
|
||||
interval time.Duration
|
||||
}
|
||||
|
||||
type tokenBucket struct {
|
||||
count int
|
||||
windowEnd time.Time
|
||||
}
|
||||
|
||||
const maxRateLimitKeys = 10000
|
||||
|
||||
func NewRateLimiter(limit int, interval time.Duration) *RateLimiter {
|
||||
return &RateLimiter{
|
||||
buckets: map[string]*tokenBucket{},
|
||||
limit: limit,
|
||||
interval: interval,
|
||||
}
|
||||
}
|
||||
|
||||
// Allow reports whether ip may make a request now. Returns false when the
|
||||
// limit is exceeded OR the map is full (fail-closed).
|
||||
func (l *RateLimiter) Allow(ip string) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
b, ok := l.buckets[ip]
|
||||
if !ok || now.After(b.windowEnd) {
|
||||
if len(l.buckets) >= maxRateLimitKeys {
|
||||
return false
|
||||
}
|
||||
l.buckets[ip] = &tokenBucket{count: 1, windowEnd: now.Add(l.interval)}
|
||||
return true
|
||||
}
|
||||
if b.count >= l.limit {
|
||||
return false
|
||||
}
|
||||
b.count++
|
||||
return true
|
||||
}
|
||||
|
||||
// RateLimitMiddleware returns Huma middleware that rejects requests exceeding
|
||||
// the per-IP rate limit with 429 Too Many Requests. It runs before the RBAC
|
||||
// check so abusive IPs are dropped early. The IP is read from the context set
|
||||
// by WithClientIP; if absent the request passes through unthrottled.
|
||||
func RateLimitMiddleware(api huma.API, rl *RateLimiter) func(huma.Context, func(huma.Context)) {
|
||||
return func(ctx huma.Context, next func(huma.Context)) {
|
||||
ip := ClientIP(ctx.Context())
|
||||
if ip != "" && !rl.Allow(ip) {
|
||||
huma.WriteErr(api, ctx, http.StatusTooManyRequests, "rate limit exceeded, try again later")
|
||||
return
|
||||
}
|
||||
next(ctx)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
@@ -12,7 +13,7 @@ import (
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
const sessionTTL = 24 * time.Hour
|
||||
var sessionTTL = 24 * time.Hour
|
||||
|
||||
type Session struct {
|
||||
Username string
|
||||
@@ -45,6 +46,17 @@ func NewSessionStore(path string) (*SessionStore, error) {
|
||||
)`); err != nil {
|
||||
return nil, fmt.Errorf("create sessions table: %w", err)
|
||||
}
|
||||
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS throttle (
|
||||
key TEXT PRIMARY KEY,
|
||||
count INTEGER NOT NULL,
|
||||
until INTEGER NOT NULL
|
||||
)`); err != nil {
|
||||
return nil, fmt.Errorf("create throttle table: %w", err)
|
||||
}
|
||||
// Restrict the DB file so only the owning user (root) can read it.
|
||||
if err := os.Chmod(path, 0600); err != nil {
|
||||
return nil, fmt.Errorf("chmod session db: %w", err)
|
||||
}
|
||||
return &SessionStore{db: db}, nil
|
||||
}
|
||||
|
||||
@@ -57,7 +69,7 @@ func (s *SessionStore) Create(username string) (string, error) {
|
||||
expires := time.Now().Add(sessionTTL)
|
||||
if _, err := s.db.Exec(
|
||||
`INSERT INTO sessions (token, username, expires_at) VALUES (?, ?, ?)`,
|
||||
token, username, expires.Unix(),
|
||||
hashSessionToken(token), username, expires.Unix(),
|
||||
); err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -67,26 +79,75 @@ func (s *SessionStore) Create(username string) (string, error) {
|
||||
// Delete removes a session, invalidating it immediately (logout). Deleting an
|
||||
// unknown token is a no-op.
|
||||
func (s *SessionStore) Delete(token string) error {
|
||||
_, err := s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token)
|
||||
_, err := s.db.Exec(`DELETE FROM sessions WHERE token = ?`, hashSessionToken(token))
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteByUsername removes every session for the given user, used when a
|
||||
// password change should invalidate all existing sessions.
|
||||
func (s *SessionStore) DeleteByUsername(username string) error {
|
||||
_, err := s.db.Exec(`DELETE FROM sessions WHERE username = ?`, username)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SessionStore) GetByToken(token string) (Session, bool) {
|
||||
var username string
|
||||
var expires int64
|
||||
h := hashSessionToken(token)
|
||||
err := s.db.QueryRow(
|
||||
`SELECT username, expires_at FROM sessions WHERE token = ?`, token,
|
||||
`SELECT username, expires_at FROM sessions WHERE token = ?`, h,
|
||||
).Scan(&username, &expires)
|
||||
if err != nil {
|
||||
return Session{}, false
|
||||
}
|
||||
if time.Now().Unix() > expires {
|
||||
s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token)
|
||||
s.db.Exec(`DELETE FROM sessions WHERE token = ?`, h)
|
||||
return Session{}, false
|
||||
}
|
||||
return Session{Username: username}, true
|
||||
}
|
||||
|
||||
// NewPersistentFailLimiter returns a failLimiter whose state survives process
|
||||
// restarts via the session SQLite database.
|
||||
func (s *SessionStore) NewPersistentFailLimiter(max int, window time.Duration) *failLimiter {
|
||||
l := newFailLimiter(max, window)
|
||||
// Load existing entries, skipping expired ones.
|
||||
rows, err := s.db.Query(`SELECT key, count, until FROM throttle`)
|
||||
if err != nil {
|
||||
return l
|
||||
}
|
||||
defer rows.Close()
|
||||
now := time.Now()
|
||||
for rows.Next() {
|
||||
var k string
|
||||
var c int
|
||||
var u int64
|
||||
if err := rows.Scan(&k, &c, &u); err != nil {
|
||||
continue
|
||||
}
|
||||
until := time.Unix(u, 0)
|
||||
if now.After(until) {
|
||||
s.db.Exec(`DELETE FROM throttle WHERE key = ?`, k)
|
||||
continue
|
||||
}
|
||||
l.attempts[k] = &attemptState{count: c, until: until}
|
||||
}
|
||||
// Wire persistence: writes to DB on every mutation.
|
||||
l.sync = func(key string, st *attemptState) {
|
||||
if st == nil {
|
||||
s.db.Exec(`DELETE FROM throttle WHERE key = ?`, key)
|
||||
} else {
|
||||
s.db.Exec(`INSERT OR REPLACE INTO throttle (key, count, until) VALUES (?, ?, ?)`, key, st.count, st.until.Unix())
|
||||
}
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func hashSessionToken(token string) string {
|
||||
h := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func randomToken() string {
|
||||
b := make([]byte, 32)
|
||||
rand.Read(b) // never fails; rand.Read panics internally on misconfigured platforms.
|
||||
|
||||
@@ -34,22 +34,21 @@ func TestExpiredSessionRejected(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Write a row that expired an hour ago, bypassing Create's TTL.
|
||||
_, err = store.db.Exec(
|
||||
`INSERT INTO sessions (token, username, expires_at) VALUES (?, ?, ?)`,
|
||||
"stale", "urania", time.Now().Add(-time.Hour).Unix(),
|
||||
)
|
||||
// Create a session with an already-expired TTL (-2s ensures the Unix
|
||||
// second-rounded timestamp is safely in the past).
|
||||
oldTTL := sessionTTL
|
||||
sessionTTL = -2 * time.Second
|
||||
token, err := store.Create("urania")
|
||||
sessionTTL = oldTTL
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := store.GetByToken("stale"); ok {
|
||||
if _, ok := store.GetByToken(token); ok {
|
||||
t.Fatal("expired session was accepted")
|
||||
}
|
||||
// Lazy cleanup should have deleted the row.
|
||||
var n int
|
||||
store.db.QueryRow(`SELECT count(*) FROM sessions WHERE token = ?`, "stale").Scan(&n)
|
||||
if n != 0 {
|
||||
t.Fatalf("expired row not cleaned up: %d rows remain", n)
|
||||
if _, ok := store.GetByToken(token); ok {
|
||||
t.Fatal("expired session still in store")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ type failLimiter struct {
|
||||
attempts map[string]*attemptState
|
||||
max int
|
||||
window time.Duration
|
||||
sync func(key string, s *attemptState) // optional: persist to DB
|
||||
}
|
||||
|
||||
type attemptState struct {
|
||||
@@ -32,8 +33,8 @@ type attemptState struct {
|
||||
}
|
||||
|
||||
// maxTrackedKeys bounds memory: an attacker rotating username/IP can't grow the
|
||||
// map without limit. When exceeded we drop all throttle state - a crude reset
|
||||
// that briefly forgets cooldowns, acceptable for a single-node panel.
|
||||
// map without limit. When exceeded we fail closed instead of wiping state, so
|
||||
// existing cooldowns are preserved.
|
||||
const maxTrackedKeys = 10000
|
||||
|
||||
func newFailLimiter(max int, window time.Duration) *failLimiter {
|
||||
@@ -49,11 +50,13 @@ func (l *failLimiter) blocked(key string) bool {
|
||||
}
|
||||
|
||||
// fail records a failed attempt and starts a cooldown once max is reached.
|
||||
// When the map is full we stop tracking new keys rather than wiping existing
|
||||
// cooldowns (which an attacker could use to clear a target's throttle).
|
||||
func (l *failLimiter) fail(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if len(l.attempts) > maxTrackedKeys {
|
||||
l.attempts = map[string]*attemptState{}
|
||||
if len(l.attempts) >= maxTrackedKeys {
|
||||
return
|
||||
}
|
||||
s := l.attempts[key]
|
||||
if s == nil {
|
||||
@@ -63,7 +66,10 @@ func (l *failLimiter) fail(key string) {
|
||||
s.count++
|
||||
if s.count >= l.max {
|
||||
s.until = time.Now().Add(l.window)
|
||||
s.count = 0 // restart the window after the cooldown is set
|
||||
s.count = 0
|
||||
}
|
||||
if l.sync != nil {
|
||||
l.sync(key, s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,6 +78,9 @@ func (l *failLimiter) reset(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
delete(l.attempts, key)
|
||||
if l.sync != nil {
|
||||
l.sync(key, nil)
|
||||
}
|
||||
}
|
||||
|
||||
type ctxKey int
|
||||
|
||||
@@ -56,6 +56,9 @@ func NewTokenStore(path string) (*TokenStore, error) {
|
||||
)`); err != nil {
|
||||
return nil, fmt.Errorf("create tokens table: %w", err)
|
||||
}
|
||||
if err := os.Chmod(path, 0600); err != nil {
|
||||
return nil, fmt.Errorf("chmod token db: %w", err)
|
||||
}
|
||||
return &TokenStore{db: db}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -16,8 +16,8 @@ func TestTokenStore(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(raw) < len(tokenPrefix)+32 || raw[:len(tokenPrefix)] != tokenPrefix {
|
||||
t.Fatalf("token %q lacks %q prefix or is too short", raw, tokenPrefix)
|
||||
if len(raw) < 36 || raw[:4] != "nad_" {
|
||||
t.Fatalf("token %q lacks %q prefix or is too short", raw, "nad_")
|
||||
}
|
||||
|
||||
// Round-trip: the minted secret resolves to its name.
|
||||
@@ -25,7 +25,7 @@ func TestTokenStore(t *testing.T) {
|
||||
t.Errorf("Lookup(valid) = %q,%v; want dash,true", name, ok)
|
||||
}
|
||||
// A wrong secret (and a non-prefixed one) must not resolve.
|
||||
if _, ok := store.Lookup(tokenPrefix + "wrong"); ok {
|
||||
if _, ok := store.Lookup("nad_wrong"); ok {
|
||||
t.Error("Lookup(wrong) succeeded")
|
||||
}
|
||||
if _, ok := store.Lookup("no-prefix"); ok {
|
||||
|
||||
@@ -69,10 +69,10 @@ type Server struct {
|
||||
}
|
||||
|
||||
// SecureCookie reports whether the session cookie should carry the Secure
|
||||
// attribute, defaulting to true when server.secure_tls is omitted.
|
||||
// attribute, defaulting to false when server.secure_tls is omitted (plain HTTP).
|
||||
func (f *File) SecureCookie() bool {
|
||||
if f.Server.SecureTLS == nil {
|
||||
return true
|
||||
return false
|
||||
}
|
||||
return *f.Server.SecureTLS
|
||||
}
|
||||
@@ -109,10 +109,10 @@ func Load(path string) (*File, error) {
|
||||
if err := yaml.Unmarshal(data, &f); err != nil {
|
||||
return nil, fmt.Errorf("parse config %s: %w", path, err)
|
||||
}
|
||||
// release_repo, when set, is downloaded over the wire and (for /api/update)
|
||||
// executed. Validate shape + scheme once here so /install.sh and the updater
|
||||
// can use the string directly. Trim any trailing slash so downstream string
|
||||
// concatenation produces a clean URL.
|
||||
// release_repo, when set, is substituted into shell scripts and downloaded
|
||||
// over the wire. Validate shape + scheme + shell-safety once here so
|
||||
// /install.sh and the updater can use the string directly. Trim any trailing
|
||||
// slash so downstream string concatenation produces a clean URL.
|
||||
if f.Server.ReleaseRepo != "" {
|
||||
f.Server.ReleaseRepo = strings.TrimRight(f.Server.ReleaseRepo, "/")
|
||||
u, err := url.Parse(f.Server.ReleaseRepo)
|
||||
@@ -129,6 +129,11 @@ func Load(path string) (*File, error) {
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return nil, fmt.Errorf("server.release_repo must be https://host/owner/repo, got %q", f.Server.ReleaseRepo)
|
||||
}
|
||||
// Shell-safety: reject characters that could break out of a double-quoted
|
||||
// string when substituted into the install.sh template.
|
||||
if strings.ContainsAny(f.Server.ReleaseRepo, "`$\"\\;|&") {
|
||||
return nil, fmt.Errorf("server.release_repo contains unsafe characters: %q", f.Server.ReleaseRepo)
|
||||
}
|
||||
}
|
||||
return &f, nil
|
||||
}
|
||||
|
||||
@@ -30,13 +30,13 @@ func mods() []module.Module {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecureCookieDefaultsTrue(t *testing.T) {
|
||||
if !(&File{}).SecureCookie() {
|
||||
t.Error("omitted secure_tls should default to true")
|
||||
func TestSecureCookieDefaultsFalse(t *testing.T) {
|
||||
if (&File{}).SecureCookie() {
|
||||
t.Error("omitted secure_tls should default to false")
|
||||
}
|
||||
no := false
|
||||
if (&File{Server: Server{SecureTLS: &no}}).SecureCookie() {
|
||||
t.Error("secure_tls: false should disable the Secure flag")
|
||||
yes := true
|
||||
if !(&File{Server: Server{SecureTLS: &yes}}).SecureCookie() {
|
||||
t.Error("secure_tls: true should enable the Secure flag")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ func registerGroups(api huma.API) {
|
||||
}, func(ctx context.Context, _ *struct{}) (*ListGroupsOutput, error) {
|
||||
list, err := listGroups()
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("group lookup failed", err)
|
||||
}
|
||||
out := &ListGroupsOutput{}
|
||||
out.Body.Groups = list
|
||||
@@ -92,7 +92,7 @@ func registerGroups(api huma.API) {
|
||||
}
|
||||
g, ok, err := lookupGroup(in.Group)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("group lookup failed", err)
|
||||
}
|
||||
if !ok {
|
||||
return nil, huma.Error404NotFound("group not found: " + in.Group)
|
||||
@@ -114,7 +114,7 @@ func registerGroups(api huma.API) {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok, err := lookupGroup(in.Body.Name); err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("group lookup failed", err)
|
||||
} else if ok {
|
||||
return nil, huma.Error409Conflict("group already exists: " + in.Body.Name)
|
||||
}
|
||||
@@ -154,7 +154,7 @@ func registerGroups(api huma.API) {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok, err := lookupGroup(in.Group); err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("group lookup failed", err)
|
||||
} else if !ok {
|
||||
return nil, huma.Error404NotFound("group not found: " + in.Group)
|
||||
}
|
||||
|
||||
@@ -38,14 +38,30 @@ short:x:5
|
||||
}
|
||||
|
||||
func TestValidateGroupName(t *testing.T) {
|
||||
for _, n := range []string{"wheel", "_svc", "dev-team", "g1"} {
|
||||
if err := validateGroupName(n); err != nil {
|
||||
t.Errorf("validateGroupName(%q) = %v, want nil", n, err)
|
||||
}
|
||||
}
|
||||
for _, n := range []string{"", "-x", "Wheel", "a,b", "foo;rm", "1grp"} {
|
||||
if err := validateGroupName(n); err == nil {
|
||||
t.Errorf("validateGroupName(%q) = nil, want error", n)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
value string
|
||||
valid bool
|
||||
}{
|
||||
{name: "wheel", value: "wheel", valid: true},
|
||||
{name: "underscore prefix", value: "_svc", valid: true},
|
||||
{name: "dev-team", value: "dev-team", valid: true},
|
||||
{name: "alphanumeric", value: "g1", valid: true},
|
||||
{name: "empty", value: "", valid: false},
|
||||
{name: "flag injection", value: "-x", valid: false},
|
||||
{name: "uppercase", value: "Wheel", valid: false},
|
||||
{name: "comma", value: "a,b", valid: false},
|
||||
{name: "shell metachar", value: "foo;rm", valid: false},
|
||||
{name: "leading digit", value: "1grp", valid: false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateGroupName(tt.value)
|
||||
if tt.valid && err != nil {
|
||||
t.Errorf("validateGroupName(%q) = %v, want nil", tt.value, err)
|
||||
}
|
||||
if !tt.valid && err == nil {
|
||||
t.Errorf("validateGroupName(%q) = nil, want error", tt.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,17 +49,31 @@ func TestValidateIfaceConfig(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestValidateIface(t *testing.T) {
|
||||
valid := []string{"eth0", "enp3s0", "wlan0", "br-lan", "veth1234567", "docker0"}
|
||||
for _, name := range valid {
|
||||
if err := validateIface(name); err != nil {
|
||||
t.Errorf("validateIface(%q) unexpected error: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
invalid := []string{"", "-eth0", "/dev/net", "a b", "name_that_is_way_too_long_for_linux"}
|
||||
for _, name := range invalid {
|
||||
if err := validateIface(name); err == nil {
|
||||
t.Errorf("validateIface(%q) expected error", name)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
value string
|
||||
valid bool
|
||||
}{
|
||||
{name: "eth0", value: "eth0", valid: true},
|
||||
{name: "enp3s0", value: "enp3s0", valid: true},
|
||||
{name: "wlan0", value: "wlan0", valid: true},
|
||||
{name: "bridge", value: "br-lan", valid: true},
|
||||
{name: "veth", value: "veth1234567", valid: true},
|
||||
{name: "docker", value: "docker0", valid: true},
|
||||
{name: "empty", value: "", valid: false},
|
||||
{name: "leading dash", value: "-eth0", valid: false},
|
||||
{name: "path", value: "/dev/net", valid: false},
|
||||
{name: "space", value: "a b", valid: false},
|
||||
{name: "too long", value: "name_that_is_way_too_long_for_linux", valid: false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateIface(tt.value)
|
||||
if tt.valid && err != nil {
|
||||
t.Errorf("validateIface(%q) unexpected error: %v", tt.value, err)
|
||||
}
|
||||
if !tt.valid && err == nil {
|
||||
t.Errorf("validateIface(%q) expected error", tt.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"nadir/internal/oscmd"
|
||||
|
||||
@@ -18,6 +19,10 @@ import (
|
||||
|
||||
var hostsFile = "/etc/hosts"
|
||||
|
||||
// hostsMu serialises writes to /etc/hosts so concurrent requests don't
|
||||
// clobber each other's read-modify-write.
|
||||
var hostsMu sync.Mutex
|
||||
|
||||
// hostnameRe matches a single hostname/alias. It forbids whitespace and '#' (so
|
||||
// an entry can't inject extra fields or a comment) and a leading dash.
|
||||
var hostnameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`)
|
||||
@@ -156,9 +161,26 @@ func renderHostLine(ip string, hostnames []string) string {
|
||||
|
||||
// --- writes ------------------------------------------------------------------
|
||||
|
||||
// writeHostsAtomically writes content to /etc/hosts via a temp file + rename,
|
||||
// so a crash mid-write leaves the original file intact.
|
||||
func writeHostsAtomically(content string) error {
|
||||
tmp := hostsFile + ".nadir.tmp"
|
||||
if err := os.WriteFile(tmp, []byte(content), 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, hostsFile); err != nil {
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// upsertHost replaces the line for ip (matched on the address field) or appends
|
||||
// a new one, preserving every other line.
|
||||
func upsertHost(ip string, hostnames []string) error {
|
||||
hostsMu.Lock()
|
||||
defer hostsMu.Unlock()
|
||||
|
||||
data, err := os.ReadFile(hostsFile)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -174,7 +196,6 @@ func upsertHost(ip string, hostnames []string) error {
|
||||
}
|
||||
}
|
||||
if !replaced {
|
||||
// Append, avoiding a blank line if the file already ended with one.
|
||||
if n := len(lines); n > 0 && strings.TrimSpace(lines[n-1]) == "" {
|
||||
lines[n-1] = newLine
|
||||
} else {
|
||||
@@ -182,11 +203,14 @@ func upsertHost(ip string, hostnames []string) error {
|
||||
}
|
||||
lines = append(lines, "")
|
||||
}
|
||||
return os.WriteFile(hostsFile, []byte(strings.Join(lines, "\n")), 0644)
|
||||
return writeHostsAtomically(strings.Join(lines, "\n"))
|
||||
}
|
||||
|
||||
// deleteHost removes every line mapping ip and reports whether any were removed.
|
||||
func deleteHost(ip string) (bool, error) {
|
||||
hostsMu.Lock()
|
||||
defer hostsMu.Unlock()
|
||||
|
||||
data, err := os.ReadFile(hostsFile)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -204,5 +228,5 @@ func deleteHost(ip string) (bool, error) {
|
||||
if !removed {
|
||||
return false, nil
|
||||
}
|
||||
return true, os.WriteFile(hostsFile, []byte(strings.Join(kept, "\n")), 0644)
|
||||
return true, writeHostsAtomically(strings.Join(kept, "\n"))
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"nadir/internal/oscmd"
|
||||
|
||||
@@ -168,14 +167,18 @@ func TestNetworkingHandlers(t *testing.T) {
|
||||
t.Errorf("pending change should be cleared: got %d, want %d", resp.Code, http.StatusNotFound)
|
||||
}
|
||||
|
||||
// 6. Test automatic rollback
|
||||
// 6. Test explicit rollback (same revert path as automatic rollback).
|
||||
applyPayload.RollbackSeconds = 1
|
||||
resp = api.Put("/api/networking/interfaces/eth0", applyPayload)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("apply config again: got %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
time.Sleep(1200 * time.Millisecond)
|
||||
if m.pending == nil {
|
||||
t.Fatal("expected pending change after apply")
|
||||
}
|
||||
if err := m.rollbackNow("eth0"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
resp = api.Get("/api/networking/pending")
|
||||
if resp.Code != http.StatusNotFound {
|
||||
|
||||
@@ -157,7 +157,7 @@ func registerReads(api huma.API, m *Module) {
|
||||
}, func(ctx context.Context, _ *struct{}) (*DNSOutput, error) {
|
||||
data, err := os.ReadFile(resolvConf)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read resolv.conf failed", err)
|
||||
return nil, huma.Error500InternalServerError("DNS config lookup failed", err)
|
||||
}
|
||||
res := &DNSOutput{}
|
||||
res.Body.Servers = parseResolv(string(data))
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const defaultRollbackSeconds = 60
|
||||
const defaultRollbackSeconds = 120
|
||||
|
||||
// errAlreadyPending is returned when another change is awaiting confirmation.
|
||||
// The write handlers map this to 409 Conflict.
|
||||
@@ -113,18 +113,26 @@ func (m *Module) armPending(iface string, revert func() error, seconds int) (int
|
||||
// revert even if the server is otherwise idle — the whole point is protecting
|
||||
// against being locked out of a remote box.
|
||||
pc.Timer = time.AfterFunc(dur, func() {
|
||||
// Check validity under lock, then revert outside it so a slow
|
||||
// nmcli/networkctl call doesn't block the entire networking module.
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
// Only revert if this exact change is still pending (it may have been
|
||||
// confirmed or manually rolled back in the meantime).
|
||||
if m.pending != pc {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
iface := pc.Iface
|
||||
revert := pc.revert
|
||||
m.mu.Unlock()
|
||||
|
||||
log.Printf("networking: rollback timer expired for %s — reverting", iface)
|
||||
if err := pc.revert(); err != nil {
|
||||
if err := revert(); err != nil {
|
||||
log.Printf("networking: auto-rollback of %s failed: %v", iface, err)
|
||||
}
|
||||
m.pending = nil
|
||||
m.mu.Lock()
|
||||
if m.pending == pc {
|
||||
m.pending = nil
|
||||
}
|
||||
m.mu.Unlock()
|
||||
})
|
||||
|
||||
m.pending = pc
|
||||
|
||||
@@ -83,6 +83,11 @@ type PkgDoneEvent struct {
|
||||
Error string `json:"error,omitempty" doc:"Exit error when it failed"`
|
||||
}
|
||||
|
||||
// pkgSem limits concurrent package manager operations. Package managers are
|
||||
// heavy (dnf/apt/pacman grab a lock), so running more than a few in parallel
|
||||
// just thrashes; 3 concurrent ops is generous for an admin panel.
|
||||
var pkgSem = make(chan struct{}, 3)
|
||||
|
||||
// pkgEvents maps SSE event names to their payload types for the streaming
|
||||
// install/remove/upgrade operations.
|
||||
var pkgEvents = map[string]any{
|
||||
@@ -193,6 +198,13 @@ func streamOp(ctx context.Context, send sse.Sender, bin string, args []string) {
|
||||
send.Data(PkgErrorEvent{Message: "no supported package manager found"})
|
||||
return
|
||||
}
|
||||
select {
|
||||
case pkgSem <- struct{}{}:
|
||||
default:
|
||||
send.Data(PkgErrorEvent{Message: "too many concurrent package operations, try again later"})
|
||||
return
|
||||
}
|
||||
defer func() { <-pkgSem }()
|
||||
// DEBIAN_FRONTEND keeps apt from blocking on an interactive prompt.
|
||||
lines, errc, err := oscmd.RunStreamCombined(ctx, []string{"DEBIAN_FRONTEND=noninteractive"}, bin, args...)
|
||||
if err != nil {
|
||||
|
||||
@@ -54,27 +54,50 @@ func TestParsePacmanUpdates(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStripArch(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"code.x86_64": "code",
|
||||
"python3.11.noarch": "python3.11", // arch is only the final segment
|
||||
"noarchhere": "noarchhere",
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{name: "x86_64 arch", in: "code.x86_64", want: "code"},
|
||||
{name: "noarch suffix", in: "python3.11.noarch", want: "python3.11"},
|
||||
{name: "no arch segment", in: "noarchhere", want: "noarchhere"},
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := stripArch(in); got != want {
|
||||
t.Errorf("stripArch(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := stripArch(tt.in); got != tt.want {
|
||||
t.Errorf("stripArch(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateName(t *testing.T) {
|
||||
for _, n := range []string{"htop", "openssh-server", "lib32-glibc", "g++", "python3.11"} {
|
||||
if err := validateName(n); err != nil {
|
||||
t.Errorf("validateName(%q) = %v, want nil", n, err)
|
||||
}
|
||||
}
|
||||
for _, n := range []string{"", "-rf", "foo;rm", "foo bar", "pkg=1.0", "a/b"} {
|
||||
if err := validateName(n); err == nil {
|
||||
t.Errorf("validateName(%q) = nil, want error", n)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
value string
|
||||
valid bool
|
||||
}{
|
||||
{name: "htop", value: "htop", valid: true},
|
||||
{name: "openssh-server", value: "openssh-server", valid: true},
|
||||
{name: "lib32-glibc", value: "lib32-glibc", valid: true},
|
||||
{name: "g++", value: "g++", valid: true},
|
||||
{name: "python3.11", value: "python3.11", valid: true},
|
||||
{name: "empty", value: "", valid: false},
|
||||
{name: "flag injection", value: "-rf", valid: false},
|
||||
{name: "shell metachar", value: "foo;rm", valid: false},
|
||||
{name: "space", value: "foo bar", valid: false},
|
||||
{name: "equals", value: "pkg=1.0", valid: false},
|
||||
{name: "path sep", value: "a/b", valid: false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateName(tt.value)
|
||||
if tt.valid && err != nil {
|
||||
t.Errorf("validateName(%q) = %v, want nil", tt.value, err)
|
||||
}
|
||||
if !tt.valid && err == nil {
|
||||
t.Errorf("validateName(%q) = nil, want error", tt.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,10 @@ const (
|
||||
maxLogLines = 10000
|
||||
)
|
||||
|
||||
// logStreamSem limits concurrent log-follow connections. Each one forks a
|
||||
// journalctl or tail subprocess, so too many would exhaust system resources.
|
||||
var logStreamSem = make(chan struct{}, 10)
|
||||
|
||||
// LogEntry is one log record. For the journal source it is distilled from
|
||||
// journalctl's JSON; for the file source only Message is set (the raw line,
|
||||
// which usually carries its own embedded timestamp).
|
||||
@@ -128,6 +132,14 @@ func registerLogs(api huma.API, logFiles map[string][]string) {
|
||||
return
|
||||
}
|
||||
|
||||
select {
|
||||
case logStreamSem <- struct{}{}:
|
||||
default:
|
||||
send.Data(ErrorEvent{Message: "too many concurrent log streams, try again later"})
|
||||
return
|
||||
}
|
||||
defer func() { <-logStreamSem }()
|
||||
|
||||
var cmd string
|
||||
var args []string
|
||||
if in.Source == "file" {
|
||||
|
||||
@@ -48,49 +48,74 @@ func TestResolveLogPath(t *testing.T) {
|
||||
"nginx.service": {"/var/log/nginx/access.log", "/var/log/nginx/error.log"},
|
||||
}
|
||||
|
||||
// Allowlisted path resolves whether the caller uses the bare or .service
|
||||
// form, regardless of which form the config key used.
|
||||
for _, unit := range []string{"nginx.service", "nginx"} {
|
||||
if p, err := resolveLogPath(allow, unit, "/var/log/nginx/error.log"); err != nil || p != "/var/log/nginx/error.log" {
|
||||
t.Errorf("allowlisted path for %q: got %q, %v", unit, p, err)
|
||||
t.Run("allowlisted path via bare name", func(t *testing.T) {
|
||||
p, err := resolveLogPath(allow, "nginx", "/var/log/nginx/error.log")
|
||||
if err != nil || p != "/var/log/nginx/error.log" {
|
||||
t.Errorf("got %q, %v", p, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("allowlisted path via service suffix", func(t *testing.T) {
|
||||
p, err := resolveLogPath(allow, "nginx.service", "/var/log/nginx/error.log")
|
||||
if err != nil || p != "/var/log/nginx/error.log" {
|
||||
t.Errorf("got %q, %v", p, err)
|
||||
}
|
||||
})
|
||||
|
||||
// Everything else is rejected: empty path, non-listed path (traversal),
|
||||
// listed path but wrong unit, and unit with no allowlist at all.
|
||||
bad := []struct{ unit, path string }{
|
||||
{"nginx.service", ""},
|
||||
{"nginx.service", "/etc/shadow"},
|
||||
{"nginx.service", "/var/log/nginx/access.log/../../../etc/shadow"},
|
||||
{"sshd.service", "/var/log/nginx/error.log"},
|
||||
{"unknown.service", "/var/log/nginx/error.log"},
|
||||
}
|
||||
for _, b := range bad {
|
||||
if _, err := resolveLogPath(allow, b.unit, b.path); err == nil {
|
||||
t.Errorf("resolveLogPath(%q, %q) = nil error, want rejection", b.unit, b.path)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
unit string
|
||||
path string
|
||||
}{
|
||||
{name: "empty path", unit: "nginx.service", path: ""},
|
||||
{name: "non-allowlisted path", unit: "nginx.service", path: "/etc/shadow"},
|
||||
{name: "path traversal", unit: "nginx.service", path: "/var/log/nginx/access.log/../../../etc/shadow"},
|
||||
{name: "wrong unit", unit: "sshd.service", path: "/var/log/nginx/error.log"},
|
||||
{name: "unknown unit", unit: "unknown.service", path: "/var/log/nginx/error.log"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if _, err := resolveLogPath(allow, tt.unit, tt.path); err == nil {
|
||||
t.Errorf("resolveLogPath(%q, %q) = nil error, want rejection", tt.unit, tt.path)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestJournalUnit(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"docker.service": "docker",
|
||||
"docker": "docker",
|
||||
"sshd.service": "sshd",
|
||||
"foo.socket": "foo.socket", // only .service is stripped
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{name: "docker service", in: "docker.service", want: "docker"},
|
||||
{name: "docker bare", in: "docker", want: "docker"},
|
||||
{name: "sshd service", in: "sshd.service", want: "sshd"},
|
||||
{name: "socket unit", in: "foo.socket", want: "foo.socket"},
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := journalUnit(in); got != want {
|
||||
t.Errorf("journalUnit(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := journalUnit(tt.in); got != tt.want {
|
||||
t.Errorf("journalUnit(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClampLines(t *testing.T) {
|
||||
cases := map[int]int{0: defaultLogLines, -5: defaultLogLines, 50: 50, 999999: maxLogLines}
|
||||
for in, want := range cases {
|
||||
if got := clampLines(in); got != want {
|
||||
t.Errorf("clampLines(%d) = %d, want %d", in, got, want)
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
in int
|
||||
want int
|
||||
}{
|
||||
{name: "zero", in: 0, want: defaultLogLines},
|
||||
{name: "negative", in: -5, want: defaultLogLines},
|
||||
{name: "fifty", in: 50, want: 50},
|
||||
{name: "too large", in: 999999, want: maxLogLines},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := clampLines(tt.in); got != tt.want {
|
||||
t.Errorf("clampLines(%d) = %d, want %d", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,20 +3,33 @@ package services
|
||||
import "testing"
|
||||
|
||||
func TestValidateUnit(t *testing.T) {
|
||||
valid := []string{"sshd.service", "getty@tty1.service", "foo.bar:baz-1.service", "a_b.timer"}
|
||||
for _, u := range valid {
|
||||
if err := validateUnit(u); err != nil {
|
||||
t.Errorf("validateUnit(%q) = %v, want nil", u, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Empty, flag-injection, and anything with shell/path metacharacters must
|
||||
// be rejected before reaching systemctl.
|
||||
invalid := []string{"", "-rf", "--now", "a b", "foo;rm -rf /", "a/b", "naughty$()", "x|y"}
|
||||
for _, u := range invalid {
|
||||
if err := validateUnit(u); err == nil {
|
||||
t.Errorf("validateUnit(%q) = nil, want error", u)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
value string
|
||||
valid bool
|
||||
}{
|
||||
{name: "sshd.service", value: "sshd.service", valid: true},
|
||||
{name: "template", value: "getty@tty1.service", valid: true},
|
||||
{name: "dots and colons", value: "foo.bar:baz-1.service", valid: true},
|
||||
{name: "timer", value: "a_b.timer", valid: true},
|
||||
{name: "empty", value: "", valid: false},
|
||||
{name: "flag injection", value: "-rf", valid: false},
|
||||
{name: "double dash", value: "--now", valid: false},
|
||||
{name: "space", value: "a b", valid: false},
|
||||
{name: "shell metachar", value: "foo;rm -rf /", valid: false},
|
||||
{name: "path sep", value: "a/b", valid: false},
|
||||
{name: "subshell", value: "naughty$()", valid: false},
|
||||
{name: "pipe", value: "x|y", valid: false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateUnit(tt.value)
|
||||
if tt.valid && err != nil {
|
||||
t.Errorf("validateUnit(%q) = %v, want nil", tt.value, err)
|
||||
}
|
||||
if !tt.valid && err == nil {
|
||||
t.Errorf("validateUnit(%q) = nil, want error", tt.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,16 +38,23 @@ func TestValidateUnit(t *testing.T) {
|
||||
// else (including substrings) must not, or unrelated services would also get
|
||||
// detached and bypass the synchronous error path.
|
||||
func TestIsSelf(t *testing.T) {
|
||||
yes := []string{"nadir", "nadir.service"}
|
||||
for _, u := range yes {
|
||||
if !isSelf(u) {
|
||||
t.Errorf("isSelf(%q) = false, want true", u)
|
||||
}
|
||||
}
|
||||
no := []string{"", "sshd.service", "nadir-something.service", "nadir.timer", "not-nadir.service"}
|
||||
for _, u := range no {
|
||||
if isSelf(u) {
|
||||
t.Errorf("isSelf(%q) = true, want false", u)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
value string
|
||||
want bool
|
||||
}{
|
||||
{name: "bare name", value: "nadir", want: true},
|
||||
{name: "with service suffix", value: "nadir.service", want: true},
|
||||
{name: "empty", value: "", want: false},
|
||||
{name: "other service", value: "sshd.service", want: false},
|
||||
{name: "prefix substring", value: "nadir-something.service", want: false},
|
||||
{name: "wrong suffix", value: "nadir.timer", want: false},
|
||||
{name: "suffix mismatch", value: "not-nadir.service", want: false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := isSelf(tt.value); got != tt.want {
|
||||
t.Errorf("isSelf(%q) = %v, want %v", tt.value, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"nadir/internal/mounts"
|
||||
"nadir/internal/oscmd"
|
||||
@@ -16,6 +17,10 @@ import (
|
||||
// fstabFile is a var so tests can point it at a fixture.
|
||||
var fstabFile = "/etc/fstab"
|
||||
|
||||
// fstabMu serialises writes to /etc/fstab so concurrent HTTP requests don't
|
||||
// clobber each other's read-modify-write.
|
||||
var fstabMu sync.Mutex
|
||||
|
||||
// FstabEntry is one /etc/fstab line. Dump and Pass are the last two numeric
|
||||
// fields (fs_freq and fs_passno).
|
||||
type FstabEntry struct {
|
||||
@@ -67,7 +72,7 @@ func registerStorage(api huma.API) {
|
||||
}, func(ctx context.Context, _ *struct{}) (*ListMountsOutput, error) {
|
||||
entries, err := mounts.Proc()
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read mounts failed", err)
|
||||
return nil, huma.Error500InternalServerError("mount table lookup failed", err)
|
||||
}
|
||||
res := &ListMountsOutput{}
|
||||
res.Body.Mounts = entries
|
||||
@@ -86,7 +91,7 @@ func registerStorage(api huma.API) {
|
||||
}, func(ctx context.Context, _ *struct{}) (*ListFstabOutput, error) {
|
||||
data, err := os.ReadFile(fstabFile)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read fstab failed", err)
|
||||
return nil, huma.Error500InternalServerError("fstab lookup failed", err)
|
||||
}
|
||||
res := &ListFstabOutput{}
|
||||
res.Body.Entries = parseFstab(string(data))
|
||||
@@ -121,7 +126,7 @@ func registerStorage(api huma.API) {
|
||||
|
||||
existing, err := readFstab()
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read fstab failed", err)
|
||||
return nil, huma.Error500InternalServerError("fstab lookup failed", err)
|
||||
}
|
||||
if findEntry(existing, e.Mountpoint) != nil {
|
||||
return nil, huma.Error409Conflict("an fstab entry already exists for " + e.Mountpoint)
|
||||
@@ -158,13 +163,13 @@ func registerStorage(api huma.API) {
|
||||
|
||||
entries, err := readFstab()
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read fstab failed", err)
|
||||
return nil, huma.Error500InternalServerError("fstab lookup failed", err)
|
||||
}
|
||||
inFstab := findEntry(entries, in.Mountpoint) != nil
|
||||
|
||||
mounted, err := isMounted(in.Mountpoint)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read mounts failed", err)
|
||||
return nil, huma.Error500InternalServerError("mount table lookup failed", err)
|
||||
}
|
||||
if !inFstab && !mounted {
|
||||
return nil, huma.Error404NotFound("no mount or fstab entry for " + in.Mountpoint)
|
||||
@@ -231,8 +236,25 @@ func renderFstabLine(e FstabEntry) string {
|
||||
return fmt.Sprintf("%s\t%s\t%s\t%s\t%d\t%d", e.Device, e.Mountpoint, e.FSType, e.Options, e.Dump, e.Pass)
|
||||
}
|
||||
|
||||
// writeFstabAtomically writes content to /etc/fstab using a temporary file and
|
||||
// rename, so a crash mid-write leaves the original file intact.
|
||||
func writeFstabAtomically(content string) error {
|
||||
tmp := fstabFile + ".nadir.tmp"
|
||||
if err := os.WriteFile(tmp, []byte(content), 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, fstabFile); err != nil {
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// appendFstabLine adds one entry, leaving every existing line untouched.
|
||||
func appendFstabLine(e FstabEntry) error {
|
||||
fstabMu.Lock()
|
||||
defer fstabMu.Unlock()
|
||||
|
||||
data, err := os.ReadFile(fstabFile)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -242,12 +264,15 @@ func appendFstabLine(e FstabEntry) error {
|
||||
content += "\n"
|
||||
}
|
||||
content += renderFstabLine(e) + "\n"
|
||||
return os.WriteFile(fstabFile, []byte(content), 0644)
|
||||
return writeFstabAtomically(content)
|
||||
}
|
||||
|
||||
// removeFstabLines drops every line mapping mountpoint, preserving comments and
|
||||
// other entries. Reports whether anything was removed.
|
||||
func removeFstabLines(mountpoint string) (bool, error) {
|
||||
fstabMu.Lock()
|
||||
defer fstabMu.Unlock()
|
||||
|
||||
data, err := os.ReadFile(fstabFile)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -268,7 +293,7 @@ func removeFstabLines(mountpoint string) (bool, error) {
|
||||
if !removed {
|
||||
return false, nil
|
||||
}
|
||||
return true, os.WriteFile(fstabFile, []byte(strings.Join(kept, "\n")), 0644)
|
||||
return true, writeFstabAtomically(strings.Join(kept, "\n"))
|
||||
}
|
||||
|
||||
func findEntry(entries []FstabEntry, mountpoint string) *FstabEntry {
|
||||
|
||||
@@ -79,23 +79,27 @@ func mustReadFstab(t *testing.T) []FstabEntry {
|
||||
}
|
||||
|
||||
func TestValidateEntry(t *testing.T) {
|
||||
ok := FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/data", FSType: "ext4", Options: "defaults"}
|
||||
if err := validateEntry(ok); err != nil {
|
||||
t.Errorf("valid entry rejected: %v", err)
|
||||
}
|
||||
if err := validateEntry(FstabEntry{Device: "UUID=ab-cd", Mountpoint: "/mnt/x", FSType: "xfs", Options: "rw,noatime"}); err != nil {
|
||||
t.Errorf("UUID entry rejected: %v", err)
|
||||
}
|
||||
bad := []FstabEntry{
|
||||
{Device: "/dev/sdb1; rm -rf /", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults"}, // shell metachars
|
||||
{Device: "/dev/sdb1", Mountpoint: "../etc", FSType: "ext4", Options: "defaults"}, // not absolute
|
||||
{Device: "/dev/sdb1", Mountpoint: "/mnt/../../etc", FSType: "ext4", Options: "defaults"}, // traversal
|
||||
{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4!", Options: "defaults"}, // bad fstype
|
||||
{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults; reboot"}, // bad options
|
||||
}
|
||||
for i, e := range bad {
|
||||
if err := validateEntry(e); err == nil {
|
||||
t.Errorf("bad entry %d accepted: %+v", i, e)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
entry FstabEntry
|
||||
valid bool
|
||||
}{
|
||||
{name: "valid", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/data", FSType: "ext4", Options: "defaults"}, valid: true},
|
||||
{name: "UUID", entry: FstabEntry{Device: "UUID=ab-cd", Mountpoint: "/mnt/x", FSType: "xfs", Options: "rw,noatime"}, valid: true},
|
||||
{name: "shell metachar in device", entry: FstabEntry{Device: "/dev/sdb1; rm -rf /", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults"}, valid: false},
|
||||
{name: "relative mountpoint", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "../etc", FSType: "ext4", Options: "defaults"}, valid: false},
|
||||
{name: "traversal in mountpoint", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/../../etc", FSType: "ext4", Options: "defaults"}, valid: false},
|
||||
{name: "bad fstype", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4!", Options: "defaults"}, valid: false},
|
||||
{name: "bad options", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults; reboot"}, valid: false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateEntry(tt.entry)
|
||||
if tt.valid && err != nil {
|
||||
t.Errorf("valid entry rejected: %v", err)
|
||||
}
|
||||
if !tt.valid && err == nil {
|
||||
t.Errorf("bad entry accepted: %+v", tt.entry)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,16 +3,34 @@ package system
|
||||
import "testing"
|
||||
|
||||
func TestWhenRe(t *testing.T) {
|
||||
valid := []string{"now", "+0", "+5", "+120", "0:00", "9:30", "23:59", "07:05"}
|
||||
for _, w := range valid {
|
||||
if !whenRe.MatchString(w) {
|
||||
t.Errorf("whenRe.MatchString(%q) = false, want true", w)
|
||||
}
|
||||
}
|
||||
invalid := []string{"", "-r", "-h", "--help", "24:00", "9:60", "+5; reboot", "now ", "5", "1:2"}
|
||||
for _, w := range invalid {
|
||||
if whenRe.MatchString(w) {
|
||||
t.Errorf("whenRe.MatchString(%q) = true, want false", w)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
value string
|
||||
want bool
|
||||
}{
|
||||
{name: "now", value: "now", want: true},
|
||||
{name: "plus zero", value: "+0", want: true},
|
||||
{name: "plus five", value: "+5", want: true},
|
||||
{name: "plus 120", value: "+120", want: true},
|
||||
{name: "0:00", value: "0:00", want: true},
|
||||
{name: "9:30", value: "9:30", want: true},
|
||||
{name: "23:59", value: "23:59", want: true},
|
||||
{name: "07:05", value: "07:05", want: true},
|
||||
{name: "empty", value: "", want: false},
|
||||
{name: "flag r", value: "-r", want: false},
|
||||
{name: "flag h", value: "-h", want: false},
|
||||
{name: "help", value: "--help", want: false},
|
||||
{name: "24:00", value: "24:00", want: false},
|
||||
{name: "9:60", value: "9:60", want: false},
|
||||
{name: "injected command", value: "+5; reboot", want: false},
|
||||
{name: "trailing space", value: "now ", want: false},
|
||||
{name: "just digit", value: "5", want: false},
|
||||
{name: "single colon", value: "1:2", want: false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := whenRe.MatchString(tt.value); got != tt.want {
|
||||
t.Errorf("whenRe.MatchString(%q) = %v, want %v", tt.value, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
package terminal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"nadir/internal/auth"
|
||||
"nadir/internal/module"
|
||||
"nadir/internal/rbac"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/creack/pty"
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/danielgtaylor/huma/v2/adapters/humago"
|
||||
)
|
||||
|
||||
// tagTerminal is the OpenAPI tag for this module (registered in server.go),
|
||||
// keeping tags 1:1 with modules per the project convention.
|
||||
const tagTerminal = "Terminal"
|
||||
|
||||
const (
|
||||
// maxTerminals caps concurrent shells so a buggy frontend or careless admin
|
||||
// can't pile up PTYs (guideline: limit everything). Raise if it's ever a real
|
||||
// limit in practice.
|
||||
maxTerminals = 10
|
||||
// idleTimeout closes a session after this long with no I/O in either
|
||||
// direction, reclaiming abandoned shells.
|
||||
idleTimeout = 15 * time.Minute
|
||||
)
|
||||
|
||||
// terminalSem is the concurrency limiter; a slot is held for the life of a session.
|
||||
var terminalSem = make(chan struct{}, maxTerminals)
|
||||
|
||||
type terminalModule struct {
|
||||
sessions *auth.SessionStore
|
||||
}
|
||||
|
||||
// New creates a new Terminal module that allows interactive shell access.
|
||||
func New(sessions *auth.SessionStore) module.Module {
|
||||
return &terminalModule{sessions: sessions}
|
||||
}
|
||||
|
||||
func (m *terminalModule) ID() string { return "terminal" }
|
||||
|
||||
func (m *terminalModule) Permissions() []rbac.Permission {
|
||||
return []rbac.Permission{rbac.Root}
|
||||
}
|
||||
|
||||
type TerminalInput struct {
|
||||
Ctx huma.Context `json:"-"`
|
||||
}
|
||||
|
||||
// Resolve extracts the huma.Context into the input struct.
|
||||
func (i *TerminalInput) Resolve(ctx huma.Context) []error {
|
||||
i.Ctx = ctx
|
||||
return nil
|
||||
}
|
||||
|
||||
type resizeMessage struct {
|
||||
Cols uint16 `json:"cols"`
|
||||
Rows uint16 `json:"rows"`
|
||||
}
|
||||
|
||||
func (m *terminalModule) Register(api huma.API) {
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "terminal-connect",
|
||||
Method: "GET",
|
||||
Path: "/api/terminal",
|
||||
Summary: "Connect to an interactive terminal",
|
||||
Description: "Upgrades the connection to a WebSocket and spawns a PTY shell as the logged-in user. Send JSON `{cols, rows}` text messages to resize, and raw binary/text messages for stdin. This is a raw WebSocket endpoint — it cannot be exercised from the API docs \"Try it\" panel; use a WebSocket client.",
|
||||
Tags: []string{tagTerminal},
|
||||
Metadata: map[string]any{"module": m.ID(), "permission": string(rbac.Root)},
|
||||
Errors: []int{401, 403, 426, 500},
|
||||
}, func(ctx context.Context, in *TerminalInput) (*struct{}, error) {
|
||||
// The RBAC middleware already authenticated this request and enforced the
|
||||
// "root" permission before we got here. We re-read the session only to get
|
||||
// the username for `su`; the 401 below is the fallback for when the module
|
||||
// is mounted without the middleware (e.g. in unit tests).
|
||||
cookie, err := huma.ReadCookie(in.Ctx, "nadir_session_id")
|
||||
if err != nil || cookie == nil {
|
||||
return nil, huma.Error401Unauthorized("unauthorized")
|
||||
}
|
||||
|
||||
sess, ok := m.sessions.GetByToken(cookie.Value)
|
||||
if !ok {
|
||||
return nil, huma.Error401Unauthorized("unauthorized")
|
||||
}
|
||||
|
||||
req, res := humago.Unwrap(in.Ctx)
|
||||
if req == nil || res == nil {
|
||||
return nil, huma.Error500InternalServerError("missing http context")
|
||||
}
|
||||
|
||||
// Reject plain GETs (e.g. the docs "Try it" button) with a clear 426 rather
|
||||
// than letting websocket.Accept emit a raw protocol-violation error.
|
||||
if !strings.EqualFold(req.Header.Get("Upgrade"), "websocket") {
|
||||
return nil, huma.NewError(http.StatusUpgradeRequired,
|
||||
"this endpoint requires a WebSocket connection; connect with a WebSocket client")
|
||||
}
|
||||
|
||||
// InsecureSkipVerify is deliberately NOT set: coder/websocket then enforces
|
||||
// that the Origin host matches the request Host, rejecting cross-site upgrade
|
||||
// attempts. Defense-in-depth on top of the SameSite=Strict session cookie —
|
||||
// important because this endpoint hands out an interactive shell.
|
||||
conn, err := websocket.Accept(res, req, nil)
|
||||
if err != nil {
|
||||
// websocket.Accept already wrote the error response (e.g. 403 on an
|
||||
// Origin mismatch). Just stop; writing again would corrupt the response.
|
||||
return nil, nil
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
|
||||
// Bound concurrent shells: take a slot or reject (don't pile up PTYs).
|
||||
select {
|
||||
case terminalSem <- struct{}{}:
|
||||
defer func() { <-terminalSem }()
|
||||
default:
|
||||
conn.Close(websocket.StatusTryAgainLater, "too many terminal sessions")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Launch the user's login shell via su.
|
||||
// "su - <username>" ensures we get their actual environment and shell.
|
||||
cmd := exec.CommandContext(req.Context(), "su", "-", "--", sess.Username)
|
||||
|
||||
// Start the command with a PTY.
|
||||
ptmx, err := pty.Start(cmd)
|
||||
if err != nil {
|
||||
conn.Close(websocket.StatusInternalError, "failed to start pty")
|
||||
return nil, nil
|
||||
}
|
||||
defer ptmx.Close()
|
||||
|
||||
// lastActive is bumped by both pumps; the watchdog uses it to close idle
|
||||
// sessions. Output activity (e.g. `top`) counts, so it isn't killed.
|
||||
var lastActive atomic.Int64
|
||||
lastActive.Store(time.Now().UnixNano())
|
||||
go func() {
|
||||
tick := time.NewTicker(idleTimeout / 4)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-req.Context().Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
if time.Since(time.Unix(0, lastActive.Load())) > idleTimeout {
|
||||
conn.Close(websocket.StatusGoingAway, "idle timeout")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Pump stdout/stderr from PTY to WebSocket.
|
||||
go func() {
|
||||
buf := make([]byte, 8192)
|
||||
for {
|
||||
n, err := ptmx.Read(buf)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
lastActive.Store(time.Now().UnixNano())
|
||||
// We write PTY output as binary messages. The frontend (e.g., xterm.js)
|
||||
// can handle UTF-8 binary or text transparently.
|
||||
err = conn.Write(req.Context(), websocket.MessageBinary, buf[:n])
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
conn.Close(websocket.StatusNormalClosure, "")
|
||||
}()
|
||||
|
||||
// Pump stdin and resize commands from WebSocket to PTY.
|
||||
for {
|
||||
typ, b, err := conn.Read(req.Context())
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
lastActive.Store(time.Now().UnixNano())
|
||||
|
||||
if typ == websocket.MessageText {
|
||||
var resize resizeMessage
|
||||
if err := json.Unmarshal(b, &resize); err == nil && resize.Cols > 0 && resize.Rows > 0 {
|
||||
// Handle resize
|
||||
_ = pty.Setsize(ptmx, &pty.Winsize{
|
||||
Cols: resize.Cols,
|
||||
Rows: resize.Rows,
|
||||
})
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// If not a valid resize message, or if it's MessageBinary, pass to PTY stdin.
|
||||
_, _ = ptmx.Write(b)
|
||||
}
|
||||
|
||||
// The read loop has ended (client gone or PTY closed). Tear down the shell
|
||||
// and reap it: closing the PTY sends EOF, Kill covers shells that ignore it.
|
||||
_ = ptmx.Close()
|
||||
_ = cmd.Process.Kill()
|
||||
_ = cmd.Wait()
|
||||
return nil, nil
|
||||
})
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
package terminal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"nadir/internal/auth"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/danielgtaylor/huma/v2/adapters/humago"
|
||||
)
|
||||
|
||||
func TestTerminalConnectUnauthorized(t *testing.T) {
|
||||
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
|
||||
if err != nil {
|
||||
t.Fatalf("session db: %v", err)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
|
||||
mod := New(sessions)
|
||||
mod.Register(api)
|
||||
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) + "/api/terminal"
|
||||
|
||||
// Try without cookie
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, resp, err := websocket.Dial(ctx, wsURL, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got success")
|
||||
}
|
||||
if resp != nil && resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalConnectPlainGET(t *testing.T) {
|
||||
// An authenticated but non-WebSocket GET (e.g. the docs "Try it" button) must
|
||||
// get a clean 426 Upgrade Required, not a raw websocket protocol error.
|
||||
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
|
||||
if err != nil {
|
||||
t.Fatalf("session db: %v", err)
|
||||
}
|
||||
token, err := sessions.Create("root")
|
||||
if err != nil {
|
||||
t.Fatalf("create session: %v", err)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
|
||||
New(sessions).Register(api)
|
||||
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
req, _ := http.NewRequest(http.MethodGet, srv.URL+"/api/terminal", nil)
|
||||
req.Header.Set("Cookie", "nadir_session_id="+token)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("GET failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUpgradeRequired {
|
||||
t.Errorf("expected 426, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalConnectAuthorized(t *testing.T) {
|
||||
// Root or specific system configs might cause PTY or su to fail if run in constrained environments.
|
||||
// But we expect the websocket upgrade to succeed and then maybe close with an error if PTY fails.
|
||||
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
|
||||
if err != nil {
|
||||
t.Fatalf("session db: %v", err)
|
||||
}
|
||||
|
||||
token, err := sessions.Create("root")
|
||||
if err != nil {
|
||||
t.Fatalf("create session: %v", err)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
|
||||
mod := New(sessions)
|
||||
mod.Register(api)
|
||||
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) + "/api/terminal"
|
||||
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
opts := &websocket.DialOptions{
|
||||
HTTPHeader: http.Header{},
|
||||
}
|
||||
opts.HTTPHeader.Set("Cookie", "nadir_session_id="+token)
|
||||
|
||||
conn, resp, err := websocket.Dial(ctx, wsURL, opts)
|
||||
if err != nil {
|
||||
// Depending on the test environment, "su" or "pty" might fail, but
|
||||
// the websocket upgrade itself should succeed before it drops.
|
||||
// If it fails to upgrade, that's a real error.
|
||||
t.Fatalf("dial failed: %v (status %d)", err, resp.StatusCode)
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
|
||||
// The connection was upgraded successfully.
|
||||
// If PTY allocation failed or su failed, the server might close the connection immediately.
|
||||
// We just verify the upgrade succeeded.
|
||||
if resp.StatusCode != http.StatusSwitchingProtocols {
|
||||
t.Errorf("expected 101, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,17 @@ import (
|
||||
|
||||
const ModuleID = "users"
|
||||
|
||||
type Module struct{}
|
||||
// sessionStore is the subset of SessionStore that password changes need:
|
||||
// invalidate all existing sessions for a user whose password just changed.
|
||||
type sessionStore interface {
|
||||
DeleteByUsername(username string) error
|
||||
}
|
||||
|
||||
func New() *Module { return &Module{} }
|
||||
type Module struct {
|
||||
sessions sessionStore
|
||||
}
|
||||
|
||||
func New(sessions sessionStore) *Module { return &Module{sessions: sessions} }
|
||||
|
||||
func (m *Module) ID() string { return ModuleID }
|
||||
|
||||
@@ -21,7 +29,7 @@ func (m *Module) Permissions() []rbac.Permission {
|
||||
}
|
||||
|
||||
func (m *Module) Register(api huma.API) {
|
||||
registerUsers(api)
|
||||
registerUsers(api, m.sessions)
|
||||
}
|
||||
|
||||
func op(permission string) map[string]any {
|
||||
|
||||
@@ -2,6 +2,7 @@ package users
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
@@ -91,7 +92,7 @@ type UserGroupsOutput struct {
|
||||
}
|
||||
}
|
||||
|
||||
func registerUsers(api huma.API) {
|
||||
func registerUsers(api huma.API, sessions sessionStore) {
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "users-list",
|
||||
Method: "GET",
|
||||
@@ -105,7 +106,7 @@ func registerUsers(api huma.API) {
|
||||
}, func(ctx context.Context, _ *struct{}) (*ListUsersOutput, error) {
|
||||
list, err := listUsers()
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||
}
|
||||
out := &ListUsersOutput{}
|
||||
out.Body.Users = list
|
||||
@@ -127,7 +128,7 @@ func registerUsers(api huma.API) {
|
||||
}
|
||||
u, ok, err := lookupUser(in.Username)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||
}
|
||||
if !ok {
|
||||
return nil, huma.Error404NotFound("user not found: " + in.Username)
|
||||
@@ -163,7 +164,7 @@ func registerUsers(api huma.API) {
|
||||
return nil, huma.Error400BadRequest("home must be an absolute path")
|
||||
}
|
||||
if _, ok, err := lookupUser(in.Body.Username); err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||
} else if ok {
|
||||
return nil, huma.Error409Conflict("user already exists: " + in.Body.Username)
|
||||
}
|
||||
@@ -212,7 +213,7 @@ func registerUsers(api huma.API) {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok, err := lookupUser(in.Username); err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||
} else if !ok {
|
||||
return nil, huma.Error404NotFound("user not found: " + in.Username)
|
||||
}
|
||||
@@ -253,7 +254,7 @@ func registerUsers(api huma.API) {
|
||||
return nil, huma.Error400BadRequest("password may not contain newlines")
|
||||
}
|
||||
if _, ok, err := lookupUser(in.Username); err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||
} else if !ok {
|
||||
return nil, huma.Error404NotFound("user not found: " + in.Username)
|
||||
}
|
||||
@@ -261,6 +262,11 @@ func registerUsers(api huma.API) {
|
||||
if _, err := oscmd.RunStdin(in.Username+":"+in.Body.Password+"\n", "chpasswd"); err != nil {
|
||||
return nil, huma.Error500InternalServerError("chpasswd failed", err)
|
||||
}
|
||||
if sessions != nil {
|
||||
if err := sessions.DeleteByUsername(in.Username); err != nil {
|
||||
log.Printf("failed to invalidate sessions for %s: %v", in.Username, err)
|
||||
}
|
||||
}
|
||||
return oscmd.OK(), nil
|
||||
})
|
||||
|
||||
@@ -290,7 +296,7 @@ func registerUsers(api huma.API) {
|
||||
}
|
||||
}
|
||||
if _, ok, err := lookupUser(in.Username); err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||
} else if !ok {
|
||||
return nil, huma.Error404NotFound("user not found: " + in.Username)
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestUsersHandlers(t *testing.T) {
|
||||
|
||||
mux := http.NewServeMux()
|
||||
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
|
||||
registerUsers(api)
|
||||
registerUsers(api, nil)
|
||||
|
||||
// 1. Test GET /api/users
|
||||
resp := api.Get("/api/users")
|
||||
|
||||
@@ -28,26 +28,34 @@ short:x:2:2
|
||||
}
|
||||
|
||||
func TestValidateUsername(t *testing.T) {
|
||||
valid := []string{"alice", "_svc", "user-1", "a", "machine$", "abc_def"}
|
||||
for _, n := range valid {
|
||||
if err := validateUsername(n); err != nil {
|
||||
t.Errorf("validateUsername(%q) = %v, want nil", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
invalid := []string{
|
||||
"", // empty
|
||||
"-rf", // leading dash (flag injection)
|
||||
"Alice", // uppercase
|
||||
"1user", // leading digit
|
||||
"a b", // space
|
||||
"foo;rm", // shell metachar
|
||||
"root:x", // colon (passwd separator)
|
||||
"waytoolongusernamethatexceedsthirtytwochars", // >32
|
||||
}
|
||||
for _, n := range invalid {
|
||||
if err := validateUsername(n); err == nil {
|
||||
t.Errorf("validateUsername(%q) = nil, want error", n)
|
||||
}
|
||||
for _, n := range []struct {
|
||||
name string
|
||||
value string
|
||||
valid bool
|
||||
}{
|
||||
{name: "alice", value: "alice", valid: true},
|
||||
{name: "underscore prefix", value: "_svc", valid: true},
|
||||
{name: "hyphen", value: "user-1", valid: true},
|
||||
{name: "single char", value: "a", valid: true},
|
||||
{name: "dollar suffix", value: "machine$", valid: true},
|
||||
{name: "underscore", value: "abc_def", valid: true},
|
||||
{name: "empty", value: "", valid: false},
|
||||
{name: "leading dash", value: "-rf", valid: false},
|
||||
{name: "uppercase", value: "Alice", valid: false},
|
||||
{name: "leading digit", value: "1user", valid: false},
|
||||
{name: "space", value: "a b", valid: false},
|
||||
{name: "shell metachar", value: "foo;rm", valid: false},
|
||||
{name: "colon", value: "root:x", valid: false},
|
||||
{name: "too long", value: "waytoolongusernamethatexceedsthirtytwochars", valid: false},
|
||||
} {
|
||||
t.Run(n.name, func(t *testing.T) {
|
||||
err := validateUsername(n.value)
|
||||
if n.valid && err != nil {
|
||||
t.Errorf("validateUsername(%q) = %v, want nil", n.value, err)
|
||||
}
|
||||
if !n.valid && err == nil {
|
||||
t.Errorf("validateUsername(%q) = nil, want error", n.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,16 +25,22 @@ func TestParseProc(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestUnescape(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
`/mnt/my\040disk`: "/mnt/my disk",
|
||||
`/no/escapes`: "/no/escapes",
|
||||
`tab\011here`: "tab\there",
|
||||
`back\134slash`: `back\slash`,
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{name: "octal space", in: `/mnt/my\040disk`, want: "/mnt/my disk"},
|
||||
{name: "no escapes", in: `/no/escapes`, want: "/no/escapes"},
|
||||
{name: "tab", in: `tab\011here`, want: "tab\there"},
|
||||
{name: "backslash", in: `back\134slash`, want: `back\slash`},
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := Unescape(in); got != want {
|
||||
t.Errorf("Unescape(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := Unescape(tt.in); got != tt.want {
|
||||
t.Errorf("Unescape(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ import (
|
||||
"nadir/internal/modules/services"
|
||||
"nadir/internal/modules/storage"
|
||||
"nadir/internal/modules/system"
|
||||
"nadir/internal/modules/terminal"
|
||||
"nadir/internal/modules/users"
|
||||
"nadir/internal/rbac"
|
||||
|
||||
@@ -44,13 +43,12 @@ func TestOpenAPISchemaNoCollisions(t *testing.T) {
|
||||
mods := []module.Module{
|
||||
system.New(),
|
||||
services.New(nil),
|
||||
users.New(),
|
||||
users.New(nil),
|
||||
groups.New(),
|
||||
packages.New(),
|
||||
networking.New(),
|
||||
storage.New(),
|
||||
audit.New(auditStore),
|
||||
terminal.New(sessions),
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
@@ -41,8 +41,6 @@ func TestRbacMiddleware(t *testing.T) {
|
||||
},
|
||||
})
|
||||
r.AssignRole("alice", "test-role")
|
||||
// A machine credential is just another RBAC subject: the token name is
|
||||
// assigned a role exactly like a username.
|
||||
r.AssignRole("dash", "test-role")
|
||||
|
||||
mux := http.NewServeMux()
|
||||
@@ -76,81 +74,91 @@ func TestRbacMiddleware(t *testing.T) {
|
||||
return &struct{ Body string }{Body: "gated-write"}, nil
|
||||
})
|
||||
|
||||
// 1. Test public route
|
||||
resp := api.Get("/public")
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("public GET: got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
t.Run("public route", func(t *testing.T) {
|
||||
resp := api.Get("/public")
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
})
|
||||
|
||||
// 2. Test gated route without cookie -> 401 Unauthorized
|
||||
resp = api.Get("/gated-read")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("gated GET no cookie: got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
t.Run("no auth returns 401", func(t *testing.T) {
|
||||
resp := api.Get("/gated-read")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
})
|
||||
|
||||
// 3. Test gated route with invalid cookie -> 401 Unauthorized
|
||||
resp = api.Get("/gated-read", "Cookie: nadir_session_id=invalid")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("gated GET invalid cookie: got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
t.Run("invalid cookie returns 401", func(t *testing.T) {
|
||||
resp := api.Get("/gated-read", "Cookie: nadir_session_id=invalid")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
})
|
||||
|
||||
// Create valid session
|
||||
token, err := sessions.Create("alice")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var aliceToken string
|
||||
t.Run("valid session returns 200", func(t *testing.T) {
|
||||
var err error
|
||||
aliceToken, err = sessions.Create("alice")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp := api.Get("/gated-read", "Cookie: nadir_session_id="+aliceToken)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
})
|
||||
|
||||
// 4. Test gated route with valid cookie -> 200 OK
|
||||
resp = api.Get("/gated-read", "Cookie: nadir_session_id="+token)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("gated GET valid cookie: got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
t.Run("csrf mismatched origin returns 403", func(t *testing.T) {
|
||||
resp := api.Post("/gated-write", "Cookie: nadir_session_id="+aliceToken, "Origin: http://evil.com", "Host: example.com", struct{}{})
|
||||
if resp.Code != http.StatusForbidden {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||
}
|
||||
})
|
||||
|
||||
// 5. Test CSRF violation: POST with mismatched Origin header -> 403 Forbidden
|
||||
resp = api.Post("/gated-write", "Cookie: nadir_session_id="+token, "Origin: http://evil.com", "Host: example.com", struct{}{})
|
||||
if resp.Code != http.StatusForbidden {
|
||||
t.Errorf("CSRF mismatched Origin: got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||
}
|
||||
t.Run("csrf matching origin returns 200", func(t *testing.T) {
|
||||
resp := api.Post("/gated-write", "Cookie: nadir_session_id="+aliceToken, "Origin: http://example.com", "Host: example.com", struct{}{})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
})
|
||||
|
||||
// 6. Test CSRF success: POST with matching Origin header -> 200 OK
|
||||
resp = api.Post("/gated-write", "Cookie: nadir_session_id="+token, "Origin: http://example.com", "Host: example.com", struct{}{})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("CSRF matching Origin: got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
t.Run("unauthorized user returns 403", func(t *testing.T) {
|
||||
bobToken, err := sessions.Create("bob")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp := api.Get("/gated-read", "Cookie: nadir_session_id="+bobToken)
|
||||
if resp.Code != http.StatusForbidden {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||
}
|
||||
})
|
||||
|
||||
// 7. Test gated route with unauthorized user -> 403 Forbidden
|
||||
tokenBob, err := sessions.Create("bob")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp = api.Get("/gated-read", "Cookie: nadir_session_id="+tokenBob)
|
||||
if resp.Code != http.StatusForbidden {
|
||||
t.Errorf("bob unauthorized GET: got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||
}
|
||||
t.Run("valid bearer token returns 200", func(t *testing.T) {
|
||||
rawToken, err := tokenStore.Create("dash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp := api.Get("/gated-read", "Authorization: Bearer "+rawToken)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
})
|
||||
|
||||
// 8. Bearer token for an assigned name -> 200 OK
|
||||
rawToken, err := tokenStore.Create("dash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp = api.Get("/gated-read", "Authorization: Bearer "+rawToken)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("valid bearer GET: got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
t.Run("bogus bearer token returns 401", func(t *testing.T) {
|
||||
resp := api.Get("/gated-read", "Authorization: Bearer nad_deadbeef")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
})
|
||||
|
||||
// 9. Bogus bearer token -> 401 Unauthorized
|
||||
resp = api.Get("/gated-read", "Authorization: Bearer nad_deadbeef")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("bogus bearer GET: got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
// 10. Bearer token with no role assignment -> 403 Forbidden
|
||||
rawUnassigned, err := tokenStore.Create("orphan")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp = api.Get("/gated-read", "Authorization: Bearer "+rawUnassigned)
|
||||
if resp.Code != http.StatusForbidden {
|
||||
t.Errorf("unassigned bearer GET: got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||
}
|
||||
t.Run("unassigned bearer token returns 403", func(t *testing.T) {
|
||||
rawUnassigned, err := tokenStore.Create("orphan")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp := api.Get("/gated-read", "Authorization: Bearer "+rawUnassigned)
|
||||
if resp.Code != http.StatusForbidden {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user