12 Commits

Author SHA1 Message Date
urania 54108c263f fix: remove terminal module and implement concurrent log stream limiting
build-and-release / release (push) Successful in 2m39s
2026-06-24 17:29:45 +02:00
urania 37e5b97507 fix: crt
build-and-release / release (push) Successful in 2m38s
2026-06-23 19:47:19 +02:00
urania 63c9a272b5 feat: add configurable TLS/proxy installation options for the systemd service
build-and-release / release (push) Successful in 2m34s
2026-06-23 19:13:34 +02:00
urania 411f7fd6d9 feat: persistent TLS cert and token auto-generation during install 2026-06-23 19:05:26 +02:00
urania 8fc4b236ac fix: whomai with bearer
build-and-release / release (push) Successful in 2m39s
2026-06-23 18:02:52 +02:00
urania 37f03816e1 fix: networking/interfaces
build-and-release / release (push) Successful in 2m29s
2026-06-23 17:40:44 +02:00
urania 541260e65e fix: networking/interfaces
build-and-release / release (push) Has been cancelled
2026-06-23 17:40:17 +02:00
urania c4180bada1 fix: networking / services / and testing
build-and-release / release (push) Successful in 2m40s
2026-06-23 17:16:01 +02:00
urania 088880f584 fix: updates
build-and-release / release (push) Successful in 2m39s
2026-06-23 14:27:06 +02:00
urania 67d95475ee fix: added package update endpoint
build-and-release / release (push) Successful in 3m1s
2026-06-23 13:15:39 +02:00
urania aec04bfe02 fix: storages and mounts
build-and-release / release (push) Successful in 2m52s
2026-06-23 11:50:55 +02:00
urania a54c42271c minor: test
build-and-release / release (push) Successful in 1m9s
2026-06-23 01:23:19 +02:00
47 changed files with 1647 additions and 822 deletions
-2
View File
@@ -31,7 +31,6 @@ API and declares its own permission vocabulary.
and upgrade - streamed live over SSE. Auto-detects `dnf`, `apt`, or `pacman`.
- **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
+69 -16
View File
@@ -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"
@@ -63,6 +62,12 @@ func main() {
}
args = append(args, rest[0])
rest = rest[1:]
if len(args) > 0 {
// Once we have identified the subcommand, the remaining arguments
// belong to it (including its own flags), so we stop parsing global flags.
args = append(args, rest...)
break
}
}
if *showVersion {
@@ -81,7 +86,7 @@ func main() {
fmt.Printf("configuration file already exists at %s\n", configPath)
os.Exit(0)
}
fatalIf(saveDefaultConfig(configPath))
fatalIf(saveDefaultConfig(configPath, DefaultConfigContent(getUsername())))
os.Exit(0)
}
@@ -96,7 +101,7 @@ func main() {
runCmd(args)
case "install":
ensureRoot()
fatalIf(installService())
fatalIf(installService(args))
case "uninstall":
ensureRoot()
fatalIf(uninstallService(slices.Contains(args, "--complete")))
@@ -200,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()
@@ -230,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 {
@@ -238,7 +244,7 @@ func runServer() {
meta.Register(api, mods)
meta.RegisterHealth(api, sessions)
meta.RegisterWhoami(api, sessions, roles, mods)
meta.RegisterWhoami(api, sessions, tokenAuth, roles, mods)
meta.RegisterUpdate(api, configPath)
auth.RegisterLogin(api, sessions, auditStore, cfg.SecureCookie())
@@ -272,17 +278,17 @@ 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).
// 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")
"font-src 'self' data: https://cdn.jsdelivr.net https://fonts.scalar.com")
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`<!doctype html><html><head><title>API</title>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
@@ -297,7 +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
@@ -307,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)
}
@@ -325,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() {
@@ -354,6 +371,40 @@ func runServer() {
}
}
// bodySizeLimit rejects requests with a body larger than 1 MB, preventing
// OOM from arbitrarily large JSON payloads. Wraps the entire mux so it
// covers both Huma-registered routes and raw mux handlers (/docs, /install.sh).
func bodySizeLimit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
next.ServeHTTP(w, r)
})
}
// requestTimeout cancels slow requests via context deadline. SSE endpoints
// (package streams, log following) are exempt because they keep the
// connection open indefinitely.
func requestTimeout(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if isSSEEndpoint(r) {
next.ServeHTTP(w, r)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// isSSEEndpoint identifies routes that stream data indefinitely and must
// not have a context deadline.
func isSSEEndpoint(r *http.Request) bool {
if strings.HasPrefix(r.URL.Path, "/api/packages") {
return r.Method == "POST" || r.Method == "DELETE"
}
return r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/logs/stream")
}
// secHeaders sets defensive response headers on every HTTP response. The
// default Content-Security-Policy denies everything (`default-src 'none'`) —
// correct for the JSON API and the tiny landing/favicon endpoints. /docs
@@ -371,6 +422,8 @@ func secHeaders(next http.Handler) http.Handler {
h.Set("Referrer-Policy", "no-referrer")
h.Set("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)
})
}
+131 -15
View File
@@ -1,6 +1,7 @@
package main
import (
"flag"
"fmt"
"io"
"os"
@@ -13,26 +14,29 @@ import (
"nadir/internal/config"
)
const defaultConfigTemplate = `# Nadir configuration - config.yaml
const configTemplateBase = `# Nadir configuration - config.yaml
#
# Single source of truth for runtime settings.
#
server:
secure_tls: true
# trust_proxy: false
# tls_cert: /etc/nadir/tls/cert.pem
# tls_key: /etc/nadir/tls/key.pem
hostname: 127.0.0.1
port: 9999
secure_tls: %s
%s
%s
%s
hostname: %s
port: %d
release_repo: https://tea.urania.dev/urania/nadir-agent
roles:
admin:
"*": ["*"]
auditor:
"*": ["read"]
assignments:
%s: [admin]
dashboard: [auditor]
`
// resolveConfigPath returns the config file path: CONFIG_PATH env (with ~ expanded)
@@ -101,7 +105,38 @@ const (
// installService writes the systemd unit, enables it on boot, and starts it.
// The unit pins the absolute executable and config paths captured now, so the
// service doesn't depend on the working directory at boot.
func installService() error {
func installService(args []string) error {
// Parse options
fs := flag.NewFlagSet("install", flag.ContinueOnError)
tlsOpt := fs.Bool("tls", false, "Generate persistent self-signed TLS cert/key and enable HTTPS")
unsecureOpt := fs.Bool("unsecure", false, "Serve plaintext HTTP directly")
trustProxyOpt := fs.Bool("trust-proxy", false, "Serve plaintext HTTP behind a trusted TLS-terminating reverse proxy")
hostnameOpt := fs.String("hostname", "127.0.0.1", "Hostname to bind to")
portOpt := fs.Int("port", 9999, "Port to bind to")
if err := fs.Parse(args); err != nil {
return err
}
optCount := 0
if *tlsOpt {
optCount++
}
if *unsecureOpt {
optCount++
}
if *trustProxyOpt {
optCount++
}
if optCount > 1 {
return fmt.Errorf("options --tls, --unsecure, and --trust-proxy are mutually exclusive")
}
// Default to unsecure (plain HTTP) if nothing is specified
isTLS := *tlsOpt
isUnsecure := *unsecureOpt || optCount == 0
isTrustProxy := *trustProxyOpt
// Provision the PAM service the server authenticates against, so it exists
// before the unit starts rather than appearing on first login. Idempotent:
// EnsurePAMService leaves an existing /etc/pam.d/nadir untouched. runServer
@@ -130,14 +165,51 @@ func installService() error {
return fmt.Errorf("create data directory: %w", err)
}
// Generate and save persistent self-signed TLS certificates if TLS mode
certPath := filepath.Join("/var/lib/nadir/tls", "cert.pem")
if isTLS {
tlsDir := "/var/lib/nadir/tls"
if err := os.MkdirAll(tlsDir, 0700); err != nil {
return fmt.Errorf("create tls directory: %w", err)
}
keyPath := filepath.Join(tlsDir, "key.pem")
if _, err := os.Stat(certPath); os.IsNotExist(err) {
if err := generateAndSaveCert(certPath, keyPath, *hostnameOpt); err != nil {
return fmt.Errorf("generate certificates: %w", err)
}
fmt.Printf("generated persistent self-signed TLS certificate at %s\n", certPath)
}
}
cfgPath, err := resolveConfigPath()
if err != nil {
return err
}
// Construct configuration template content based on installation options
secureTLSVal := "true"
trustProxyLine := "# trust_proxy: false"
certLine := "tls_cert: /var/lib/nadir/tls/cert.pem"
keyLine := "tls_key: /var/lib/nadir/tls/key.pem"
if isUnsecure {
secureTLSVal = "false"
trustProxyLine = "# trust_proxy: false"
certLine = "# tls_cert: /var/lib/nadir/tls/cert.pem"
keyLine = "# tls_key: /var/lib/nadir/tls/key.pem"
} else if isTrustProxy {
secureTLSVal = "false"
trustProxyLine = "trust_proxy: true"
certLine = "# tls_cert: /var/lib/nadir/tls/cert.pem"
keyLine = "# tls_key: /var/lib/nadir/tls/key.pem"
}
username := getUsername()
configContent := fmt.Sprintf(configTemplateBase, secureTLSVal, trustProxyLine, certLine, keyLine, *hostnameOpt, *portOpt, username)
// Ensure default config file exists
if _, err := os.Stat(cfgPath); os.IsNotExist(err) {
if err := saveDefaultConfig(cfgPath); err != nil {
if err := saveDefaultConfig(cfgPath, configContent); err != nil {
return err
}
}
@@ -182,6 +254,44 @@ WantedBy=multi-user.target
fmt.Printf("created logrotate configuration %s\n", logrotatePath)
}
// Generate a token for the dashboard if it doesn't exist
var tokenStr string
store, err := auth.NewTokenStore(tokenDBPath)
if err == nil {
defer store.Close()
infos, err := store.List()
hasDashboard := false
if err == nil {
for _, t := range infos {
if t.Name == "dashboard" {
hasDashboard = true
break
}
}
}
if !hasDashboard {
tokenStr, _ = store.Create("dashboard")
} else {
tokenStr = "(already created; run 'nadir token add dashboard' to replace/generate a new one if lost)"
}
} else {
fmt.Printf("warning: failed to open token store: %v\n", err)
}
// Output credentials to copy to the frontend
fmt.Println("\n======================================================================")
fmt.Println(" NADIR CLIENT CREDENTIALS (COPY THESE TO NADIR WEBUI)")
fmt.Println("======================================================================")
fmt.Printf("Token for \"dashboard\" (Bearer):\n %s\n", tokenStr)
if isTLS {
certBytes, err := os.ReadFile(certPath)
if err == nil {
fmt.Println("\nCA Certificate (Trust Store):")
fmt.Println(string(certBytes))
}
}
fmt.Println("======================================================================")
fmt.Printf("installed and started %s; follow logs with: %s logs\n", serviceName, filepath.Base(exe))
return nil
}
@@ -393,21 +503,24 @@ func fatalIf(err error) {
}
}
// DefaultConfigContent returns the default configuration template filled with the username.
func DefaultConfigContent(username string) string {
return fmt.Sprintf(configTemplateBase, "false", "# trust_proxy: false", "# tls_cert: /var/lib/nadir/tls/cert.pem", "# tls_key: /var/lib/nadir/tls/key.pem", "127.0.0.1", 9999, username)
}
// saveDefaultConfig writes the default configuration template to cfgPath.
func saveDefaultConfig(cfgPath string) error {
func saveDefaultConfig(cfgPath, content string) error {
dir := filepath.Dir(cfgPath)
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("create config directory: %w", err)
}
chownToSudoUser(dir)
username := getUsername()
configContent := fmt.Sprintf(defaultConfigTemplate, username)
if err := os.WriteFile(cfgPath, []byte(configContent), 0600); err != nil {
if err := os.WriteFile(cfgPath, []byte(content), 0600); err != nil {
return fmt.Errorf("write default config: %w", err)
}
chownToSudoUser(cfgPath)
fmt.Printf("created default configuration file at %s (assigned admin role to user %q)\n", cfgPath, username)
fmt.Printf("created default configuration file at %s\n", cfgPath)
return nil
}
@@ -417,7 +530,10 @@ func usage(w io.Writer) {
Usage:
nadir [run] [-d] [-f <path>] Start the server (-d / --detach: run in background)
nadir --save-config [-f <path>] Save default configuration to path and exit
nadir install [-f <path>] Install + enable the systemd service (starts on boot)
nadir install [--tls|--unsecure|--trust-proxy] Install + enable the systemd service (starts on boot)
(--tls: enable HTTPS with self-signed certificate)
(--unsecure: serve HTTP directly, default)
(--trust-proxy: serve HTTP behind a reverse proxy)
nadir uninstall [--complete] Remove the service (keeps data/config; --complete wipes all)
nadir start|stop|restart|status Control the running service
nadir enable|disable Toggle start-on-boot without removing the unit
+53 -22
View File
@@ -4,44 +4,33 @@ import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"log"
"encoding/pem"
"math/big"
"net"
"os"
"time"
)
// serverCert returns the TLS certificate to serve: the admin-supplied PEM pair
// when both paths are set, otherwise a freshly generated in-memory self-signed
// cert for local development.
func serverCert(certPath, keyPath string) (tls.Certificate, error) {
if certPath != "" && keyPath != "" {
return tls.LoadX509KeyPair(certPath, keyPath)
}
log.Printf("tls: no tls_cert/tls_key configured - generating a self-signed certificate (dev only)")
return generateSelfSignedCert()
}
func generateSelfSignedCert() (tls.Certificate, error) {
// generateAndSaveCert generates a self-signed certificate and private key,
// and saves them as PEM files.
func generateAndSaveCert(certPath, keyPath string, hostname string) error {
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return tls.Certificate{}, err
return err
}
// Random serial: a fixed serial (1) makes every generated cert collide in a
// browser/OS trust store, so a previously-accepted cert can't be replaced.
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
return tls.Certificate{}, err
return err
}
template := x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{Organization: []string{"nadir-dev-local"}},
Subject: pkix.Name{Organization: []string{"nadir-agent-tls"}},
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 * time.Hour),
NotAfter: time.Now().Add(365 * 24 * time.Hour), // 1 year
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
@@ -49,9 +38,51 @@ func generateSelfSignedCert() (tls.Certificate, error) {
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback},
}
if hostname != "" && hostname != "localhost" && hostname != "127.0.0.1" && hostname != "::1" {
if ip := net.ParseIP(hostname); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, hostname)
}
}
// Automatically add the machine's external IP addresses to SANs so it can be verified
// correctly over the local network (e.g. Tailscale or Netbird).
if addrs, err := net.InterfaceAddrs(); err == nil {
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
template.IPAddresses = append(template.IPAddresses, ipnet.IP)
template.DNSNames = append(template.DNSNames, ipnet.IP.String())
}
}
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return tls.Certificate{}, err
return err
}
return tls.Certificate{Certificate: [][]byte{derBytes}, PrivateKey: priv}, nil
certOut, err := os.Create(certPath)
if err != nil {
return err
}
defer certOut.Close()
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return err
}
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer keyOut.Close()
privBytes, err := x509.MarshalECPrivateKey(priv)
if err != nil {
return err
}
if err := pem.Encode(keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: privBytes}); err != nil {
return err
}
return nil
}
+72
View File
@@ -0,0 +1,72 @@
package main
import (
"strings"
"testing"
)
// TestReleaseAPIURL pins the contract that downstream code (the updater and
// /install.sh) relies on: only https://host/owner/repo produces an API URL,
// everything else errors. Plain HTTP must be rejected — M7 makes auto-update
// only trust TLS-protected release feeds, since the binary it downloads is
// exec'd as root.
func TestReleaseAPIURL(t *testing.T) {
tests := []struct {
name string
in string
want string
wantErr string // substring expected in the error message; "" means success
}{
{
name: "valid https repo",
in: "https://tea.example.com/owner/repo",
want: "https://tea.example.com/api/v1/repos/owner/repo/releases/latest",
},
{
name: "http rejected",
in: "http://tea.example.com/owner/repo",
wantErr: "https",
},
{
name: "ssh scheme rejected",
in: "ssh://tea.example.com/owner/repo",
wantErr: "https",
},
{
name: "missing repo segment",
in: "https://tea.example.com/owner",
wantErr: "owner/repo",
},
{
name: "extra path segments",
in: "https://tea.example.com/owner/repo/extra",
wantErr: "owner/repo",
},
{
name: "empty",
in: "",
wantErr: "https",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := releaseAPIURL(tt.in)
if tt.wantErr == "" {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != tt.want {
t.Errorf("got %q, want %q", got, tt.want)
}
return
}
if err == nil {
t.Fatalf("expected error containing %q, got nil (result %q)", tt.wantErr, got)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("error %q does not contain %q", err.Error(), tt.wantErr)
}
})
}
}
-2
View File
@@ -7,8 +7,6 @@ require github.com/msteinert/pam v1.2.0
require github.com/danielgtaylor/huma/v2 v2.38.0
require (
github.com/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
)
-4
View File
@@ -1,9 +1,5 @@
aead.dev/minisign v0.3.0 h1:8Xafzy5PEVZqYDNP60yJHARlW1eOQtsKNp/Ph2c0vRA=
aead.dev/minisign v0.3.0/go.mod h1:NLvG3Uoq3skkRMDuc3YHpWUTMTrSExqm+Ij73W13F6Y=
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/danielgtaylor/huma/v2 v2.38.0 h1:fb0WZCatnaiHLphMQDDWDjygNxfMkX/ENma3QsRl7vY=
github.com/danielgtaylor/huma/v2 v2.38.0/go.mod h1:k9hwjlgWFt1t2jsmQGlsgXAG2FBTZa4kkjV581qAtfo=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+5 -4
View File
@@ -13,7 +13,7 @@ import (
// loginNameRe is the useradd default NAME_REGEX. Validating at this trust
// boundary keeps a flag-like name (e.g. "-c", "--help") from reaching `su` in
// the terminal handler or showing up verbatim in audit logs / throttle keys.
// showing up verbatim in audit logs / throttle keys.
var loginNameRe = regexp.MustCompile(`^[a-z_][a-z0-9_-]{0,31}\$?$`)
// authenticator verifies a username/password (PAM in production). It's a field
@@ -43,8 +43,9 @@ type LoginOutput struct {
// development over plain HTTP, where a Secure cookie would never be sent back.
func RegisterLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store, secure bool) {
// loginThrottle blunts brute force: 5 failures for a username+source IP
// trigger a one-minute cooldown. See throttle.go for the ceiling/upgrade path.
registerLogin(api, sessions, auditor, secure, Authenticate, newFailLimiter(5, time.Minute))
// trigger a one-minute cooldown. Persisted in SQLite so cooldowns survive
// process restarts.
registerLogin(api, sessions, auditor, secure, Authenticate, sessions.NewPersistentFailLimiter(5, time.Minute))
}
func registerLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store, secure bool, authenticate authenticator, throttle *failLimiter) {
@@ -92,7 +93,7 @@ func registerLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store
HttpOnly: true,
Secure: secure,
SameSite: http.SameSiteStrictMode,
Expires: time.Now().Add(24 * time.Hour),
MaxAge: 86400,
},
}
out.Body.Status = "logged in"
+25 -29
View File
@@ -68,20 +68,17 @@ 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
t.Run("failed login returns 401", func(t *testing.T) {
resp := api.Post("/api/login", struct {
Username string `json:"username"`
Password string `json:"password"`
@@ -90,11 +87,13 @@ func TestLoginLogoutThrottling(t *testing.T) {
Password: "wrong",
})
if resp.Code != http.StatusUnauthorized {
t.Errorf("failed login: got code %d, want %d", resp.Code, http.StatusUnauthorized)
t.Errorf("got code %d, want %d", resp.Code, http.StatusUnauthorized)
}
})
// 2. Test successful login
resp = api.Post("/api/login", struct {
var sessionID string
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"`
}{
@@ -102,7 +101,7 @@ func TestLoginLogoutThrottling(t *testing.T) {
Password: "correct",
})
if resp.Code != http.StatusOK {
t.Errorf("successful login: got code %d, want %d", resp.Code, http.StatusOK)
t.Fatalf("got code %d, want %d", resp.Code, http.StatusOK)
}
cookieHeader := resp.Header().Get("Set-Cookie")
@@ -110,7 +109,6 @@ func TestLoginLogoutThrottling(t *testing.T) {
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)
@@ -119,28 +117,25 @@ func TestLoginLogoutThrottling(t *testing.T) {
break
}
}
if sessionID == "" {
t.Fatal("nadir_session_id cookie not found")
}
_, ok := sessions.GetByToken(sessionID)
if !ok {
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{}{})
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.Errorf("logout failed: got code %d, want %d", resp.Code, http.StatusOK)
t.Fatalf("logout failed: got code %d, want %d", resp.Code, http.StatusOK)
}
_, ok = sessions.GetByToken(sessionID)
if ok {
if _, ok := sessions.GetByToken(sessionID); ok {
t.Fatal("session still valid after logout")
}
})
// 4. Test throttling (the handler was registered with a 3-failure limiter).
t.Run("throttling blocks after 3 failures", func(t *testing.T) {
for range 3 {
api.Post("/api/login", struct {
Username string `json:"username"`
@@ -150,8 +145,7 @@ func TestLoginLogoutThrottling(t *testing.T) {
Password: "wrong",
})
}
resp = api.Post("/api/login", struct {
resp := api.Post("/api/login", struct {
Username string `json:"username"`
Password string `json:"password"`
}{
@@ -159,12 +153,13 @@ func TestLoginLogoutThrottling(t *testing.T) {
Password: "correct",
})
if resp.Code != http.StatusTooManyRequests {
t.Errorf("throttled login: got code %d, want %d", resp.Code, http.StatusTooManyRequests)
t.Errorf("got code %d, want %d", resp.Code, http.StatusTooManyRequests)
}
})
time.Sleep(600 * time.Millisecond)
resp = api.Post("/api/login", struct {
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"`
}{
@@ -172,6 +167,7 @@ func TestLoginLogoutThrottling(t *testing.T) {
Password: "correct",
})
if resp.Code != http.StatusOK {
t.Errorf("login after cooldown: got code %d, want %d", resp.Code, http.StatusOK)
t.Errorf("got code %d, want %d", resp.Code, http.StatusOK)
}
})
}
+72
View File
@@ -0,0 +1,72 @@
package auth
import (
"net/http"
"sync"
"time"
"github.com/danielgtaylor/huma/v2"
)
// RateLimiter provides per-IP rate limiting for authenticated API endpoints,
// complementing the login-specific failLimiter with a broader cap on all
// requests. The window aligns to wall-clock intervals so all IPs share the
// same boundary.
type RateLimiter struct {
mu sync.Mutex
buckets map[string]*tokenBucket
limit int
interval time.Duration
}
type tokenBucket struct {
count int
windowEnd time.Time
}
const maxRateLimitKeys = 10000
func NewRateLimiter(limit int, interval time.Duration) *RateLimiter {
return &RateLimiter{
buckets: map[string]*tokenBucket{},
limit: limit,
interval: interval,
}
}
// Allow reports whether ip may make a request now. Returns false when the
// limit is exceeded OR the map is full (fail-closed).
func (l *RateLimiter) Allow(ip string) bool {
l.mu.Lock()
defer l.mu.Unlock()
now := time.Now()
b, ok := l.buckets[ip]
if !ok || now.After(b.windowEnd) {
if len(l.buckets) >= maxRateLimitKeys {
return false
}
l.buckets[ip] = &tokenBucket{count: 1, windowEnd: now.Add(l.interval)}
return true
}
if b.count >= l.limit {
return false
}
b.count++
return true
}
// RateLimitMiddleware returns Huma middleware that rejects requests exceeding
// the per-IP rate limit with 429 Too Many Requests. It runs before the RBAC
// check so abusive IPs are dropped early. The IP is read from the context set
// by WithClientIP; if absent the request passes through unthrottled.
func RateLimitMiddleware(api huma.API, rl *RateLimiter) func(huma.Context, func(huma.Context)) {
return func(ctx huma.Context, next func(huma.Context)) {
ip := ClientIP(ctx.Context())
if ip != "" && !rl.Allow(ip) {
huma.WriteErr(api, ctx, http.StatusTooManyRequests, "rate limit exceeded, try again later")
return
}
next(ctx)
}
}
+66 -5
View File
@@ -2,6 +2,7 @@ package auth
import (
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/hex"
"fmt"
@@ -12,7 +13,7 @@ import (
_ "modernc.org/sqlite"
)
const sessionTTL = 24 * time.Hour
var sessionTTL = 24 * time.Hour
type Session struct {
Username string
@@ -45,6 +46,17 @@ func NewSessionStore(path string) (*SessionStore, error) {
)`); err != nil {
return nil, fmt.Errorf("create sessions table: %w", err)
}
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS throttle (
key TEXT PRIMARY KEY,
count INTEGER NOT NULL,
until INTEGER NOT NULL
)`); err != nil {
return nil, fmt.Errorf("create throttle table: %w", err)
}
// Restrict the DB file so only the owning user (root) can read it.
if err := os.Chmod(path, 0600); err != nil {
return nil, fmt.Errorf("chmod session db: %w", err)
}
return &SessionStore{db: db}, nil
}
@@ -57,7 +69,7 @@ func (s *SessionStore) Create(username string) (string, error) {
expires := time.Now().Add(sessionTTL)
if _, err := s.db.Exec(
`INSERT INTO sessions (token, username, expires_at) VALUES (?, ?, ?)`,
token, username, expires.Unix(),
hashSessionToken(token), username, expires.Unix(),
); err != nil {
return "", err
}
@@ -67,26 +79,75 @@ func (s *SessionStore) Create(username string) (string, error) {
// Delete removes a session, invalidating it immediately (logout). Deleting an
// unknown token is a no-op.
func (s *SessionStore) Delete(token string) error {
_, err := s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token)
_, err := s.db.Exec(`DELETE FROM sessions WHERE token = ?`, hashSessionToken(token))
return err
}
// DeleteByUsername removes every session for the given user, used when a
// password change should invalidate all existing sessions.
func (s *SessionStore) DeleteByUsername(username string) error {
_, err := s.db.Exec(`DELETE FROM sessions WHERE username = ?`, username)
return err
}
func (s *SessionStore) GetByToken(token string) (Session, bool) {
var username string
var expires int64
h := hashSessionToken(token)
err := s.db.QueryRow(
`SELECT username, expires_at FROM sessions WHERE token = ?`, token,
`SELECT username, expires_at FROM sessions WHERE token = ?`, h,
).Scan(&username, &expires)
if err != nil {
return Session{}, false
}
if time.Now().Unix() > expires {
s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token)
s.db.Exec(`DELETE FROM sessions WHERE token = ?`, h)
return Session{}, false
}
return Session{Username: username}, true
}
// NewPersistentFailLimiter returns a failLimiter whose state survives process
// restarts via the session SQLite database.
func (s *SessionStore) NewPersistentFailLimiter(max int, window time.Duration) *failLimiter {
l := newFailLimiter(max, window)
// Load existing entries, skipping expired ones.
rows, err := s.db.Query(`SELECT key, count, until FROM throttle`)
if err != nil {
return l
}
defer rows.Close()
now := time.Now()
for rows.Next() {
var k string
var c int
var u int64
if err := rows.Scan(&k, &c, &u); err != nil {
continue
}
until := time.Unix(u, 0)
if now.After(until) {
s.db.Exec(`DELETE FROM throttle WHERE key = ?`, k)
continue
}
l.attempts[k] = &attemptState{count: c, until: until}
}
// Wire persistence: writes to DB on every mutation.
l.sync = func(key string, st *attemptState) {
if st == nil {
s.db.Exec(`DELETE FROM throttle WHERE key = ?`, key)
} else {
s.db.Exec(`INSERT OR REPLACE INTO throttle (key, count, until) VALUES (?, ?, ?)`, key, st.count, st.until.Unix())
}
}
return l
}
func hashSessionToken(token string) string {
h := sha256.Sum256([]byte(token))
return hex.EncodeToString(h[:])
}
func randomToken() string {
b := make([]byte, 32)
rand.Read(b) // never fails; rand.Read panics internally on misconfigured platforms.
+9 -10
View File
@@ -34,22 +34,21 @@ func TestExpiredSessionRejected(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// Write a row that expired an hour ago, bypassing Create's TTL.
_, err = store.db.Exec(
`INSERT INTO sessions (token, username, expires_at) VALUES (?, ?, ?)`,
"stale", "urania", time.Now().Add(-time.Hour).Unix(),
)
// Create a session with an already-expired TTL (-2s ensures the Unix
// second-rounded timestamp is safely in the past).
oldTTL := sessionTTL
sessionTTL = -2 * time.Second
token, err := store.Create("urania")
sessionTTL = oldTTL
if err != nil {
t.Fatal(err)
}
if _, ok := store.GetByToken("stale"); ok {
if _, ok := store.GetByToken(token); ok {
t.Fatal("expired session was accepted")
}
// Lazy cleanup should have deleted the row.
var n int
store.db.QueryRow(`SELECT count(*) FROM sessions WHERE token = ?`, "stale").Scan(&n)
if n != 0 {
t.Fatalf("expired row not cleaned up: %d rows remain", n)
if _, ok := store.GetByToken(token); ok {
t.Fatal("expired session still in store")
}
}
+14 -5
View File
@@ -24,6 +24,7 @@ type failLimiter struct {
attempts map[string]*attemptState
max int
window time.Duration
sync func(key string, s *attemptState) // optional: persist to DB
}
type attemptState struct {
@@ -32,8 +33,8 @@ type attemptState struct {
}
// maxTrackedKeys bounds memory: an attacker rotating username/IP can't grow the
// map without limit. When exceeded we drop all throttle state - a crude reset
// that briefly forgets cooldowns, acceptable for a single-node panel.
// map without limit. When exceeded we fail closed instead of wiping state, so
// existing cooldowns are preserved.
const maxTrackedKeys = 10000
func newFailLimiter(max int, window time.Duration) *failLimiter {
@@ -49,11 +50,13 @@ func (l *failLimiter) blocked(key string) bool {
}
// fail records a failed attempt and starts a cooldown once max is reached.
// When the map is full we stop tracking new keys rather than wiping existing
// cooldowns (which an attacker could use to clear a target's throttle).
func (l *failLimiter) fail(key string) {
l.mu.Lock()
defer l.mu.Unlock()
if len(l.attempts) > maxTrackedKeys {
l.attempts = map[string]*attemptState{}
if len(l.attempts) >= maxTrackedKeys {
return
}
s := l.attempts[key]
if s == nil {
@@ -63,7 +66,10 @@ func (l *failLimiter) fail(key string) {
s.count++
if s.count >= l.max {
s.until = time.Now().Add(l.window)
s.count = 0 // restart the window after the cooldown is set
s.count = 0
}
if l.sync != nil {
l.sync(key, s)
}
}
@@ -72,6 +78,9 @@ func (l *failLimiter) reset(key string) {
l.mu.Lock()
defer l.mu.Unlock()
delete(l.attempts, key)
if l.sync != nil {
l.sync(key, nil)
}
}
type ctxKey int
+3
View File
@@ -56,6 +56,9 @@ func NewTokenStore(path string) (*TokenStore, error) {
)`); err != nil {
return nil, fmt.Errorf("create tokens table: %w", err)
}
if err := os.Chmod(path, 0600); err != nil {
return nil, fmt.Errorf("chmod token db: %w", err)
}
return &TokenStore{db: db}, nil
}
+3 -3
View File
@@ -16,8 +16,8 @@ func TestTokenStore(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(raw) < len(tokenPrefix)+32 || raw[:len(tokenPrefix)] != tokenPrefix {
t.Fatalf("token %q lacks %q prefix or is too short", raw, tokenPrefix)
if len(raw) < 36 || raw[:4] != "nad_" {
t.Fatalf("token %q lacks %q prefix or is too short", raw, "nad_")
}
// Round-trip: the minted secret resolves to its name.
@@ -25,7 +25,7 @@ func TestTokenStore(t *testing.T) {
t.Errorf("Lookup(valid) = %q,%v; want dash,true", name, ok)
}
// A wrong secret (and a non-prefixed one) must not resolve.
if _, ok := store.Lookup(tokenPrefix + "wrong"); ok {
if _, ok := store.Lookup("nad_wrong"); ok {
t.Error("Lookup(wrong) succeeded")
}
if _, ok := store.Lookup("no-prefix"); ok {
+11 -6
View File
@@ -69,10 +69,10 @@ type Server struct {
}
// SecureCookie reports whether the session cookie should carry the Secure
// attribute, defaulting to true when server.secure_tls is omitted.
// attribute, defaulting to false when server.secure_tls is omitted (plain HTTP).
func (f *File) SecureCookie() bool {
if f.Server.SecureTLS == nil {
return true
return false
}
return *f.Server.SecureTLS
}
@@ -109,10 +109,10 @@ func Load(path string) (*File, error) {
if err := yaml.Unmarshal(data, &f); err != nil {
return nil, fmt.Errorf("parse config %s: %w", path, err)
}
// release_repo, when set, is downloaded over the wire and (for /api/update)
// executed. Validate shape + scheme once here so /install.sh and the updater
// can use the string directly. Trim any trailing slash so downstream string
// concatenation produces a clean URL.
// release_repo, when set, is substituted into shell scripts and downloaded
// over the wire. Validate shape + scheme + shell-safety once here so
// /install.sh and the updater can use the string directly. Trim any trailing
// slash so downstream string concatenation produces a clean URL.
if f.Server.ReleaseRepo != "" {
f.Server.ReleaseRepo = strings.TrimRight(f.Server.ReleaseRepo, "/")
u, err := url.Parse(f.Server.ReleaseRepo)
@@ -129,6 +129,11 @@ func Load(path string) (*File, error) {
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return nil, fmt.Errorf("server.release_repo must be https://host/owner/repo, got %q", f.Server.ReleaseRepo)
}
// Shell-safety: reject characters that could break out of a double-quoted
// string when substituted into the install.sh template.
if strings.ContainsAny(f.Server.ReleaseRepo, "`$\"\\;|&") {
return nil, fmt.Errorf("server.release_repo contains unsafe characters: %q", f.Server.ReleaseRepo)
}
}
return &f, nil
}
+6 -6
View File
@@ -30,13 +30,13 @@ func mods() []module.Module {
}
}
func TestSecureCookieDefaultsTrue(t *testing.T) {
if !(&File{}).SecureCookie() {
t.Error("omitted secure_tls should default to true")
func TestSecureCookieDefaultsFalse(t *testing.T) {
if (&File{}).SecureCookie() {
t.Error("omitted secure_tls should default to false")
}
no := false
if (&File{Server: Server{SecureTLS: &no}}).SecureCookie() {
t.Error("secure_tls: false should disable the Secure flag")
yes := true
if !(&File{Server: Server{SecureTLS: &yes}}).SecureCookie() {
t.Error("secure_tls: true should enable the Secure flag")
}
}
+23 -4
View File
@@ -15,6 +15,7 @@ import (
// itself.
type WhoamiInput struct {
SessionID string `cookie:"nadir_session_id"`
Auth string `header:"Authorization"`
}
// WhoamiBody reports who the caller is and, per module, which permissions they
@@ -30,7 +31,7 @@ type WhoamiOutput struct{ Body WhoamiBody }
// RegisterWhoami adds the current-user endpoint. It resolves the caller's
// concrete grants by asking the RBAC store about each module's permissions,
// so "*" wildcards in roles are expanded for free.
func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC, mods []module.Module) {
func RegisterWhoami(api huma.API, sessions *auth.SessionStore, tokens *auth.TokenAuth, roles *rbac.RBAC, mods []module.Module) {
huma.Register(api, huma.Operation{
OperationID: "whoami",
Method: "GET",
@@ -40,18 +41,35 @@ func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC,
"permissions the caller holds (wildcards resolved). Pair with " +
"/api/_modules to render the full permission matrix.",
Tags: []string{"Meta"},
Errors: []int{401},
Errors: []int{401, 429},
}, func(ctx context.Context, in *WhoamiInput) (*WhoamiOutput, error) {
var username string
if raw, isBearer := auth.BearerToken(in.Auth); isBearer {
if tokens == nil {
return nil, huma.Error401Unauthorized("unauthorized")
}
name, ok, throttled := tokens.Verify(auth.ClientIP(ctx), raw)
if throttled {
return nil, huma.Error429TooManyRequests("too many failed token attempts; wait a minute")
}
if !ok {
return nil, huma.Error401Unauthorized("unauthorized")
}
username = name
} else {
sess, ok := sessions.GetByToken(in.SessionID)
if !ok {
return nil, huma.Error401Unauthorized("unauthorized")
}
username = sess.Username
}
held := make(map[string][]string)
for _, m := range mods {
var perms []string
for _, p := range m.Permissions() {
if roles.Can(sess.Username, m.ID(), p) {
if roles.Can(username, m.ID(), p) {
perms = append(perms, string(p))
}
}
@@ -61,7 +79,8 @@ func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC,
}
out := &WhoamiOutput{}
out.Body = WhoamiBody{Username: sess.Username, Permissions: held}
out.Body = WhoamiBody{Username: username, Permissions: held}
return out, nil
})
}
+115
View File
@@ -0,0 +1,115 @@
package meta
import (
"encoding/json"
"net/http"
"path/filepath"
"slices"
"testing"
"nadir/internal/auth"
"nadir/internal/module"
"nadir/internal/rbac"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
"github.com/danielgtaylor/huma/v2/humatest"
)
type dummyModule struct {
id string
perms []rbac.Permission
}
func (m *dummyModule) ID() string { return m.id }
func (m *dummyModule) Name() string { return m.id }
func (m *dummyModule) Permissions() []rbac.Permission { return m.perms }
func (m *dummyModule) Register(api huma.API) {}
func TestWhoami(t *testing.T) {
tempDir := t.TempDir()
sessions, err := auth.NewSessionStore(filepath.Join(tempDir, "sessions.db"))
if err != nil {
t.Fatal(err)
}
tokenStore, err := auth.NewTokenStore(filepath.Join(tempDir, "tokens.db"))
if err != nil {
t.Fatal(err)
}
defer tokenStore.Close()
tokenAuth := auth.NewTokenAuth(tokenStore)
roles := rbac.New()
roles.DefineRole(rbac.Role{
Name: "admin-role",
ModuleGrants: map[string][]rbac.Permission{
"system": {rbac.Read},
},
})
roles.AssignRole("admin", "admin-role")
mods := []module.Module{
&dummyModule{
id: "system",
perms: []rbac.Permission{rbac.Read, rbac.Write},
},
}
mux := http.NewServeMux()
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
RegisterWhoami(api, sessions, tokenAuth, roles, mods)
// 1. Unauthorized request (no token, no session)
resp := api.Get("/api/whoami")
if resp.Code != http.StatusUnauthorized {
t.Errorf("expected 401, got %d", resp.Code)
}
// 2. Cookie session request
sessToken, err := sessions.Create("admin")
if err != nil {
t.Fatal(err)
}
resp = api.Get("/api/whoami", "Cookie: nadir_session_id="+sessToken)
if resp.Code != http.StatusOK {
t.Errorf("expected 200, got %d", resp.Code)
}
var body WhoamiBody
if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.Username != "admin" {
t.Errorf("expected username admin, got %q", body.Username)
}
if !slices.Contains(body.Permissions["system"], "read") {
t.Errorf("expected system read permission, got %v", body.Permissions["system"])
}
// 3. Token request
bearerToken, err := tokenStore.Create("api-user")
if err != nil {
t.Fatal(err)
}
roles.DefineRole(rbac.Role{
Name: "api-role",
ModuleGrants: map[string][]rbac.Permission{
"system": {rbac.Write},
},
})
roles.AssignRole("api-user", "api-role")
resp = api.Get("/api/whoami", "Authorization: Bearer "+bearerToken)
if resp.Code != http.StatusOK {
t.Errorf("expected 200, got %d", resp.Code)
}
if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.Username != "api-user" {
t.Errorf("expected username api-user, got %q", body.Username)
}
if !slices.Contains(body.Permissions["system"], "write") {
t.Errorf("expected system write permission, got %v", body.Permissions["system"])
}
}
+4 -4
View File
@@ -70,7 +70,7 @@ func registerGroups(api huma.API) {
}, func(ctx context.Context, _ *struct{}) (*ListGroupsOutput, error) {
list, err := listGroups()
if err != nil {
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
return nil, huma.Error500InternalServerError("group lookup failed", err)
}
out := &ListGroupsOutput{}
out.Body.Groups = list
@@ -92,7 +92,7 @@ func registerGroups(api huma.API) {
}
g, ok, err := lookupGroup(in.Group)
if err != nil {
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
return nil, huma.Error500InternalServerError("group lookup failed", err)
}
if !ok {
return nil, huma.Error404NotFound("group not found: " + in.Group)
@@ -114,7 +114,7 @@ func registerGroups(api huma.API) {
return nil, err
}
if _, ok, err := lookupGroup(in.Body.Name); err != nil {
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
return nil, huma.Error500InternalServerError("group lookup failed", err)
} else if ok {
return nil, huma.Error409Conflict("group already exists: " + in.Body.Name)
}
@@ -154,7 +154,7 @@ func registerGroups(api huma.API) {
return nil, err
}
if _, ok, err := lookupGroup(in.Group); err != nil {
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
return nil, huma.Error500InternalServerError("group lookup failed", err)
} else if !ok {
return nil, huma.Error404NotFound("group not found: " + in.Group)
}
+25 -9
View File
@@ -38,14 +38,30 @@ short:x:5
}
func TestValidateGroupName(t *testing.T) {
for _, n := range []string{"wheel", "_svc", "dev-team", "g1"} {
if err := validateGroupName(n); err != nil {
t.Errorf("validateGroupName(%q) = %v, want nil", n, err)
}
}
for _, n := range []string{"", "-x", "Wheel", "a,b", "foo;rm", "1grp"} {
if err := validateGroupName(n); err == nil {
t.Errorf("validateGroupName(%q) = nil, want error", n)
}
for _, tt := range []struct {
name string
value string
valid bool
}{
{name: "wheel", value: "wheel", valid: true},
{name: "underscore prefix", value: "_svc", valid: true},
{name: "dev-team", value: "dev-team", valid: true},
{name: "alphanumeric", value: "g1", valid: true},
{name: "empty", value: "", valid: false},
{name: "flag injection", value: "-x", valid: false},
{name: "uppercase", value: "Wheel", valid: false},
{name: "comma", value: "a,b", valid: false},
{name: "shell metachar", value: "foo;rm", valid: false},
{name: "leading digit", value: "1grp", valid: false},
} {
t.Run(tt.name, func(t *testing.T) {
err := validateGroupName(tt.value)
if tt.valid && err != nil {
t.Errorf("validateGroupName(%q) = %v, want nil", tt.value, err)
}
if !tt.valid && err == nil {
t.Errorf("validateGroupName(%q) = nil, want error", tt.value)
}
})
}
}
+26 -12
View File
@@ -49,17 +49,31 @@ func TestValidateIfaceConfig(t *testing.T) {
}
func TestValidateIface(t *testing.T) {
valid := []string{"eth0", "enp3s0", "wlan0", "br-lan", "veth1234567", "docker0"}
for _, name := range valid {
if err := validateIface(name); err != nil {
t.Errorf("validateIface(%q) unexpected error: %v", name, err)
}
}
invalid := []string{"", "-eth0", "/dev/net", "a b", "name_that_is_way_too_long_for_linux"}
for _, name := range invalid {
if err := validateIface(name); err == nil {
t.Errorf("validateIface(%q) expected error", name)
}
for _, tt := range []struct {
name string
value string
valid bool
}{
{name: "eth0", value: "eth0", valid: true},
{name: "enp3s0", value: "enp3s0", valid: true},
{name: "wlan0", value: "wlan0", valid: true},
{name: "bridge", value: "br-lan", valid: true},
{name: "veth", value: "veth1234567", valid: true},
{name: "docker", value: "docker0", valid: true},
{name: "empty", value: "", valid: false},
{name: "leading dash", value: "-eth0", valid: false},
{name: "path", value: "/dev/net", valid: false},
{name: "space", value: "a b", valid: false},
{name: "too long", value: "name_that_is_way_too_long_for_linux", valid: false},
} {
t.Run(tt.name, func(t *testing.T) {
err := validateIface(tt.value)
if tt.valid && err != nil {
t.Errorf("validateIface(%q) unexpected error: %v", tt.value, err)
}
if !tt.valid && err == nil {
t.Errorf("validateIface(%q) expected error", tt.value)
}
})
}
}
+27 -3
View File
@@ -6,6 +6,7 @@ import (
"os"
"regexp"
"strings"
"sync"
"nadir/internal/oscmd"
@@ -18,6 +19,10 @@ import (
var hostsFile = "/etc/hosts"
// hostsMu serialises writes to /etc/hosts so concurrent requests don't
// clobber each other's read-modify-write.
var hostsMu sync.Mutex
// hostnameRe matches a single hostname/alias. It forbids whitespace and '#' (so
// an entry can't inject extra fields or a comment) and a leading dash.
var hostnameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`)
@@ -156,9 +161,26 @@ func renderHostLine(ip string, hostnames []string) string {
// --- writes ------------------------------------------------------------------
// writeHostsAtomically writes content to /etc/hosts via a temp file + rename,
// so a crash mid-write leaves the original file intact.
func writeHostsAtomically(content string) error {
tmp := hostsFile + ".nadir.tmp"
if err := os.WriteFile(tmp, []byte(content), 0644); err != nil {
return err
}
if err := os.Rename(tmp, hostsFile); err != nil {
os.Remove(tmp)
return err
}
return nil
}
// upsertHost replaces the line for ip (matched on the address field) or appends
// a new one, preserving every other line.
func upsertHost(ip string, hostnames []string) error {
hostsMu.Lock()
defer hostsMu.Unlock()
data, err := os.ReadFile(hostsFile)
if err != nil {
return err
@@ -174,7 +196,6 @@ func upsertHost(ip string, hostnames []string) error {
}
}
if !replaced {
// Append, avoiding a blank line if the file already ended with one.
if n := len(lines); n > 0 && strings.TrimSpace(lines[n-1]) == "" {
lines[n-1] = newLine
} else {
@@ -182,11 +203,14 @@ func upsertHost(ip string, hostnames []string) error {
}
lines = append(lines, "")
}
return os.WriteFile(hostsFile, []byte(strings.Join(lines, "\n")), 0644)
return writeHostsAtomically(strings.Join(lines, "\n"))
}
// deleteHost removes every line mapping ip and reports whether any were removed.
func deleteHost(ip string) (bool, error) {
hostsMu.Lock()
defer hostsMu.Unlock()
data, err := os.ReadFile(hostsFile)
if err != nil {
return false, err
@@ -204,5 +228,5 @@ func deleteHost(ip string) (bool, error) {
if !removed {
return false, nil
}
return true, os.WriteFile(hostsFile, []byte(strings.Join(kept, "\n")), 0644)
return true, writeHostsAtomically(strings.Join(kept, "\n"))
}
+1 -1
View File
@@ -32,7 +32,7 @@ func (m *Module) Permissions() []rbac.Permission {
}
func (m *Module) Register(api huma.API) {
registerReads(api)
registerReads(api, m)
registerWrites(api, m)
registerHosts(api)
}
@@ -10,7 +10,6 @@ import (
"reflect"
"strings"
"testing"
"time"
"nadir/internal/oscmd"
@@ -87,6 +86,30 @@ func TestNetworkingHandlers(t *testing.T) {
t.Errorf("list interfaces: got %d, want %d", resp.Code, http.StatusOK)
}
// 1b. Test GET /api/networking/interfaces/{name} (used by edit-form prefill).
// Asserts the backend's Snapshot output is returned verbatim as the body, so
// the same shape can feed straight into PUT.
resp = api.Get("/api/networking/interfaces/eth0")
if resp.Code != http.StatusOK {
t.Errorf("get interface: got %d, want %d", resp.Code, http.StatusOK)
}
var ifaceRes GetInterfaceConfigOutput
if err := json.Unmarshal(resp.Body.Bytes(), &ifaceRes.Body); err != nil {
t.Fatal(err)
}
if ifaceRes.Body.Method != "dhcp" || ifaceRes.Body.Address != "192.168.1.10/24" {
t.Errorf("get interface: got %+v, want snapshot result", ifaceRes.Body)
}
// Same endpoint with no backend should return 501.
noBackend := &Module{}
noBackendMux := http.NewServeMux()
noBackendAPI := humatest.Wrap(t, humago.New(noBackendMux, huma.DefaultConfig("Test", "1.0.0")))
noBackend.Register(noBackendAPI)
if got := noBackendAPI.Get("/api/networking/interfaces/eth0").Code; got != http.StatusNotImplemented {
t.Errorf("get interface without backend: got %d, want 501", got)
}
// 2. Test GET /api/networking/routes
resp = api.Get("/api/networking/routes")
if resp.Code != http.StatusOK {
@@ -144,14 +167,18 @@ func TestNetworkingHandlers(t *testing.T) {
t.Errorf("pending change should be cleared: got %d, want %d", resp.Code, http.StatusNotFound)
}
// 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 {
@@ -388,3 +415,69 @@ func TestBackendImplementations(t *testing.T) {
t.Fatal(err)
}
}
func TestGetInterfaceConfigAugment(t *testing.T) {
mux := http.NewServeMux()
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
be := &mockBackend{
name: "mockbe",
snapshotResult: IfaceConfig{
Method: "dhcp",
},
}
m := &Module{be: be}
m.Register(api)
tempResolv := filepath.Join(t.TempDir(), "resolv.conf")
if err := os.WriteFile(tempResolv, []byte("nameserver 1.1.1.1\nnameserver 8.8.8.8\n"), 0644); err != nil {
t.Fatal(err)
}
oldResolv := resolvConf
resolvConf = tempResolv
defer func() { resolvConf = oldResolv }()
oscmd.SetMock("ip", func(args []string) oscmd.MockCommand {
argStr := strings.Join(args, " ")
if strings.Contains(argStr, "addr show") {
out := `[{"ifname": "eth0", "operstate": "UP", "address": "aa:bb:cc:dd:ee:ff", "mtu": 1500, "addr_info": [{"family": "inet", "local": "192.168.1.10", "prefixlen": 24}, {"family": "inet6", "local": "2001:db8::10", "prefixlen": 64}]}]`
return oscmd.MockCommand{Stdout: out, ExitCode: 0}
}
if strings.Contains(argStr, "route show") && !strings.Contains(argStr, "-6") {
out := `[{"dst": "default", "gateway": "192.168.1.1", "dev": "eth0"}]`
return oscmd.MockCommand{Stdout: out, ExitCode: 0}
}
if strings.Contains(argStr, "-6") && strings.Contains(argStr, "route show") {
out := `[{"dst": "default", "gateway": "2001:db8::1", "dev": "eth0"}]`
return oscmd.MockCommand{Stdout: out, ExitCode: 0}
}
return oscmd.MockCommand{ExitCode: 1}
})
defer oscmd.ClearMocks()
resp := api.Get("/api/networking/interfaces/eth0")
if resp.Code != http.StatusOK {
t.Errorf("get interface: got %d, want %d", resp.Code, http.StatusOK)
}
var ifaceRes GetInterfaceConfigOutput
if err := json.Unmarshal(resp.Body.Bytes(), &ifaceRes.Body); err != nil {
t.Fatal(err)
}
if ifaceRes.Body.Method != "dhcp" {
t.Errorf("expected Method to be dhcp, got %s", ifaceRes.Body.Method)
}
if ifaceRes.Body.Address != "192.168.1.10" || ifaceRes.Body.Prefix != 24 {
t.Errorf("expected augmented Address 192.168.1.10/24, got %s/%d", ifaceRes.Body.Address, ifaceRes.Body.Prefix)
}
if ifaceRes.Body.Gateway != "192.168.1.1" {
t.Errorf("expected augmented Gateway 192.168.1.1, got %s", ifaceRes.Body.Gateway)
}
if len(ifaceRes.Body.DNS) != 2 || ifaceRes.Body.DNS[0] != "1.1.1.1" || ifaceRes.Body.DNS[1] != "8.8.8.8" {
t.Errorf("expected augmented DNS [1.1.1.1, 8.8.8.8], got %v", ifaceRes.Body.DNS)
}
if ifaceRes.Body.IPv6 == nil || ifaceRes.Body.IPv6.Method != "auto" || ifaceRes.Body.IPv6.Address != "2001:db8::10" || ifaceRes.Body.IPv6.Prefix != 64 || ifaceRes.Body.IPv6.Gateway != "2001:db8::1" {
t.Errorf("expected augmented IPv6, got %+v", ifaceRes.Body.IPv6)
}
}
+16 -8
View File
@@ -46,11 +46,19 @@ func (b *nmcliBackend) Snapshot(ctx context.Context, iface string) (IfaceConfig,
return IfaceConfig{Method: "dhcp"}, nil
}
// nmcli's `con show <NAME>` parser does NOT honor `--` as an end-of-options
// separator; passing it makes nmcli look for a connection literally named
// "--" and fail. `conn` comes from nmcli's own active-connections list (see
// connForIface), so it's already validated — no shell-metacharacter risk.
// Same applies to con up / con down / con modify below.
out, err := oscmd.RunContext(ctx, "nmcli", "-t", "-f",
"ipv4.method,ipv4.addresses,ipv4.gateway,ipv4.dns,ipv4.routes,ipv6.method,ipv6.addresses,ipv6.gateway",
"con", "show", "--", conn)
"con", "show", conn)
if err != nil {
return IfaceConfig{}, fmt.Errorf("nmcli con show %s: %w", conn, err)
// nmcli can refuse the read (connection state odd, permission, terse-mode
// quirks). Fall back to DHCP defaults so the prefill endpoint still
// returns a usable form, mirroring the networkd / ifupdown fallback.
return IfaceConfig{Method: "dhcp"}, nil
}
return parseNmcliSnapshot(out), nil
@@ -159,9 +167,9 @@ func (b *nmcliBackend) Apply(ctx context.Context, iface string, cfg IfaceConfig)
return fmt.Errorf("cannot apply: %w", err)
}
// Build the nmcli con modify arguments. Note: conn is safe to place after
// -- since it comes from nmcli output, not directly from the user.
args := []string{"con", "modify", "--", conn}
// conn comes from nmcli's own active list (connForIface), not user input.
// nmcli's con subcommands don't honor "--" as an end-of-options separator.
args := []string{"con", "modify", conn}
switch cfg.Method {
case "static":
@@ -222,7 +230,7 @@ func (b *nmcliBackend) Apply(ctx context.Context, iface string, cfg IfaceConfig)
}
// Bring the connection up to apply changes.
if _, err := oscmd.RunContext(ctx, "nmcli", "con", "up", "--", conn); err != nil {
if _, err := oscmd.RunContext(ctx, "nmcli", "con", "up", conn); err != nil {
return fmt.Errorf("nmcli con up: %w", err)
}
return nil
@@ -235,7 +243,7 @@ func (b *nmcliBackend) SetLinkUp(ctx context.Context, iface string) error {
_, err = oscmd.RunContext(ctx, "ip", "link", "set", "--", iface, "up")
return err
}
_, err = oscmd.RunContext(ctx, "nmcli", "con", "up", "--", conn)
_, err = oscmd.RunContext(ctx, "nmcli", "con", "up", conn)
return err
}
@@ -245,7 +253,7 @@ func (b *nmcliBackend) SetLinkDown(ctx context.Context, iface string) error {
_, err = oscmd.RunContext(ctx, "ip", "link", "set", "--", iface, "down")
return err
}
_, err = oscmd.RunContext(ctx, "nmcli", "con", "down", "--", conn)
_, err = oscmd.RunContext(ctx, "nmcli", "con", "down", conn)
return err
}
+155 -2
View File
@@ -3,6 +3,8 @@ package networking
import (
"context"
"encoding/json"
"fmt"
"net/netip"
"os"
"strconv"
"strings"
@@ -53,7 +55,48 @@ type DNSOutput struct {
}
}
func registerReads(api huma.API) {
// GetInterfaceConfigInput carries the path param; matches the PUT endpoint's
// IfacePathInput so the frontend can use the same path for both verbs.
type GetInterfaceConfigInput struct {
Name string `path:"name" example:"eth0" doc:"Interface name"`
}
// GetInterfaceConfigOutput returns the same IfaceConfig shape that PUT
// accepts, so the form can be pre-filled directly from this response.
type GetInterfaceConfigOutput struct {
Body IfaceConfig
}
func registerReads(api huma.API, m *Module) {
huma.Register(api, huma.Operation{
OperationID: "networking-get-interface",
Method: "GET",
Path: "/api/networking/interfaces/{name}",
Summary: "Get an interface's current configuration",
Description: "Returns the IfaceConfig the backend currently has for this " +
"interface (method, address/prefix, gateway, DNS, IPv6). Same schema as " +
"PUT /api/networking/interfaces/{name}, so the frontend can prefill an " +
"edit form from this response directly. Returns 501 when no backend was " +
"detected (nmcli / networkd / ifupdown).",
Tags: []string{tagNetworking},
Metadata: op("read"),
Errors: readErrors,
}, func(ctx context.Context, in *GetInterfaceConfigInput) (*GetInterfaceConfigOutput, error) {
if m.be == nil {
return nil, huma.Error501NotImplemented("", errNoBackend)
}
if err := validateIface(in.Name); err != nil {
return nil, err
}
cfg, err := m.be.Snapshot(ctx, in.Name)
if err != nil {
return nil, huma.Error500InternalServerError("snapshot failed", err)
}
augmentWithLiveState(ctx, in.Name, &cfg)
return &GetInterfaceConfigOutput{Body: cfg}, nil
})
huma.Register(api, huma.Operation{
OperationID: "networking-list-interfaces",
Method: "GET",
@@ -114,7 +157,7 @@ func registerReads(api huma.API) {
}, 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))
@@ -209,3 +252,113 @@ func parseResolv(text string) []string {
}
return servers
}
func getLiveInterface(ctx context.Context, iface string) (*Interface, error) {
out, err := oscmd.RunContext(ctx, "ip", "-j", "addr", "show", "--", iface)
if err != nil {
out, err = oscmd.RunContext(ctx, "ip", "-j", "addr")
if err != nil {
return nil, err
}
}
ifaces, err := parseInterfaces(out)
if err != nil {
return nil, err
}
for i := range ifaces {
if ifaces[i].Name == iface {
return &ifaces[i], nil
}
}
return nil, fmt.Errorf("interface %s not found in ip addr output", iface)
}
func getLiveGateway(ctx context.Context, iface string) string {
routeOut, err := oscmd.RunContext(ctx, "ip", "-j", "route", "show", "dev", "--", iface)
if err != nil {
routeOut, err = oscmd.RunContext(ctx, "ip", "-j", "route")
if err != nil {
return ""
}
}
routes, err := parseRoutes(routeOut)
if err != nil {
return ""
}
for _, r := range routes {
if r.Destination == "default" && (r.Interface == iface || r.Interface == "") && r.Gateway != "" {
return r.Gateway
}
}
return ""
}
func getLiveIPv6Gateway(ctx context.Context, iface string) string {
routeOut, err := oscmd.RunContext(ctx, "ip", "-6", "-j", "route", "show", "dev", "--", iface)
if err != nil {
routeOut, err = oscmd.RunContext(ctx, "ip", "-6", "-j", "route")
if err != nil {
return ""
}
}
routes, err := parseRoutes(routeOut)
if err != nil {
return ""
}
for _, r := range routes {
if r.Destination == "default" && (r.Interface == iface || r.Interface == "") && r.Gateway != "" {
return r.Gateway
}
}
return ""
}
func augmentWithLiveState(ctx context.Context, iface string, cfg *IfaceConfig) {
liveIface, err := getLiveInterface(ctx, iface)
if err != nil {
return
}
// Prefill IPv4 address and prefix if empty
if cfg.Address == "" && len(liveIface.IPv4) > 0 {
addr, prefix := splitCIDR(liveIface.IPv4[0])
if addr != "" {
cfg.Address = addr
cfg.Prefix = prefix
}
}
// Prefill Gateway if empty
if cfg.Gateway == "" {
cfg.Gateway = getLiveGateway(ctx, iface)
}
// Prefill DNS if empty
if len(cfg.DNS) == 0 {
if data, err := os.ReadFile(resolvConf); err == nil {
cfg.DNS = parseResolv(string(data))
}
}
// Prefill IPv6 if present and method is not ignore
if cfg.IPv6 == nil {
cfg.IPv6 = &IPv6Config{Method: "auto"}
}
if cfg.IPv6.Method != "ignore" {
// Capture first global IPv6 if address is empty
if cfg.IPv6.Address == "" {
for _, c := range liveIface.IPv6 {
addr, prefix := splitCIDR(c)
if ip, err := netip.ParseAddr(addr); err == nil && !ip.IsLinkLocalUnicast() {
cfg.IPv6.Address = addr
cfg.IPv6.Prefix = prefix
break
}
}
}
// Capture IPv6 default gateway if empty
if cfg.IPv6.Gateway == "" {
cfg.IPv6.Gateway = getLiveIPv6Gateway(ctx, iface)
}
}
}
+13 -5
View File
@@ -8,7 +8,7 @@ import (
"time"
)
const defaultRollbackSeconds = 60
const defaultRollbackSeconds = 120
// errAlreadyPending is returned when another change is awaiting confirmation.
// The write handlers map this to 409 Conflict.
@@ -113,18 +113,26 @@ func (m *Module) armPending(iface string, revert func() error, seconds int) (int
// revert even if the server is otherwise idle — the whole point is protecting
// against being locked out of a remote box.
pc.Timer = time.AfterFunc(dur, func() {
// Check validity under lock, then revert outside it so a slow
// nmcli/networkctl call doesn't block the entire networking module.
m.mu.Lock()
defer m.mu.Unlock()
// Only revert if this exact change is still pending (it may have been
// confirmed or manually rolled back in the meantime).
if m.pending != pc {
m.mu.Unlock()
return
}
iface := pc.Iface
revert := pc.revert
m.mu.Unlock()
log.Printf("networking: rollback timer expired for %s — reverting", iface)
if err := pc.revert(); err != nil {
if err := revert(); err != nil {
log.Printf("networking: auto-rollback of %s failed: %v", iface, err)
}
m.mu.Lock()
if m.pending == pc {
m.pending = nil
}
m.mu.Unlock()
})
m.pending = pc
+56 -6
View File
@@ -65,6 +65,10 @@ type RemoveInput struct {
Name string `path:"name" example:"htop" doc:"Package to remove"`
}
type UpgradeOneInput struct {
Name string `path:"name" example:"htop" doc:"Package to upgrade"`
}
// SSE event types for streaming package operations.
type PkgOutputEvent struct {
Line string `json:"line" doc:"One line of the package manager's terminal output"`
@@ -79,6 +83,11 @@ type PkgDoneEvent struct {
Error string `json:"error,omitempty" doc:"Exit error when it failed"`
}
// 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{
@@ -162,6 +171,25 @@ func registerPackages(api huma.API, pm manager) {
bin, args := pm.upgradeArgs()
streamOp(ctx, send, bin, args)
})
sse.Register(api, huma.Operation{
OperationID: "packages-upgrade-one",
Method: "POST",
Path: "/api/packages/upgrade/{name}",
Summary: "Upgrade a single package (streamed)",
Description: "Upgrades the named package to its latest version, streaming the " +
"package manager's output live. apt uses `install --only-upgrade` so the " +
"package must already be installed; dnf/pacman handle this natively.",
Tags: []string{tagPackages},
Metadata: op("write"),
}, pkgEvents, func(ctx context.Context, in *UpgradeOneInput, send sse.Sender) {
if validateName(in.Name) != nil {
send.Data(PkgErrorEvent{Message: "invalid package name: " + in.Name})
return
}
bin, args := pm.upgradeOneArgs(in.Name)
streamOp(ctx, send, bin, args)
})
}
// streamOp runs a package write and streams its combined output to the client.
@@ -170,6 +198,13 @@ func streamOp(ctx context.Context, send sse.Sender, bin string, args []string) {
send.Data(PkgErrorEvent{Message: "no supported package manager found"})
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 {
@@ -260,11 +295,11 @@ func result(pm manager, pkgs []Package) *ListOutput {
func (m manager) installArgs(name string) (string, []string) {
switch m.name {
case "dnf":
return "dnf", []string{"install", "-y", "--", name}
return "dnf", []string{"install", "-y", name}
case "apt":
return "apt-get", []string{"install", "-y", "--", name}
return "apt-get", []string{"install", "-y", name}
case "pacman":
return "pacman", []string{"-S", "--noconfirm", "--", name}
return "pacman", []string{"-S", "--noconfirm", name}
}
return "", nil
}
@@ -272,11 +307,11 @@ func (m manager) installArgs(name string) (string, []string) {
func (m manager) removeArgs(name string) (string, []string) {
switch m.name {
case "dnf":
return "dnf", []string{"remove", "-y", "--", name}
return "dnf", []string{"remove", "-y", name}
case "apt":
return "apt-get", []string{"remove", "-y", "--", name}
return "apt-get", []string{"remove", "-y", name}
case "pacman":
return "pacman", []string{"-R", "--noconfirm", "--", name}
return "pacman", []string{"-R", "--noconfirm", name}
}
return "", nil
}
@@ -293,6 +328,21 @@ func (m manager) upgradeArgs() (string, []string) {
return "", nil
}
// upgradeOneArgs upgrades a single package to its latest version. apt's
// `install --only-upgrade` is the safe variant (won't install if absent);
// pacman -S re-syncs to latest; dnf upgrade is naturally scoped by name.
func (m manager) upgradeOneArgs(name string) (string, []string) {
switch m.name {
case "dnf":
return "dnf", []string{"upgrade", "-y", name}
case "apt":
return "apt-get", []string{"install", "--only-upgrade", "-y", name}
case "pacman":
return "pacman", []string{"-S", "--noconfirm", name}
}
return "", nil
}
// --- parsers (pure, tested) --------------------------------------------------
// parseTabbed reads "name\tversion" lines (dpkg-query / rpm output).
+39 -16
View File
@@ -54,27 +54,50 @@ func TestParsePacmanUpdates(t *testing.T) {
}
func TestStripArch(t *testing.T) {
cases := map[string]string{
"code.x86_64": "code",
"python3.11.noarch": "python3.11", // arch is only the final segment
"noarchhere": "noarchhere",
tests := []struct {
name string
in string
want string
}{
{name: "x86_64 arch", in: "code.x86_64", want: "code"},
{name: "noarch suffix", in: "python3.11.noarch", want: "python3.11"},
{name: "no arch segment", in: "noarchhere", want: "noarchhere"},
}
for in, want := range cases {
if got := stripArch(in); got != want {
t.Errorf("stripArch(%q) = %q, want %q", in, got, want)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := stripArch(tt.in); got != tt.want {
t.Errorf("stripArch(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}
func TestValidateName(t *testing.T) {
for _, n := range []string{"htop", "openssh-server", "lib32-glibc", "g++", "python3.11"} {
if err := validateName(n); err != nil {
t.Errorf("validateName(%q) = %v, want nil", n, err)
}
}
for _, n := range []string{"", "-rf", "foo;rm", "foo bar", "pkg=1.0", "a/b"} {
if err := validateName(n); err == nil {
t.Errorf("validateName(%q) = nil, want error", n)
}
for _, tt := range []struct {
name string
value string
valid bool
}{
{name: "htop", value: "htop", valid: true},
{name: "openssh-server", value: "openssh-server", valid: true},
{name: "lib32-glibc", value: "lib32-glibc", valid: true},
{name: "g++", value: "g++", valid: true},
{name: "python3.11", value: "python3.11", valid: true},
{name: "empty", value: "", valid: false},
{name: "flag injection", value: "-rf", valid: false},
{name: "shell metachar", value: "foo;rm", valid: false},
{name: "space", value: "foo bar", valid: false},
{name: "equals", value: "pkg=1.0", valid: false},
{name: "path sep", value: "a/b", valid: false},
} {
t.Run(tt.name, func(t *testing.T) {
err := validateName(tt.value)
if tt.valid && err != nil {
t.Errorf("validateName(%q) = %v, want nil", tt.value, err)
}
if !tt.valid && err == nil {
t.Errorf("validateName(%q) = nil, want error", tt.value)
}
})
}
}
+12
View File
@@ -19,6 +19,10 @@ const (
maxLogLines = 10000
)
// logStreamSem limits concurrent log-follow connections. Each one forks a
// journalctl or tail subprocess, so too many would exhaust system resources.
var logStreamSem = make(chan struct{}, 10)
// LogEntry is one log record. For the journal source it is distilled from
// journalctl's JSON; for the file source only Message is set (the raw line,
// which usually carries its own embedded timestamp).
@@ -128,6 +132,14 @@ func registerLogs(api huma.API, logFiles map[string][]string) {
return
}
select {
case logStreamSem <- struct{}{}:
default:
send.Data(ErrorEvent{Message: "too many concurrent log streams, try again later"})
return
}
defer func() { <-logStreamSem }()
var cmd string
var args []string
if in.Source == "file" {
+55 -30
View File
@@ -48,49 +48,74 @@ func TestResolveLogPath(t *testing.T) {
"nginx.service": {"/var/log/nginx/access.log", "/var/log/nginx/error.log"},
}
// Allowlisted path resolves whether the caller uses the bare or .service
// form, regardless of which form the config key used.
for _, unit := range []string{"nginx.service", "nginx"} {
if p, err := resolveLogPath(allow, unit, "/var/log/nginx/error.log"); err != nil || p != "/var/log/nginx/error.log" {
t.Errorf("allowlisted path for %q: got %q, %v", unit, p, err)
t.Run("allowlisted path via bare name", func(t *testing.T) {
p, err := resolveLogPath(allow, "nginx", "/var/log/nginx/error.log")
if err != nil || p != "/var/log/nginx/error.log" {
t.Errorf("got %q, %v", p, err)
}
})
t.Run("allowlisted path via service suffix", func(t *testing.T) {
p, err := resolveLogPath(allow, "nginx.service", "/var/log/nginx/error.log")
if err != nil || p != "/var/log/nginx/error.log" {
t.Errorf("got %q, %v", p, err)
}
})
// Everything else is rejected: empty path, non-listed path (traversal),
// listed path but wrong unit, and unit with no allowlist at all.
bad := []struct{ unit, path string }{
{"nginx.service", ""},
{"nginx.service", "/etc/shadow"},
{"nginx.service", "/var/log/nginx/access.log/../../../etc/shadow"},
{"sshd.service", "/var/log/nginx/error.log"},
{"unknown.service", "/var/log/nginx/error.log"},
}
for _, b := range bad {
if _, err := resolveLogPath(allow, b.unit, b.path); err == nil {
t.Errorf("resolveLogPath(%q, %q) = nil error, want rejection", b.unit, b.path)
for _, tt := range []struct {
name string
unit string
path string
}{
{name: "empty path", unit: "nginx.service", path: ""},
{name: "non-allowlisted path", unit: "nginx.service", path: "/etc/shadow"},
{name: "path traversal", unit: "nginx.service", path: "/var/log/nginx/access.log/../../../etc/shadow"},
{name: "wrong unit", unit: "sshd.service", path: "/var/log/nginx/error.log"},
{name: "unknown unit", unit: "unknown.service", path: "/var/log/nginx/error.log"},
} {
t.Run(tt.name, func(t *testing.T) {
if _, err := resolveLogPath(allow, tt.unit, tt.path); err == nil {
t.Errorf("resolveLogPath(%q, %q) = nil error, want rejection", tt.unit, tt.path)
}
})
}
}
func TestJournalUnit(t *testing.T) {
cases := map[string]string{
"docker.service": "docker",
"docker": "docker",
"sshd.service": "sshd",
"foo.socket": "foo.socket", // only .service is stripped
tests := []struct {
name string
in string
want string
}{
{name: "docker service", in: "docker.service", want: "docker"},
{name: "docker bare", in: "docker", want: "docker"},
{name: "sshd service", in: "sshd.service", want: "sshd"},
{name: "socket unit", in: "foo.socket", want: "foo.socket"},
}
for in, want := range cases {
if got := journalUnit(in); got != want {
t.Errorf("journalUnit(%q) = %q, want %q", in, got, want)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := journalUnit(tt.in); got != tt.want {
t.Errorf("journalUnit(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}
func TestClampLines(t *testing.T) {
cases := map[int]int{0: defaultLogLines, -5: defaultLogLines, 50: 50, 999999: maxLogLines}
for in, want := range cases {
if got := clampLines(in); got != want {
t.Errorf("clampLines(%d) = %d, want %d", in, got, want)
}
tests := []struct {
name string
in int
want int
}{
{name: "zero", in: 0, want: defaultLogLines},
{name: "negative", in: -5, want: defaultLogLines},
{name: "fifty", in: 50, want: 50},
{name: "too large", in: 999999, want: maxLogLines},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := clampLines(tt.in); got != tt.want {
t.Errorf("clampLines(%d) = %d, want %d", tt.in, got, tt.want)
}
})
}
}
+32
View File
@@ -3,14 +3,22 @@ package services
import (
"context"
"encoding/json"
"os/exec"
"regexp"
"strings"
"syscall"
"nadir/internal/oscmd"
"github.com/danielgtaylor/huma/v2"
)
// selfUnit is nadir's own systemd unit name. Acting on it via the normal
// synchronous path would have systemd SIGTERM the very process serving the
// request, so the client sees a dropped connection / 500 even though the
// action succeeded. We detach those calls into a Setsid subprocess instead.
const selfUnit = "nadir"
const tagServices = "Services"
var (
@@ -136,6 +144,9 @@ func registerServices(api huma.API) {
if err := ensureExists(in.Unit); err != nil {
return nil, err
}
if isSelf(in.Unit) {
return runDetached(c.action, in.Unit)
}
if _, err := oscmd.Run("systemctl", c.action, "--", in.Unit); err != nil {
return nil, huma.Error500InternalServerError("systemctl "+c.action+" failed", err)
}
@@ -144,6 +155,27 @@ func registerServices(api huma.API) {
}
}
// isSelf reports whether unit names nadir's own service, with or without the
// .service suffix.
func isSelf(unit string) bool {
return unit == selfUnit || unit == selfUnit+".service"
}
// runDetached fires systemctl in a new session so a "systemctl restart nadir"
// (or stop) doesn't kill its own caller before the HTTP response is written.
// Returns success once the subprocess has *started* — the actual systemd
// operation may complete after the response is sent, which is the whole point.
func runDetached(action, unit string) (*oscmd.StatusOutput, error) {
cmd := exec.Command("systemctl", action, "--", unit)
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
if err := cmd.Start(); err != nil {
return nil, huma.Error500InternalServerError("could not start detached systemctl", err)
}
// Reap in the background so the child doesn't become a zombie.
go cmd.Wait()
return oscmd.OK(), nil
}
// validateUnit guards against empty, flag-like, or malformed unit names.
func validateUnit(unit string) error {
if unit == "" || strings.HasPrefix(unit, "-") || !unitNameRe.MatchString(unit) {
+50 -11
View File
@@ -3,19 +3,58 @@ 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)
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)
}
})
}
}
// 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)
}
// TestIsSelf pins the dispatch that detaches stop/restart-of-self into a
// Setsid subprocess. Both "nadir" and "nadir.service" must match; anything
// else (including substrings) must not, or unrelated services would also get
// detached and bypass the synchronous error path.
func TestIsSelf(t *testing.T) {
for _, tt := range []struct {
name string
value string
want bool
}{
{name: "bare name", value: "nadir", want: true},
{name: "with service suffix", value: "nadir.service", want: true},
{name: "empty", value: "", want: false},
{name: "other service", value: "sshd.service", want: false},
{name: "prefix substring", value: "nadir-something.service", want: false},
{name: "wrong suffix", value: "nadir.timer", want: false},
{name: "suffix mismatch", value: "not-nadir.service", want: false},
} {
t.Run(tt.name, func(t *testing.T) {
if got := isSelf(tt.value); got != tt.want {
t.Errorf("isSelf(%q) = %v, want %v", tt.value, got, tt.want)
}
})
}
}
+32 -7
View File
@@ -6,6 +6,7 @@ import (
"os"
"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 {
+19 -15
View File
@@ -79,23 +79,27 @@ func mustReadFstab(t *testing.T) []FstabEntry {
}
func TestValidateEntry(t *testing.T) {
ok := FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/data", FSType: "ext4", Options: "defaults"}
if err := validateEntry(ok); err != nil {
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 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)
if !tt.valid && err == nil {
t.Errorf("bad entry accepted: %+v", tt.entry)
}
})
}
}
+39 -3
View File
@@ -499,9 +499,12 @@ func diskInfo() []DiskInfo {
disks := []DiskInfo{}
seen := map[string]bool{}
for _, e := range entries {
// Only real block devices; skip pseudo filesystems and snap's squashfs
// loop mounts that would otherwise clutter the list.
if !strings.HasPrefix(e.Device, "/dev/") || e.FSType == "squashfs" || seen[e.Mountpoint] {
// ponytail: filter by fstype, not device path. LXC/Docker containers
// expose their rootfs as a ZFS dataset name, an overlayfs, or a bind
// path — never /dev/* — so a "must start with /dev/" check silently
// returned no disks on those hosts. statfs + non-zero blocks already
// excludes mounts that aren't real storage.
if pseudoFS[e.FSType] || seen[e.Mountpoint] {
continue
}
var st syscall.Statfs_t
@@ -522,6 +525,39 @@ func diskInfo() []DiskInfo {
return disks
}
// pseudoFS lists kernel-virtual filesystems that show up in /proc/mounts but
// aren't user-facing storage. squashfs covers snap loop mounts; fuse.lxcfs is
// LXC's per-container /proc/* shim. Anything not on this list and statfs-able
// with non-zero blocks is treated as real storage — covers ext*, btrfs, xfs,
// zfs, nfs, cifs, overlay, and the bind-mount cases inside Proxmox LXC.
var pseudoFS = map[string]bool{
"autofs": true,
"binfmt_misc": true,
"bpf": true,
"cgroup": true,
"cgroup2": true,
"configfs": true,
"debugfs": true,
"devpts": true,
"devtmpfs": true,
"fuse.gvfsd-fuse": true,
"fuse.lxcfs": true,
"fusectl": true,
"hugetlbfs": true,
"mqueue": true,
"nsfs": true,
"overlay": true,
"proc": true,
"pstore": true,
"ramfs": true,
"rpc_pipefs": true,
"securityfs": true,
"squashfs": true,
"sysfs": true,
"tmpfs": true,
"tracefs": true,
}
func netInfo() []NetInterface {
ifaces, err := net.Interfaces()
if err != nil {
+29 -11
View File
@@ -3,16 +3,34 @@ package system
import "testing"
func TestWhenRe(t *testing.T) {
valid := []string{"now", "+0", "+5", "+120", "0:00", "9:30", "23:59", "07:05"}
for _, w := range valid {
if !whenRe.MatchString(w) {
t.Errorf("whenRe.MatchString(%q) = false, want true", w)
}
}
invalid := []string{"", "-r", "-h", "--help", "24:00", "9:60", "+5; reboot", "now ", "5", "1:2"}
for _, w := range invalid {
if whenRe.MatchString(w) {
t.Errorf("whenRe.MatchString(%q) = true, want false", w)
}
for _, tt := range []struct {
name string
value string
want bool
}{
{name: "now", value: "now", want: true},
{name: "plus zero", value: "+0", want: true},
{name: "plus five", value: "+5", want: true},
{name: "plus 120", value: "+120", want: true},
{name: "0:00", value: "0:00", want: true},
{name: "9:30", value: "9:30", want: true},
{name: "23:59", value: "23:59", want: true},
{name: "07:05", value: "07:05", want: true},
{name: "empty", value: "", want: false},
{name: "flag r", value: "-r", want: false},
{name: "flag h", value: "-h", want: false},
{name: "help", value: "--help", want: false},
{name: "24:00", value: "24:00", want: false},
{name: "9:60", value: "9:60", want: false},
{name: "injected command", value: "+5; reboot", want: false},
{name: "trailing space", value: "now ", want: false},
{name: "just digit", value: "5", want: false},
{name: "single colon", value: "1:2", want: false},
} {
t.Run(tt.name, func(t *testing.T) {
if got := whenRe.MatchString(tt.value); got != tt.want {
t.Errorf("whenRe.MatchString(%q) = %v, want %v", tt.value, got, tt.want)
}
})
}
}
-209
View File
@@ -1,209 +0,0 @@
package terminal
import (
"context"
"encoding/json"
"net/http"
"os/exec"
"strings"
"sync/atomic"
"time"
"nadir/internal/auth"
"nadir/internal/module"
"nadir/internal/rbac"
"github.com/coder/websocket"
"github.com/creack/pty"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
)
// tagTerminal is the OpenAPI tag for this module (registered in server.go),
// keeping tags 1:1 with modules per the project convention.
const tagTerminal = "Terminal"
const (
// maxTerminals caps concurrent shells so a buggy frontend or careless admin
// can't pile up PTYs (guideline: limit everything). Raise if it's ever a real
// limit in practice.
maxTerminals = 10
// idleTimeout closes a session after this long with no I/O in either
// direction, reclaiming abandoned shells.
idleTimeout = 15 * time.Minute
)
// terminalSem is the concurrency limiter; a slot is held for the life of a session.
var terminalSem = make(chan struct{}, maxTerminals)
type terminalModule struct {
sessions *auth.SessionStore
}
// New creates a new Terminal module that allows interactive shell access.
func New(sessions *auth.SessionStore) module.Module {
return &terminalModule{sessions: sessions}
}
func (m *terminalModule) ID() string { return "terminal" }
func (m *terminalModule) Permissions() []rbac.Permission {
return []rbac.Permission{rbac.Root}
}
type TerminalInput struct {
Ctx huma.Context `json:"-"`
}
// Resolve extracts the huma.Context into the input struct.
func (i *TerminalInput) Resolve(ctx huma.Context) []error {
i.Ctx = ctx
return nil
}
type resizeMessage struct {
Cols uint16 `json:"cols"`
Rows uint16 `json:"rows"`
}
func (m *terminalModule) Register(api huma.API) {
huma.Register(api, huma.Operation{
OperationID: "terminal-connect",
Method: "GET",
Path: "/api/terminal",
Summary: "Connect to an interactive terminal",
Description: "Upgrades the connection to a WebSocket and spawns a PTY shell as the logged-in user. Send JSON `{cols, rows}` text messages to resize, and raw binary/text messages for stdin. This is a raw WebSocket endpoint — it cannot be exercised from the API docs \"Try it\" panel; use a WebSocket client.",
Tags: []string{tagTerminal},
Metadata: map[string]any{"module": m.ID(), "permission": string(rbac.Root)},
Errors: []int{401, 403, 426, 500},
}, func(ctx context.Context, in *TerminalInput) (*struct{}, error) {
// The RBAC middleware already authenticated this request and enforced the
// "root" permission before we got here. We re-read the session only to get
// the username for `su`; the 401 below is the fallback for when the module
// is mounted without the middleware (e.g. in unit tests).
cookie, err := huma.ReadCookie(in.Ctx, "nadir_session_id")
if err != nil || cookie == nil {
return nil, huma.Error401Unauthorized("unauthorized")
}
sess, ok := m.sessions.GetByToken(cookie.Value)
if !ok {
return nil, huma.Error401Unauthorized("unauthorized")
}
req, res := humago.Unwrap(in.Ctx)
if req == nil || res == nil {
return nil, huma.Error500InternalServerError("missing http context")
}
// Reject plain GETs (e.g. the docs "Try it" button) with a clear 426 rather
// than letting websocket.Accept emit a raw protocol-violation error.
if !strings.EqualFold(req.Header.Get("Upgrade"), "websocket") {
return nil, huma.NewError(http.StatusUpgradeRequired,
"this endpoint requires a WebSocket connection; connect with a WebSocket client")
}
// InsecureSkipVerify is deliberately NOT set: coder/websocket then enforces
// that the Origin host matches the request Host, rejecting cross-site upgrade
// attempts. Defense-in-depth on top of the SameSite=Strict session cookie —
// important because this endpoint hands out an interactive shell.
conn, err := websocket.Accept(res, req, nil)
if err != nil {
// websocket.Accept already wrote the error response (e.g. 403 on an
// Origin mismatch). Just stop; writing again would corrupt the response.
return nil, nil
}
defer conn.CloseNow()
// Bound concurrent shells: take a slot or reject (don't pile up PTYs).
select {
case terminalSem <- struct{}{}:
defer func() { <-terminalSem }()
default:
conn.Close(websocket.StatusTryAgainLater, "too many terminal sessions")
return nil, nil
}
// Launch the user's login shell via su.
// "su - <username>" ensures we get their actual environment and shell.
cmd := exec.CommandContext(req.Context(), "su", "-", "--", sess.Username)
// Start the command with a PTY.
ptmx, err := pty.Start(cmd)
if err != nil {
conn.Close(websocket.StatusInternalError, "failed to start pty")
return nil, nil
}
defer ptmx.Close()
// lastActive is bumped by both pumps; the watchdog uses it to close idle
// sessions. Output activity (e.g. `top`) counts, so it isn't killed.
var lastActive atomic.Int64
lastActive.Store(time.Now().UnixNano())
go func() {
tick := time.NewTicker(idleTimeout / 4)
defer tick.Stop()
for {
select {
case <-req.Context().Done():
return
case <-tick.C:
if time.Since(time.Unix(0, lastActive.Load())) > idleTimeout {
conn.Close(websocket.StatusGoingAway, "idle timeout")
return
}
}
}
}()
// Pump stdout/stderr from PTY to WebSocket.
go func() {
buf := make([]byte, 8192)
for {
n, err := ptmx.Read(buf)
if err != nil {
break
}
lastActive.Store(time.Now().UnixNano())
// We write PTY output as binary messages. The frontend (e.g., xterm.js)
// can handle UTF-8 binary or text transparently.
err = conn.Write(req.Context(), websocket.MessageBinary, buf[:n])
if err != nil {
break
}
}
conn.Close(websocket.StatusNormalClosure, "")
}()
// Pump stdin and resize commands from WebSocket to PTY.
for {
typ, b, err := conn.Read(req.Context())
if err != nil {
break
}
lastActive.Store(time.Now().UnixNano())
if typ == websocket.MessageText {
var resize resizeMessage
if err := json.Unmarshal(b, &resize); err == nil && resize.Cols > 0 && resize.Rows > 0 {
// Handle resize
_ = pty.Setsize(ptmx, &pty.Winsize{
Cols: resize.Cols,
Rows: resize.Rows,
})
continue
}
}
// If not a valid resize message, or if it's MessageBinary, pass to PTY stdin.
_, _ = ptmx.Write(b)
}
// The read loop has ended (client gone or PTY closed). Tear down the shell
// and reap it: closing the PTY sends EOF, Kill covers shells that ignore it.
_ = ptmx.Close()
_ = cmd.Process.Kill()
_ = cmd.Wait()
return nil, nil
})
}
-124
View File
@@ -1,124 +0,0 @@
package terminal
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"nadir/internal/auth"
"github.com/coder/websocket"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
)
func TestTerminalConnectUnauthorized(t *testing.T) {
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
if err != nil {
t.Fatalf("session db: %v", err)
}
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
mod := New(sessions)
mod.Register(api)
srv := httptest.NewServer(mux)
defer srv.Close()
wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) + "/api/terminal"
// Try without cookie
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
_, resp, err := websocket.Dial(ctx, wsURL, nil)
if err == nil {
t.Fatal("expected error, got success")
}
if resp != nil && resp.StatusCode != http.StatusUnauthorized {
t.Errorf("expected 401, got %d", resp.StatusCode)
}
}
func TestTerminalConnectPlainGET(t *testing.T) {
// An authenticated but non-WebSocket GET (e.g. the docs "Try it" button) must
// get a clean 426 Upgrade Required, not a raw websocket protocol error.
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
if err != nil {
t.Fatalf("session db: %v", err)
}
token, err := sessions.Create("root")
if err != nil {
t.Fatalf("create session: %v", err)
}
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
New(sessions).Register(api)
srv := httptest.NewServer(mux)
defer srv.Close()
req, _ := http.NewRequest(http.MethodGet, srv.URL+"/api/terminal", nil)
req.Header.Set("Cookie", "nadir_session_id="+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("GET failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusUpgradeRequired {
t.Errorf("expected 426, got %d", resp.StatusCode)
}
}
func TestTerminalConnectAuthorized(t *testing.T) {
// Root or specific system configs might cause PTY or su to fail if run in constrained environments.
// But we expect the websocket upgrade to succeed and then maybe close with an error if PTY fails.
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
if err != nil {
t.Fatalf("session db: %v", err)
}
token, err := sessions.Create("root")
if err != nil {
t.Fatalf("create session: %v", err)
}
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
mod := New(sessions)
mod.Register(api)
srv := httptest.NewServer(mux)
defer srv.Close()
wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) + "/api/terminal"
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
opts := &websocket.DialOptions{
HTTPHeader: http.Header{},
}
opts.HTTPHeader.Set("Cookie", "nadir_session_id="+token)
conn, resp, err := websocket.Dial(ctx, wsURL, opts)
if err != nil {
// Depending on the test environment, "su" or "pty" might fail, but
// the websocket upgrade itself should succeed before it drops.
// If it fails to upgrade, that's a real error.
t.Fatalf("dial failed: %v (status %d)", err, resp.StatusCode)
}
defer conn.CloseNow()
// The connection was upgraded successfully.
// If PTY allocation failed or su failed, the server might close the connection immediately.
// We just verify the upgrade succeeded.
if resp.StatusCode != http.StatusSwitchingProtocols {
t.Errorf("expected 101, got %d", resp.StatusCode)
}
}
+11 -3
View File
@@ -8,9 +8,17 @@ import (
const ModuleID = "users"
type Module struct{}
// sessionStore is the subset of SessionStore that password changes need:
// invalidate all existing sessions for a user whose password just changed.
type sessionStore interface {
DeleteByUsername(username string) error
}
func New() *Module { return &Module{} }
type Module struct {
sessions sessionStore
}
func New(sessions sessionStore) *Module { return &Module{sessions: sessions} }
func (m *Module) ID() string { return ModuleID }
@@ -21,7 +29,7 @@ func (m *Module) Permissions() []rbac.Permission {
}
func (m *Module) Register(api huma.API) {
registerUsers(api)
registerUsers(api, m.sessions)
}
func op(permission string) map[string]any {
+13 -7
View File
@@ -2,6 +2,7 @@ package users
import (
"context"
"log"
"os"
"path/filepath"
"regexp"
@@ -91,7 +92,7 @@ type UserGroupsOutput struct {
}
}
func registerUsers(api huma.API) {
func registerUsers(api huma.API, sessions sessionStore) {
huma.Register(api, huma.Operation{
OperationID: "users-list",
Method: "GET",
@@ -105,7 +106,7 @@ func registerUsers(api huma.API) {
}, func(ctx context.Context, _ *struct{}) (*ListUsersOutput, error) {
list, err := listUsers()
if err != nil {
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
return nil, huma.Error500InternalServerError("user lookup failed", err)
}
out := &ListUsersOutput{}
out.Body.Users = list
@@ -127,7 +128,7 @@ func registerUsers(api huma.API) {
}
u, ok, err := lookupUser(in.Username)
if err != nil {
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
return nil, huma.Error500InternalServerError("user lookup failed", err)
}
if !ok {
return nil, huma.Error404NotFound("user not found: " + in.Username)
@@ -163,7 +164,7 @@ func registerUsers(api huma.API) {
return nil, huma.Error400BadRequest("home must be an absolute path")
}
if _, ok, err := lookupUser(in.Body.Username); err != nil {
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
return nil, huma.Error500InternalServerError("user lookup failed", err)
} else if ok {
return nil, huma.Error409Conflict("user already exists: " + in.Body.Username)
}
@@ -212,7 +213,7 @@ func registerUsers(api huma.API) {
return nil, err
}
if _, ok, err := lookupUser(in.Username); err != nil {
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
return nil, huma.Error500InternalServerError("user lookup failed", err)
} else if !ok {
return nil, huma.Error404NotFound("user not found: " + in.Username)
}
@@ -253,7 +254,7 @@ func registerUsers(api huma.API) {
return nil, huma.Error400BadRequest("password may not contain newlines")
}
if _, ok, err := lookupUser(in.Username); err != nil {
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
return nil, huma.Error500InternalServerError("user lookup failed", err)
} else if !ok {
return nil, huma.Error404NotFound("user not found: " + in.Username)
}
@@ -261,6 +262,11 @@ func registerUsers(api huma.API) {
if _, err := oscmd.RunStdin(in.Username+":"+in.Body.Password+"\n", "chpasswd"); err != nil {
return nil, huma.Error500InternalServerError("chpasswd failed", err)
}
if sessions != nil {
if err := sessions.DeleteByUsername(in.Username); err != nil {
log.Printf("failed to invalidate sessions for %s: %v", in.Username, err)
}
}
return oscmd.OK(), nil
})
@@ -290,7 +296,7 @@ func registerUsers(api huma.API) {
}
}
if _, ok, err := lookupUser(in.Username); err != nil {
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
return nil, huma.Error500InternalServerError("user lookup failed", err)
} else if !ok {
return nil, huma.Error404NotFound("user not found: " + in.Username)
}
+1 -1
View File
@@ -28,7 +28,7 @@ func TestUsersHandlers(t *testing.T) {
mux := http.NewServeMux()
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
registerUsers(api)
registerUsers(api, nil)
// 1. Test GET /api/users
resp := api.Get("/api/users")
+29 -21
View File
@@ -28,26 +28,34 @@ short:x:2:2
}
func TestValidateUsername(t *testing.T) {
valid := []string{"alice", "_svc", "user-1", "a", "machine$", "abc_def"}
for _, n := range valid {
if err := validateUsername(n); err != nil {
t.Errorf("validateUsername(%q) = %v, want nil", n, err)
}
}
invalid := []string{
"", // empty
"-rf", // leading dash (flag injection)
"Alice", // uppercase
"1user", // leading digit
"a b", // space
"foo;rm", // shell metachar
"root:x", // colon (passwd separator)
"waytoolongusernamethatexceedsthirtytwochars", // >32
}
for _, n := range invalid {
if err := validateUsername(n); err == nil {
t.Errorf("validateUsername(%q) = nil, want error", n)
}
for _, n := range []struct {
name string
value string
valid bool
}{
{name: "alice", value: "alice", valid: true},
{name: "underscore prefix", value: "_svc", valid: true},
{name: "hyphen", value: "user-1", valid: true},
{name: "single char", value: "a", valid: true},
{name: "dollar suffix", value: "machine$", valid: true},
{name: "underscore", value: "abc_def", valid: true},
{name: "empty", value: "", valid: false},
{name: "leading dash", value: "-rf", valid: false},
{name: "uppercase", value: "Alice", valid: false},
{name: "leading digit", value: "1user", valid: false},
{name: "space", value: "a b", valid: false},
{name: "shell metachar", value: "foo;rm", valid: false},
{name: "colon", value: "root:x", valid: false},
{name: "too long", value: "waytoolongusernamethatexceedsthirtytwochars", valid: false},
} {
t.Run(n.name, func(t *testing.T) {
err := validateUsername(n.value)
if n.valid && err != nil {
t.Errorf("validateUsername(%q) = %v, want nil", n.value, err)
}
if !n.valid && err == nil {
t.Errorf("validateUsername(%q) = nil, want error", n.value)
}
})
}
}
+14 -8
View File
@@ -25,16 +25,22 @@ func TestParseProc(t *testing.T) {
}
func TestUnescape(t *testing.T) {
cases := map[string]string{
`/mnt/my\040disk`: "/mnt/my disk",
`/no/escapes`: "/no/escapes",
`tab\011here`: "tab\there",
`back\134slash`: `back\slash`,
tests := []struct {
name string
in string
want string
}{
{name: "octal space", in: `/mnt/my\040disk`, want: "/mnt/my disk"},
{name: "no escapes", in: `/no/escapes`, want: "/no/escapes"},
{name: "tab", in: `tab\011here`, want: "tab\there"},
{name: "backslash", in: `back\134slash`, want: `back\slash`},
}
for in, want := range cases {
if got := Unescape(in); got != want {
t.Errorf("Unescape(%q) = %q, want %q", in, got, want)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Unescape(tt.in); got != tt.want {
t.Errorf("Unescape(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}
+2 -4
View File
@@ -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()
@@ -60,7 +58,7 @@ func TestOpenAPISchemaNoCollisions(t *testing.T) {
}
meta.Register(api, mods)
meta.RegisterHealth(api, sessions)
meta.RegisterWhoami(api, sessions, roles, mods)
meta.RegisterWhoami(api, sessions, nil, roles, mods)
auth.RegisterLogin(api, sessions, auditStore, true)
auth.RegisterLogout(api, sessions, true)
+43 -35
View File
@@ -41,8 +41,6 @@ func TestRbacMiddleware(t *testing.T) {
},
})
r.AssignRole("alice", "test-role")
// A machine credential is just another RBAC subject: the token name is
// assigned a role exactly like a username.
r.AssignRole("dash", "test-role")
mux := http.NewServeMux()
@@ -76,81 +74,91 @@ func TestRbacMiddleware(t *testing.T) {
return &struct{ Body string }{Body: "gated-write"}, nil
})
// 1. Test public route
t.Run("public route", func(t *testing.T) {
resp := api.Get("/public")
if resp.Code != http.StatusOK {
t.Errorf("public GET: got status %d, want %d", resp.Code, http.StatusOK)
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
}
})
// 2. Test gated route without cookie -> 401 Unauthorized
resp = api.Get("/gated-read")
t.Run("no auth returns 401", func(t *testing.T) {
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.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")
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("gated GET invalid cookie: got status %d, want %d", resp.Code, http.StatusUnauthorized)
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
}
})
// Create valid session
token, err := sessions.Create("alice")
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)
}
// 4. Test gated route with valid cookie -> 200 OK
resp = api.Get("/gated-read", "Cookie: nadir_session_id="+token)
resp := api.Get("/gated-read", "Cookie: nadir_session_id="+aliceToken)
if resp.Code != http.StatusOK {
t.Errorf("gated GET valid cookie: got status %d, want %d", resp.Code, http.StatusOK)
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
}
})
// 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{}{})
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("CSRF mismatched Origin: got status %d, want %d", resp.Code, http.StatusForbidden)
t.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
}
})
// 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{}{})
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("CSRF matching Origin: got status %d, want %d", resp.Code, http.StatusOK)
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
}
})
// 7. Test gated route with unauthorized user -> 403 Forbidden
tokenBob, err := sessions.Create("bob")
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="+tokenBob)
resp := api.Get("/gated-read", "Cookie: nadir_session_id="+bobToken)
if resp.Code != http.StatusForbidden {
t.Errorf("bob unauthorized GET: got status %d, want %d", resp.Code, http.StatusForbidden)
t.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
}
})
// 8. Bearer token for an assigned name -> 200 OK
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)
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.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
}
})
// 9. Bogus bearer token -> 401 Unauthorized
resp = api.Get("/gated-read", "Authorization: Bearer nad_deadbeef")
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("bogus bearer GET: got status %d, want %d", resp.Code, http.StatusUnauthorized)
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
}
})
// 10. Bearer token with no role assignment -> 403 Forbidden
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)
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.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
}
})
}