12 Commits

Author SHA1 Message Date
urania 63c9a272b5 feat: add configurable TLS/proxy installation options for the systemd service
build-and-release / release (push) Successful in 2m34s
2026-06-23 19:13:34 +02:00
urania 411f7fd6d9 feat: persistent TLS cert and token auto-generation during install 2026-06-23 19:05:26 +02:00
urania 8fc4b236ac fix: whomai with bearer
build-and-release / release (push) Successful in 2m39s
2026-06-23 18:02:52 +02:00
urania 37f03816e1 fix: networking/interfaces
build-and-release / release (push) Successful in 2m29s
2026-06-23 17:40:44 +02:00
urania 541260e65e fix: networking/interfaces
build-and-release / release (push) Has been cancelled
2026-06-23 17:40:17 +02:00
urania c4180bada1 fix: networking / services / and testing
build-and-release / release (push) Successful in 2m40s
2026-06-23 17:16:01 +02:00
urania 088880f584 fix: updates
build-and-release / release (push) Successful in 2m39s
2026-06-23 14:27:06 +02:00
urania 67d95475ee fix: added package update endpoint
build-and-release / release (push) Successful in 3m1s
2026-06-23 13:15:39 +02:00
urania aec04bfe02 fix: storages and mounts
build-and-release / release (push) Successful in 2m52s
2026-06-23 11:50:55 +02:00
urania a54c42271c minor: test
build-and-release / release (push) Successful in 1m9s
2026-06-23 01:23:19 +02:00
urania b10abb24e3 fix: various
build-and-release / release (push) Successful in 2m49s
2026-06-22 22:40:34 +02:00
urania 9587d11e21 fix: localectl
build-and-release / release (push) Successful in 2m38s
2026-06-22 22:22:36 +02:00
19 changed files with 930 additions and 98 deletions
+6 -7
View File
@@ -81,7 +81,7 @@ func main() {
fmt.Printf("configuration file already exists at %s\n", configPath) fmt.Printf("configuration file already exists at %s\n", configPath)
os.Exit(0) os.Exit(0)
} }
fatalIf(saveDefaultConfig(configPath)) fatalIf(saveDefaultConfig(configPath, DefaultConfigContent(getUsername())))
os.Exit(0) os.Exit(0)
} }
@@ -96,7 +96,7 @@ func main() {
runCmd(args) runCmd(args)
case "install": case "install":
ensureRoot() ensureRoot()
fatalIf(installService()) fatalIf(installService(args))
case "uninstall": case "uninstall":
ensureRoot() ensureRoot()
fatalIf(uninstallService(slices.Contains(args, "--complete"))) fatalIf(uninstallService(slices.Contains(args, "--complete")))
@@ -238,9 +238,8 @@ func runServer() {
meta.Register(api, mods) meta.Register(api, mods)
meta.RegisterHealth(api, sessions) meta.RegisterHealth(api, sessions)
meta.RegisterWhoami(api, sessions, roles, mods) meta.RegisterWhoami(api, sessions, tokenAuth, roles, mods)
meta.ConfigPath = configPath meta.RegisterUpdate(api, configPath)
meta.RegisterUpdate(api)
auth.RegisterLogin(api, sessions, auditStore, cfg.SecureCookie()) auth.RegisterLogin(api, sessions, auditStore, cfg.SecureCookie())
auth.RegisterLogout(api, sessions, cfg.SecureCookie()) auth.RegisterLogout(api, sessions, cfg.SecureCookie())
@@ -279,11 +278,11 @@ func runServer() {
// is the follow-up (M5 partial). // is the follow-up (M5 partial).
w.Header().Set("Content-Security-Policy", w.Header().Set("Content-Security-Policy",
"default-src 'self'; "+ "default-src 'self'; "+
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+ "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net; "+
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+ "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
"img-src 'self' data: https:; "+ "img-src 'self' data: https:; "+
"connect-src 'self'; "+ "connect-src 'self'; "+
"font-src 'self' data: https://cdn.jsdelivr.net") "font-src 'self' data: https://cdn.jsdelivr.net https://fonts.scalar.com")
w.Header().Set("Content-Type", "text/html") w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`<!doctype html><html><head><title>API</title> w.Write([]byte(`<!doctype html><html><head><title>API</title>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"> <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+143 -27
View File
@@ -1,6 +1,7 @@
package main package main
import ( import (
"flag"
"fmt" "fmt"
"io" "io"
"os" "os"
@@ -13,26 +14,29 @@ import (
"nadir/internal/config" "nadir/internal/config"
) )
const defaultConfigTemplate = `# Nadir configuration - config.yaml const configTemplateBase = `# Nadir configuration - config.yaml
# #
# Single source of truth for runtime settings. # Single source of truth for runtime settings.
# #
server: server:
secure_tls: true secure_tls: %s
# trust_proxy: false %s
# tls_cert: /etc/nadir/tls/cert.pem %s
# tls_key: /etc/nadir/tls/key.pem %s
hostname: 127.0.0.1 hostname: %s
port: 9999 port: %d
release_repo: https://tea.urania.dev/urania/nadir-agent release_repo: https://tea.urania.dev/urania/nadir-agent
roles: roles:
admin: admin:
"*": ["*"] "*": ["*"]
auditor:
"*": ["read"]
assignments: assignments:
%s: [admin] %s: [admin]
dashboard: [auditor]
` `
// resolveConfigPath returns the config file path: CONFIG_PATH env (with ~ expanded) // resolveConfigPath returns the config file path: CONFIG_PATH env (with ~ expanded)
@@ -101,7 +105,38 @@ const (
// installService writes the systemd unit, enables it on boot, and starts it. // installService writes the systemd unit, enables it on boot, and starts it.
// The unit pins the absolute executable and config paths captured now, so the // The unit pins the absolute executable and config paths captured now, so the
// service doesn't depend on the working directory at boot. // service doesn't depend on the working directory at boot.
func installService() error { func installService(args []string) error {
// Parse options
fs := flag.NewFlagSet("install", flag.ContinueOnError)
tlsOpt := fs.Bool("tls", false, "Generate persistent self-signed TLS cert/key and enable HTTPS")
unsecureOpt := fs.Bool("unsecure", false, "Serve plaintext HTTP directly")
trustProxyOpt := fs.Bool("trust-proxy", false, "Serve plaintext HTTP behind a trusted TLS-terminating reverse proxy")
hostnameOpt := fs.String("hostname", "127.0.0.1", "Hostname to bind to")
portOpt := fs.Int("port", 9999, "Port to bind to")
if err := fs.Parse(args); err != nil {
return err
}
optCount := 0
if *tlsOpt {
optCount++
}
if *unsecureOpt {
optCount++
}
if *trustProxyOpt {
optCount++
}
if optCount > 1 {
return fmt.Errorf("options --tls, --unsecure, and --trust-proxy are mutually exclusive")
}
// Default to tls if nothing is specified
isTLS := *tlsOpt || optCount == 0
isUnsecure := *unsecureOpt
isTrustProxy := *trustProxyOpt
// Provision the PAM service the server authenticates against, so it exists // Provision the PAM service the server authenticates against, so it exists
// before the unit starts rather than appearing on first login. Idempotent: // before the unit starts rather than appearing on first login. Idempotent:
// EnsurePAMService leaves an existing /etc/pam.d/nadir untouched. runServer // EnsurePAMService leaves an existing /etc/pam.d/nadir untouched. runServer
@@ -130,14 +165,51 @@ func installService() error {
return fmt.Errorf("create data directory: %w", err) return fmt.Errorf("create data directory: %w", err)
} }
// Generate and save persistent self-signed TLS certificates if TLS mode
certPath := filepath.Join("/var/lib/nadir/tls", "cert.pem")
if isTLS {
tlsDir := "/var/lib/nadir/tls"
if err := os.MkdirAll(tlsDir, 0700); err != nil {
return fmt.Errorf("create tls directory: %w", err)
}
keyPath := filepath.Join(tlsDir, "key.pem")
if _, err := os.Stat(certPath); os.IsNotExist(err) {
if err := generateAndSaveCert(certPath, keyPath, *hostnameOpt); err != nil {
return fmt.Errorf("generate certificates: %w", err)
}
fmt.Printf("generated persistent self-signed TLS certificate at %s\n", certPath)
}
}
cfgPath, err := resolveConfigPath() cfgPath, err := resolveConfigPath()
if err != nil { if err != nil {
return err return err
} }
// Construct configuration template content based on installation options
secureTLSVal := "true"
trustProxyLine := "# trust_proxy: false"
certLine := "tls_cert: /var/lib/nadir/tls/cert.pem"
keyLine := "tls_key: /var/lib/nadir/tls/key.pem"
if isUnsecure {
secureTLSVal = "false"
trustProxyLine = "# trust_proxy: false"
certLine = "# tls_cert: /var/lib/nadir/tls/cert.pem"
keyLine = "# tls_key: /var/lib/nadir/tls/key.pem"
} else if isTrustProxy {
secureTLSVal = "false"
trustProxyLine = "trust_proxy: true"
certLine = "# tls_cert: /var/lib/nadir/tls/cert.pem"
keyLine = "# tls_key: /var/lib/nadir/tls/key.pem"
}
username := getUsername()
configContent := fmt.Sprintf(configTemplateBase, secureTLSVal, trustProxyLine, certLine, keyLine, *hostnameOpt, *portOpt, username)
// Ensure default config file exists // Ensure default config file exists
if _, err := os.Stat(cfgPath); os.IsNotExist(err) { if _, err := os.Stat(cfgPath); os.IsNotExist(err) {
if err := saveDefaultConfig(cfgPath); err != nil { if err := saveDefaultConfig(cfgPath, configContent); err != nil {
return err return err
} }
} }
@@ -182,6 +254,44 @@ WantedBy=multi-user.target
fmt.Printf("created logrotate configuration %s\n", logrotatePath) fmt.Printf("created logrotate configuration %s\n", logrotatePath)
} }
// Generate a token for the dashboard if it doesn't exist
var tokenStr string
store, err := auth.NewTokenStore(tokenDBPath)
if err == nil {
defer store.Close()
infos, err := store.List()
hasDashboard := false
if err == nil {
for _, t := range infos {
if t.Name == "dashboard" {
hasDashboard = true
break
}
}
}
if !hasDashboard {
tokenStr, _ = store.Create("dashboard")
} else {
tokenStr = "(already created; run 'nadir token add dashboard' to replace/generate a new one if lost)"
}
} else {
fmt.Printf("warning: failed to open token store: %v\n", err)
}
// Output credentials to copy to the frontend
fmt.Println("\n======================================================================")
fmt.Println(" NADIR CLIENT CREDENTIALS (COPY THESE TO SVELTEKIT FRONTEND)")
fmt.Println("======================================================================")
fmt.Printf("Token for \"dashboard\" (Bearer):\n %s\n", tokenStr)
if isTLS {
certBytes, err := os.ReadFile(certPath)
if err == nil {
fmt.Println("\nCA Certificate (Trust Store):")
fmt.Println(string(certBytes))
}
}
fmt.Println("======================================================================")
fmt.Printf("installed and started %s; follow logs with: %s logs\n", serviceName, filepath.Base(exe)) fmt.Printf("installed and started %s; follow logs with: %s logs\n", serviceName, filepath.Base(exe))
return nil return nil
} }
@@ -393,21 +503,24 @@ func fatalIf(err error) {
} }
} }
// DefaultConfigContent returns the default configuration template filled with the username.
func DefaultConfigContent(username string) string {
return fmt.Sprintf(configTemplateBase, "true", "# trust_proxy: false", "# tls_cert: /var/lib/nadir/tls/cert.pem", "# tls_key: /var/lib/nadir/tls/key.pem", "127.0.0.1", 9999, username)
}
// saveDefaultConfig writes the default configuration template to cfgPath. // saveDefaultConfig writes the default configuration template to cfgPath.
func saveDefaultConfig(cfgPath string) error { func saveDefaultConfig(cfgPath, content string) error {
dir := filepath.Dir(cfgPath) dir := filepath.Dir(cfgPath)
if err := os.MkdirAll(dir, 0755); err != nil { if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("create config directory: %w", err) return fmt.Errorf("create config directory: %w", err)
} }
chownToSudoUser(dir) chownToSudoUser(dir)
username := getUsername() if err := os.WriteFile(cfgPath, []byte(content), 0600); err != nil {
configContent := fmt.Sprintf(defaultConfigTemplate, username)
if err := os.WriteFile(cfgPath, []byte(configContent), 0600); err != nil {
return fmt.Errorf("write default config: %w", err) return fmt.Errorf("write default config: %w", err)
} }
chownToSudoUser(cfgPath) chownToSudoUser(cfgPath)
fmt.Printf("created default configuration file at %s (assigned admin role to user %q)\n", cfgPath, username) fmt.Printf("created default configuration file at %s\n", cfgPath)
return nil return nil
} }
@@ -415,19 +528,22 @@ func usage(w io.Writer) {
fmt.Fprint(w, `nadir - Linux system administration backend fmt.Fprint(w, `nadir - Linux system administration backend
Usage: Usage:
nadir [run] [-d] [-f <path>] Start the server (-d / --detach: run in background) nadir [run] [-d] [-f <path>] Start the server (-d / --detach: run in background)
nadir --save-config [-f <path>] Save default configuration to path and exit nadir --save-config [-f <path>] Save default configuration to path and exit
nadir install [-f <path>] Install + enable the systemd service (starts on boot) nadir install [--tls|--unsecure|--trust-proxy] Install + enable the systemd service (starts on boot)
nadir uninstall [--complete] Remove the service (keeps data/config; --complete wipes all) (--tls: enable HTTPS with self-signed certificate, default)
nadir start|stop|restart|status Control the running service (--unsecure: serve HTTP directly)
nadir enable|disable Toggle start-on-boot without removing the unit (--trust-proxy: serve HTTP behind a reverse proxy)
nadir logs [clear] Follow (default) or clear server logs nadir uninstall [--complete] Remove the service (keeps data/config; --complete wipes all)
nadir token add <name> Mint a machine credential (Bearer token), shown once nadir start|stop|restart|status Control the running service
nadir token rm <name> Revoke a token (effective immediately, no restart) nadir enable|disable Toggle start-on-boot without removing the unit
nadir token ls List token names and when they were created nadir logs [clear] Follow (default) or clear server logs
nadir update [--check|--force] Fetch the latest release from server.release_repo and restart nadir token add <name> Mint a machine credential (Bearer token), shown once
(--check: report only; --force: re-download when already current) nadir token rm <name> Revoke a token (effective immediately, no restart)
nadir help Show this help nadir token ls List token names and when they were created
nadir update [--check|--force] Fetch the latest release from server.release_repo and restart
(--check: report only; --force: re-download when already current)
nadir help Show this help
Most commands need root. Config path is specified via -f/--config or CONFIG_PATH (default ~/.config/config.yaml). Most commands need root. Config path is specified via -f/--config or CONFIG_PATH (default ~/.config/config.yaml).
`) `)
+79 -2
View File
@@ -1,14 +1,17 @@
package main package main
import ( import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand" "crypto/rand"
"crypto/rsa"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"crypto/x509/pkix" "crypto/x509/pkix"
"encoding/pem"
"log" "log"
"math/big" "math/big"
"net" "net"
"os"
"time" "time"
) )
@@ -24,7 +27,7 @@ func serverCert(certPath, keyPath string) (tls.Certificate, error) {
} }
func generateSelfSignedCert() (tls.Certificate, error) { func generateSelfSignedCert() (tls.Certificate, error) {
priv, err := rsa.GenerateKey(rand.Reader, 2048) priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil { if err != nil {
return tls.Certificate{}, err return tls.Certificate{}, err
} }
@@ -54,3 +57,77 @@ func generateSelfSignedCert() (tls.Certificate, error) {
} }
return tls.Certificate{Certificate: [][]byte{derBytes}, PrivateKey: priv}, nil return tls.Certificate{Certificate: [][]byte{derBytes}, PrivateKey: priv}, nil
} }
// generateAndSaveCert generates a self-signed certificate and private key,
// and saves them as PEM files.
func generateAndSaveCert(certPath, keyPath string, hostname string) error {
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return err
}
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
return err
}
template := x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{Organization: []string{"nadir-agent-tls"}},
NotBefore: time.Now(),
NotAfter: time.Now().Add(3650 * 24 * time.Hour), // 10 years
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
DNSNames: []string{"localhost"},
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback},
}
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 err
}
certOut, err := os.Create(certPath)
if err != nil {
return err
}
defer certOut.Close()
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return err
}
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer keyOut.Close()
privBytes, err := x509.MarshalECPrivateKey(priv)
if err != nil {
return err
}
if err := pem.Encode(keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: privBytes}); err != nil {
return err
}
return nil
}
+72
View File
@@ -0,0 +1,72 @@
package main
import (
"strings"
"testing"
)
// TestReleaseAPIURL pins the contract that downstream code (the updater and
// /install.sh) relies on: only https://host/owner/repo produces an API URL,
// everything else errors. Plain HTTP must be rejected — M7 makes auto-update
// only trust TLS-protected release feeds, since the binary it downloads is
// exec'd as root.
func TestReleaseAPIURL(t *testing.T) {
tests := []struct {
name string
in string
want string
wantErr string // substring expected in the error message; "" means success
}{
{
name: "valid https repo",
in: "https://tea.example.com/owner/repo",
want: "https://tea.example.com/api/v1/repos/owner/repo/releases/latest",
},
{
name: "http rejected",
in: "http://tea.example.com/owner/repo",
wantErr: "https",
},
{
name: "ssh scheme rejected",
in: "ssh://tea.example.com/owner/repo",
wantErr: "https",
},
{
name: "missing repo segment",
in: "https://tea.example.com/owner",
wantErr: "owner/repo",
},
{
name: "extra path segments",
in: "https://tea.example.com/owner/repo/extra",
wantErr: "owner/repo",
},
{
name: "empty",
in: "",
wantErr: "https",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := releaseAPIURL(tt.in)
if tt.wantErr == "" {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != tt.want {
t.Errorf("got %q, want %q", got, tt.want)
}
return
}
if err == nil {
t.Fatalf("expected error containing %q, got nil (result %q)", tt.wantErr, got)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("error %q does not contain %q", err.Error(), tt.wantErr)
}
})
}
}
+15 -3
View File
@@ -110,13 +110,25 @@ func Load(path string) (*File, error) {
return nil, fmt.Errorf("parse config %s: %w", path, err) return nil, fmt.Errorf("parse config %s: %w", path, err)
} }
// release_repo, when set, is downloaded over the wire and (for /api/update) // release_repo, when set, is downloaded over the wire and (for /api/update)
// executed. Reject http:// at the boundary so /install.sh and the updater // executed. Validate shape + scheme once here so /install.sh and the updater
// never have to re-check. // can use the string directly. Trim any trailing slash so downstream string
// concatenation produces a clean URL.
if f.Server.ReleaseRepo != "" { if f.Server.ReleaseRepo != "" {
f.Server.ReleaseRepo = strings.TrimRight(f.Server.ReleaseRepo, "/")
u, err := url.Parse(f.Server.ReleaseRepo) u, err := url.Parse(f.Server.ReleaseRepo)
if err != nil || u.Scheme != "https" { 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) 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)
}
} }
return &f, nil return &f, nil
} }
+8 -9
View File
@@ -12,19 +12,18 @@ import (
"github.com/danielgtaylor/huma/v2" "github.com/danielgtaylor/huma/v2"
) )
// ConfigPath is set at startup so the update handler can re-load config and // RegisterUpdate wires POST /api/update. It runs the equivalent of
// surface release_repo / parse errors to the caller instead of only stderr.
var ConfigPath string
// RegisterUpdate wires POST /api/meta/update. It runs the equivalent of
// `sudo nadir update` in a detached session and returns 202 immediately; the // `sudo nadir update` in a detached session and returns 202 immediately; the
// systemctl restart that ends the updater drops in-flight connections, so the // systemctl restart that ends the updater drops in-flight connections, so the
// caller should poll /api/health to confirm the new version is up. // caller should poll /api/health to confirm the new version is up.
// //
// configPath is re-read by the handler so a missing release_repo (or any other
// config error) surfaces as 4xx/5xx to the caller, not as stderr only.
//
// Authorization: requires (meta, root). Only roles with a wildcard grant // Authorization: requires (meta, root). Only roles with a wildcard grant
// (the default admin role) match, since "meta" isn't a real module with a // (the default admin role) match, since "meta" isn't a real module with a
// declared permission vocabulary. // declared permission vocabulary.
func RegisterUpdate(api huma.API) { func RegisterUpdate(api huma.API, configPath string) {
huma.Register(api, huma.Operation{ huma.Register(api, huma.Operation{
OperationID: "meta-update", OperationID: "meta-update",
Method: "POST", Method: "POST",
@@ -36,13 +35,13 @@ func RegisterUpdate(api huma.API) {
Errors: []int{400, 401, 403, 500}, Errors: []int{400, 401, 403, 500},
DefaultStatus: 202, DefaultStatus: 202,
}, func(ctx context.Context, _ *struct{}) (*oscmd.StatusOutput, error) { }, func(ctx context.Context, _ *struct{}) (*oscmd.StatusOutput, error) {
if ConfigPath != "" { if configPath != "" {
cfg, err := config.Load(ConfigPath) cfg, err := config.Load(configPath)
if err != nil { if err != nil {
return nil, huma.Error500InternalServerError("config load failed", err) return nil, huma.Error500InternalServerError("config load failed", err)
} }
if cfg.Server.ReleaseRepo == "" { if cfg.Server.ReleaseRepo == "" {
return nil, huma.Error400BadRequest("server.release_repo not set in " + ConfigPath) return nil, huma.Error400BadRequest("server.release_repo not set in " + configPath)
} }
} }
exe, err := os.Executable() exe, err := os.Executable()
+26 -7
View File
@@ -15,6 +15,7 @@ import (
// itself. // itself.
type WhoamiInput struct { type WhoamiInput struct {
SessionID string `cookie:"nadir_session_id"` SessionID string `cookie:"nadir_session_id"`
Auth string `header:"Authorization"`
} }
// WhoamiBody reports who the caller is and, per module, which permissions they // WhoamiBody reports who the caller is and, per module, which permissions they
@@ -30,7 +31,7 @@ type WhoamiOutput struct{ Body WhoamiBody }
// RegisterWhoami adds the current-user endpoint. It resolves the caller's // RegisterWhoami adds the current-user endpoint. It resolves the caller's
// concrete grants by asking the RBAC store about each module's permissions, // concrete grants by asking the RBAC store about each module's permissions,
// so "*" wildcards in roles are expanded for free. // so "*" wildcards in roles are expanded for free.
func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC, mods []module.Module) { func RegisterWhoami(api huma.API, sessions *auth.SessionStore, tokens *auth.TokenAuth, roles *rbac.RBAC, mods []module.Module) {
huma.Register(api, huma.Operation{ huma.Register(api, huma.Operation{
OperationID: "whoami", OperationID: "whoami",
Method: "GET", Method: "GET",
@@ -40,18 +41,35 @@ func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC,
"permissions the caller holds (wildcards resolved). Pair with " + "permissions the caller holds (wildcards resolved). Pair with " +
"/api/_modules to render the full permission matrix.", "/api/_modules to render the full permission matrix.",
Tags: []string{"Meta"}, Tags: []string{"Meta"},
Errors: []int{401}, Errors: []int{401, 429},
}, func(ctx context.Context, in *WhoamiInput) (*WhoamiOutput, error) { }, func(ctx context.Context, in *WhoamiInput) (*WhoamiOutput, error) {
sess, ok := sessions.GetByToken(in.SessionID) var username string
if !ok {
return nil, huma.Error401Unauthorized("unauthorized") if raw, isBearer := auth.BearerToken(in.Auth); isBearer {
if tokens == nil {
return nil, huma.Error401Unauthorized("unauthorized")
}
name, ok, throttled := tokens.Verify(auth.ClientIP(ctx), raw)
if throttled {
return nil, huma.Error429TooManyRequests("too many failed token attempts; wait a minute")
}
if !ok {
return nil, huma.Error401Unauthorized("unauthorized")
}
username = name
} else {
sess, ok := sessions.GetByToken(in.SessionID)
if !ok {
return nil, huma.Error401Unauthorized("unauthorized")
}
username = sess.Username
} }
held := make(map[string][]string) held := make(map[string][]string)
for _, m := range mods { for _, m := range mods {
var perms []string var perms []string
for _, p := range m.Permissions() { for _, p := range m.Permissions() {
if roles.Can(sess.Username, m.ID(), p) { if roles.Can(username, m.ID(), p) {
perms = append(perms, string(p)) perms = append(perms, string(p))
} }
} }
@@ -61,7 +79,8 @@ func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC,
} }
out := &WhoamiOutput{} out := &WhoamiOutput{}
out.Body = WhoamiBody{Username: sess.Username, Permissions: held} out.Body = WhoamiBody{Username: username, Permissions: held}
return out, nil return out, nil
}) })
} }
+115
View File
@@ -0,0 +1,115 @@
package meta
import (
"encoding/json"
"net/http"
"path/filepath"
"slices"
"testing"
"nadir/internal/auth"
"nadir/internal/module"
"nadir/internal/rbac"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
"github.com/danielgtaylor/huma/v2/humatest"
)
type dummyModule struct {
id string
perms []rbac.Permission
}
func (m *dummyModule) ID() string { return m.id }
func (m *dummyModule) Name() string { return m.id }
func (m *dummyModule) Permissions() []rbac.Permission { return m.perms }
func (m *dummyModule) Register(api huma.API) {}
func TestWhoami(t *testing.T) {
tempDir := t.TempDir()
sessions, err := auth.NewSessionStore(filepath.Join(tempDir, "sessions.db"))
if err != nil {
t.Fatal(err)
}
tokenStore, err := auth.NewTokenStore(filepath.Join(tempDir, "tokens.db"))
if err != nil {
t.Fatal(err)
}
defer tokenStore.Close()
tokenAuth := auth.NewTokenAuth(tokenStore)
roles := rbac.New()
roles.DefineRole(rbac.Role{
Name: "admin-role",
ModuleGrants: map[string][]rbac.Permission{
"system": {rbac.Read},
},
})
roles.AssignRole("admin", "admin-role")
mods := []module.Module{
&dummyModule{
id: "system",
perms: []rbac.Permission{rbac.Read, rbac.Write},
},
}
mux := http.NewServeMux()
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
RegisterWhoami(api, sessions, tokenAuth, roles, mods)
// 1. Unauthorized request (no token, no session)
resp := api.Get("/api/whoami")
if resp.Code != http.StatusUnauthorized {
t.Errorf("expected 401, got %d", resp.Code)
}
// 2. Cookie session request
sessToken, err := sessions.Create("admin")
if err != nil {
t.Fatal(err)
}
resp = api.Get("/api/whoami", "Cookie: nadir_session_id="+sessToken)
if resp.Code != http.StatusOK {
t.Errorf("expected 200, got %d", resp.Code)
}
var body WhoamiBody
if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.Username != "admin" {
t.Errorf("expected username admin, got %q", body.Username)
}
if !slices.Contains(body.Permissions["system"], "read") {
t.Errorf("expected system read permission, got %v", body.Permissions["system"])
}
// 3. Token request
bearerToken, err := tokenStore.Create("api-user")
if err != nil {
t.Fatal(err)
}
roles.DefineRole(rbac.Role{
Name: "api-role",
ModuleGrants: map[string][]rbac.Permission{
"system": {rbac.Write},
},
})
roles.AssignRole("api-user", "api-role")
resp = api.Get("/api/whoami", "Authorization: Bearer "+bearerToken)
if resp.Code != http.StatusOK {
t.Errorf("expected 200, got %d", resp.Code)
}
if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.Username != "api-user" {
t.Errorf("expected username api-user, got %q", body.Username)
}
if !slices.Contains(body.Permissions["system"], "write") {
t.Errorf("expected system write permission, got %v", body.Permissions["system"])
}
}
+1 -1
View File
@@ -32,7 +32,7 @@ func (m *Module) Permissions() []rbac.Permission {
} }
func (m *Module) Register(api huma.API) { func (m *Module) Register(api huma.API) {
registerReads(api) registerReads(api, m)
registerWrites(api, m) registerWrites(api, m)
registerHosts(api) registerHosts(api)
} }
@@ -87,6 +87,30 @@ func TestNetworkingHandlers(t *testing.T) {
t.Errorf("list interfaces: got %d, want %d", resp.Code, http.StatusOK) t.Errorf("list interfaces: got %d, want %d", resp.Code, http.StatusOK)
} }
// 1b. Test GET /api/networking/interfaces/{name} (used by edit-form prefill).
// Asserts the backend's Snapshot output is returned verbatim as the body, so
// the same shape can feed straight into PUT.
resp = api.Get("/api/networking/interfaces/eth0")
if resp.Code != http.StatusOK {
t.Errorf("get interface: got %d, want %d", resp.Code, http.StatusOK)
}
var ifaceRes GetInterfaceConfigOutput
if err := json.Unmarshal(resp.Body.Bytes(), &ifaceRes.Body); err != nil {
t.Fatal(err)
}
if ifaceRes.Body.Method != "dhcp" || ifaceRes.Body.Address != "192.168.1.10/24" {
t.Errorf("get interface: got %+v, want snapshot result", ifaceRes.Body)
}
// Same endpoint with no backend should return 501.
noBackend := &Module{}
noBackendMux := http.NewServeMux()
noBackendAPI := humatest.Wrap(t, humago.New(noBackendMux, huma.DefaultConfig("Test", "1.0.0")))
noBackend.Register(noBackendAPI)
if got := noBackendAPI.Get("/api/networking/interfaces/eth0").Code; got != http.StatusNotImplemented {
t.Errorf("get interface without backend: got %d, want 501", got)
}
// 2. Test GET /api/networking/routes // 2. Test GET /api/networking/routes
resp = api.Get("/api/networking/routes") resp = api.Get("/api/networking/routes")
if resp.Code != http.StatusOK { if resp.Code != http.StatusOK {
@@ -388,3 +412,69 @@ func TestBackendImplementations(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
} }
func TestGetInterfaceConfigAugment(t *testing.T) {
mux := http.NewServeMux()
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
be := &mockBackend{
name: "mockbe",
snapshotResult: IfaceConfig{
Method: "dhcp",
},
}
m := &Module{be: be}
m.Register(api)
tempResolv := filepath.Join(t.TempDir(), "resolv.conf")
if err := os.WriteFile(tempResolv, []byte("nameserver 1.1.1.1\nnameserver 8.8.8.8\n"), 0644); err != nil {
t.Fatal(err)
}
oldResolv := resolvConf
resolvConf = tempResolv
defer func() { resolvConf = oldResolv }()
oscmd.SetMock("ip", func(args []string) oscmd.MockCommand {
argStr := strings.Join(args, " ")
if strings.Contains(argStr, "addr show") {
out := `[{"ifname": "eth0", "operstate": "UP", "address": "aa:bb:cc:dd:ee:ff", "mtu": 1500, "addr_info": [{"family": "inet", "local": "192.168.1.10", "prefixlen": 24}, {"family": "inet6", "local": "2001:db8::10", "prefixlen": 64}]}]`
return oscmd.MockCommand{Stdout: out, ExitCode: 0}
}
if strings.Contains(argStr, "route show") && !strings.Contains(argStr, "-6") {
out := `[{"dst": "default", "gateway": "192.168.1.1", "dev": "eth0"}]`
return oscmd.MockCommand{Stdout: out, ExitCode: 0}
}
if strings.Contains(argStr, "-6") && strings.Contains(argStr, "route show") {
out := `[{"dst": "default", "gateway": "2001:db8::1", "dev": "eth0"}]`
return oscmd.MockCommand{Stdout: out, ExitCode: 0}
}
return oscmd.MockCommand{ExitCode: 1}
})
defer oscmd.ClearMocks()
resp := api.Get("/api/networking/interfaces/eth0")
if resp.Code != http.StatusOK {
t.Errorf("get interface: got %d, want %d", resp.Code, http.StatusOK)
}
var ifaceRes GetInterfaceConfigOutput
if err := json.Unmarshal(resp.Body.Bytes(), &ifaceRes.Body); err != nil {
t.Fatal(err)
}
if ifaceRes.Body.Method != "dhcp" {
t.Errorf("expected Method to be dhcp, got %s", ifaceRes.Body.Method)
}
if ifaceRes.Body.Address != "192.168.1.10" || ifaceRes.Body.Prefix != 24 {
t.Errorf("expected augmented Address 192.168.1.10/24, got %s/%d", ifaceRes.Body.Address, ifaceRes.Body.Prefix)
}
if ifaceRes.Body.Gateway != "192.168.1.1" {
t.Errorf("expected augmented Gateway 192.168.1.1, got %s", ifaceRes.Body.Gateway)
}
if len(ifaceRes.Body.DNS) != 2 || ifaceRes.Body.DNS[0] != "1.1.1.1" || ifaceRes.Body.DNS[1] != "8.8.8.8" {
t.Errorf("expected augmented DNS [1.1.1.1, 8.8.8.8], got %v", ifaceRes.Body.DNS)
}
if ifaceRes.Body.IPv6 == nil || ifaceRes.Body.IPv6.Method != "auto" || ifaceRes.Body.IPv6.Address != "2001:db8::10" || ifaceRes.Body.IPv6.Prefix != 64 || ifaceRes.Body.IPv6.Gateway != "2001:db8::1" {
t.Errorf("expected augmented IPv6, got %+v", ifaceRes.Body.IPv6)
}
}
+16 -8
View File
@@ -46,11 +46,19 @@ func (b *nmcliBackend) Snapshot(ctx context.Context, iface string) (IfaceConfig,
return IfaceConfig{Method: "dhcp"}, nil return IfaceConfig{Method: "dhcp"}, nil
} }
// nmcli's `con show <NAME>` parser does NOT honor `--` as an end-of-options
// separator; passing it makes nmcli look for a connection literally named
// "--" and fail. `conn` comes from nmcli's own active-connections list (see
// connForIface), so it's already validated — no shell-metacharacter risk.
// Same applies to con up / con down / con modify below.
out, err := oscmd.RunContext(ctx, "nmcli", "-t", "-f", out, err := oscmd.RunContext(ctx, "nmcli", "-t", "-f",
"ipv4.method,ipv4.addresses,ipv4.gateway,ipv4.dns,ipv4.routes,ipv6.method,ipv6.addresses,ipv6.gateway", "ipv4.method,ipv4.addresses,ipv4.gateway,ipv4.dns,ipv4.routes,ipv6.method,ipv6.addresses,ipv6.gateway",
"con", "show", "--", conn) "con", "show", conn)
if err != nil { if err != nil {
return IfaceConfig{}, fmt.Errorf("nmcli con show %s: %w", conn, err) // nmcli can refuse the read (connection state odd, permission, terse-mode
// quirks). Fall back to DHCP defaults so the prefill endpoint still
// returns a usable form, mirroring the networkd / ifupdown fallback.
return IfaceConfig{Method: "dhcp"}, nil
} }
return parseNmcliSnapshot(out), nil return parseNmcliSnapshot(out), nil
@@ -159,9 +167,9 @@ func (b *nmcliBackend) Apply(ctx context.Context, iface string, cfg IfaceConfig)
return fmt.Errorf("cannot apply: %w", err) return fmt.Errorf("cannot apply: %w", err)
} }
// Build the nmcli con modify arguments. Note: conn is safe to place after // conn comes from nmcli's own active list (connForIface), not user input.
// -- since it comes from nmcli output, not directly from the user. // nmcli's con subcommands don't honor "--" as an end-of-options separator.
args := []string{"con", "modify", "--", conn} args := []string{"con", "modify", conn}
switch cfg.Method { switch cfg.Method {
case "static": case "static":
@@ -222,7 +230,7 @@ func (b *nmcliBackend) Apply(ctx context.Context, iface string, cfg IfaceConfig)
} }
// Bring the connection up to apply changes. // Bring the connection up to apply changes.
if _, err := oscmd.RunContext(ctx, "nmcli", "con", "up", "--", conn); err != nil { if _, err := oscmd.RunContext(ctx, "nmcli", "con", "up", conn); err != nil {
return fmt.Errorf("nmcli con up: %w", err) return fmt.Errorf("nmcli con up: %w", err)
} }
return nil return nil
@@ -235,7 +243,7 @@ func (b *nmcliBackend) SetLinkUp(ctx context.Context, iface string) error {
_, err = oscmd.RunContext(ctx, "ip", "link", "set", "--", iface, "up") _, err = oscmd.RunContext(ctx, "ip", "link", "set", "--", iface, "up")
return err return err
} }
_, err = oscmd.RunContext(ctx, "nmcli", "con", "up", "--", conn) _, err = oscmd.RunContext(ctx, "nmcli", "con", "up", conn)
return err return err
} }
@@ -245,7 +253,7 @@ func (b *nmcliBackend) SetLinkDown(ctx context.Context, iface string) error {
_, err = oscmd.RunContext(ctx, "ip", "link", "set", "--", iface, "down") _, err = oscmd.RunContext(ctx, "ip", "link", "set", "--", iface, "down")
return err return err
} }
_, err = oscmd.RunContext(ctx, "nmcli", "con", "down", "--", conn) _, err = oscmd.RunContext(ctx, "nmcli", "con", "down", conn)
return err return err
} }
+154 -1
View File
@@ -3,6 +3,8 @@ package networking
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"fmt"
"net/netip"
"os" "os"
"strconv" "strconv"
"strings" "strings"
@@ -53,7 +55,48 @@ type DNSOutput struct {
} }
} }
func registerReads(api huma.API) { // GetInterfaceConfigInput carries the path param; matches the PUT endpoint's
// IfacePathInput so the frontend can use the same path for both verbs.
type GetInterfaceConfigInput struct {
Name string `path:"name" example:"eth0" doc:"Interface name"`
}
// GetInterfaceConfigOutput returns the same IfaceConfig shape that PUT
// accepts, so the form can be pre-filled directly from this response.
type GetInterfaceConfigOutput struct {
Body IfaceConfig
}
func registerReads(api huma.API, m *Module) {
huma.Register(api, huma.Operation{
OperationID: "networking-get-interface",
Method: "GET",
Path: "/api/networking/interfaces/{name}",
Summary: "Get an interface's current configuration",
Description: "Returns the IfaceConfig the backend currently has for this " +
"interface (method, address/prefix, gateway, DNS, IPv6). Same schema as " +
"PUT /api/networking/interfaces/{name}, so the frontend can prefill an " +
"edit form from this response directly. Returns 501 when no backend was " +
"detected (nmcli / networkd / ifupdown).",
Tags: []string{tagNetworking},
Metadata: op("read"),
Errors: readErrors,
}, func(ctx context.Context, in *GetInterfaceConfigInput) (*GetInterfaceConfigOutput, error) {
if m.be == nil {
return nil, huma.Error501NotImplemented("", errNoBackend)
}
if err := validateIface(in.Name); err != nil {
return nil, err
}
cfg, err := m.be.Snapshot(ctx, in.Name)
if err != nil {
return nil, huma.Error500InternalServerError("snapshot failed", err)
}
augmentWithLiveState(ctx, in.Name, &cfg)
return &GetInterfaceConfigOutput{Body: cfg}, nil
})
huma.Register(api, huma.Operation{ huma.Register(api, huma.Operation{
OperationID: "networking-list-interfaces", OperationID: "networking-list-interfaces",
Method: "GET", Method: "GET",
@@ -209,3 +252,113 @@ func parseResolv(text string) []string {
} }
return servers return servers
} }
func getLiveInterface(ctx context.Context, iface string) (*Interface, error) {
out, err := oscmd.RunContext(ctx, "ip", "-j", "addr", "show", "--", iface)
if err != nil {
out, err = oscmd.RunContext(ctx, "ip", "-j", "addr")
if err != nil {
return nil, err
}
}
ifaces, err := parseInterfaces(out)
if err != nil {
return nil, err
}
for i := range ifaces {
if ifaces[i].Name == iface {
return &ifaces[i], nil
}
}
return nil, fmt.Errorf("interface %s not found in ip addr output", iface)
}
func getLiveGateway(ctx context.Context, iface string) string {
routeOut, err := oscmd.RunContext(ctx, "ip", "-j", "route", "show", "dev", "--", iface)
if err != nil {
routeOut, err = oscmd.RunContext(ctx, "ip", "-j", "route")
if err != nil {
return ""
}
}
routes, err := parseRoutes(routeOut)
if err != nil {
return ""
}
for _, r := range routes {
if r.Destination == "default" && (r.Interface == iface || r.Interface == "") && r.Gateway != "" {
return r.Gateway
}
}
return ""
}
func getLiveIPv6Gateway(ctx context.Context, iface string) string {
routeOut, err := oscmd.RunContext(ctx, "ip", "-6", "-j", "route", "show", "dev", "--", iface)
if err != nil {
routeOut, err = oscmd.RunContext(ctx, "ip", "-6", "-j", "route")
if err != nil {
return ""
}
}
routes, err := parseRoutes(routeOut)
if err != nil {
return ""
}
for _, r := range routes {
if r.Destination == "default" && (r.Interface == iface || r.Interface == "") && r.Gateway != "" {
return r.Gateway
}
}
return ""
}
func augmentWithLiveState(ctx context.Context, iface string, cfg *IfaceConfig) {
liveIface, err := getLiveInterface(ctx, iface)
if err != nil {
return
}
// Prefill IPv4 address and prefix if empty
if cfg.Address == "" && len(liveIface.IPv4) > 0 {
addr, prefix := splitCIDR(liveIface.IPv4[0])
if addr != "" {
cfg.Address = addr
cfg.Prefix = prefix
}
}
// Prefill Gateway if empty
if cfg.Gateway == "" {
cfg.Gateway = getLiveGateway(ctx, iface)
}
// Prefill DNS if empty
if len(cfg.DNS) == 0 {
if data, err := os.ReadFile(resolvConf); err == nil {
cfg.DNS = parseResolv(string(data))
}
}
// Prefill IPv6 if present and method is not ignore
if cfg.IPv6 == nil {
cfg.IPv6 = &IPv6Config{Method: "auto"}
}
if cfg.IPv6.Method != "ignore" {
// Capture first global IPv6 if address is empty
if cfg.IPv6.Address == "" {
for _, c := range liveIface.IPv6 {
addr, prefix := splitCIDR(c)
if ip, err := netip.ParseAddr(addr); err == nil && !ip.IsLinkLocalUnicast() {
cfg.IPv6.Address = addr
cfg.IPv6.Prefix = prefix
break
}
}
}
// Capture IPv6 default gateway if empty
if cfg.IPv6.Gateway == "" {
cfg.IPv6.Gateway = getLiveIPv6Gateway(ctx, iface)
}
}
}
+44 -6
View File
@@ -65,6 +65,10 @@ type RemoveInput struct {
Name string `path:"name" example:"htop" doc:"Package to remove"` Name string `path:"name" example:"htop" doc:"Package to remove"`
} }
type UpgradeOneInput struct {
Name string `path:"name" example:"htop" doc:"Package to upgrade"`
}
// SSE event types for streaming package operations. // SSE event types for streaming package operations.
type PkgOutputEvent struct { type PkgOutputEvent struct {
Line string `json:"line" doc:"One line of the package manager's terminal output"` Line string `json:"line" doc:"One line of the package manager's terminal output"`
@@ -162,6 +166,25 @@ func registerPackages(api huma.API, pm manager) {
bin, args := pm.upgradeArgs() bin, args := pm.upgradeArgs()
streamOp(ctx, send, bin, args) streamOp(ctx, send, bin, args)
}) })
sse.Register(api, huma.Operation{
OperationID: "packages-upgrade-one",
Method: "POST",
Path: "/api/packages/upgrade/{name}",
Summary: "Upgrade a single package (streamed)",
Description: "Upgrades the named package to its latest version, streaming the " +
"package manager's output live. apt uses `install --only-upgrade` so the " +
"package must already be installed; dnf/pacman handle this natively.",
Tags: []string{tagPackages},
Metadata: op("write"),
}, pkgEvents, func(ctx context.Context, in *UpgradeOneInput, send sse.Sender) {
if validateName(in.Name) != nil {
send.Data(PkgErrorEvent{Message: "invalid package name: " + in.Name})
return
}
bin, args := pm.upgradeOneArgs(in.Name)
streamOp(ctx, send, bin, args)
})
} }
// streamOp runs a package write and streams its combined output to the client. // streamOp runs a package write and streams its combined output to the client.
@@ -260,11 +283,11 @@ func result(pm manager, pkgs []Package) *ListOutput {
func (m manager) installArgs(name string) (string, []string) { func (m manager) installArgs(name string) (string, []string) {
switch m.name { switch m.name {
case "dnf": case "dnf":
return "dnf", []string{"install", "-y", "--", name} return "dnf", []string{"install", "-y", name}
case "apt": case "apt":
return "apt-get", []string{"install", "-y", "--", name} return "apt-get", []string{"install", "-y", name}
case "pacman": case "pacman":
return "pacman", []string{"-S", "--noconfirm", "--", name} return "pacman", []string{"-S", "--noconfirm", name}
} }
return "", nil return "", nil
} }
@@ -272,11 +295,11 @@ func (m manager) installArgs(name string) (string, []string) {
func (m manager) removeArgs(name string) (string, []string) { func (m manager) removeArgs(name string) (string, []string) {
switch m.name { switch m.name {
case "dnf": case "dnf":
return "dnf", []string{"remove", "-y", "--", name} return "dnf", []string{"remove", "-y", name}
case "apt": case "apt":
return "apt-get", []string{"remove", "-y", "--", name} return "apt-get", []string{"remove", "-y", name}
case "pacman": case "pacman":
return "pacman", []string{"-R", "--noconfirm", "--", name} return "pacman", []string{"-R", "--noconfirm", name}
} }
return "", nil return "", nil
} }
@@ -293,6 +316,21 @@ func (m manager) upgradeArgs() (string, []string) {
return "", nil return "", nil
} }
// upgradeOneArgs upgrades a single package to its latest version. apt's
// `install --only-upgrade` is the safe variant (won't install if absent);
// pacman -S re-syncs to latest; dnf upgrade is naturally scoped by name.
func (m manager) upgradeOneArgs(name string) (string, []string) {
switch m.name {
case "dnf":
return "dnf", []string{"upgrade", "-y", name}
case "apt":
return "apt-get", []string{"install", "--only-upgrade", "-y", name}
case "pacman":
return "pacman", []string{"-S", "--noconfirm", name}
}
return "", nil
}
// --- parsers (pure, tested) -------------------------------------------------- // --- parsers (pure, tested) --------------------------------------------------
// parseTabbed reads "name\tversion" lines (dpkg-query / rpm output). // parseTabbed reads "name\tversion" lines (dpkg-query / rpm output).
+32
View File
@@ -3,14 +3,22 @@ package services
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"os/exec"
"regexp" "regexp"
"strings" "strings"
"syscall"
"nadir/internal/oscmd" "nadir/internal/oscmd"
"github.com/danielgtaylor/huma/v2" "github.com/danielgtaylor/huma/v2"
) )
// selfUnit is nadir's own systemd unit name. Acting on it via the normal
// synchronous path would have systemd SIGTERM the very process serving the
// request, so the client sees a dropped connection / 500 even though the
// action succeeded. We detach those calls into a Setsid subprocess instead.
const selfUnit = "nadir"
const tagServices = "Services" const tagServices = "Services"
var ( var (
@@ -136,6 +144,9 @@ func registerServices(api huma.API) {
if err := ensureExists(in.Unit); err != nil { if err := ensureExists(in.Unit); err != nil {
return nil, err return nil, err
} }
if isSelf(in.Unit) {
return runDetached(c.action, in.Unit)
}
if _, err := oscmd.Run("systemctl", c.action, "--", in.Unit); err != nil { if _, err := oscmd.Run("systemctl", c.action, "--", in.Unit); err != nil {
return nil, huma.Error500InternalServerError("systemctl "+c.action+" failed", err) return nil, huma.Error500InternalServerError("systemctl "+c.action+" failed", err)
} }
@@ -144,6 +155,27 @@ func registerServices(api huma.API) {
} }
} }
// isSelf reports whether unit names nadir's own service, with or without the
// .service suffix.
func isSelf(unit string) bool {
return unit == selfUnit || unit == selfUnit+".service"
}
// runDetached fires systemctl in a new session so a "systemctl restart nadir"
// (or stop) doesn't kill its own caller before the HTTP response is written.
// Returns success once the subprocess has *started* — the actual systemd
// operation may complete after the response is sent, which is the whole point.
func runDetached(action, unit string) (*oscmd.StatusOutput, error) {
cmd := exec.Command("systemctl", action, "--", unit)
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
if err := cmd.Start(); err != nil {
return nil, huma.Error500InternalServerError("could not start detached systemctl", err)
}
// Reap in the background so the child doesn't become a zombie.
go cmd.Wait()
return oscmd.OK(), nil
}
// validateUnit guards against empty, flag-like, or malformed unit names. // validateUnit guards against empty, flag-like, or malformed unit names.
func validateUnit(unit string) error { func validateUnit(unit string) error {
if unit == "" || strings.HasPrefix(unit, "-") || !unitNameRe.MatchString(unit) { if unit == "" || strings.HasPrefix(unit, "-") || !unitNameRe.MatchString(unit) {
@@ -19,3 +19,22 @@ func TestValidateUnit(t *testing.T) {
} }
} }
} }
// 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) {
yes := []string{"nadir", "nadir.service"}
for _, u := range yes {
if !isSelf(u) {
t.Errorf("isSelf(%q) = false, want true", u)
}
}
no := []string{"", "sshd.service", "nadir-something.service", "nadir.timer", "not-nadir.service"}
for _, u := range no {
if isSelf(u) {
t.Errorf("isSelf(%q) = true, want false", u)
}
}
}
+39 -3
View File
@@ -499,9 +499,12 @@ func diskInfo() []DiskInfo {
disks := []DiskInfo{} disks := []DiskInfo{}
seen := map[string]bool{} seen := map[string]bool{}
for _, e := range entries { for _, e := range entries {
// Only real block devices; skip pseudo filesystems and snap's squashfs // ponytail: filter by fstype, not device path. LXC/Docker containers
// loop mounts that would otherwise clutter the list. // expose their rootfs as a ZFS dataset name, an overlayfs, or a bind
if !strings.HasPrefix(e.Device, "/dev/") || e.FSType == "squashfs" || seen[e.Mountpoint] { // 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 continue
} }
var st syscall.Statfs_t var st syscall.Statfs_t
@@ -522,6 +525,39 @@ func diskInfo() []DiskInfo {
return disks 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 { func netInfo() []NetInterface {
ifaces, err := net.Interfaces() ifaces, err := net.Interfaces()
if err != nil { if err != nil {
+54 -21
View File
@@ -16,6 +16,7 @@ import (
type LocaleStatusBody struct { type LocaleStatusBody struct {
Lang string `json:"lang" example:"it_IT.UTF-8" doc:"System locale (LANG)"` Lang string `json:"lang" example:"it_IT.UTF-8" doc:"System locale (LANG)"`
Language string `json:"language" example:"en_US:" doc:"Fallback language list (LANGUAGE)"`
VCKeymap string `json:"vc_keymap" example:"it" doc:"Virtual console keymap"` VCKeymap string `json:"vc_keymap" example:"it" doc:"Virtual console keymap"`
X11Layout string `json:"x11_layout" example:"it" doc:"X11 keyboard layout"` X11Layout string `json:"x11_layout" example:"it" doc:"X11 keyboard layout"`
} }
@@ -31,12 +32,14 @@ type LocalesOutput struct {
type KeymapsOutput struct { type KeymapsOutput struct {
Body struct { Body struct {
Keymaps []string `json:"keymaps" doc:"Available virtual console keymaps"` Keymaps []string `json:"keymaps" doc:"Available virtual console keymaps"`
Reason string `json:"reason,omitempty" doc:"When keymaps is empty, why: e.g. \"kbd not installed on this server\""`
} }
} }
type SetLocaleInput struct { type SetLocaleInput struct {
Body struct { Body struct {
Lang string `json:"lang" example:"it_IT.UTF-8" doc:"Locale to set as LANG"` Lang string `json:"lang" example:"it_IT.UTF-8" doc:"Locale to set as LANG"`
Language *string `json:"language,omitempty" example:"en_US:" doc:"Fallback language list (LANGUAGE)"`
} }
} }
@@ -56,6 +59,10 @@ type GenerateLocaleInput struct {
// .charmap suffix (e.g. fr_FR, fr_FR.UTF-8, en_US.ISO-8859-1). // .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_-]+)?$`) var localeRe = regexp.MustCompile(`^[a-z]{2,3}_[A-Z]{2}(\.[A-Za-z0-9_-]+)?$`)
// languageRe validates the LANGUAGE fallback list: colon-separated locale names
// like "en_US:de_DE". Anchored so a leading "-" can't survive into argv.
var languageRe = regexp.MustCompile(`^[a-zA-Z0-9_.:-]*$`)
func localeStatus() (LocaleStatusBody, error) { func localeStatus() (LocaleStatusBody, error) {
lines, err := oscmd.RunLines("localectl", "status") lines, err := oscmd.RunLines("localectl", "status")
if err != nil { if err != nil {
@@ -63,21 +70,28 @@ func localeStatus() (LocaleStatusBody, error) {
} }
var b LocaleStatusBody var b LocaleStatusBody
for _, line := range lines { for _, line := range lines {
label, val, ok := strings.Cut(line, ":") trimmed := strings.TrimSpace(line)
if !ok { if strings.HasPrefix(trimmed, "VC Keymap:") {
b.VCKeymap = strings.TrimSpace(strings.TrimPrefix(trimmed, "VC Keymap:"))
continue continue
} }
switch strings.TrimSpace(label) { if strings.HasPrefix(trimmed, "X11 Layout:") {
case "System Locale": b.X11Layout = strings.TrimSpace(strings.TrimPrefix(trimmed, "X11 Layout:"))
for kv := range strings.FieldsSeq(val) { continue
if k, v, ok := strings.Cut(kv, "="); ok && k == "LANG" { }
// Parse k=v fields on any other line (like System Locale block).
parts := strings.Fields(trimmed)
for _, part := range parts {
part = strings.TrimPrefix(part, "System Locale:")
part = strings.TrimSpace(part)
if k, v, ok := strings.Cut(part, "="); ok {
switch k {
case "LANG":
b.Lang = v b.Lang = v
case "LANGUAGE":
b.Language = v
} }
} }
case "VC Keymap":
b.VCKeymap = strings.TrimSpace(val)
case "X11 Layout":
b.X11Layout = strings.TrimSpace(val)
} }
} }
return b, nil return b, nil
@@ -144,7 +158,17 @@ func registerLocale(api huma.API) {
if !slices.Contains(locales, lang) { if !slices.Contains(locales, lang) {
return nil, huma.Error400BadRequest("unknown locale: " + lang) return nil, huma.Error400BadRequest("unknown locale: " + lang)
} }
if _, err := oscmd.Run("localectl", "set-locale", "LANG="+lang); err != nil {
args := []string{"set-locale", "LANG=" + lang}
if in.Body.Language != nil {
langVal := strings.TrimSpace(*in.Body.Language)
if !languageRe.MatchString(langVal) {
return nil, huma.Error400BadRequest("invalid language format: " + langVal)
}
args = append(args, "LANGUAGE="+langVal)
}
if _, err := oscmd.Run("localectl", args...); err != nil {
return nil, huma.Error500InternalServerError("set-locale failed", err) return nil, huma.Error500InternalServerError("set-locale failed", err)
} }
return oscmd.OK(), nil return oscmd.OK(), nil
@@ -160,12 +184,15 @@ func registerLocale(api huma.API) {
Metadata: op("read"), Metadata: op("read"),
Errors: readErrors, Errors: readErrors,
}, func(ctx context.Context, _ *struct{}) (*KeymapsOutput, error) { }, func(ctx context.Context, _ *struct{}) (*KeymapsOutput, error) {
// ponytail: minimal servers ship without kbd / /usr/share/keymaps, so
// localectl errors instead of returning empty. Surface that as a `reason`
// the frontend can display ("kbd not installed") instead of an opaque N/A.
keymaps, err := oscmd.RunLines("localectl", "list-keymaps") keymaps, err := oscmd.RunLines("localectl", "list-keymaps")
if err != nil {
return nil, huma.Error500InternalServerError("localectl failed", err)
}
out := &KeymapsOutput{} out := &KeymapsOutput{}
out.Body.Keymaps = keymaps out.Body.Keymaps = keymaps
if err != nil || len(keymaps) == 0 {
out.Body.Reason = "kbd is not installed on this server (install the kbd / console-data package to enable keymap selection)"
}
return out, nil return out, nil
}) })
@@ -185,10 +212,9 @@ func registerLocale(api huma.API) {
if km == "" { if km == "" {
return nil, huma.Error400BadRequest("empty keymap") return nil, huma.Error400BadRequest("empty keymap")
} }
keymaps, err := oscmd.RunLines("localectl", "list-keymaps") // list-keymaps failure means no keymap allowlist on this host (kbd absent);
if err != nil { // fall through to unknown-keymap 400 instead of 500.
return nil, huma.Error500InternalServerError("localectl failed", err) keymaps, _ := oscmd.RunLines("localectl", "list-keymaps")
}
if !slices.Contains(keymaps, km) { if !slices.Contains(keymaps, km) {
return nil, huma.Error400BadRequest("unknown keymap: " + km) return nil, huma.Error400BadRequest("unknown keymap: " + km)
} }
@@ -209,7 +235,7 @@ func registerLocale(api huma.API) {
"already generated, returns 200 immediately.", "already generated, returns 200 immediately.",
Tags: []string{tagSystem}, Tags: []string{tagSystem},
Metadata: op("write"), Metadata: op("write"),
Errors: append(writeErrors, 501), Errors: []int{400, 401, 403, 500, 501},
}, func(ctx context.Context, in *GenerateLocaleInput) (*oscmd.StatusOutput, error) { }, func(ctx context.Context, in *GenerateLocaleInput) (*oscmd.StatusOutput, error) {
locale := strings.TrimSpace(in.Body.Locale) locale := strings.TrimSpace(in.Body.Locale)
if locale == "" { if locale == "" {
@@ -263,9 +289,16 @@ func enableLocaleGen(path, locale string) error {
if !found { if !found {
return huma.Error400BadRequest("locale not available for generation: " + locale) return huma.Error400BadRequest("locale not available for generation: " + locale)
} }
if err := os.WriteFile(path, []byte(newContent), 0644); err != nil { // 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) 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 { if _, err := oscmd.Run("locale-gen"); err != nil {
return huma.Error500InternalServerError("locale-gen failed", err) return huma.Error500InternalServerError("locale-gen failed", err)
} }
+16 -2
View File
@@ -142,7 +142,7 @@ func TestSystemHandlers(t *testing.T) {
// 4. Test GET & POST /api/system/locale // 4. Test GET & POST /api/system/locale
oscmd.SetMock("localectl", func(args []string) oscmd.MockCommand { oscmd.SetMock("localectl", func(args []string) oscmd.MockCommand {
if reflect.DeepEqual(args, []string{"status"}) { if reflect.DeepEqual(args, []string{"status"}) {
statusOut := " System Locale: LANG=it_IT.UTF-8\n VC Keymap: it\n X11 Layout: it\n" statusOut := " System Locale: LANG=it_IT.UTF-8\n LANGUAGE=en_US:\n VC Keymap: it\n X11 Layout: it\n"
return oscmd.MockCommand{Stdout: statusOut, ExitCode: 0} return oscmd.MockCommand{Stdout: statusOut, ExitCode: 0}
} }
if reflect.DeepEqual(args, []string{"list-locales"}) { if reflect.DeepEqual(args, []string{"list-locales"}) {
@@ -151,6 +151,9 @@ func TestSystemHandlers(t *testing.T) {
if reflect.DeepEqual(args, []string{"set-locale", "LANG=it_IT.UTF-8"}) { if reflect.DeepEqual(args, []string{"set-locale", "LANG=it_IT.UTF-8"}) {
return oscmd.MockCommand{ExitCode: 0} return oscmd.MockCommand{ExitCode: 0}
} }
if reflect.DeepEqual(args, []string{"set-locale", "LANG=it_IT.UTF-8", "LANGUAGE=en_US:"}) {
return oscmd.MockCommand{ExitCode: 0}
}
if reflect.DeepEqual(args, []string{"list-keymaps"}) { if reflect.DeepEqual(args, []string{"list-keymaps"}) {
return oscmd.MockCommand{Stdout: "it\nus\n", ExitCode: 0} return oscmd.MockCommand{Stdout: "it\nus\n", ExitCode: 0}
} }
@@ -168,7 +171,7 @@ func TestSystemHandlers(t *testing.T) {
if err := json.Unmarshal(resp.Body.Bytes(), &localeRes.Body); err != nil { if err := json.Unmarshal(resp.Body.Bytes(), &localeRes.Body); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if localeRes.Body.Lang != "it_IT.UTF-8" || localeRes.Body.VCKeymap != "it" { if localeRes.Body.Lang != "it_IT.UTF-8" || localeRes.Body.Language != "en_US:" || localeRes.Body.VCKeymap != "it" {
t.Errorf("got locale status: %+v", localeRes.Body) t.Errorf("got locale status: %+v", localeRes.Body)
} }
@@ -186,6 +189,17 @@ func TestSystemHandlers(t *testing.T) {
t.Errorf("set locale: got %d, want %d", resp.Code, http.StatusOK) t.Errorf("set locale: got %d, want %d", resp.Code, http.StatusOK)
} }
resp = api.Post("/api/system/locale", struct {
Lang string `json:"lang"`
Language string `json:"language"`
}{
Lang: "it_IT.UTF-8",
Language: "en_US:",
})
if resp.Code != http.StatusOK {
t.Errorf("set locale with language: got %d, want %d", resp.Code, http.StatusOK)
}
resp = api.Get("/api/system/keymaps") resp = api.Get("/api/system/keymaps")
if resp.Code != http.StatusOK { if resp.Code != http.StatusOK {
t.Errorf("list keymaps: got %d, want %d", resp.Code, http.StatusOK) t.Errorf("list keymaps: got %d, want %d", resp.Code, http.StatusOK)
+1 -1
View File
@@ -60,7 +60,7 @@ func TestOpenAPISchemaNoCollisions(t *testing.T) {
} }
meta.Register(api, mods) meta.Register(api, mods)
meta.RegisterHealth(api, sessions) meta.RegisterHealth(api, sessions)
meta.RegisterWhoami(api, sessions, roles, mods) meta.RegisterWhoami(api, sessions, nil, roles, mods)
auth.RegisterLogin(api, sessions, auditStore, true) auth.RegisterLogin(api, sessions, auditStore, true)
auth.RegisterLogout(api, sessions, true) auth.RegisterLogout(api, sessions, true)