Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 54108c263f | |||
| 37e5b97507 | |||
| 63c9a272b5 | |||
| 411f7fd6d9 | |||
| 8fc4b236ac | |||
| 37f03816e1 | |||
| 541260e65e | |||
| c4180bada1 | |||
| 088880f584 | |||
| 67d95475ee | |||
| aec04bfe02 | |||
| a54c42271c | |||
| b10abb24e3 | |||
| 9587d11e21 | |||
| ac196e720b | |||
| a106b7413f | |||
| 0e041fac5e |
@@ -10,13 +10,22 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # svu needs full history + tags
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.26'
|
||||
go-version: "1.26"
|
||||
cache: false
|
||||
|
||||
- name: Install PAM headers (needed by go test)
|
||||
run: sudo apt-get update && sudo apt-get install -y libpam0g-dev
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
set -ex
|
||||
go vet ./...
|
||||
go test ./...
|
||||
|
||||
- name: Install svu
|
||||
timeout-minutes: 3
|
||||
run: |
|
||||
@@ -87,6 +96,19 @@ jobs:
|
||||
go build -ldflags="$LDFLAGS" -o dist/nadir-$VERSION-linux-arm64 ./cmd/server
|
||||
upx --best --lzma dist/nadir-$VERSION-linux-amd64 dist/nadir-$VERSION-linux-arm64
|
||||
|
||||
- name: Sign checksums
|
||||
if: steps.ver.outputs.release == 'true'
|
||||
env:
|
||||
MINISIGN_SECRET_KEY: ${{ secrets.MINISIGN_SECRET_KEY }}
|
||||
MINISIGN_PASSWORD: ${{ secrets.MINISIGN_PASSWORD }}
|
||||
run: |
|
||||
set -ex
|
||||
cd dist
|
||||
sha256sum nadir-* > sha256sums.txt
|
||||
cat sha256sums.txt
|
||||
go run ../tools/sign-checksums sha256sums.txt
|
||||
ls -la sha256sums.txt sha256sums.txt.minisig
|
||||
|
||||
- name: Tag and release
|
||||
if: steps.ver.outputs.release == 'true'
|
||||
env:
|
||||
|
||||
+3
-1
@@ -11,4 +11,6 @@ config.yml
|
||||
# Editor
|
||||
*.swp
|
||||
|
||||
CLAUDE.md
|
||||
CLAUDE.md
|
||||
|
||||
minisign.key
|
||||
@@ -31,7 +31,6 @@ API and declares its own permission vocabulary.
|
||||
and upgrade - streamed live over SSE. Auto-detects `dnf`, `apt`, or `pacman`.
|
||||
- **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
|
||||
|
||||
@@ -28,3 +28,14 @@ var InstallScriptTemplate string
|
||||
// go build -ldflags "-X nadir.Version=v1.2.3"
|
||||
// Local dev builds leave it as "dev".
|
||||
var Version = "dev"
|
||||
|
||||
// ReleasePublicKey is the minisign public key whose signature on a release's
|
||||
// sha256sums.txt is required by the auto-updater. Replacing the binary is the
|
||||
// most dangerous thing nadir does, so it gets the strongest verification: the
|
||||
// updater downloads sha256sums.txt + .minisig from the configured Gitea repo,
|
||||
// verifies the signature against this embedded key, then verifies the binary's
|
||||
// sha256 against the file. Rotation requires a rebuild — intentional, so a
|
||||
// compromised Gitea instance cannot also rotate the trust anchor.
|
||||
//
|
||||
//go:embed minisign.pub
|
||||
var ReleasePublicKey string
|
||||
|
||||
+99
-14
@@ -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,9 +244,8 @@ func runServer() {
|
||||
|
||||
meta.Register(api, mods)
|
||||
meta.RegisterHealth(api, sessions)
|
||||
meta.RegisterWhoami(api, sessions, roles, mods)
|
||||
meta.ConfigPath = configPath
|
||||
meta.RegisterUpdate(api)
|
||||
meta.RegisterWhoami(api, sessions, tokenAuth, roles, mods)
|
||||
meta.RegisterUpdate(api, configPath)
|
||||
|
||||
auth.RegisterLogin(api, sessions, auditStore, cfg.SecureCookie())
|
||||
auth.RegisterLogout(api, sessions, cfg.SecureCookie())
|
||||
@@ -272,12 +277,24 @@ 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 pinned
|
||||
// jsdelivr CDN version + inline (Scalar uses inline <script> + inline styles).
|
||||
// unsafe-eval is removed Scalar does not need it. The CDN host is the
|
||||
// supply-chain trust boundary; SRI pinning would close the remaining gap.
|
||||
w.Header().Set("Content-Security-Policy",
|
||||
"default-src 'self'; "+
|
||||
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
|
||||
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
|
||||
"img-src 'self' data: https:; "+
|
||||
"connect-src 'self'; "+
|
||||
"font-src 'self' data: https://cdn.jsdelivr.net https://fonts.scalar.com")
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Write([]byte(`<!doctype html><html><head><title>API</title>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg"></head>
|
||||
<body><script id="api-reference" data-url="/openapi.json" data-configuration='{"layout":"classic"}'></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script></body></html>`))
|
||||
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference" crossorigin="anonymous"></script></body></html>`))
|
||||
})
|
||||
|
||||
addr := cfg.Server.Hostname + ":" + cfg.Server.Port
|
||||
@@ -286,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: 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
|
||||
@@ -296,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)
|
||||
}
|
||||
@@ -314,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() {
|
||||
@@ -343,6 +371,63 @@ func runServer() {
|
||||
}
|
||||
}
|
||||
|
||||
// bodySizeLimit rejects requests with a body larger than 1 MB, preventing
|
||||
// OOM from arbitrarily large JSON payloads. Wraps the entire mux so it
|
||||
// covers both Huma-registered routes and raw mux handlers (/docs, /install.sh).
|
||||
func bodySizeLimit(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// requestTimeout cancels slow requests via context deadline. SSE endpoints
|
||||
// (package streams, log following) are exempt because they keep the
|
||||
// connection open indefinitely.
|
||||
func requestTimeout(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if isSSEEndpoint(r) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// isSSEEndpoint identifies routes that stream data indefinitely and must
|
||||
// not have a context deadline.
|
||||
func isSSEEndpoint(r *http.Request) bool {
|
||||
if strings.HasPrefix(r.URL.Path, "/api/packages") {
|
||||
return r.Method == "POST" || r.Method == "DELETE"
|
||||
}
|
||||
return r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/logs/stream")
|
||||
}
|
||||
|
||||
// secHeaders sets defensive response headers on every HTTP response. The
|
||||
// default Content-Security-Policy denies everything (`default-src 'none'`) —
|
||||
// correct for the JSON API and the tiny landing/favicon endpoints. /docs
|
||||
// overrides it with a CDN-permissive policy because the Scalar bundle needs
|
||||
// to execute.
|
||||
//
|
||||
// HSTS is set unconditionally: nadir always serves TLS directly or sits behind
|
||||
// a TLS-terminating proxy (config rejects any other shape), so a browser
|
||||
// receiving this header is on an HTTPS connection.
|
||||
func secHeaders(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h := w.Header()
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("X-Frame-Options", "DENY")
|
||||
h.Set("Referrer-Policy", "no-referrer")
|
||||
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
|
||||
h.Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")
|
||||
h.Set("Cache-Control", "no-store, no-cache, must-revalidate, private")
|
||||
h.Set("Pragma", "no-cache")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func ensureRoot() {
|
||||
if os.Getuid() != 0 {
|
||||
fatalIf(fmt.Errorf("nadir must run as root"))
|
||||
|
||||
+143
-27
@@ -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
|
||||
}
|
||||
|
||||
@@ -415,19 +528,22 @@ func usage(w io.Writer) {
|
||||
fmt.Fprint(w, `nadir - Linux system administration backend
|
||||
|
||||
Usage:
|
||||
nadir [run] [-d] [-f <path>] Start the server (-d / --detach: run in background)
|
||||
nadir --save-config [-f <path>] Save default configuration to path and exit
|
||||
nadir install [-f <path>] Install + enable the systemd service (starts on boot)
|
||||
nadir uninstall [--complete] Remove the service (keeps data/config; --complete wipes all)
|
||||
nadir start|stop|restart|status Control the running service
|
||||
nadir enable|disable Toggle start-on-boot without removing the unit
|
||||
nadir logs [clear] Follow (default) or clear server logs
|
||||
nadir token add <name> Mint a machine credential (Bearer token), shown once
|
||||
nadir token rm <name> Revoke a token (effective immediately, no restart)
|
||||
nadir token ls List token names and when they were created
|
||||
nadir update [--check|--force] Fetch the latest release from server.release_repo and restart
|
||||
(--check: report only; --force: re-download when already current)
|
||||
nadir help Show this help
|
||||
nadir [run] [-d] [-f <path>] Start the server (-d / --detach: run in background)
|
||||
nadir --save-config [-f <path>] Save default configuration to path and exit
|
||||
nadir install [--tls|--unsecure|--trust-proxy] Install + enable the systemd service (starts on boot)
|
||||
(--tls: enable HTTPS with self-signed certificate)
|
||||
(--unsecure: serve HTTP directly, default)
|
||||
(--trust-proxy: serve HTTP behind a reverse proxy)
|
||||
nadir uninstall [--complete] Remove the service (keeps data/config; --complete wipes all)
|
||||
nadir start|stop|restart|status Control the running service
|
||||
nadir enable|disable Toggle start-on-boot without removing the unit
|
||||
nadir logs [clear] Follow (default) or clear server logs
|
||||
nadir token add <name> Mint a machine credential (Bearer token), shown once
|
||||
nadir token rm <name> Revoke a token (effective immediately, no restart)
|
||||
nadir token ls List token names and when they were created
|
||||
nadir update [--check|--force] Fetch the latest release from server.release_repo and restart
|
||||
(--check: report only; --force: re-download when already current)
|
||||
nadir help Show this help
|
||||
|
||||
Most commands need root. Config path is specified via -f/--config or CONFIG_PATH (default ~/.config/config.yaml).
|
||||
`)
|
||||
|
||||
+56
-24
@@ -1,46 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"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) {
|
||||
priv, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
// 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,
|
||||
@@ -48,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
|
||||
}
|
||||
|
||||
+136
-3
@@ -1,6 +1,8 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
@@ -15,10 +17,13 @@ import (
|
||||
|
||||
"nadir"
|
||||
"nadir/internal/config"
|
||||
|
||||
"github.com/jedisct1/go-minisign"
|
||||
)
|
||||
|
||||
// updateCmd implements `nadir update`: hit the configured Gitea repo's
|
||||
// releases/latest, pick the asset for the host's GOARCH, atomically replace
|
||||
// releases/latest, pick the asset for the host's GOARCH, verify the release
|
||||
// signature (minisign) and checksum (SHA-256), atomically replace
|
||||
// /usr/local/bin/nadir (or wherever the running binary lives), and restart
|
||||
// the systemd unit so the new code takes effect.
|
||||
func updateCmd(args []string) error {
|
||||
@@ -66,16 +71,25 @@ func updateCmd(args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Locate the binary asset and the two verification assets in the release.
|
||||
var assetURL, assetName string
|
||||
var sumsURL, sigURL string
|
||||
for _, a := range rel.Assets {
|
||||
if strings.HasSuffix(a.Name, suffix) {
|
||||
switch {
|
||||
case strings.HasSuffix(a.Name, suffix):
|
||||
assetURL, assetName = a.URL, a.Name
|
||||
break
|
||||
case a.Name == "sha256sums.txt":
|
||||
sumsURL = a.URL
|
||||
case a.Name == "sha256sums.txt.minisig":
|
||||
sigURL = a.URL
|
||||
}
|
||||
}
|
||||
if assetURL == "" {
|
||||
return fmt.Errorf("no %s asset in release %s", suffix, rel.TagName)
|
||||
}
|
||||
if sumsURL == "" || sigURL == "" {
|
||||
return fmt.Errorf("release %s is missing sha256sums.txt or sha256sums.txt.minisig — cannot verify; refusing to install an unverified binary", rel.TagName)
|
||||
}
|
||||
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
@@ -88,6 +102,15 @@ func updateCmd(args []string) error {
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
|
||||
// Verify: download checksums + signature, check minisign, check SHA-256.
|
||||
fmt.Println("verifying release signature ...")
|
||||
if err := verifyRelease(tmp, assetName, sumsURL, sigURL); err != nil {
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("verification failed: %w", err)
|
||||
}
|
||||
fmt.Println("signature and checksum OK.")
|
||||
|
||||
// Atomic on the same filesystem; replaces the on-disk file without
|
||||
// disturbing the still-running process (its inode stays alive).
|
||||
if err := os.Rename(tmp, exe); err != nil {
|
||||
@@ -103,6 +126,113 @@ func updateCmd(args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyRelease downloads sha256sums.txt + its minisig from the release,
|
||||
// verifies the signature against the embedded public key, then checks the
|
||||
// downloaded binary's SHA-256 against the matching line in the checksums file.
|
||||
func verifyRelease(binaryPath, assetName, sumsURL, sigURL string) error {
|
||||
// Parse the embedded public key. The placeholder file will fail here
|
||||
// (no valid base64 line), which is the desired behavior: updates are
|
||||
// disabled until a real key is committed.
|
||||
pubKey, err := minisign.DecodePublicKey(nadir.ReleasePublicKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("embedded minisign public key is invalid (is minisign.pub still the placeholder?): %w", err)
|
||||
}
|
||||
|
||||
// Download the checksums file and its signature.
|
||||
sumsBody, err := downloadBytes(sumsURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("download sha256sums.txt: %w", err)
|
||||
}
|
||||
sigBody, err := downloadBytes(sigURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("download sha256sums.txt.minisig: %w", err)
|
||||
}
|
||||
|
||||
// Verify the minisign signature on the checksums file.
|
||||
sig, err := minisign.DecodeSignature(string(sigBody))
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode minisig: %w", err)
|
||||
}
|
||||
ok, err := pubKey.Verify(sumsBody, sig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("minisign verify: %w", err)
|
||||
}
|
||||
if !ok {
|
||||
return fmt.Errorf("minisign signature is not valid for this sha256sums.txt")
|
||||
}
|
||||
|
||||
// Find the expected hash for our binary in the signed checksums file.
|
||||
expectedHash, err := findChecksum(string(sumsBody), assetName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Hash the downloaded binary and compare.
|
||||
actualHash, err := sha256File(binaryPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("hash downloaded binary: %w", err)
|
||||
}
|
||||
if actualHash != expectedHash {
|
||||
return fmt.Errorf("SHA-256 mismatch for %s: expected %s, got %s", assetName, expectedHash, actualHash)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// findChecksum parses a sha256sums.txt body (one "hash filename\n" per line)
|
||||
// and returns the hex hash for the named asset.
|
||||
func findChecksum(sums, assetName string) (string, error) {
|
||||
for _, line := range strings.Split(sums, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
// Standard sha256sum output: "<hex> <filename>" (two spaces).
|
||||
parts := strings.SplitN(line, " ", 2)
|
||||
if len(parts) != 2 {
|
||||
// Also accept single-space separation.
|
||||
parts = strings.SplitN(line, " ", 2)
|
||||
}
|
||||
if len(parts) == 2 && strings.TrimSpace(parts[1]) == assetName {
|
||||
h := strings.TrimSpace(parts[0])
|
||||
if len(h) != 64 {
|
||||
return "", fmt.Errorf("sha256sums.txt: invalid hash length for %s: %q", assetName, h)
|
||||
}
|
||||
return strings.ToLower(h), nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("sha256sums.txt does not contain a hash for %s", assetName)
|
||||
}
|
||||
|
||||
// sha256File returns the lowercase hex SHA-256 of the file at path.
|
||||
func sha256File(path string) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// downloadBytes fetches a URL and returns its body as a byte slice (for small
|
||||
// files like sha256sums.txt and .minisig).
|
||||
func downloadBytes(srcURL string) ([]byte, error) {
|
||||
c := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := c.Get(srcURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("GET %s: %s", srcURL, resp.Status)
|
||||
}
|
||||
// Cap read to 1 MB — sha256sums.txt and .minisig are tiny.
|
||||
return io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
}
|
||||
|
||||
type giteaRelease struct {
|
||||
TagName string `json:"tag_name"`
|
||||
Assets []struct {
|
||||
@@ -136,6 +266,9 @@ func releaseAPIURL(repoURL string) (string, error) {
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("release_repo: %w", err)
|
||||
}
|
||||
if u.Scheme != "https" {
|
||||
return "", fmt.Errorf("release_repo must use https:// (got %q) — auto-update downloads and executes the binary, plaintext would let any on-path attacker replace it", repoURL)
|
||||
}
|
||||
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return "", fmt.Errorf("release_repo must look like https://host/owner/repo, got %q", repoURL)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestReleaseAPIURL pins the contract that downstream code (the updater and
|
||||
// /install.sh) relies on: only https://host/owner/repo produces an API URL,
|
||||
// everything else errors. Plain HTTP must be rejected — M7 makes auto-update
|
||||
// only trust TLS-protected release feeds, since the binary it downloads is
|
||||
// exec'd as root.
|
||||
func TestReleaseAPIURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
wantErr string // substring expected in the error message; "" means success
|
||||
}{
|
||||
{
|
||||
name: "valid https repo",
|
||||
in: "https://tea.example.com/owner/repo",
|
||||
want: "https://tea.example.com/api/v1/repos/owner/repo/releases/latest",
|
||||
},
|
||||
{
|
||||
name: "http rejected",
|
||||
in: "http://tea.example.com/owner/repo",
|
||||
wantErr: "https",
|
||||
},
|
||||
{
|
||||
name: "ssh scheme rejected",
|
||||
in: "ssh://tea.example.com/owner/repo",
|
||||
wantErr: "https",
|
||||
},
|
||||
{
|
||||
name: "missing repo segment",
|
||||
in: "https://tea.example.com/owner",
|
||||
wantErr: "owner/repo",
|
||||
},
|
||||
{
|
||||
name: "extra path segments",
|
||||
in: "https://tea.example.com/owner/repo/extra",
|
||||
wantErr: "owner/repo",
|
||||
},
|
||||
{
|
||||
name: "empty",
|
||||
in: "",
|
||||
wantErr: "https",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := releaseAPIURL(tt.in)
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Errorf("got %q, want %q", got, tt.want)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatalf("expected error containing %q, got nil (result %q)", tt.wantErr, got)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Errorf("error %q does not contain %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -9,17 +9,18 @@ require github.com/danielgtaylor/huma/v2 v2.38.0
|
||||
require (
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
modernc.org/sqlite v1.52.0
|
||||
github.com/coder/websocket v1.8.15
|
||||
github.com/creack/pty v1.1.24
|
||||
)
|
||||
|
||||
require (
|
||||
aead.dev/minisign v0.3.0
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/jedisct1/go-minisign v0.0.0-20260527172527-a09352b57a22
|
||||
github.com/mattn/go-isatty v0.0.21 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/sys v0.43.0 // indirect
|
||||
golang.org/x/crypto v0.52.0 // indirect
|
||||
golang.org/x/sys v0.45.0 // indirect
|
||||
modernc.org/libc v1.72.3 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
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=
|
||||
aead.dev/minisign v0.3.0 h1:8Xafzy5PEVZqYDNP60yJHARlW1eOQtsKNp/Ph2c0vRA=
|
||||
aead.dev/minisign v0.3.0/go.mod h1:NLvG3Uoq3skkRMDuc3YHpWUTMTrSExqm+Ij73W13F6Y=
|
||||
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=
|
||||
@@ -16,6 +14,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/jedisct1/go-minisign v0.0.0-20260527172527-a09352b57a22 h1:C68TAi+k12EKJCAmsdaERzQ22ZxVE6n+CuB3kOkhQ7c=
|
||||
github.com/jedisct1/go-minisign v0.0.0-20260527172527-a09352b57a22/go.mod h1:vYVVh81Lqe/TP0sPLjiNYcX9Hxy/YSfkUx96lYJeyKo=
|
||||
github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs=
|
||||
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/msteinert/pam v1.2.0 h1:mYfjlvN2KYs2Pb9G6nb/1f/nPfAttT/Jee5Sq9r3bGE=
|
||||
@@ -30,14 +30,16 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
|
||||
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
|
||||
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
|
||||
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=
|
||||
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
|
||||
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
|
||||
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
||||
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
||||
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
||||
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
|
||||
@@ -60,6 +60,40 @@ do_install() {
|
||||
|
||||
echo "downloading $asset_url ..."
|
||||
curl -f --progress-bar -L "$asset_url" -o /usr/local/bin/nadir.tmp
|
||||
|
||||
asset_name=$(basename "$asset_url")
|
||||
|
||||
# Verify SHA-256: download the checksums file published alongside the binary
|
||||
# and confirm the hash matches. This catches CDN corruption and (together with
|
||||
# the HTTPS transport) makes tampered binaries detectable.
|
||||
sums_url="$host/api/v1/repos/$path/releases/latest"
|
||||
sums_asset_url=$(curl -fsSL "$sums_url" \
|
||||
| grep -o '"browser_download_url":"[^"]*sha256sums\.txt"' \
|
||||
| head -n1 \
|
||||
| cut -d'"' -f4)
|
||||
|
||||
if [ -n "$sums_asset_url" ]; then
|
||||
echo "verifying checksum ..."
|
||||
curl -fsSL "$sums_asset_url" -o /tmp/nadir-sha256sums.txt
|
||||
# Extract the expected hash for our asset and compare.
|
||||
expected=$(grep "$asset_name" /tmp/nadir-sha256sums.txt | awk '{print $1}')
|
||||
actual=$(sha256sum /usr/local/bin/nadir.tmp | awk '{print $1}')
|
||||
rm -f /tmp/nadir-sha256sums.txt
|
||||
if [ -z "$expected" ]; then
|
||||
echo "warning: sha256sums.txt does not contain a hash for $asset_name" >&2
|
||||
echo "proceeding without verification" >&2
|
||||
elif [ "$expected" != "$actual" ]; then
|
||||
echo "SHA-256 MISMATCH: expected $expected, got $actual" >&2
|
||||
echo "the downloaded binary may be corrupted or tampered with — aborting" >&2
|
||||
rm -f /usr/local/bin/nadir.tmp
|
||||
exit 1
|
||||
else
|
||||
echo "checksum OK ($actual)"
|
||||
fi
|
||||
else
|
||||
echo "warning: no sha256sums.txt in release — skipping verification" >&2
|
||||
fi
|
||||
|
||||
mv /usr/local/bin/nadir.tmp /usr/local/bin/nadir
|
||||
chmod +x /usr/local/bin/nadir
|
||||
|
||||
|
||||
+23
-11
@@ -3,6 +3,7 @@ package auth
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"nadir/internal/auditlog"
|
||||
@@ -10,6 +11,11 @@ import (
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
)
|
||||
|
||||
// loginNameRe is the useradd default NAME_REGEX. Validating at this trust
|
||||
// boundary keeps a flag-like name (e.g. "-c", "--help") from reaching `su` in
|
||||
// showing up verbatim in audit logs / throttle keys.
|
||||
var loginNameRe = regexp.MustCompile(`^[a-z_][a-z0-9_-]{0,31}\$?$`)
|
||||
|
||||
// authenticator verifies a username/password (PAM in production). It's a field
|
||||
// of the login handler rather than a package global so tests can inject a stub
|
||||
// without mutating shared state.
|
||||
@@ -37,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) {
|
||||
@@ -53,6 +60,11 @@ func registerLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store
|
||||
Tags: []string{"Authentication"},
|
||||
Errors: []int{401, 429},
|
||||
}, func(ctx context.Context, in *LoginInput) (*LoginOutput, error) {
|
||||
// Reject malformed usernames at the trust boundary so PAM, su, and the
|
||||
// audit log never see flag-like or shell-metacharacter input.
|
||||
if !loginNameRe.MatchString(in.Body.Username) {
|
||||
return nil, huma.Error401Unauthorized("invalid credentials")
|
||||
}
|
||||
// Throttle brute force: too many recent failures for this account/source
|
||||
// put it in a short cooldown before the password is even checked.
|
||||
throttleKey := in.Body.Username + "|" + ClientIP(ctx)
|
||||
@@ -74,15 +86,15 @@ func registerLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store
|
||||
return nil, huma.Error500InternalServerError("could not create session", err)
|
||||
}
|
||||
out := &LoginOutput{
|
||||
SetCookie: http.Cookie{
|
||||
Name: "nadir_session_id",
|
||||
Value: sessionID,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Expires: time.Now().Add(24 * time.Hour),
|
||||
},
|
||||
SetCookie: http.Cookie{
|
||||
Name: "nadir_session_id",
|
||||
Value: sessionID,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
MaxAge: 86400,
|
||||
},
|
||||
}
|
||||
out.Body.Status = "logged in"
|
||||
return out, nil
|
||||
|
||||
+78
-82
@@ -68,110 +68,106 @@ func TestLoginLogoutThrottling(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
|
||||
|
||||
// Inject a stub authenticator and a short-window throttle (3 failures) at
|
||||
// registration — no package globals to mutate. The throttle keys on
|
||||
// username+IP, so the success/failure cases below and the throttle case (a
|
||||
// distinct user) don't interfere.
|
||||
authMock := func(username, password string) error {
|
||||
if password == "correct" {
|
||||
return nil
|
||||
}
|
||||
return errors.New("pam error")
|
||||
}
|
||||
registerLogin(api, sessions, auditStore, false, authMock, newFailLimiter(3, 500*time.Millisecond))
|
||||
throttle := newFailLimiter(3, 500*time.Millisecond)
|
||||
registerLogin(api, sessions, auditStore, false, authMock, throttle)
|
||||
RegisterLogout(api, sessions, false)
|
||||
|
||||
// 1. Test failed login
|
||||
resp := api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "admin",
|
||||
Password: "wrong",
|
||||
t.Run("failed login returns 401", func(t *testing.T) {
|
||||
resp := api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "admin",
|
||||
Password: "wrong",
|
||||
})
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("got code %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
})
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("failed login: got code %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
// 2. Test successful login
|
||||
resp = api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "admin",
|
||||
Password: "correct",
|
||||
})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("successful login: got code %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
cookieHeader := resp.Header().Get("Set-Cookie")
|
||||
if !strings.Contains(cookieHeader, "nadir_session_id=") {
|
||||
t.Fatalf("Set-Cookie header missing nadir_session_id: %q", cookieHeader)
|
||||
}
|
||||
|
||||
var sessionID string
|
||||
parts := strings.SplitSeq(cookieHeader, ";")
|
||||
for part := range parts {
|
||||
part = strings.TrimSpace(part)
|
||||
if after, ok := strings.CutPrefix(part, "nadir_session_id="); ok {
|
||||
sessionID = after
|
||||
break
|
||||
t.Run("successful login returns session cookie", func(t *testing.T) {
|
||||
resp := api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "admin",
|
||||
Password: "correct",
|
||||
})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Fatalf("got code %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
if sessionID == "" {
|
||||
t.Fatal("nadir_session_id cookie not found")
|
||||
}
|
||||
cookieHeader := resp.Header().Get("Set-Cookie")
|
||||
if !strings.Contains(cookieHeader, "nadir_session_id=") {
|
||||
t.Fatalf("Set-Cookie header missing nadir_session_id: %q", cookieHeader)
|
||||
}
|
||||
|
||||
_, ok := sessions.GetByToken(sessionID)
|
||||
if !ok {
|
||||
t.Fatal("session not found in session store")
|
||||
}
|
||||
parts := strings.SplitSeq(cookieHeader, ";")
|
||||
for part := range parts {
|
||||
part = strings.TrimSpace(part)
|
||||
if after, ok := strings.CutPrefix(part, "nadir_session_id="); ok {
|
||||
sessionID = after
|
||||
break
|
||||
}
|
||||
}
|
||||
if sessionID == "" {
|
||||
t.Fatal("nadir_session_id cookie not found")
|
||||
}
|
||||
if _, ok := sessions.GetByToken(sessionID); !ok {
|
||||
t.Fatal("session not found in session store")
|
||||
}
|
||||
})
|
||||
|
||||
// 3. Test logout
|
||||
resp = api.Post("/api/logout", "Cookie: nadir_session_id="+sessionID, struct{}{})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("logout failed: got code %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
t.Run("logout invalidates session", func(t *testing.T) {
|
||||
resp := api.Post("/api/logout", "Cookie: nadir_session_id="+sessionID, struct{}{})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Fatalf("logout failed: got code %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
if _, ok := sessions.GetByToken(sessionID); ok {
|
||||
t.Fatal("session still valid after logout")
|
||||
}
|
||||
})
|
||||
|
||||
_, ok = sessions.GetByToken(sessionID)
|
||||
if ok {
|
||||
t.Fatal("session still valid after logout")
|
||||
}
|
||||
|
||||
// 4. Test throttling (the handler was registered with a 3-failure limiter).
|
||||
for range 3 {
|
||||
api.Post("/api/login", struct {
|
||||
t.Run("throttling blocks after 3 failures", func(t *testing.T) {
|
||||
for range 3 {
|
||||
api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "throttled-user",
|
||||
Password: "wrong",
|
||||
})
|
||||
}
|
||||
resp := api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "throttled-user",
|
||||
Password: "wrong",
|
||||
Password: "correct",
|
||||
})
|
||||
}
|
||||
|
||||
resp = api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "throttled-user",
|
||||
Password: "correct",
|
||||
if resp.Code != http.StatusTooManyRequests {
|
||||
t.Errorf("got code %d, want %d", resp.Code, http.StatusTooManyRequests)
|
||||
}
|
||||
})
|
||||
if resp.Code != http.StatusTooManyRequests {
|
||||
t.Errorf("throttled login: got code %d, want %d", resp.Code, http.StatusTooManyRequests)
|
||||
}
|
||||
|
||||
time.Sleep(600 * time.Millisecond)
|
||||
|
||||
resp = api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "throttled-user",
|
||||
Password: "correct",
|
||||
t.Run("throttle reset allows login", func(t *testing.T) {
|
||||
throttle.reset("throttled-user|")
|
||||
resp := api.Post("/api/login", struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
Username: "throttled-user",
|
||||
Password: "correct",
|
||||
})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("got code %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("login after cooldown: got code %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
)
|
||||
|
||||
// RateLimiter provides per-IP rate limiting for authenticated API endpoints,
|
||||
// complementing the login-specific failLimiter with a broader cap on all
|
||||
// requests. The window aligns to wall-clock intervals so all IPs share the
|
||||
// same boundary.
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
buckets map[string]*tokenBucket
|
||||
limit int
|
||||
interval time.Duration
|
||||
}
|
||||
|
||||
type tokenBucket struct {
|
||||
count int
|
||||
windowEnd time.Time
|
||||
}
|
||||
|
||||
const maxRateLimitKeys = 10000
|
||||
|
||||
func NewRateLimiter(limit int, interval time.Duration) *RateLimiter {
|
||||
return &RateLimiter{
|
||||
buckets: map[string]*tokenBucket{},
|
||||
limit: limit,
|
||||
interval: interval,
|
||||
}
|
||||
}
|
||||
|
||||
// Allow reports whether ip may make a request now. Returns false when the
|
||||
// limit is exceeded OR the map is full (fail-closed).
|
||||
func (l *RateLimiter) Allow(ip string) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
b, ok := l.buckets[ip]
|
||||
if !ok || now.After(b.windowEnd) {
|
||||
if len(l.buckets) >= maxRateLimitKeys {
|
||||
return false
|
||||
}
|
||||
l.buckets[ip] = &tokenBucket{count: 1, windowEnd: now.Add(l.interval)}
|
||||
return true
|
||||
}
|
||||
if b.count >= l.limit {
|
||||
return false
|
||||
}
|
||||
b.count++
|
||||
return true
|
||||
}
|
||||
|
||||
// RateLimitMiddleware returns Huma middleware that rejects requests exceeding
|
||||
// the per-IP rate limit with 429 Too Many Requests. It runs before the RBAC
|
||||
// check so abusive IPs are dropped early. The IP is read from the context set
|
||||
// by WithClientIP; if absent the request passes through unthrottled.
|
||||
func RateLimitMiddleware(api huma.API, rl *RateLimiter) func(huma.Context, func(huma.Context)) {
|
||||
return func(ctx huma.Context, next func(huma.Context)) {
|
||||
ip := ClientIP(ctx.Context())
|
||||
if ip != "" && !rl.Allow(ip) {
|
||||
huma.WriteErr(api, ctx, http.StatusTooManyRequests, "rate limit exceeded, try again later")
|
||||
return
|
||||
}
|
||||
next(ctx)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
@@ -12,7 +13,7 @@ import (
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
const sessionTTL = 24 * time.Hour
|
||||
var sessionTTL = 24 * time.Hour
|
||||
|
||||
type Session struct {
|
||||
Username string
|
||||
@@ -45,6 +46,17 @@ func NewSessionStore(path string) (*SessionStore, error) {
|
||||
)`); err != nil {
|
||||
return nil, fmt.Errorf("create sessions table: %w", err)
|
||||
}
|
||||
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS throttle (
|
||||
key TEXT PRIMARY KEY,
|
||||
count INTEGER NOT NULL,
|
||||
until INTEGER NOT NULL
|
||||
)`); err != nil {
|
||||
return nil, fmt.Errorf("create throttle table: %w", err)
|
||||
}
|
||||
// Restrict the DB file so only the owning user (root) can read it.
|
||||
if err := os.Chmod(path, 0600); err != nil {
|
||||
return nil, fmt.Errorf("chmod session db: %w", err)
|
||||
}
|
||||
return &SessionStore{db: db}, nil
|
||||
}
|
||||
|
||||
@@ -57,7 +69,7 @@ func (s *SessionStore) Create(username string) (string, error) {
|
||||
expires := time.Now().Add(sessionTTL)
|
||||
if _, err := s.db.Exec(
|
||||
`INSERT INTO sessions (token, username, expires_at) VALUES (?, ?, ?)`,
|
||||
token, username, expires.Unix(),
|
||||
hashSessionToken(token), username, expires.Unix(),
|
||||
); err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -67,26 +79,75 @@ func (s *SessionStore) Create(username string) (string, error) {
|
||||
// Delete removes a session, invalidating it immediately (logout). Deleting an
|
||||
// unknown token is a no-op.
|
||||
func (s *SessionStore) Delete(token string) error {
|
||||
_, err := s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token)
|
||||
_, err := s.db.Exec(`DELETE FROM sessions WHERE token = ?`, hashSessionToken(token))
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteByUsername removes every session for the given user, used when a
|
||||
// password change should invalidate all existing sessions.
|
||||
func (s *SessionStore) DeleteByUsername(username string) error {
|
||||
_, err := s.db.Exec(`DELETE FROM sessions WHERE username = ?`, username)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SessionStore) GetByToken(token string) (Session, bool) {
|
||||
var username string
|
||||
var expires int64
|
||||
h := hashSessionToken(token)
|
||||
err := s.db.QueryRow(
|
||||
`SELECT username, expires_at FROM sessions WHERE token = ?`, token,
|
||||
`SELECT username, expires_at FROM sessions WHERE token = ?`, h,
|
||||
).Scan(&username, &expires)
|
||||
if err != nil {
|
||||
return Session{}, false
|
||||
}
|
||||
if time.Now().Unix() > expires {
|
||||
s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token)
|
||||
s.db.Exec(`DELETE FROM sessions WHERE token = ?`, h)
|
||||
return Session{}, false
|
||||
}
|
||||
return Session{Username: username}, true
|
||||
}
|
||||
|
||||
// NewPersistentFailLimiter returns a failLimiter whose state survives process
|
||||
// restarts via the session SQLite database.
|
||||
func (s *SessionStore) NewPersistentFailLimiter(max int, window time.Duration) *failLimiter {
|
||||
l := newFailLimiter(max, window)
|
||||
// Load existing entries, skipping expired ones.
|
||||
rows, err := s.db.Query(`SELECT key, count, until FROM throttle`)
|
||||
if err != nil {
|
||||
return l
|
||||
}
|
||||
defer rows.Close()
|
||||
now := time.Now()
|
||||
for rows.Next() {
|
||||
var k string
|
||||
var c int
|
||||
var u int64
|
||||
if err := rows.Scan(&k, &c, &u); err != nil {
|
||||
continue
|
||||
}
|
||||
until := time.Unix(u, 0)
|
||||
if now.After(until) {
|
||||
s.db.Exec(`DELETE FROM throttle WHERE key = ?`, k)
|
||||
continue
|
||||
}
|
||||
l.attempts[k] = &attemptState{count: c, until: until}
|
||||
}
|
||||
// Wire persistence: writes to DB on every mutation.
|
||||
l.sync = func(key string, st *attemptState) {
|
||||
if st == nil {
|
||||
s.db.Exec(`DELETE FROM throttle WHERE key = ?`, key)
|
||||
} else {
|
||||
s.db.Exec(`INSERT OR REPLACE INTO throttle (key, count, until) VALUES (?, ?, ?)`, key, st.count, st.until.Unix())
|
||||
}
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func hashSessionToken(token string) string {
|
||||
h := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func randomToken() string {
|
||||
b := make([]byte, 32)
|
||||
rand.Read(b) // never fails; rand.Read panics internally on misconfigured platforms.
|
||||
|
||||
@@ -34,22 +34,21 @@ func TestExpiredSessionRejected(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Write a row that expired an hour ago, bypassing Create's TTL.
|
||||
_, err = store.db.Exec(
|
||||
`INSERT INTO sessions (token, username, expires_at) VALUES (?, ?, ?)`,
|
||||
"stale", "urania", time.Now().Add(-time.Hour).Unix(),
|
||||
)
|
||||
// Create a session with an already-expired TTL (-2s ensures the Unix
|
||||
// second-rounded timestamp is safely in the past).
|
||||
oldTTL := sessionTTL
|
||||
sessionTTL = -2 * time.Second
|
||||
token, err := store.Create("urania")
|
||||
sessionTTL = oldTTL
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := store.GetByToken("stale"); ok {
|
||||
if _, ok := store.GetByToken(token); ok {
|
||||
t.Fatal("expired session was accepted")
|
||||
}
|
||||
// Lazy cleanup should have deleted the row.
|
||||
var n int
|
||||
store.db.QueryRow(`SELECT count(*) FROM sessions WHERE token = ?`, "stale").Scan(&n)
|
||||
if n != 0 {
|
||||
t.Fatalf("expired row not cleaned up: %d rows remain", n)
|
||||
if _, ok := store.GetByToken(token); ok {
|
||||
t.Fatal("expired session still in store")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ type failLimiter struct {
|
||||
attempts map[string]*attemptState
|
||||
max int
|
||||
window time.Duration
|
||||
sync func(key string, s *attemptState) // optional: persist to DB
|
||||
}
|
||||
|
||||
type attemptState struct {
|
||||
@@ -32,8 +33,8 @@ type attemptState struct {
|
||||
}
|
||||
|
||||
// maxTrackedKeys bounds memory: an attacker rotating username/IP can't grow the
|
||||
// map without limit. When exceeded we drop all throttle state - a crude reset
|
||||
// that briefly forgets cooldowns, acceptable for a single-node panel.
|
||||
// map without limit. When exceeded we fail closed instead of wiping state, so
|
||||
// existing cooldowns are preserved.
|
||||
const maxTrackedKeys = 10000
|
||||
|
||||
func newFailLimiter(max int, window time.Duration) *failLimiter {
|
||||
@@ -49,11 +50,13 @@ func (l *failLimiter) blocked(key string) bool {
|
||||
}
|
||||
|
||||
// fail records a failed attempt and starts a cooldown once max is reached.
|
||||
// When the map is full we stop tracking new keys rather than wiping existing
|
||||
// cooldowns (which an attacker could use to clear a target's throttle).
|
||||
func (l *failLimiter) fail(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if len(l.attempts) > maxTrackedKeys {
|
||||
l.attempts = map[string]*attemptState{}
|
||||
if len(l.attempts) >= maxTrackedKeys {
|
||||
return
|
||||
}
|
||||
s := l.attempts[key]
|
||||
if s == nil {
|
||||
@@ -63,7 +66,10 @@ func (l *failLimiter) fail(key string) {
|
||||
s.count++
|
||||
if s.count >= l.max {
|
||||
s.until = time.Now().Add(l.window)
|
||||
s.count = 0 // restart the window after the cooldown is set
|
||||
s.count = 0
|
||||
}
|
||||
if l.sync != nil {
|
||||
l.sync(key, s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,6 +78,9 @@ func (l *failLimiter) reset(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
delete(l.attempts, key)
|
||||
if l.sync != nil {
|
||||
l.sync(key, nil)
|
||||
}
|
||||
}
|
||||
|
||||
type ctxKey int
|
||||
|
||||
@@ -56,6 +56,9 @@ func NewTokenStore(path string) (*TokenStore, error) {
|
||||
)`); err != nil {
|
||||
return nil, fmt.Errorf("create tokens table: %w", err)
|
||||
}
|
||||
if err := os.Chmod(path, 0600); err != nil {
|
||||
return nil, fmt.Errorf("chmod token db: %w", err)
|
||||
}
|
||||
return &TokenStore{db: db}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -16,8 +16,8 @@ func TestTokenStore(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(raw) < len(tokenPrefix)+32 || raw[:len(tokenPrefix)] != tokenPrefix {
|
||||
t.Fatalf("token %q lacks %q prefix or is too short", raw, tokenPrefix)
|
||||
if len(raw) < 36 || raw[:4] != "nad_" {
|
||||
t.Fatalf("token %q lacks %q prefix or is too short", raw, "nad_")
|
||||
}
|
||||
|
||||
// Round-trip: the minted secret resolves to its name.
|
||||
@@ -25,7 +25,7 @@ func TestTokenStore(t *testing.T) {
|
||||
t.Errorf("Lookup(valid) = %q,%v; want dash,true", name, ok)
|
||||
}
|
||||
// A wrong secret (and a non-prefixed one) must not resolve.
|
||||
if _, ok := store.Lookup(tokenPrefix + "wrong"); ok {
|
||||
if _, ok := store.Lookup("nad_wrong"); ok {
|
||||
t.Error("Lookup(wrong) succeeded")
|
||||
}
|
||||
if _, ok := store.Lookup("no-prefix"); ok {
|
||||
|
||||
@@ -2,6 +2,7 @@ package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -68,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
|
||||
}
|
||||
@@ -108,6 +109,32 @@ 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 substituted into shell scripts and downloaded
|
||||
// over the wire. Validate shape + scheme + shell-safety once here so
|
||||
// /install.sh and the updater can use the string directly. Trim any trailing
|
||||
// slash so downstream string concatenation produces a clean URL.
|
||||
if f.Server.ReleaseRepo != "" {
|
||||
f.Server.ReleaseRepo = strings.TrimRight(f.Server.ReleaseRepo, "/")
|
||||
u, err := url.Parse(f.Server.ReleaseRepo)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("server.release_repo: %w", err)
|
||||
}
|
||||
if u.Scheme != "https" {
|
||||
return nil, fmt.Errorf("server.release_repo must use https:// (got %q)", f.Server.ReleaseRepo)
|
||||
}
|
||||
if u.Host == "" {
|
||||
return nil, fmt.Errorf("server.release_repo missing host: %q", f.Server.ReleaseRepo)
|
||||
}
|
||||
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return nil, fmt.Errorf("server.release_repo must be https://host/owner/repo, got %q", f.Server.ReleaseRepo)
|
||||
}
|
||||
// Shell-safety: reject characters that could break out of a double-quoted
|
||||
// string when substituted into the install.sh template.
|
||||
if strings.ContainsAny(f.Server.ReleaseRepo, "`$\"\\;|&") {
|
||||
return nil, fmt.Errorf("server.release_repo contains unsafe characters: %q", f.Server.ReleaseRepo)
|
||||
}
|
||||
}
|
||||
return &f, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,19 +12,18 @@ import (
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
)
|
||||
|
||||
// ConfigPath is set at startup so the update handler can re-load config and
|
||||
// surface release_repo / parse errors to the caller instead of only stderr.
|
||||
var ConfigPath string
|
||||
|
||||
// RegisterUpdate wires POST /api/meta/update. It runs the equivalent of
|
||||
// RegisterUpdate wires POST /api/update. It runs the equivalent of
|
||||
// `sudo nadir update` in a detached session and returns 202 immediately; the
|
||||
// systemctl restart that ends the updater drops in-flight connections, so the
|
||||
// caller should poll /api/health to confirm the new version is up.
|
||||
//
|
||||
// configPath is re-read by the handler so a missing release_repo (or any other
|
||||
// config error) surfaces as 4xx/5xx to the caller, not as stderr only.
|
||||
//
|
||||
// Authorization: requires (meta, root). Only roles with a wildcard grant
|
||||
// (the default admin role) match, since "meta" isn't a real module with a
|
||||
// declared permission vocabulary.
|
||||
func RegisterUpdate(api huma.API) {
|
||||
func RegisterUpdate(api huma.API, configPath string) {
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "meta-update",
|
||||
Method: "POST",
|
||||
@@ -36,13 +35,13 @@ func RegisterUpdate(api huma.API) {
|
||||
Errors: []int{400, 401, 403, 500},
|
||||
DefaultStatus: 202,
|
||||
}, func(ctx context.Context, _ *struct{}) (*oscmd.StatusOutput, error) {
|
||||
if ConfigPath != "" {
|
||||
cfg, err := config.Load(ConfigPath)
|
||||
if configPath != "" {
|
||||
cfg, err := config.Load(configPath)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("config load failed", err)
|
||||
}
|
||||
if cfg.Server.ReleaseRepo == "" {
|
||||
return nil, huma.Error400BadRequest("server.release_repo not set in " + ConfigPath)
|
||||
return nil, huma.Error400BadRequest("server.release_repo not set in " + configPath)
|
||||
}
|
||||
}
|
||||
exe, err := os.Executable()
|
||||
|
||||
+26
-7
@@ -15,6 +15,7 @@ import (
|
||||
// itself.
|
||||
type WhoamiInput struct {
|
||||
SessionID string `cookie:"nadir_session_id"`
|
||||
Auth string `header:"Authorization"`
|
||||
}
|
||||
|
||||
// WhoamiBody reports who the caller is and, per module, which permissions they
|
||||
@@ -30,7 +31,7 @@ type WhoamiOutput struct{ Body WhoamiBody }
|
||||
// RegisterWhoami adds the current-user endpoint. It resolves the caller's
|
||||
// concrete grants by asking the RBAC store about each module's permissions,
|
||||
// so "*" wildcards in roles are expanded for free.
|
||||
func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC, mods []module.Module) {
|
||||
func RegisterWhoami(api huma.API, sessions *auth.SessionStore, tokens *auth.TokenAuth, roles *rbac.RBAC, mods []module.Module) {
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "whoami",
|
||||
Method: "GET",
|
||||
@@ -40,18 +41,35 @@ func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC,
|
||||
"permissions the caller holds (wildcards resolved). Pair with " +
|
||||
"/api/_modules to render the full permission matrix.",
|
||||
Tags: []string{"Meta"},
|
||||
Errors: []int{401},
|
||||
Errors: []int{401, 429},
|
||||
}, func(ctx context.Context, in *WhoamiInput) (*WhoamiOutput, error) {
|
||||
sess, ok := sessions.GetByToken(in.SessionID)
|
||||
if !ok {
|
||||
return nil, huma.Error401Unauthorized("unauthorized")
|
||||
var username string
|
||||
|
||||
if raw, isBearer := auth.BearerToken(in.Auth); isBearer {
|
||||
if tokens == nil {
|
||||
return nil, huma.Error401Unauthorized("unauthorized")
|
||||
}
|
||||
name, ok, throttled := tokens.Verify(auth.ClientIP(ctx), raw)
|
||||
if throttled {
|
||||
return nil, huma.Error429TooManyRequests("too many failed token attempts; wait a minute")
|
||||
}
|
||||
if !ok {
|
||||
return nil, huma.Error401Unauthorized("unauthorized")
|
||||
}
|
||||
username = name
|
||||
} else {
|
||||
sess, ok := sessions.GetByToken(in.SessionID)
|
||||
if !ok {
|
||||
return nil, huma.Error401Unauthorized("unauthorized")
|
||||
}
|
||||
username = sess.Username
|
||||
}
|
||||
|
||||
held := make(map[string][]string)
|
||||
for _, m := range mods {
|
||||
var perms []string
|
||||
for _, p := range m.Permissions() {
|
||||
if roles.Can(sess.Username, m.ID(), p) {
|
||||
if roles.Can(username, m.ID(), p) {
|
||||
perms = append(perms, string(p))
|
||||
}
|
||||
}
|
||||
@@ -61,7 +79,8 @@ func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC,
|
||||
}
|
||||
|
||||
out := &WhoamiOutput{}
|
||||
out.Body = WhoamiBody{Username: sess.Username, Permissions: held}
|
||||
out.Body = WhoamiBody{Username: username, Permissions: held}
|
||||
return out, nil
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package meta
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"nadir/internal/auth"
|
||||
"nadir/internal/module"
|
||||
"nadir/internal/rbac"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/danielgtaylor/huma/v2/adapters/humago"
|
||||
"github.com/danielgtaylor/huma/v2/humatest"
|
||||
)
|
||||
|
||||
type dummyModule struct {
|
||||
id string
|
||||
perms []rbac.Permission
|
||||
}
|
||||
|
||||
func (m *dummyModule) ID() string { return m.id }
|
||||
func (m *dummyModule) Name() string { return m.id }
|
||||
func (m *dummyModule) Permissions() []rbac.Permission { return m.perms }
|
||||
func (m *dummyModule) Register(api huma.API) {}
|
||||
|
||||
func TestWhoami(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
sessions, err := auth.NewSessionStore(filepath.Join(tempDir, "sessions.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tokenStore, err := auth.NewTokenStore(filepath.Join(tempDir, "tokens.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tokenStore.Close()
|
||||
tokenAuth := auth.NewTokenAuth(tokenStore)
|
||||
|
||||
roles := rbac.New()
|
||||
roles.DefineRole(rbac.Role{
|
||||
Name: "admin-role",
|
||||
ModuleGrants: map[string][]rbac.Permission{
|
||||
"system": {rbac.Read},
|
||||
},
|
||||
})
|
||||
roles.AssignRole("admin", "admin-role")
|
||||
|
||||
mods := []module.Module{
|
||||
&dummyModule{
|
||||
id: "system",
|
||||
perms: []rbac.Permission{rbac.Read, rbac.Write},
|
||||
},
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
|
||||
RegisterWhoami(api, sessions, tokenAuth, roles, mods)
|
||||
|
||||
// 1. Unauthorized request (no token, no session)
|
||||
resp := api.Get("/api/whoami")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", resp.Code)
|
||||
}
|
||||
|
||||
// 2. Cookie session request
|
||||
sessToken, err := sessions.Create("admin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp = api.Get("/api/whoami", "Cookie: nadir_session_id="+sessToken)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", resp.Code)
|
||||
}
|
||||
var body WhoamiBody
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body.Username != "admin" {
|
||||
t.Errorf("expected username admin, got %q", body.Username)
|
||||
}
|
||||
if !slices.Contains(body.Permissions["system"], "read") {
|
||||
t.Errorf("expected system read permission, got %v", body.Permissions["system"])
|
||||
}
|
||||
|
||||
// 3. Token request
|
||||
bearerToken, err := tokenStore.Create("api-user")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
roles.DefineRole(rbac.Role{
|
||||
Name: "api-role",
|
||||
ModuleGrants: map[string][]rbac.Permission{
|
||||
"system": {rbac.Write},
|
||||
},
|
||||
})
|
||||
roles.AssignRole("api-user", "api-role")
|
||||
|
||||
resp = api.Get("/api/whoami", "Authorization: Bearer "+bearerToken)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", resp.Code)
|
||||
}
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body.Username != "api-user" {
|
||||
t.Errorf("expected username api-user, got %q", body.Username)
|
||||
}
|
||||
if !slices.Contains(body.Permissions["system"], "write") {
|
||||
t.Errorf("expected system write permission, got %v", body.Permissions["system"])
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,7 @@ func registerGroups(api huma.API) {
|
||||
}, func(ctx context.Context, _ *struct{}) (*ListGroupsOutput, error) {
|
||||
list, err := listGroups()
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("group lookup failed", err)
|
||||
}
|
||||
out := &ListGroupsOutput{}
|
||||
out.Body.Groups = list
|
||||
@@ -92,7 +92,7 @@ func registerGroups(api huma.API) {
|
||||
}
|
||||
g, ok, err := lookupGroup(in.Group)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("group lookup failed", err)
|
||||
}
|
||||
if !ok {
|
||||
return nil, huma.Error404NotFound("group not found: " + in.Group)
|
||||
@@ -114,7 +114,7 @@ func registerGroups(api huma.API) {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok, err := lookupGroup(in.Body.Name); err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("group lookup failed", err)
|
||||
} else if ok {
|
||||
return nil, huma.Error409Conflict("group already exists: " + in.Body.Name)
|
||||
}
|
||||
@@ -154,7 +154,7 @@ func registerGroups(api huma.API) {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok, err := lookupGroup(in.Group); err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+groupPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("group lookup failed", err)
|
||||
} else if !ok {
|
||||
return nil, huma.Error404NotFound("group not found: " + in.Group)
|
||||
}
|
||||
|
||||
@@ -38,14 +38,30 @@ short:x:5
|
||||
}
|
||||
|
||||
func TestValidateGroupName(t *testing.T) {
|
||||
for _, n := range []string{"wheel", "_svc", "dev-team", "g1"} {
|
||||
if err := validateGroupName(n); err != nil {
|
||||
t.Errorf("validateGroupName(%q) = %v, want nil", n, err)
|
||||
}
|
||||
}
|
||||
for _, n := range []string{"", "-x", "Wheel", "a,b", "foo;rm", "1grp"} {
|
||||
if err := validateGroupName(n); err == nil {
|
||||
t.Errorf("validateGroupName(%q) = nil, want error", n)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
value string
|
||||
valid bool
|
||||
}{
|
||||
{name: "wheel", value: "wheel", valid: true},
|
||||
{name: "underscore prefix", value: "_svc", valid: true},
|
||||
{name: "dev-team", value: "dev-team", valid: true},
|
||||
{name: "alphanumeric", value: "g1", valid: true},
|
||||
{name: "empty", value: "", valid: false},
|
||||
{name: "flag injection", value: "-x", valid: false},
|
||||
{name: "uppercase", value: "Wheel", valid: false},
|
||||
{name: "comma", value: "a,b", valid: false},
|
||||
{name: "shell metachar", value: "foo;rm", valid: false},
|
||||
{name: "leading digit", value: "1grp", valid: false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateGroupName(tt.value)
|
||||
if tt.valid && err != nil {
|
||||
t.Errorf("validateGroupName(%q) = %v, want nil", tt.value, err)
|
||||
}
|
||||
if !tt.valid && err == nil {
|
||||
t.Errorf("validateGroupName(%q) = nil, want error", tt.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,17 +49,31 @@ func TestValidateIfaceConfig(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestValidateIface(t *testing.T) {
|
||||
valid := []string{"eth0", "enp3s0", "wlan0", "br-lan", "veth1234567", "docker0"}
|
||||
for _, name := range valid {
|
||||
if err := validateIface(name); err != nil {
|
||||
t.Errorf("validateIface(%q) unexpected error: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
invalid := []string{"", "-eth0", "/dev/net", "a b", "name_that_is_way_too_long_for_linux"}
|
||||
for _, name := range invalid {
|
||||
if err := validateIface(name); err == nil {
|
||||
t.Errorf("validateIface(%q) expected error", name)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
value string
|
||||
valid bool
|
||||
}{
|
||||
{name: "eth0", value: "eth0", valid: true},
|
||||
{name: "enp3s0", value: "enp3s0", valid: true},
|
||||
{name: "wlan0", value: "wlan0", valid: true},
|
||||
{name: "bridge", value: "br-lan", valid: true},
|
||||
{name: "veth", value: "veth1234567", valid: true},
|
||||
{name: "docker", value: "docker0", valid: true},
|
||||
{name: "empty", value: "", valid: false},
|
||||
{name: "leading dash", value: "-eth0", valid: false},
|
||||
{name: "path", value: "/dev/net", valid: false},
|
||||
{name: "space", value: "a b", valid: false},
|
||||
{name: "too long", value: "name_that_is_way_too_long_for_linux", valid: false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateIface(tt.value)
|
||||
if tt.valid && err != nil {
|
||||
t.Errorf("validateIface(%q) unexpected error: %v", tt.value, err)
|
||||
}
|
||||
if !tt.valid && err == nil {
|
||||
t.Errorf("validateIface(%q) expected error", tt.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"nadir/internal/oscmd"
|
||||
|
||||
@@ -18,6 +19,10 @@ import (
|
||||
|
||||
var hostsFile = "/etc/hosts"
|
||||
|
||||
// hostsMu serialises writes to /etc/hosts so concurrent requests don't
|
||||
// clobber each other's read-modify-write.
|
||||
var hostsMu sync.Mutex
|
||||
|
||||
// hostnameRe matches a single hostname/alias. It forbids whitespace and '#' (so
|
||||
// an entry can't inject extra fields or a comment) and a leading dash.
|
||||
var hostnameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`)
|
||||
@@ -156,9 +161,26 @@ func renderHostLine(ip string, hostnames []string) string {
|
||||
|
||||
// --- writes ------------------------------------------------------------------
|
||||
|
||||
// writeHostsAtomically writes content to /etc/hosts via a temp file + rename,
|
||||
// so a crash mid-write leaves the original file intact.
|
||||
func writeHostsAtomically(content string) error {
|
||||
tmp := hostsFile + ".nadir.tmp"
|
||||
if err := os.WriteFile(tmp, []byte(content), 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, hostsFile); err != nil {
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// upsertHost replaces the line for ip (matched on the address field) or appends
|
||||
// a new one, preserving every other line.
|
||||
func upsertHost(ip string, hostnames []string) error {
|
||||
hostsMu.Lock()
|
||||
defer hostsMu.Unlock()
|
||||
|
||||
data, err := os.ReadFile(hostsFile)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -174,7 +196,6 @@ func upsertHost(ip string, hostnames []string) error {
|
||||
}
|
||||
}
|
||||
if !replaced {
|
||||
// Append, avoiding a blank line if the file already ended with one.
|
||||
if n := len(lines); n > 0 && strings.TrimSpace(lines[n-1]) == "" {
|
||||
lines[n-1] = newLine
|
||||
} else {
|
||||
@@ -182,11 +203,14 @@ func upsertHost(ip string, hostnames []string) error {
|
||||
}
|
||||
lines = append(lines, "")
|
||||
}
|
||||
return os.WriteFile(hostsFile, []byte(strings.Join(lines, "\n")), 0644)
|
||||
return writeHostsAtomically(strings.Join(lines, "\n"))
|
||||
}
|
||||
|
||||
// deleteHost removes every line mapping ip and reports whether any were removed.
|
||||
func deleteHost(ip string) (bool, error) {
|
||||
hostsMu.Lock()
|
||||
defer hostsMu.Unlock()
|
||||
|
||||
data, err := os.ReadFile(hostsFile)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -204,5 +228,5 @@ func deleteHost(ip string) (bool, error) {
|
||||
if !removed {
|
||||
return false, nil
|
||||
}
|
||||
return true, os.WriteFile(hostsFile, []byte(strings.Join(kept, "\n")), 0644)
|
||||
return true, writeHostsAtomically(strings.Join(kept, "\n"))
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const defaultRollbackSeconds = 60
|
||||
const defaultRollbackSeconds = 120
|
||||
|
||||
// errAlreadyPending is returned when another change is awaiting confirmation.
|
||||
// The write handlers map this to 409 Conflict.
|
||||
@@ -113,18 +113,26 @@ func (m *Module) armPending(iface string, revert func() error, seconds int) (int
|
||||
// revert even if the server is otherwise idle — the whole point is protecting
|
||||
// against being locked out of a remote box.
|
||||
pc.Timer = time.AfterFunc(dur, func() {
|
||||
// Check validity under lock, then revert outside it so a slow
|
||||
// nmcli/networkctl call doesn't block the entire networking module.
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
// Only revert if this exact change is still pending (it may have been
|
||||
// confirmed or manually rolled back in the meantime).
|
||||
if m.pending != pc {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
iface := pc.Iface
|
||||
revert := pc.revert
|
||||
m.mu.Unlock()
|
||||
|
||||
log.Printf("networking: rollback timer expired for %s — reverting", iface)
|
||||
if err := pc.revert(); err != nil {
|
||||
if err := revert(); err != nil {
|
||||
log.Printf("networking: auto-rollback of %s failed: %v", iface, err)
|
||||
}
|
||||
m.pending = nil
|
||||
m.mu.Lock()
|
||||
if m.pending == pc {
|
||||
m.pending = nil
|
||||
}
|
||||
m.mu.Unlock()
|
||||
})
|
||||
|
||||
m.pending = pc
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -54,27 +54,50 @@ func TestParsePacmanUpdates(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStripArch(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"code.x86_64": "code",
|
||||
"python3.11.noarch": "python3.11", // arch is only the final segment
|
||||
"noarchhere": "noarchhere",
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{name: "x86_64 arch", in: "code.x86_64", want: "code"},
|
||||
{name: "noarch suffix", in: "python3.11.noarch", want: "python3.11"},
|
||||
{name: "no arch segment", in: "noarchhere", want: "noarchhere"},
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := stripArch(in); got != want {
|
||||
t.Errorf("stripArch(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := stripArch(tt.in); got != tt.want {
|
||||
t.Errorf("stripArch(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateName(t *testing.T) {
|
||||
for _, n := range []string{"htop", "openssh-server", "lib32-glibc", "g++", "python3.11"} {
|
||||
if err := validateName(n); err != nil {
|
||||
t.Errorf("validateName(%q) = %v, want nil", n, err)
|
||||
}
|
||||
}
|
||||
for _, n := range []string{"", "-rf", "foo;rm", "foo bar", "pkg=1.0", "a/b"} {
|
||||
if err := validateName(n); err == nil {
|
||||
t.Errorf("validateName(%q) = nil, want error", n)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
value string
|
||||
valid bool
|
||||
}{
|
||||
{name: "htop", value: "htop", valid: true},
|
||||
{name: "openssh-server", value: "openssh-server", valid: true},
|
||||
{name: "lib32-glibc", value: "lib32-glibc", valid: true},
|
||||
{name: "g++", value: "g++", valid: true},
|
||||
{name: "python3.11", value: "python3.11", valid: true},
|
||||
{name: "empty", value: "", valid: false},
|
||||
{name: "flag injection", value: "-rf", valid: false},
|
||||
{name: "shell metachar", value: "foo;rm", valid: false},
|
||||
{name: "space", value: "foo bar", valid: false},
|
||||
{name: "equals", value: "pkg=1.0", valid: false},
|
||||
{name: "path sep", value: "a/b", valid: false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateName(tt.value)
|
||||
if tt.valid && err != nil {
|
||||
t.Errorf("validateName(%q) = %v, want nil", tt.value, err)
|
||||
}
|
||||
if !tt.valid && err == nil {
|
||||
t.Errorf("validateName(%q) = nil, want error", tt.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,10 @@ const (
|
||||
maxLogLines = 10000
|
||||
)
|
||||
|
||||
// logStreamSem limits concurrent log-follow connections. Each one forks a
|
||||
// journalctl or tail subprocess, so too many would exhaust system resources.
|
||||
var logStreamSem = make(chan struct{}, 10)
|
||||
|
||||
// LogEntry is one log record. For the journal source it is distilled from
|
||||
// journalctl's JSON; for the file source only Message is set (the raw line,
|
||||
// which usually carries its own embedded timestamp).
|
||||
@@ -128,6 +132,14 @@ func registerLogs(api huma.API, logFiles map[string][]string) {
|
||||
return
|
||||
}
|
||||
|
||||
select {
|
||||
case logStreamSem <- struct{}{}:
|
||||
default:
|
||||
send.Data(ErrorEvent{Message: "too many concurrent log streams, try again later"})
|
||||
return
|
||||
}
|
||||
defer func() { <-logStreamSem }()
|
||||
|
||||
var cmd string
|
||||
var args []string
|
||||
if in.Source == "file" {
|
||||
|
||||
@@ -48,49 +48,74 @@ func TestResolveLogPath(t *testing.T) {
|
||||
"nginx.service": {"/var/log/nginx/access.log", "/var/log/nginx/error.log"},
|
||||
}
|
||||
|
||||
// Allowlisted path resolves whether the caller uses the bare or .service
|
||||
// form, regardless of which form the config key used.
|
||||
for _, unit := range []string{"nginx.service", "nginx"} {
|
||||
if p, err := resolveLogPath(allow, unit, "/var/log/nginx/error.log"); err != nil || p != "/var/log/nginx/error.log" {
|
||||
t.Errorf("allowlisted path for %q: got %q, %v", unit, p, err)
|
||||
t.Run("allowlisted path via bare name", func(t *testing.T) {
|
||||
p, err := resolveLogPath(allow, "nginx", "/var/log/nginx/error.log")
|
||||
if err != nil || p != "/var/log/nginx/error.log" {
|
||||
t.Errorf("got %q, %v", p, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("allowlisted path via service suffix", func(t *testing.T) {
|
||||
p, err := resolveLogPath(allow, "nginx.service", "/var/log/nginx/error.log")
|
||||
if err != nil || p != "/var/log/nginx/error.log" {
|
||||
t.Errorf("got %q, %v", p, err)
|
||||
}
|
||||
})
|
||||
|
||||
// Everything else is rejected: empty path, non-listed path (traversal),
|
||||
// listed path but wrong unit, and unit with no allowlist at all.
|
||||
bad := []struct{ unit, path string }{
|
||||
{"nginx.service", ""},
|
||||
{"nginx.service", "/etc/shadow"},
|
||||
{"nginx.service", "/var/log/nginx/access.log/../../../etc/shadow"},
|
||||
{"sshd.service", "/var/log/nginx/error.log"},
|
||||
{"unknown.service", "/var/log/nginx/error.log"},
|
||||
}
|
||||
for _, b := range bad {
|
||||
if _, err := resolveLogPath(allow, b.unit, b.path); err == nil {
|
||||
t.Errorf("resolveLogPath(%q, %q) = nil error, want rejection", b.unit, b.path)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
unit string
|
||||
path string
|
||||
}{
|
||||
{name: "empty path", unit: "nginx.service", path: ""},
|
||||
{name: "non-allowlisted path", unit: "nginx.service", path: "/etc/shadow"},
|
||||
{name: "path traversal", unit: "nginx.service", path: "/var/log/nginx/access.log/../../../etc/shadow"},
|
||||
{name: "wrong unit", unit: "sshd.service", path: "/var/log/nginx/error.log"},
|
||||
{name: "unknown unit", unit: "unknown.service", path: "/var/log/nginx/error.log"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if _, err := resolveLogPath(allow, tt.unit, tt.path); err == nil {
|
||||
t.Errorf("resolveLogPath(%q, %q) = nil error, want rejection", tt.unit, tt.path)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestJournalUnit(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"docker.service": "docker",
|
||||
"docker": "docker",
|
||||
"sshd.service": "sshd",
|
||||
"foo.socket": "foo.socket", // only .service is stripped
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{name: "docker service", in: "docker.service", want: "docker"},
|
||||
{name: "docker bare", in: "docker", want: "docker"},
|
||||
{name: "sshd service", in: "sshd.service", want: "sshd"},
|
||||
{name: "socket unit", in: "foo.socket", want: "foo.socket"},
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := journalUnit(in); got != want {
|
||||
t.Errorf("journalUnit(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := journalUnit(tt.in); got != tt.want {
|
||||
t.Errorf("journalUnit(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClampLines(t *testing.T) {
|
||||
cases := map[int]int{0: defaultLogLines, -5: defaultLogLines, 50: 50, 999999: maxLogLines}
|
||||
for in, want := range cases {
|
||||
if got := clampLines(in); got != want {
|
||||
t.Errorf("clampLines(%d) = %d, want %d", in, got, want)
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
in int
|
||||
want int
|
||||
}{
|
||||
{name: "zero", in: 0, want: defaultLogLines},
|
||||
{name: "negative", in: -5, want: defaultLogLines},
|
||||
{name: "fifty", in: 50, want: 50},
|
||||
{name: "too large", in: 999999, want: maxLogLines},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := clampLines(tt.in); got != tt.want {
|
||||
t.Errorf("clampLines(%d) = %d, want %d", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
// Empty, flag-injection, and anything with shell/path metacharacters must
|
||||
// be rejected before reaching systemctl.
|
||||
invalid := []string{"", "-rf", "--now", "a b", "foo;rm -rf /", "a/b", "naughty$()", "x|y"}
|
||||
for _, u := range invalid {
|
||||
if err := validateUnit(u); err == nil {
|
||||
t.Errorf("validateUnit(%q) = nil, want error", u)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
value string
|
||||
valid bool
|
||||
}{
|
||||
{name: "sshd.service", value: "sshd.service", valid: true},
|
||||
{name: "template", value: "getty@tty1.service", valid: true},
|
||||
{name: "dots and colons", value: "foo.bar:baz-1.service", valid: true},
|
||||
{name: "timer", value: "a_b.timer", valid: true},
|
||||
{name: "empty", value: "", valid: false},
|
||||
{name: "flag injection", value: "-rf", valid: false},
|
||||
{name: "double dash", value: "--now", valid: false},
|
||||
{name: "space", value: "a b", valid: false},
|
||||
{name: "shell metachar", value: "foo;rm -rf /", valid: false},
|
||||
{name: "path sep", value: "a/b", valid: false},
|
||||
{name: "subshell", value: "naughty$()", valid: false},
|
||||
{name: "pipe", value: "x|y", valid: false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateUnit(tt.value)
|
||||
if tt.valid && err != nil {
|
||||
t.Errorf("validateUnit(%q) = %v, want nil", tt.value, err)
|
||||
}
|
||||
if !tt.valid && err == nil {
|
||||
t.Errorf("validateUnit(%q) = nil, want error", tt.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsSelf pins the dispatch that detaches stop/restart-of-self into a
|
||||
// Setsid subprocess. Both "nadir" and "nadir.service" must match; anything
|
||||
// else (including substrings) must not, or unrelated services would also get
|
||||
// detached and bypass the synchronous error path.
|
||||
func TestIsSelf(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
value string
|
||||
want bool
|
||||
}{
|
||||
{name: "bare name", value: "nadir", want: true},
|
||||
{name: "with service suffix", value: "nadir.service", want: true},
|
||||
{name: "empty", value: "", want: false},
|
||||
{name: "other service", value: "sshd.service", want: false},
|
||||
{name: "prefix substring", value: "nadir-something.service", want: false},
|
||||
{name: "wrong suffix", value: "nadir.timer", want: false},
|
||||
{name: "suffix mismatch", value: "not-nadir.service", want: false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := isSelf(tt.value); got != tt.want {
|
||||
t.Errorf("isSelf(%q) = %v, want %v", tt.value, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"nadir/internal/mounts"
|
||||
"nadir/internal/oscmd"
|
||||
@@ -16,6 +17,10 @@ import (
|
||||
// fstabFile is a var so tests can point it at a fixture.
|
||||
var fstabFile = "/etc/fstab"
|
||||
|
||||
// fstabMu serialises writes to /etc/fstab so concurrent HTTP requests don't
|
||||
// clobber each other's read-modify-write.
|
||||
var fstabMu sync.Mutex
|
||||
|
||||
// FstabEntry is one /etc/fstab line. Dump and Pass are the last two numeric
|
||||
// fields (fs_freq and fs_passno).
|
||||
type FstabEntry struct {
|
||||
@@ -67,7 +72,7 @@ func registerStorage(api huma.API) {
|
||||
}, func(ctx context.Context, _ *struct{}) (*ListMountsOutput, error) {
|
||||
entries, err := mounts.Proc()
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read mounts failed", err)
|
||||
return nil, huma.Error500InternalServerError("mount table lookup failed", err)
|
||||
}
|
||||
res := &ListMountsOutput{}
|
||||
res.Body.Mounts = entries
|
||||
@@ -86,7 +91,7 @@ func registerStorage(api huma.API) {
|
||||
}, func(ctx context.Context, _ *struct{}) (*ListFstabOutput, error) {
|
||||
data, err := os.ReadFile(fstabFile)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read fstab failed", err)
|
||||
return nil, huma.Error500InternalServerError("fstab lookup failed", err)
|
||||
}
|
||||
res := &ListFstabOutput{}
|
||||
res.Body.Entries = parseFstab(string(data))
|
||||
@@ -121,7 +126,7 @@ func registerStorage(api huma.API) {
|
||||
|
||||
existing, err := readFstab()
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read fstab failed", err)
|
||||
return nil, huma.Error500InternalServerError("fstab lookup failed", err)
|
||||
}
|
||||
if findEntry(existing, e.Mountpoint) != nil {
|
||||
return nil, huma.Error409Conflict("an fstab entry already exists for " + e.Mountpoint)
|
||||
@@ -158,13 +163,13 @@ func registerStorage(api huma.API) {
|
||||
|
||||
entries, err := readFstab()
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read fstab failed", err)
|
||||
return nil, huma.Error500InternalServerError("fstab lookup failed", err)
|
||||
}
|
||||
inFstab := findEntry(entries, in.Mountpoint) != nil
|
||||
|
||||
mounted, err := isMounted(in.Mountpoint)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read mounts failed", err)
|
||||
return nil, huma.Error500InternalServerError("mount table lookup failed", err)
|
||||
}
|
||||
if !inFstab && !mounted {
|
||||
return nil, huma.Error404NotFound("no mount or fstab entry for " + in.Mountpoint)
|
||||
@@ -231,8 +236,25 @@ func renderFstabLine(e FstabEntry) string {
|
||||
return fmt.Sprintf("%s\t%s\t%s\t%s\t%d\t%d", e.Device, e.Mountpoint, e.FSType, e.Options, e.Dump, e.Pass)
|
||||
}
|
||||
|
||||
// writeFstabAtomically writes content to /etc/fstab using a temporary file and
|
||||
// rename, so a crash mid-write leaves the original file intact.
|
||||
func writeFstabAtomically(content string) error {
|
||||
tmp := fstabFile + ".nadir.tmp"
|
||||
if err := os.WriteFile(tmp, []byte(content), 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, fstabFile); err != nil {
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// appendFstabLine adds one entry, leaving every existing line untouched.
|
||||
func appendFstabLine(e FstabEntry) error {
|
||||
fstabMu.Lock()
|
||||
defer fstabMu.Unlock()
|
||||
|
||||
data, err := os.ReadFile(fstabFile)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -242,12 +264,15 @@ func appendFstabLine(e FstabEntry) error {
|
||||
content += "\n"
|
||||
}
|
||||
content += renderFstabLine(e) + "\n"
|
||||
return os.WriteFile(fstabFile, []byte(content), 0644)
|
||||
return writeFstabAtomically(content)
|
||||
}
|
||||
|
||||
// removeFstabLines drops every line mapping mountpoint, preserving comments and
|
||||
// other entries. Reports whether anything was removed.
|
||||
func removeFstabLines(mountpoint string) (bool, error) {
|
||||
fstabMu.Lock()
|
||||
defer fstabMu.Unlock()
|
||||
|
||||
data, err := os.ReadFile(fstabFile)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -268,7 +293,7 @@ func removeFstabLines(mountpoint string) (bool, error) {
|
||||
if !removed {
|
||||
return false, nil
|
||||
}
|
||||
return true, os.WriteFile(fstabFile, []byte(strings.Join(kept, "\n")), 0644)
|
||||
return true, writeFstabAtomically(strings.Join(kept, "\n"))
|
||||
}
|
||||
|
||||
func findEntry(entries []FstabEntry, mountpoint string) *FstabEntry {
|
||||
|
||||
@@ -79,23 +79,27 @@ func mustReadFstab(t *testing.T) []FstabEntry {
|
||||
}
|
||||
|
||||
func TestValidateEntry(t *testing.T) {
|
||||
ok := FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/data", FSType: "ext4", Options: "defaults"}
|
||||
if err := validateEntry(ok); err != nil {
|
||||
t.Errorf("valid entry rejected: %v", err)
|
||||
}
|
||||
if err := validateEntry(FstabEntry{Device: "UUID=ab-cd", Mountpoint: "/mnt/x", FSType: "xfs", Options: "rw,noatime"}); err != nil {
|
||||
t.Errorf("UUID entry rejected: %v", err)
|
||||
}
|
||||
bad := []FstabEntry{
|
||||
{Device: "/dev/sdb1; rm -rf /", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults"}, // shell metachars
|
||||
{Device: "/dev/sdb1", Mountpoint: "../etc", FSType: "ext4", Options: "defaults"}, // not absolute
|
||||
{Device: "/dev/sdb1", Mountpoint: "/mnt/../../etc", FSType: "ext4", Options: "defaults"}, // traversal
|
||||
{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4!", Options: "defaults"}, // bad fstype
|
||||
{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults; reboot"}, // bad options
|
||||
}
|
||||
for i, e := range bad {
|
||||
if err := validateEntry(e); err == nil {
|
||||
t.Errorf("bad entry %d accepted: %+v", i, e)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
entry FstabEntry
|
||||
valid bool
|
||||
}{
|
||||
{name: "valid", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/data", FSType: "ext4", Options: "defaults"}, valid: true},
|
||||
{name: "UUID", entry: FstabEntry{Device: "UUID=ab-cd", Mountpoint: "/mnt/x", FSType: "xfs", Options: "rw,noatime"}, valid: true},
|
||||
{name: "shell metachar in device", entry: FstabEntry{Device: "/dev/sdb1; rm -rf /", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults"}, valid: false},
|
||||
{name: "relative mountpoint", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "../etc", FSType: "ext4", Options: "defaults"}, valid: false},
|
||||
{name: "traversal in mountpoint", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/../../etc", FSType: "ext4", Options: "defaults"}, valid: false},
|
||||
{name: "bad fstype", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4!", Options: "defaults"}, valid: false},
|
||||
{name: "bad options", entry: FstabEntry{Device: "/dev/sdb1", Mountpoint: "/mnt/x", FSType: "ext4", Options: "defaults; reboot"}, valid: false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateEntry(tt.entry)
|
||||
if tt.valid && err != nil {
|
||||
t.Errorf("valid entry rejected: %v", err)
|
||||
}
|
||||
if !tt.valid && err == nil {
|
||||
t.Errorf("bad entry accepted: %+v", tt.entry)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"nadir/internal/oscmd"
|
||||
@@ -9,6 +10,11 @@ import (
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
)
|
||||
|
||||
// hostnameRe matches RFC-1123 labels joined by dots, max 253 chars total. Anchored
|
||||
// so a leading "-" can't be read as a hostnamectl flag and shell metacharacters
|
||||
// can't survive — same pattern the other modules use (CLAUDE.md §5).
|
||||
var hostnameRe = regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9-]{0,62})(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,62}))*$`)
|
||||
|
||||
type HostnameBody struct {
|
||||
Hostname string `json:"hostname" example:"server01" doc:"System hostname"`
|
||||
}
|
||||
@@ -49,7 +55,10 @@ func registerHostname(api huma.API) {
|
||||
if name == "" {
|
||||
return nil, huma.Error400BadRequest("empty hostname")
|
||||
}
|
||||
if _, err := oscmd.Run("hostnamectl", "set-hostname", name); err != nil {
|
||||
if len(name) > 253 || !hostnameRe.MatchString(name) {
|
||||
return nil, huma.Error400BadRequest("invalid hostname: " + name)
|
||||
}
|
||||
if _, err := oscmd.Run("hostnamectl", "set-hostname", "--", name); err != nil {
|
||||
return nil, huma.Error500InternalServerError("hostnamectl failed", err)
|
||||
}
|
||||
return oscmd.OK(), nil
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"math"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
@@ -161,7 +162,19 @@ func cpuInfo() CPUInfo {
|
||||
// ponytail: cpufreq sysfs is absent on many VMs and stock Ubuntu server
|
||||
// kernels; fall back to /proc/cpuinfo "cpu MHz" — VMs have a fixed clock,
|
||||
// so min == max == cur is the honest answer.
|
||||
if mhz := cpuinfoMaxMHz(string(data)); mhz > 0 {
|
||||
mhz := cpuinfoMaxMHz(string(data))
|
||||
// ponytail: ARM /proc/cpuinfo has no "cpu MHz" and often no "model name";
|
||||
// lscpu decodes the ARM part-id table and reads DMI, so use it as last resort.
|
||||
if c.Model == "" || mhz == 0 {
|
||||
model, lscpuMHz := lscpuFallback()
|
||||
if c.Model == "" {
|
||||
c.Model = model
|
||||
}
|
||||
if mhz == 0 {
|
||||
mhz = lscpuMHz
|
||||
}
|
||||
}
|
||||
if mhz > 0 {
|
||||
if c.CurrentMHz == 0 {
|
||||
c.CurrentMHz = mhz
|
||||
}
|
||||
@@ -175,6 +188,56 @@ func cpuInfo() CPUInfo {
|
||||
return c
|
||||
}
|
||||
|
||||
// lscpuFallback parses `lscpu` for "Model name" and any embedded "@ X.X GHz"
|
||||
// or "CPU max MHz:" value. Returns zeros when lscpu is missing or silent.
|
||||
func lscpuFallback() (model string, mhz int) {
|
||||
out, err := exec.Command("lscpu").Output()
|
||||
if err != nil {
|
||||
return "", 0
|
||||
}
|
||||
for line := range strings.SplitSeq(string(out), "\n") {
|
||||
k, v, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
k, v = strings.TrimSpace(k), strings.TrimSpace(v)
|
||||
switch k {
|
||||
case "Model name":
|
||||
if model == "" {
|
||||
model = v
|
||||
}
|
||||
case "BIOS Model name":
|
||||
if model == "" {
|
||||
model = v
|
||||
}
|
||||
case "CPU max MHz", "CPU MHz":
|
||||
if f, err := strconv.ParseFloat(v, 64); err == nil && int(f) > mhz {
|
||||
mhz = int(math.Round(f))
|
||||
}
|
||||
}
|
||||
}
|
||||
if mhz == 0 {
|
||||
mhz = parseGHzSuffix(model)
|
||||
}
|
||||
return model, mhz
|
||||
}
|
||||
|
||||
// parseGHzSuffix pulls "2.0GHz" / "@ 2.0 GHz" out of a model string.
|
||||
func parseGHzSuffix(s string) int {
|
||||
i := strings.LastIndex(s, "@")
|
||||
if i < 0 {
|
||||
return 0
|
||||
}
|
||||
rest := strings.TrimSpace(s[i+1:])
|
||||
rest = strings.TrimSuffix(strings.TrimSuffix(rest, "GHz"), "Ghz")
|
||||
rest = strings.TrimSpace(strings.TrimSuffix(rest, "G"))
|
||||
f, err := strconv.ParseFloat(strings.TrimSpace(rest), 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return int(math.Round(f * 1000))
|
||||
}
|
||||
|
||||
// cpuinfoMaxMHz returns the highest "cpu MHz" value across all cores in
|
||||
// /proc/cpuinfo, rounded to an int. Returns 0 when no such line exists.
|
||||
func cpuinfoMaxMHz(cpuinfo string) int {
|
||||
@@ -436,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
|
||||
@@ -459,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 {
|
||||
|
||||
@@ -2,6 +2,10 @@ package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
@@ -12,6 +16,7 @@ import (
|
||||
|
||||
type LocaleStatusBody struct {
|
||||
Lang string `json:"lang" example:"it_IT.UTF-8" doc:"System locale (LANG)"`
|
||||
Language string `json:"language" example:"en_US:" doc:"Fallback language list (LANGUAGE)"`
|
||||
VCKeymap string `json:"vc_keymap" example:"it" doc:"Virtual console keymap"`
|
||||
X11Layout string `json:"x11_layout" example:"it" doc:"X11 keyboard layout"`
|
||||
}
|
||||
@@ -27,12 +32,14 @@ type LocalesOutput struct {
|
||||
type KeymapsOutput struct {
|
||||
Body struct {
|
||||
Keymaps []string `json:"keymaps" doc:"Available virtual console keymaps"`
|
||||
Reason string `json:"reason,omitempty" doc:"When keymaps is empty, why: e.g. \"kbd not installed on this server\""`
|
||||
}
|
||||
}
|
||||
|
||||
type SetLocaleInput struct {
|
||||
Body struct {
|
||||
Lang string `json:"lang" example:"it_IT.UTF-8" doc:"Locale to set as LANG"`
|
||||
Lang string `json:"lang" example:"it_IT.UTF-8" doc:"Locale to set as LANG"`
|
||||
Language *string `json:"language,omitempty" example:"en_US:" doc:"Fallback language list (LANGUAGE)"`
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +49,20 @@ type SetKeymapInput struct {
|
||||
}
|
||||
}
|
||||
|
||||
type GenerateLocaleInput struct {
|
||||
Body struct {
|
||||
Locale string `json:"locale" example:"fr_FR.UTF-8" doc:"Locale to generate (e.g. fr_FR.UTF-8)"`
|
||||
}
|
||||
}
|
||||
|
||||
// localeRe validates a locale identifier: language_TERRITORY with an optional
|
||||
// .charmap suffix (e.g. fr_FR, fr_FR.UTF-8, en_US.ISO-8859-1).
|
||||
var localeRe = regexp.MustCompile(`^[a-z]{2,3}_[A-Z]{2}(\.[A-Za-z0-9_-]+)?$`)
|
||||
|
||||
// languageRe validates the LANGUAGE fallback list: colon-separated locale names
|
||||
// like "en_US:de_DE". Anchored so a leading "-" can't survive into argv.
|
||||
var languageRe = regexp.MustCompile(`^[a-zA-Z0-9_.:-]*$`)
|
||||
|
||||
func localeStatus() (LocaleStatusBody, error) {
|
||||
lines, err := oscmd.RunLines("localectl", "status")
|
||||
if err != nil {
|
||||
@@ -49,21 +70,28 @@ func localeStatus() (LocaleStatusBody, error) {
|
||||
}
|
||||
var b LocaleStatusBody
|
||||
for _, line := range lines {
|
||||
label, val, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(trimmed, "VC Keymap:") {
|
||||
b.VCKeymap = strings.TrimSpace(strings.TrimPrefix(trimmed, "VC Keymap:"))
|
||||
continue
|
||||
}
|
||||
switch strings.TrimSpace(label) {
|
||||
case "System Locale":
|
||||
for kv := range strings.FieldsSeq(val) {
|
||||
if k, v, ok := strings.Cut(kv, "="); ok && k == "LANG" {
|
||||
if strings.HasPrefix(trimmed, "X11 Layout:") {
|
||||
b.X11Layout = strings.TrimSpace(strings.TrimPrefix(trimmed, "X11 Layout:"))
|
||||
continue
|
||||
}
|
||||
// Parse k=v fields on any other line (like System Locale block).
|
||||
parts := strings.Fields(trimmed)
|
||||
for _, part := range parts {
|
||||
part = strings.TrimPrefix(part, "System Locale:")
|
||||
part = strings.TrimSpace(part)
|
||||
if k, v, ok := strings.Cut(part, "="); ok {
|
||||
switch k {
|
||||
case "LANG":
|
||||
b.Lang = v
|
||||
case "LANGUAGE":
|
||||
b.Language = v
|
||||
}
|
||||
}
|
||||
case "VC Keymap":
|
||||
b.VCKeymap = strings.TrimSpace(val)
|
||||
case "X11 Layout":
|
||||
b.X11Layout = strings.TrimSpace(val)
|
||||
}
|
||||
}
|
||||
return b, nil
|
||||
@@ -130,7 +158,17 @@ func registerLocale(api huma.API) {
|
||||
if !slices.Contains(locales, lang) {
|
||||
return nil, huma.Error400BadRequest("unknown locale: " + lang)
|
||||
}
|
||||
if _, err := oscmd.Run("localectl", "set-locale", "LANG="+lang); err != nil {
|
||||
|
||||
args := []string{"set-locale", "LANG=" + lang}
|
||||
if in.Body.Language != nil {
|
||||
langVal := strings.TrimSpace(*in.Body.Language)
|
||||
if !languageRe.MatchString(langVal) {
|
||||
return nil, huma.Error400BadRequest("invalid language format: " + langVal)
|
||||
}
|
||||
args = append(args, "LANGUAGE="+langVal)
|
||||
}
|
||||
|
||||
if _, err := oscmd.Run("localectl", args...); err != nil {
|
||||
return nil, huma.Error500InternalServerError("set-locale failed", err)
|
||||
}
|
||||
return oscmd.OK(), nil
|
||||
@@ -146,12 +184,15 @@ func registerLocale(api huma.API) {
|
||||
Metadata: op("read"),
|
||||
Errors: readErrors,
|
||||
}, func(ctx context.Context, _ *struct{}) (*KeymapsOutput, error) {
|
||||
// ponytail: minimal servers ship without kbd / /usr/share/keymaps, so
|
||||
// localectl errors instead of returning empty. Surface that as a `reason`
|
||||
// the frontend can display ("kbd not installed") instead of an opaque N/A.
|
||||
keymaps, err := oscmd.RunLines("localectl", "list-keymaps")
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("localectl failed", err)
|
||||
}
|
||||
out := &KeymapsOutput{}
|
||||
out.Body.Keymaps = keymaps
|
||||
if err != nil || len(keymaps) == 0 {
|
||||
out.Body.Reason = "kbd is not installed on this server (install the kbd / console-data package to enable keymap selection)"
|
||||
}
|
||||
return out, nil
|
||||
})
|
||||
|
||||
@@ -171,10 +212,9 @@ func registerLocale(api huma.API) {
|
||||
if km == "" {
|
||||
return nil, huma.Error400BadRequest("empty keymap")
|
||||
}
|
||||
keymaps, err := oscmd.RunLines("localectl", "list-keymaps")
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("localectl failed", err)
|
||||
}
|
||||
// list-keymaps failure means no keymap allowlist on this host (kbd absent);
|
||||
// fall through to unknown-keymap 400 instead of 500.
|
||||
keymaps, _ := oscmd.RunLines("localectl", "list-keymaps")
|
||||
if !slices.Contains(keymaps, km) {
|
||||
return nil, huma.Error400BadRequest("unknown keymap: " + km)
|
||||
}
|
||||
@@ -183,4 +223,124 @@ func registerLocale(api huma.API) {
|
||||
}
|
||||
return oscmd.OK(), nil
|
||||
})
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "system-generate-locale",
|
||||
Method: "POST",
|
||||
Path: "/api/system/locale/generate",
|
||||
Summary: "Generate (install) a new locale",
|
||||
Description: "Generates a locale so it becomes available for use with set-locale. " +
|
||||
"On Debian/Ubuntu/Arch this uncomments the entry in /etc/locale.gen and runs " +
|
||||
"locale-gen; on RHEL/Fedora it uses localedef. Idempotent: if the locale is " +
|
||||
"already generated, returns 200 immediately.",
|
||||
Tags: []string{tagSystem},
|
||||
Metadata: op("write"),
|
||||
Errors: []int{400, 401, 403, 500, 501},
|
||||
}, func(ctx context.Context, in *GenerateLocaleInput) (*oscmd.StatusOutput, error) {
|
||||
locale := strings.TrimSpace(in.Body.Locale)
|
||||
if locale == "" {
|
||||
return nil, huma.Error400BadRequest("empty locale")
|
||||
}
|
||||
if !localeRe.MatchString(locale) {
|
||||
return nil, huma.Error400BadRequest("invalid locale format: "+locale,
|
||||
fmt.Errorf("expected language_TERRITORY[.charmap], e.g. fr_FR.UTF-8"))
|
||||
}
|
||||
|
||||
// Idempotency: already generated → success.
|
||||
existing, err := oscmd.RunLines("localectl", "list-locales")
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("localectl failed", err)
|
||||
}
|
||||
if slices.Contains(existing, locale) {
|
||||
return oscmd.OK(), nil
|
||||
}
|
||||
|
||||
// Detect which generation path the host supports.
|
||||
localeGenFile := "/etc/locale.gen"
|
||||
_, hasFile := os.Stat(localeGenFile)
|
||||
_, hasLocaleGen := exec.LookPath("locale-gen")
|
||||
_, hasLocaledef := exec.LookPath("localedef")
|
||||
|
||||
switch {
|
||||
case hasFile == nil && hasLocaleGen == nil:
|
||||
if err := enableLocaleGen(localeGenFile, locale); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case hasLocaledef == nil:
|
||||
if err := generateLocaledef(locale); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
return nil, huma.Error501NotImplemented(
|
||||
"locale generation not supported on this host (no locale-gen or localedef found)")
|
||||
}
|
||||
return oscmd.OK(), nil
|
||||
})
|
||||
}
|
||||
|
||||
// enableLocaleGen uncomments the locale in /etc/locale.gen and runs locale-gen.
|
||||
// This is the Debian/Ubuntu/Arch path.
|
||||
func enableLocaleGen(path, locale string) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return huma.Error500InternalServerError("reading locale.gen failed", err)
|
||||
}
|
||||
newContent, found := uncommentLocaleGen(string(data), locale)
|
||||
if !found {
|
||||
return huma.Error400BadRequest("locale not available for generation: " + locale)
|
||||
}
|
||||
// Write atomically: a crash mid-write would leave /etc/locale.gen truncated
|
||||
// and break every subsequent locale-gen on the host.
|
||||
tmp := path + ".nadir.tmp"
|
||||
if err := os.WriteFile(tmp, []byte(newContent), 0644); err != nil {
|
||||
return huma.Error500InternalServerError("writing locale.gen failed", err)
|
||||
}
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
os.Remove(tmp)
|
||||
return huma.Error500InternalServerError("replacing locale.gen failed", err)
|
||||
}
|
||||
if _, err := oscmd.Run("locale-gen"); err != nil {
|
||||
return huma.Error500InternalServerError("locale-gen failed", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// uncommentLocaleGen finds a commented-out line for the given locale in a
|
||||
// locale.gen file and uncomments it. Returns the modified content and whether
|
||||
// a matching line was found. Pure function for testability.
|
||||
func uncommentLocaleGen(content, locale string) (string, bool) {
|
||||
lines := strings.Split(content, "\n")
|
||||
found := false
|
||||
for i, line := range lines {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
// Match lines like "# fr_FR.UTF-8 UTF-8" or "#fr_FR.UTF-8 UTF-8".
|
||||
if !strings.HasPrefix(trimmed, "#") {
|
||||
// Also check if already uncommented (idempotent at the file level).
|
||||
if strings.HasPrefix(trimmed, locale+" ") || trimmed == locale {
|
||||
found = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
uncommented := strings.TrimSpace(strings.TrimPrefix(trimmed, "#"))
|
||||
if strings.HasPrefix(uncommented, locale+" ") || uncommented == locale {
|
||||
lines[i] = uncommented
|
||||
found = true
|
||||
}
|
||||
}
|
||||
return strings.Join(lines, "\n"), found
|
||||
}
|
||||
|
||||
// generateLocaledef generates a locale using localedef. This is the RHEL/Fedora
|
||||
// path where there is no /etc/locale.gen.
|
||||
func generateLocaledef(locale string) error {
|
||||
// Parse "fr_FR.UTF-8" into language_territory="fr_FR" and charmap="UTF-8".
|
||||
// If there is no dot, default to UTF-8 (the common case on modern systems).
|
||||
langTerritory, charmap, _ := strings.Cut(locale, ".")
|
||||
if charmap == "" {
|
||||
charmap = "UTF-8"
|
||||
}
|
||||
if _, err := oscmd.Run("localedef", "-i", langTerritory, "-f", charmap, locale); err != nil {
|
||||
return huma.Error500InternalServerError("localedef failed", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"nadir/internal/oscmd"
|
||||
@@ -46,7 +47,7 @@ func TestSystemHandlers(t *testing.T) {
|
||||
if reflect.DeepEqual(args, []string{"hostname"}) {
|
||||
return oscmd.MockCommand{Stdout: "server01\n", ExitCode: 0}
|
||||
}
|
||||
if reflect.DeepEqual(args, []string{"set-hostname", "server02"}) {
|
||||
if reflect.DeepEqual(args, []string{"set-hostname", "--", "server02"}) {
|
||||
return oscmd.MockCommand{ExitCode: 0}
|
||||
}
|
||||
return oscmd.MockCommand{ExitCode: 1}
|
||||
@@ -141,7 +142,7 @@ func TestSystemHandlers(t *testing.T) {
|
||||
// 4. Test GET & POST /api/system/locale
|
||||
oscmd.SetMock("localectl", func(args []string) oscmd.MockCommand {
|
||||
if reflect.DeepEqual(args, []string{"status"}) {
|
||||
statusOut := " System Locale: LANG=it_IT.UTF-8\n VC Keymap: it\n X11 Layout: it\n"
|
||||
statusOut := " System Locale: LANG=it_IT.UTF-8\n LANGUAGE=en_US:\n VC Keymap: it\n X11 Layout: it\n"
|
||||
return oscmd.MockCommand{Stdout: statusOut, ExitCode: 0}
|
||||
}
|
||||
if reflect.DeepEqual(args, []string{"list-locales"}) {
|
||||
@@ -150,6 +151,9 @@ func TestSystemHandlers(t *testing.T) {
|
||||
if reflect.DeepEqual(args, []string{"set-locale", "LANG=it_IT.UTF-8"}) {
|
||||
return oscmd.MockCommand{ExitCode: 0}
|
||||
}
|
||||
if reflect.DeepEqual(args, []string{"set-locale", "LANG=it_IT.UTF-8", "LANGUAGE=en_US:"}) {
|
||||
return oscmd.MockCommand{ExitCode: 0}
|
||||
}
|
||||
if reflect.DeepEqual(args, []string{"list-keymaps"}) {
|
||||
return oscmd.MockCommand{Stdout: "it\nus\n", ExitCode: 0}
|
||||
}
|
||||
@@ -167,7 +171,7 @@ func TestSystemHandlers(t *testing.T) {
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &localeRes.Body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if localeRes.Body.Lang != "it_IT.UTF-8" || localeRes.Body.VCKeymap != "it" {
|
||||
if localeRes.Body.Lang != "it_IT.UTF-8" || localeRes.Body.Language != "en_US:" || localeRes.Body.VCKeymap != "it" {
|
||||
t.Errorf("got locale status: %+v", localeRes.Body)
|
||||
}
|
||||
|
||||
@@ -185,6 +189,17 @@ func TestSystemHandlers(t *testing.T) {
|
||||
t.Errorf("set locale: got %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
resp = api.Post("/api/system/locale", struct {
|
||||
Lang string `json:"lang"`
|
||||
Language string `json:"language"`
|
||||
}{
|
||||
Lang: "it_IT.UTF-8",
|
||||
Language: "en_US:",
|
||||
})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("set locale with language: got %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
resp = api.Get("/api/system/keymaps")
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("list keymaps: got %d, want %d", resp.Code, http.StatusOK)
|
||||
@@ -199,6 +214,37 @@ func TestSystemHandlers(t *testing.T) {
|
||||
t.Errorf("set keymap: got %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
// 4b. Test POST /api/system/locale/generate (validation & idempotent)
|
||||
// Empty locale → 422 (huma validates non-empty before handler runs)
|
||||
resp = api.Post("/api/system/locale/generate", struct {
|
||||
Locale string `json:"locale"`
|
||||
}{
|
||||
Locale: "",
|
||||
})
|
||||
if resp.Code != http.StatusBadRequest && resp.Code != http.StatusUnprocessableEntity {
|
||||
t.Errorf("generate empty locale: got %d, want 400 or 422", resp.Code)
|
||||
}
|
||||
|
||||
// Invalid format → 400
|
||||
resp = api.Post("/api/system/locale/generate", struct {
|
||||
Locale string `json:"locale"`
|
||||
}{
|
||||
Locale: "not-a-locale!!",
|
||||
})
|
||||
if resp.Code != http.StatusBadRequest {
|
||||
t.Errorf("generate invalid locale: got %d, want %d", resp.Code, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
// Already generated (it_IT.UTF-8 is in list-locales mock) → 200 (idempotent)
|
||||
resp = api.Post("/api/system/locale/generate", struct {
|
||||
Locale string `json:"locale"`
|
||||
}{
|
||||
Locale: "it_IT.UTF-8",
|
||||
})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("generate existing locale (idempotent): got %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
// 5. Test POST /api/system/reboot and /api/system/poweroff
|
||||
oscmd.SetMock("shutdown", func(args []string) oscmd.MockCommand {
|
||||
if reflect.DeepEqual(args, []string{"-r", "now"}) || reflect.DeepEqual(args, []string{"-h", "now"}) {
|
||||
@@ -225,3 +271,58 @@ func TestSystemHandlers(t *testing.T) {
|
||||
t.Errorf("poweroff: got %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUncommentLocaleGen(t *testing.T) {
|
||||
const sampleLocaleGen = `# This file lists locales that you wish to have built.
|
||||
#
|
||||
# en_US.UTF-8 UTF-8
|
||||
# fr_FR.UTF-8 UTF-8
|
||||
# de_DE.UTF-8 UTF-8
|
||||
it_IT.UTF-8 UTF-8
|
||||
`
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
locale string
|
||||
wantFound bool
|
||||
wantSubstr string // substring that should appear uncommented
|
||||
}{
|
||||
{
|
||||
name: "uncomment commented locale",
|
||||
locale: "fr_FR.UTF-8",
|
||||
wantFound: true,
|
||||
wantSubstr: "\nfr_FR.UTF-8 UTF-8\n",
|
||||
},
|
||||
{
|
||||
name: "already uncommented",
|
||||
locale: "it_IT.UTF-8",
|
||||
wantFound: true,
|
||||
},
|
||||
{
|
||||
name: "locale not in file",
|
||||
locale: "ja_JP.UTF-8",
|
||||
wantFound: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, found := uncommentLocaleGen(sampleLocaleGen, tt.locale)
|
||||
if found != tt.wantFound {
|
||||
t.Errorf("found = %v, want %v", found, tt.wantFound)
|
||||
}
|
||||
if tt.wantSubstr != "" && !contains(result, tt.wantSubstr) {
|
||||
t.Errorf("result does not contain %q:\n%s", tt.wantSubstr, result)
|
||||
}
|
||||
// The commented versions of OTHER locales should remain commented.
|
||||
if tt.locale == "fr_FR.UTF-8" && !contains(result, "# en_US.UTF-8 UTF-8") {
|
||||
t.Errorf("other locales should stay commented:\n%s", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
return len(s) >= len(substr) && (s == substr || len(substr) == 0 ||
|
||||
(len(s) > 0 && strings.Contains(s, substr)))
|
||||
}
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
package terminal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"nadir/internal/auth"
|
||||
"nadir/internal/module"
|
||||
"nadir/internal/rbac"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/creack/pty"
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/danielgtaylor/huma/v2/adapters/humago"
|
||||
)
|
||||
|
||||
// tagTerminal is the OpenAPI tag for this module (registered in server.go),
|
||||
// keeping tags 1:1 with modules per the project convention.
|
||||
const tagTerminal = "Terminal"
|
||||
|
||||
const (
|
||||
// maxTerminals caps concurrent shells so a buggy frontend or careless admin
|
||||
// can't pile up PTYs (guideline: limit everything). Raise if it's ever a real
|
||||
// limit in practice.
|
||||
maxTerminals = 10
|
||||
// idleTimeout closes a session after this long with no I/O in either
|
||||
// direction, reclaiming abandoned shells.
|
||||
idleTimeout = 15 * time.Minute
|
||||
)
|
||||
|
||||
// terminalSem is the concurrency limiter; a slot is held for the life of a session.
|
||||
var terminalSem = make(chan struct{}, maxTerminals)
|
||||
|
||||
type terminalModule struct {
|
||||
sessions *auth.SessionStore
|
||||
}
|
||||
|
||||
// New creates a new Terminal module that allows interactive shell access.
|
||||
func New(sessions *auth.SessionStore) module.Module {
|
||||
return &terminalModule{sessions: sessions}
|
||||
}
|
||||
|
||||
func (m *terminalModule) ID() string { return "terminal" }
|
||||
|
||||
func (m *terminalModule) Permissions() []rbac.Permission {
|
||||
return []rbac.Permission{rbac.Root}
|
||||
}
|
||||
|
||||
type TerminalInput struct {
|
||||
Ctx huma.Context `json:"-"`
|
||||
}
|
||||
|
||||
// Resolve extracts the huma.Context into the input struct.
|
||||
func (i *TerminalInput) Resolve(ctx huma.Context) []error {
|
||||
i.Ctx = ctx
|
||||
return nil
|
||||
}
|
||||
|
||||
type resizeMessage struct {
|
||||
Cols uint16 `json:"cols"`
|
||||
Rows uint16 `json:"rows"`
|
||||
}
|
||||
|
||||
func (m *terminalModule) Register(api huma.API) {
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "terminal-connect",
|
||||
Method: "GET",
|
||||
Path: "/api/terminal",
|
||||
Summary: "Connect to an interactive terminal",
|
||||
Description: "Upgrades the connection to a WebSocket and spawns a PTY shell as the logged-in user. Send JSON `{cols, rows}` text messages to resize, and raw binary/text messages for stdin. This is a raw WebSocket endpoint — it cannot be exercised from the API docs \"Try it\" panel; use a WebSocket client.",
|
||||
Tags: []string{tagTerminal},
|
||||
Metadata: map[string]any{"module": m.ID(), "permission": string(rbac.Root)},
|
||||
Errors: []int{401, 403, 426, 500},
|
||||
}, func(ctx context.Context, in *TerminalInput) (*struct{}, error) {
|
||||
// The RBAC middleware already authenticated this request and enforced the
|
||||
// "root" permission before we got here. We re-read the session only to get
|
||||
// the username for `su`; the 401 below is the fallback for when the module
|
||||
// is mounted without the middleware (e.g. in unit tests).
|
||||
cookie, err := huma.ReadCookie(in.Ctx, "nadir_session_id")
|
||||
if err != nil || cookie == nil {
|
||||
return nil, huma.Error401Unauthorized("unauthorized")
|
||||
}
|
||||
|
||||
sess, ok := m.sessions.GetByToken(cookie.Value)
|
||||
if !ok {
|
||||
return nil, huma.Error401Unauthorized("unauthorized")
|
||||
}
|
||||
|
||||
req, res := humago.Unwrap(in.Ctx)
|
||||
if req == nil || res == nil {
|
||||
return nil, huma.Error500InternalServerError("missing http context")
|
||||
}
|
||||
|
||||
// Reject plain GETs (e.g. the docs "Try it" button) with a clear 426 rather
|
||||
// than letting websocket.Accept emit a raw protocol-violation error.
|
||||
if !strings.EqualFold(req.Header.Get("Upgrade"), "websocket") {
|
||||
return nil, huma.NewError(http.StatusUpgradeRequired,
|
||||
"this endpoint requires a WebSocket connection; connect with a WebSocket client")
|
||||
}
|
||||
|
||||
// InsecureSkipVerify is deliberately NOT set: coder/websocket then enforces
|
||||
// that the Origin host matches the request Host, rejecting cross-site upgrade
|
||||
// attempts. Defense-in-depth on top of the SameSite=Strict session cookie —
|
||||
// important because this endpoint hands out an interactive shell.
|
||||
conn, err := websocket.Accept(res, req, nil)
|
||||
if err != nil {
|
||||
// websocket.Accept already wrote the error response (e.g. 403 on an
|
||||
// Origin mismatch). Just stop; writing again would corrupt the response.
|
||||
return nil, nil
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
|
||||
// Bound concurrent shells: take a slot or reject (don't pile up PTYs).
|
||||
select {
|
||||
case terminalSem <- struct{}{}:
|
||||
defer func() { <-terminalSem }()
|
||||
default:
|
||||
conn.Close(websocket.StatusTryAgainLater, "too many terminal sessions")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Launch the user's login shell via su.
|
||||
// "su - <username>" ensures we get their actual environment and shell.
|
||||
cmd := exec.CommandContext(req.Context(), "su", "-", sess.Username)
|
||||
|
||||
// Start the command with a PTY.
|
||||
ptmx, err := pty.Start(cmd)
|
||||
if err != nil {
|
||||
conn.Close(websocket.StatusInternalError, "failed to start pty")
|
||||
return nil, nil
|
||||
}
|
||||
defer ptmx.Close()
|
||||
|
||||
// lastActive is bumped by both pumps; the watchdog uses it to close idle
|
||||
// sessions. Output activity (e.g. `top`) counts, so it isn't killed.
|
||||
var lastActive atomic.Int64
|
||||
lastActive.Store(time.Now().UnixNano())
|
||||
go func() {
|
||||
tick := time.NewTicker(idleTimeout / 4)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-req.Context().Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
if time.Since(time.Unix(0, lastActive.Load())) > idleTimeout {
|
||||
conn.Close(websocket.StatusGoingAway, "idle timeout")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Pump stdout/stderr from PTY to WebSocket.
|
||||
go func() {
|
||||
buf := make([]byte, 8192)
|
||||
for {
|
||||
n, err := ptmx.Read(buf)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
lastActive.Store(time.Now().UnixNano())
|
||||
// We write PTY output as binary messages. The frontend (e.g., xterm.js)
|
||||
// can handle UTF-8 binary or text transparently.
|
||||
err = conn.Write(req.Context(), websocket.MessageBinary, buf[:n])
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
conn.Close(websocket.StatusNormalClosure, "")
|
||||
}()
|
||||
|
||||
// Pump stdin and resize commands from WebSocket to PTY.
|
||||
for {
|
||||
typ, b, err := conn.Read(req.Context())
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
lastActive.Store(time.Now().UnixNano())
|
||||
|
||||
if typ == websocket.MessageText {
|
||||
var resize resizeMessage
|
||||
if err := json.Unmarshal(b, &resize); err == nil && resize.Cols > 0 && resize.Rows > 0 {
|
||||
// Handle resize
|
||||
_ = pty.Setsize(ptmx, &pty.Winsize{
|
||||
Cols: resize.Cols,
|
||||
Rows: resize.Rows,
|
||||
})
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// If not a valid resize message, or if it's MessageBinary, pass to PTY stdin.
|
||||
_, _ = ptmx.Write(b)
|
||||
}
|
||||
|
||||
// The read loop has ended (client gone or PTY closed). Tear down the shell
|
||||
// and reap it: closing the PTY sends EOF, Kill covers shells that ignore it.
|
||||
_ = ptmx.Close()
|
||||
_ = cmd.Process.Kill()
|
||||
_ = cmd.Wait()
|
||||
return nil, nil
|
||||
})
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
package terminal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"nadir/internal/auth"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/danielgtaylor/huma/v2/adapters/humago"
|
||||
)
|
||||
|
||||
func TestTerminalConnectUnauthorized(t *testing.T) {
|
||||
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
|
||||
if err != nil {
|
||||
t.Fatalf("session db: %v", err)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
|
||||
mod := New(sessions)
|
||||
mod.Register(api)
|
||||
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) + "/api/terminal"
|
||||
|
||||
// Try without cookie
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, resp, err := websocket.Dial(ctx, wsURL, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got success")
|
||||
}
|
||||
if resp != nil && resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalConnectPlainGET(t *testing.T) {
|
||||
// An authenticated but non-WebSocket GET (e.g. the docs "Try it" button) must
|
||||
// get a clean 426 Upgrade Required, not a raw websocket protocol error.
|
||||
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
|
||||
if err != nil {
|
||||
t.Fatalf("session db: %v", err)
|
||||
}
|
||||
token, err := sessions.Create("root")
|
||||
if err != nil {
|
||||
t.Fatalf("create session: %v", err)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
|
||||
New(sessions).Register(api)
|
||||
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
req, _ := http.NewRequest(http.MethodGet, srv.URL+"/api/terminal", nil)
|
||||
req.Header.Set("Cookie", "nadir_session_id="+token)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("GET failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUpgradeRequired {
|
||||
t.Errorf("expected 426, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalConnectAuthorized(t *testing.T) {
|
||||
// Root or specific system configs might cause PTY or su to fail if run in constrained environments.
|
||||
// But we expect the websocket upgrade to succeed and then maybe close with an error if PTY fails.
|
||||
sessions, err := auth.NewSessionStore("file::memory:?cache=shared")
|
||||
if err != nil {
|
||||
t.Fatalf("session db: %v", err)
|
||||
}
|
||||
|
||||
token, err := sessions.Create("root")
|
||||
if err != nil {
|
||||
t.Fatalf("create session: %v", err)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test", "1.0.0"))
|
||||
mod := New(sessions)
|
||||
mod.Register(api)
|
||||
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) + "/api/terminal"
|
||||
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
opts := &websocket.DialOptions{
|
||||
HTTPHeader: http.Header{},
|
||||
}
|
||||
opts.HTTPHeader.Set("Cookie", "nadir_session_id="+token)
|
||||
|
||||
conn, resp, err := websocket.Dial(ctx, wsURL, opts)
|
||||
if err != nil {
|
||||
// Depending on the test environment, "su" or "pty" might fail, but
|
||||
// the websocket upgrade itself should succeed before it drops.
|
||||
// If it fails to upgrade, that's a real error.
|
||||
t.Fatalf("dial failed: %v (status %d)", err, resp.StatusCode)
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
|
||||
// The connection was upgraded successfully.
|
||||
// If PTY allocation failed or su failed, the server might close the connection immediately.
|
||||
// We just verify the upgrade succeeded.
|
||||
if resp.StatusCode != http.StatusSwitchingProtocols {
|
||||
t.Errorf("expected 101, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,17 @@ import (
|
||||
|
||||
const ModuleID = "users"
|
||||
|
||||
type Module struct{}
|
||||
// sessionStore is the subset of SessionStore that password changes need:
|
||||
// invalidate all existing sessions for a user whose password just changed.
|
||||
type sessionStore interface {
|
||||
DeleteByUsername(username string) error
|
||||
}
|
||||
|
||||
func New() *Module { return &Module{} }
|
||||
type Module struct {
|
||||
sessions sessionStore
|
||||
}
|
||||
|
||||
func New(sessions sessionStore) *Module { return &Module{sessions: sessions} }
|
||||
|
||||
func (m *Module) ID() string { return ModuleID }
|
||||
|
||||
@@ -21,7 +29,7 @@ func (m *Module) Permissions() []rbac.Permission {
|
||||
}
|
||||
|
||||
func (m *Module) Register(api huma.API) {
|
||||
registerUsers(api)
|
||||
registerUsers(api, m.sessions)
|
||||
}
|
||||
|
||||
func op(permission string) map[string]any {
|
||||
|
||||
@@ -2,6 +2,7 @@ package users
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
@@ -91,7 +92,7 @@ type UserGroupsOutput struct {
|
||||
}
|
||||
}
|
||||
|
||||
func registerUsers(api huma.API) {
|
||||
func registerUsers(api huma.API, sessions sessionStore) {
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "users-list",
|
||||
Method: "GET",
|
||||
@@ -105,7 +106,7 @@ func registerUsers(api huma.API) {
|
||||
}, func(ctx context.Context, _ *struct{}) (*ListUsersOutput, error) {
|
||||
list, err := listUsers()
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||
}
|
||||
out := &ListUsersOutput{}
|
||||
out.Body.Users = list
|
||||
@@ -127,7 +128,7 @@ func registerUsers(api huma.API) {
|
||||
}
|
||||
u, ok, err := lookupUser(in.Username)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||
}
|
||||
if !ok {
|
||||
return nil, huma.Error404NotFound("user not found: " + in.Username)
|
||||
@@ -163,7 +164,7 @@ func registerUsers(api huma.API) {
|
||||
return nil, huma.Error400BadRequest("home must be an absolute path")
|
||||
}
|
||||
if _, ok, err := lookupUser(in.Body.Username); err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||
} else if ok {
|
||||
return nil, huma.Error409Conflict("user already exists: " + in.Body.Username)
|
||||
}
|
||||
@@ -212,7 +213,7 @@ func registerUsers(api huma.API) {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok, err := lookupUser(in.Username); err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||
} else if !ok {
|
||||
return nil, huma.Error404NotFound("user not found: " + in.Username)
|
||||
}
|
||||
@@ -253,7 +254,7 @@ func registerUsers(api huma.API) {
|
||||
return nil, huma.Error400BadRequest("password may not contain newlines")
|
||||
}
|
||||
if _, ok, err := lookupUser(in.Username); err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||
} else if !ok {
|
||||
return nil, huma.Error404NotFound("user not found: " + in.Username)
|
||||
}
|
||||
@@ -261,6 +262,11 @@ func registerUsers(api huma.API) {
|
||||
if _, err := oscmd.RunStdin(in.Username+":"+in.Body.Password+"\n", "chpasswd"); err != nil {
|
||||
return nil, huma.Error500InternalServerError("chpasswd failed", err)
|
||||
}
|
||||
if sessions != nil {
|
||||
if err := sessions.DeleteByUsername(in.Username); err != nil {
|
||||
log.Printf("failed to invalidate sessions for %s: %v", in.Username, err)
|
||||
}
|
||||
}
|
||||
return oscmd.OK(), nil
|
||||
})
|
||||
|
||||
@@ -290,7 +296,7 @@ func registerUsers(api huma.API) {
|
||||
}
|
||||
}
|
||||
if _, ok, err := lookupUser(in.Username); err != nil {
|
||||
return nil, huma.Error500InternalServerError("read "+passwdPath+" failed", err)
|
||||
return nil, huma.Error500InternalServerError("user lookup failed", err)
|
||||
} else if !ok {
|
||||
return nil, huma.Error404NotFound("user not found: " + in.Username)
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestUsersHandlers(t *testing.T) {
|
||||
|
||||
mux := http.NewServeMux()
|
||||
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
|
||||
registerUsers(api)
|
||||
registerUsers(api, nil)
|
||||
|
||||
// 1. Test GET /api/users
|
||||
resp := api.Get("/api/users")
|
||||
|
||||
@@ -28,26 +28,34 @@ short:x:2:2
|
||||
}
|
||||
|
||||
func TestValidateUsername(t *testing.T) {
|
||||
valid := []string{"alice", "_svc", "user-1", "a", "machine$", "abc_def"}
|
||||
for _, n := range valid {
|
||||
if err := validateUsername(n); err != nil {
|
||||
t.Errorf("validateUsername(%q) = %v, want nil", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
invalid := []string{
|
||||
"", // empty
|
||||
"-rf", // leading dash (flag injection)
|
||||
"Alice", // uppercase
|
||||
"1user", // leading digit
|
||||
"a b", // space
|
||||
"foo;rm", // shell metachar
|
||||
"root:x", // colon (passwd separator)
|
||||
"waytoolongusernamethatexceedsthirtytwochars", // >32
|
||||
}
|
||||
for _, n := range invalid {
|
||||
if err := validateUsername(n); err == nil {
|
||||
t.Errorf("validateUsername(%q) = nil, want error", n)
|
||||
}
|
||||
for _, n := range []struct {
|
||||
name string
|
||||
value string
|
||||
valid bool
|
||||
}{
|
||||
{name: "alice", value: "alice", valid: true},
|
||||
{name: "underscore prefix", value: "_svc", valid: true},
|
||||
{name: "hyphen", value: "user-1", valid: true},
|
||||
{name: "single char", value: "a", valid: true},
|
||||
{name: "dollar suffix", value: "machine$", valid: true},
|
||||
{name: "underscore", value: "abc_def", valid: true},
|
||||
{name: "empty", value: "", valid: false},
|
||||
{name: "leading dash", value: "-rf", valid: false},
|
||||
{name: "uppercase", value: "Alice", valid: false},
|
||||
{name: "leading digit", value: "1user", valid: false},
|
||||
{name: "space", value: "a b", valid: false},
|
||||
{name: "shell metachar", value: "foo;rm", valid: false},
|
||||
{name: "colon", value: "root:x", valid: false},
|
||||
{name: "too long", value: "waytoolongusernamethatexceedsthirtytwochars", valid: false},
|
||||
} {
|
||||
t.Run(n.name, func(t *testing.T) {
|
||||
err := validateUsername(n.value)
|
||||
if n.valid && err != nil {
|
||||
t.Errorf("validateUsername(%q) = %v, want nil", n.value, err)
|
||||
}
|
||||
if !n.valid && err == nil {
|
||||
t.Errorf("validateUsername(%q) = nil, want error", n.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,16 +25,22 @@ func TestParseProc(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestUnescape(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
`/mnt/my\040disk`: "/mnt/my disk",
|
||||
`/no/escapes`: "/no/escapes",
|
||||
`tab\011here`: "tab\there",
|
||||
`back\134slash`: `back\slash`,
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{name: "octal space", in: `/mnt/my\040disk`, want: "/mnt/my disk"},
|
||||
{name: "no escapes", in: `/no/escapes`, want: "/no/escapes"},
|
||||
{name: "tab", in: `tab\011here`, want: "tab\there"},
|
||||
{name: "backslash", in: `back\134slash`, want: `back\slash`},
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := Unescape(in); got != want {
|
||||
t.Errorf("Unescape(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := Unescape(tt.in); got != tt.want {
|
||||
t.Errorf("Unescape(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ import (
|
||||
"nadir/internal/modules/services"
|
||||
"nadir/internal/modules/storage"
|
||||
"nadir/internal/modules/system"
|
||||
"nadir/internal/modules/terminal"
|
||||
"nadir/internal/modules/users"
|
||||
"nadir/internal/rbac"
|
||||
|
||||
@@ -44,13 +43,12 @@ func TestOpenAPISchemaNoCollisions(t *testing.T) {
|
||||
mods := []module.Module{
|
||||
system.New(),
|
||||
services.New(nil),
|
||||
users.New(),
|
||||
users.New(nil),
|
||||
groups.New(),
|
||||
packages.New(),
|
||||
networking.New(),
|
||||
storage.New(),
|
||||
audit.New(auditStore),
|
||||
terminal.New(sessions),
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -41,8 +41,6 @@ func TestRbacMiddleware(t *testing.T) {
|
||||
},
|
||||
})
|
||||
r.AssignRole("alice", "test-role")
|
||||
// A machine credential is just another RBAC subject: the token name is
|
||||
// assigned a role exactly like a username.
|
||||
r.AssignRole("dash", "test-role")
|
||||
|
||||
mux := http.NewServeMux()
|
||||
@@ -76,81 +74,91 @@ func TestRbacMiddleware(t *testing.T) {
|
||||
return &struct{ Body string }{Body: "gated-write"}, nil
|
||||
})
|
||||
|
||||
// 1. Test public route
|
||||
resp := api.Get("/public")
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("public GET: got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
t.Run("public route", func(t *testing.T) {
|
||||
resp := api.Get("/public")
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
})
|
||||
|
||||
// 2. Test gated route without cookie -> 401 Unauthorized
|
||||
resp = api.Get("/gated-read")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("gated GET no cookie: got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
t.Run("no auth returns 401", func(t *testing.T) {
|
||||
resp := api.Get("/gated-read")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
})
|
||||
|
||||
// 3. Test gated route with invalid cookie -> 401 Unauthorized
|
||||
resp = api.Get("/gated-read", "Cookie: nadir_session_id=invalid")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("gated GET invalid cookie: got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
t.Run("invalid cookie returns 401", func(t *testing.T) {
|
||||
resp := api.Get("/gated-read", "Cookie: nadir_session_id=invalid")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
})
|
||||
|
||||
// Create valid session
|
||||
token, err := sessions.Create("alice")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var aliceToken string
|
||||
t.Run("valid session returns 200", func(t *testing.T) {
|
||||
var err error
|
||||
aliceToken, err = sessions.Create("alice")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp := api.Get("/gated-read", "Cookie: nadir_session_id="+aliceToken)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
})
|
||||
|
||||
// 4. Test gated route with valid cookie -> 200 OK
|
||||
resp = api.Get("/gated-read", "Cookie: nadir_session_id="+token)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("gated GET valid cookie: got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
t.Run("csrf mismatched origin returns 403", func(t *testing.T) {
|
||||
resp := api.Post("/gated-write", "Cookie: nadir_session_id="+aliceToken, "Origin: http://evil.com", "Host: example.com", struct{}{})
|
||||
if resp.Code != http.StatusForbidden {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||
}
|
||||
})
|
||||
|
||||
// 5. Test CSRF violation: POST with mismatched Origin header -> 403 Forbidden
|
||||
resp = api.Post("/gated-write", "Cookie: nadir_session_id="+token, "Origin: http://evil.com", "Host: example.com", struct{}{})
|
||||
if resp.Code != http.StatusForbidden {
|
||||
t.Errorf("CSRF mismatched Origin: got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||
}
|
||||
t.Run("csrf matching origin returns 200", func(t *testing.T) {
|
||||
resp := api.Post("/gated-write", "Cookie: nadir_session_id="+aliceToken, "Origin: http://example.com", "Host: example.com", struct{}{})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
})
|
||||
|
||||
// 6. Test CSRF success: POST with matching Origin header -> 200 OK
|
||||
resp = api.Post("/gated-write", "Cookie: nadir_session_id="+token, "Origin: http://example.com", "Host: example.com", struct{}{})
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("CSRF matching Origin: got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
t.Run("unauthorized user returns 403", func(t *testing.T) {
|
||||
bobToken, err := sessions.Create("bob")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp := api.Get("/gated-read", "Cookie: nadir_session_id="+bobToken)
|
||||
if resp.Code != http.StatusForbidden {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||
}
|
||||
})
|
||||
|
||||
// 7. Test gated route with unauthorized user -> 403 Forbidden
|
||||
tokenBob, err := sessions.Create("bob")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp = api.Get("/gated-read", "Cookie: nadir_session_id="+tokenBob)
|
||||
if resp.Code != http.StatusForbidden {
|
||||
t.Errorf("bob unauthorized GET: got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||
}
|
||||
t.Run("valid bearer token returns 200", func(t *testing.T) {
|
||||
rawToken, err := tokenStore.Create("dash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp := api.Get("/gated-read", "Authorization: Bearer "+rawToken)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
})
|
||||
|
||||
// 8. Bearer token for an assigned name -> 200 OK
|
||||
rawToken, err := tokenStore.Create("dash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp = api.Get("/gated-read", "Authorization: Bearer "+rawToken)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("valid bearer GET: got status %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
t.Run("bogus bearer token returns 401", func(t *testing.T) {
|
||||
resp := api.Get("/gated-read", "Authorization: Bearer nad_deadbeef")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
})
|
||||
|
||||
// 9. Bogus bearer token -> 401 Unauthorized
|
||||
resp = api.Get("/gated-read", "Authorization: Bearer nad_deadbeef")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("bogus bearer GET: got status %d, want %d", resp.Code, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
// 10. Bearer token with no role assignment -> 403 Forbidden
|
||||
rawUnassigned, err := tokenStore.Create("orphan")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp = api.Get("/gated-read", "Authorization: Bearer "+rawUnassigned)
|
||||
if resp.Code != http.StatusForbidden {
|
||||
t.Errorf("unassigned bearer GET: got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||
}
|
||||
t.Run("unassigned bearer token returns 403", func(t *testing.T) {
|
||||
rawUnassigned, err := tokenStore.Create("orphan")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp := api.Get("/gated-read", "Authorization: Bearer "+rawUnassigned)
|
||||
if resp.Code != http.StatusForbidden {
|
||||
t.Errorf("got status %d, want %d", resp.Code, http.StatusForbidden)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
untrusted comment: minisign public key: 702ABD7F45200669
|
||||
RWRpBiBFf70qcEXS0cOS+8tZ1hpoLj9mX0V5OiE8qYIIZsetU8hNA4Ou
|
||||
Executable
BIN
Binary file not shown.
@@ -0,0 +1,54 @@
|
||||
// Command sign-checksums is a CI helper that signs a file using minisign.
|
||||
//
|
||||
// The minisign CLI reads passwords from /dev/tty, which doesn't exist in CI
|
||||
// runners. This program uses the library directly: password and encrypted
|
||||
// secret key come from environment variables, no terminal required.
|
||||
//
|
||||
// Usage (in CI):
|
||||
//
|
||||
// MINISIGN_SECRET_KEY=... MINISIGN_PASSWORD=... go run ./tools/sign-checksums dist/sha256sums.txt
|
||||
//
|
||||
// Produces dist/sha256sums.txt.minisig alongside the input.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"aead.dev/minisign"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 2 {
|
||||
fmt.Fprintf(os.Stderr, "usage: sign-checksums <file>\n")
|
||||
os.Exit(2)
|
||||
}
|
||||
filePath := os.Args[1]
|
||||
|
||||
password := os.Getenv("MINISIGN_PASSWORD")
|
||||
keyBytes := []byte(os.Getenv("MINISIGN_SECRET_KEY"))
|
||||
if len(keyBytes) == 0 {
|
||||
fmt.Fprintln(os.Stderr, "MINISIGN_SECRET_KEY is not set")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
key, err := minisign.DecryptKey(password, keyBytes)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "decrypt key: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
message, err := os.ReadFile(filePath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "read %s: %v\n", filePath, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
sig := minisign.Sign(key, message)
|
||||
sigPath := filePath + ".minisig"
|
||||
if err := os.WriteFile(sigPath, sig, 0644); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "write %s: %v\n", sigPath, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf("signed %s -> %s\n", filePath, sigPath)
|
||||
}
|
||||
Reference in New Issue
Block a user