5 Commits

Author SHA1 Message Date
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
6 changed files with 224 additions and 31 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)
}
})
}
}
+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).
+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 {
+51 -18
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
@@ -161,12 +185,14 @@ func registerLocale(api huma.API) {
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 // ponytail: minimal servers ship without kbd / /usr/share/keymaps, so
// localectl errors instead of returning empty. Treat that as "no keymaps // localectl errors instead of returning empty. Surface that as a `reason`
// available" rather than a server fault — set-keymap stays unreachable // the frontend can display ("kbd not installed") instead of an opaque N/A.
// because nothing will be in the allowlist. keymaps, err := oscmd.RunLines("localectl", "list-keymaps")
keymaps, _ := oscmd.RunLines("localectl", "list-keymaps")
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
}) })
@@ -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)