Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| aec04bfe02 | |||
| a54c42271c | |||
| b10abb24e3 | |||
| 9587d11e21 | |||
| ac196e720b |
@@ -239,8 +239,7 @@ 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, 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())
|
||||||
|
|||||||
+3
-2
@@ -1,8 +1,9 @@
|
|||||||
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"
|
||||||
@@ -24,7 +25,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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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()
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -2,6 +2,10 @@ package system
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"regexp"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -12,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"`
|
||||||
}
|
}
|
||||||
@@ -27,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)"`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,6 +49,20 @@ type SetKeymapInput struct {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type GenerateLocaleInput struct {
|
||||||
|
Body struct {
|
||||||
|
Locale string `json:"locale" example:"fr_FR.UTF-8" doc:"Locale to generate (e.g. fr_FR.UTF-8)"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// localeRe validates a locale identifier: language_TERRITORY with an optional
|
||||||
|
// .charmap suffix (e.g. fr_FR, fr_FR.UTF-8, en_US.ISO-8859-1).
|
||||||
|
var localeRe = regexp.MustCompile(`^[a-z]{2,3}_[A-Z]{2}(\.[A-Za-z0-9_-]+)?$`)
|
||||||
|
|
||||||
|
// languageRe validates the LANGUAGE fallback list: colon-separated locale names
|
||||||
|
// like "en_US:de_DE". Anchored so a leading "-" can't survive into argv.
|
||||||
|
var languageRe = regexp.MustCompile(`^[a-zA-Z0-9_.:-]*$`)
|
||||||
|
|
||||||
func localeStatus() (LocaleStatusBody, error) {
|
func localeStatus() (LocaleStatusBody, error) {
|
||||||
lines, err := oscmd.RunLines("localectl", "status")
|
lines, err := oscmd.RunLines("localectl", "status")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -49,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
|
||||||
@@ -130,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
|
||||||
@@ -146,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
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -171,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)
|
||||||
}
|
}
|
||||||
@@ -183,4 +223,124 @@ func registerLocale(api huma.API) {
|
|||||||
}
|
}
|
||||||
return oscmd.OK(), nil
|
return oscmd.OK(), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
huma.Register(api, huma.Operation{
|
||||||
|
OperationID: "system-generate-locale",
|
||||||
|
Method: "POST",
|
||||||
|
Path: "/api/system/locale/generate",
|
||||||
|
Summary: "Generate (install) a new locale",
|
||||||
|
Description: "Generates a locale so it becomes available for use with set-locale. " +
|
||||||
|
"On Debian/Ubuntu/Arch this uncomments the entry in /etc/locale.gen and runs " +
|
||||||
|
"locale-gen; on RHEL/Fedora it uses localedef. Idempotent: if the locale is " +
|
||||||
|
"already generated, returns 200 immediately.",
|
||||||
|
Tags: []string{tagSystem},
|
||||||
|
Metadata: op("write"),
|
||||||
|
Errors: []int{400, 401, 403, 500, 501},
|
||||||
|
}, func(ctx context.Context, in *GenerateLocaleInput) (*oscmd.StatusOutput, error) {
|
||||||
|
locale := strings.TrimSpace(in.Body.Locale)
|
||||||
|
if locale == "" {
|
||||||
|
return nil, huma.Error400BadRequest("empty locale")
|
||||||
|
}
|
||||||
|
if !localeRe.MatchString(locale) {
|
||||||
|
return nil, huma.Error400BadRequest("invalid locale format: "+locale,
|
||||||
|
fmt.Errorf("expected language_TERRITORY[.charmap], e.g. fr_FR.UTF-8"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Idempotency: already generated → success.
|
||||||
|
existing, err := oscmd.RunLines("localectl", "list-locales")
|
||||||
|
if err != nil {
|
||||||
|
return nil, huma.Error500InternalServerError("localectl failed", err)
|
||||||
|
}
|
||||||
|
if slices.Contains(existing, locale) {
|
||||||
|
return oscmd.OK(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detect which generation path the host supports.
|
||||||
|
localeGenFile := "/etc/locale.gen"
|
||||||
|
_, hasFile := os.Stat(localeGenFile)
|
||||||
|
_, hasLocaleGen := exec.LookPath("locale-gen")
|
||||||
|
_, hasLocaledef := exec.LookPath("localedef")
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case hasFile == nil && hasLocaleGen == nil:
|
||||||
|
if err := enableLocaleGen(localeGenFile, locale); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
case hasLocaledef == nil:
|
||||||
|
if err := generateLocaledef(locale); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return nil, huma.Error501NotImplemented(
|
||||||
|
"locale generation not supported on this host (no locale-gen or localedef found)")
|
||||||
|
}
|
||||||
|
return oscmd.OK(), nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// enableLocaleGen uncomments the locale in /etc/locale.gen and runs locale-gen.
|
||||||
|
// This is the Debian/Ubuntu/Arch path.
|
||||||
|
func enableLocaleGen(path, locale string) error {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return huma.Error500InternalServerError("reading locale.gen failed", err)
|
||||||
|
}
|
||||||
|
newContent, found := uncommentLocaleGen(string(data), locale)
|
||||||
|
if !found {
|
||||||
|
return huma.Error400BadRequest("locale not available for generation: " + locale)
|
||||||
|
}
|
||||||
|
// Write atomically: a crash mid-write would leave /etc/locale.gen truncated
|
||||||
|
// and break every subsequent locale-gen on the host.
|
||||||
|
tmp := path + ".nadir.tmp"
|
||||||
|
if err := os.WriteFile(tmp, []byte(newContent), 0644); err != nil {
|
||||||
|
return huma.Error500InternalServerError("writing locale.gen failed", err)
|
||||||
|
}
|
||||||
|
if err := os.Rename(tmp, path); err != nil {
|
||||||
|
os.Remove(tmp)
|
||||||
|
return huma.Error500InternalServerError("replacing locale.gen failed", err)
|
||||||
|
}
|
||||||
|
if _, err := oscmd.Run("locale-gen"); err != nil {
|
||||||
|
return huma.Error500InternalServerError("locale-gen failed", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// uncommentLocaleGen finds a commented-out line for the given locale in a
|
||||||
|
// locale.gen file and uncomments it. Returns the modified content and whether
|
||||||
|
// a matching line was found. Pure function for testability.
|
||||||
|
func uncommentLocaleGen(content, locale string) (string, bool) {
|
||||||
|
lines := strings.Split(content, "\n")
|
||||||
|
found := false
|
||||||
|
for i, line := range lines {
|
||||||
|
trimmed := strings.TrimSpace(line)
|
||||||
|
// Match lines like "# fr_FR.UTF-8 UTF-8" or "#fr_FR.UTF-8 UTF-8".
|
||||||
|
if !strings.HasPrefix(trimmed, "#") {
|
||||||
|
// Also check if already uncommented (idempotent at the file level).
|
||||||
|
if strings.HasPrefix(trimmed, locale+" ") || trimmed == locale {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
uncommented := strings.TrimSpace(strings.TrimPrefix(trimmed, "#"))
|
||||||
|
if strings.HasPrefix(uncommented, locale+" ") || uncommented == locale {
|
||||||
|
lines[i] = uncommented
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n"), found
|
||||||
|
}
|
||||||
|
|
||||||
|
// generateLocaledef generates a locale using localedef. This is the RHEL/Fedora
|
||||||
|
// path where there is no /etc/locale.gen.
|
||||||
|
func generateLocaledef(locale string) error {
|
||||||
|
// Parse "fr_FR.UTF-8" into language_territory="fr_FR" and charmap="UTF-8".
|
||||||
|
// If there is no dot, default to UTF-8 (the common case on modern systems).
|
||||||
|
langTerritory, charmap, _ := strings.Cut(locale, ".")
|
||||||
|
if charmap == "" {
|
||||||
|
charmap = "UTF-8"
|
||||||
|
}
|
||||||
|
if _, err := oscmd.Run("localedef", "-i", langTerritory, "-f", charmap, locale); err != nil {
|
||||||
|
return huma.Error500InternalServerError("localedef failed", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"nadir/internal/oscmd"
|
"nadir/internal/oscmd"
|
||||||
@@ -141,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"}) {
|
||||||
@@ -150,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}
|
||||||
}
|
}
|
||||||
@@ -167,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,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)
|
||||||
@@ -199,6 +214,37 @@ func TestSystemHandlers(t *testing.T) {
|
|||||||
t.Errorf("set keymap: got %d, want %d", resp.Code, http.StatusOK)
|
t.Errorf("set keymap: got %d, want %d", resp.Code, http.StatusOK)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 4b. Test POST /api/system/locale/generate (validation & idempotent)
|
||||||
|
// Empty locale → 422 (huma validates non-empty before handler runs)
|
||||||
|
resp = api.Post("/api/system/locale/generate", struct {
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
}{
|
||||||
|
Locale: "",
|
||||||
|
})
|
||||||
|
if resp.Code != http.StatusBadRequest && resp.Code != http.StatusUnprocessableEntity {
|
||||||
|
t.Errorf("generate empty locale: got %d, want 400 or 422", resp.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invalid format → 400
|
||||||
|
resp = api.Post("/api/system/locale/generate", struct {
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
}{
|
||||||
|
Locale: "not-a-locale!!",
|
||||||
|
})
|
||||||
|
if resp.Code != http.StatusBadRequest {
|
||||||
|
t.Errorf("generate invalid locale: got %d, want %d", resp.Code, http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Already generated (it_IT.UTF-8 is in list-locales mock) → 200 (idempotent)
|
||||||
|
resp = api.Post("/api/system/locale/generate", struct {
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
}{
|
||||||
|
Locale: "it_IT.UTF-8",
|
||||||
|
})
|
||||||
|
if resp.Code != http.StatusOK {
|
||||||
|
t.Errorf("generate existing locale (idempotent): got %d, want %d", resp.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
// 5. Test POST /api/system/reboot and /api/system/poweroff
|
// 5. Test POST /api/system/reboot and /api/system/poweroff
|
||||||
oscmd.SetMock("shutdown", func(args []string) oscmd.MockCommand {
|
oscmd.SetMock("shutdown", func(args []string) oscmd.MockCommand {
|
||||||
if reflect.DeepEqual(args, []string{"-r", "now"}) || reflect.DeepEqual(args, []string{"-h", "now"}) {
|
if reflect.DeepEqual(args, []string{"-r", "now"}) || reflect.DeepEqual(args, []string{"-h", "now"}) {
|
||||||
@@ -225,3 +271,58 @@ func TestSystemHandlers(t *testing.T) {
|
|||||||
t.Errorf("poweroff: got %d, want %d", resp.Code, http.StatusOK)
|
t.Errorf("poweroff: got %d, want %d", resp.Code, http.StatusOK)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestUncommentLocaleGen(t *testing.T) {
|
||||||
|
const sampleLocaleGen = `# This file lists locales that you wish to have built.
|
||||||
|
#
|
||||||
|
# en_US.UTF-8 UTF-8
|
||||||
|
# fr_FR.UTF-8 UTF-8
|
||||||
|
# de_DE.UTF-8 UTF-8
|
||||||
|
it_IT.UTF-8 UTF-8
|
||||||
|
`
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
locale string
|
||||||
|
wantFound bool
|
||||||
|
wantSubstr string // substring that should appear uncommented
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "uncomment commented locale",
|
||||||
|
locale: "fr_FR.UTF-8",
|
||||||
|
wantFound: true,
|
||||||
|
wantSubstr: "\nfr_FR.UTF-8 UTF-8\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "already uncommented",
|
||||||
|
locale: "it_IT.UTF-8",
|
||||||
|
wantFound: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "locale not in file",
|
||||||
|
locale: "ja_JP.UTF-8",
|
||||||
|
wantFound: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
result, found := uncommentLocaleGen(sampleLocaleGen, tt.locale)
|
||||||
|
if found != tt.wantFound {
|
||||||
|
t.Errorf("found = %v, want %v", found, tt.wantFound)
|
||||||
|
}
|
||||||
|
if tt.wantSubstr != "" && !contains(result, tt.wantSubstr) {
|
||||||
|
t.Errorf("result does not contain %q:\n%s", tt.wantSubstr, result)
|
||||||
|
}
|
||||||
|
// The commented versions of OTHER locales should remain commented.
|
||||||
|
if tt.locale == "fr_FR.UTF-8" && !contains(result, "# en_US.UTF-8 UTF-8") {
|
||||||
|
t.Errorf("other locales should stay commented:\n%s", result)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func contains(s, substr string) bool {
|
||||||
|
return len(s) >= len(substr) && (s == substr || len(substr) == 0 ||
|
||||||
|
(len(s) > 0 && strings.Contains(s, substr)))
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user