5 Commits

Author SHA1 Message Date
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
9 changed files with 274 additions and 13 deletions
+2 -2
View File
@@ -278,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">
+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)
}
})
}
}
+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 {
+41 -1
View File
@@ -53,7 +53,47 @@ 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)
}
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",
+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 {