Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8fc4b236ac | |||
| 37f03816e1 | |||
| 541260e65e | |||
| c4180bada1 | |||
| 088880f584 |
@@ -238,7 +238,7 @@ func runServer() {
|
||||
|
||||
meta.Register(api, mods)
|
||||
meta.RegisterHealth(api, sessions)
|
||||
meta.RegisterWhoami(api, sessions, roles, mods)
|
||||
meta.RegisterWhoami(api, sessions, tokenAuth, roles, mods)
|
||||
meta.RegisterUpdate(api, configPath)
|
||||
|
||||
auth.RegisterLogin(api, sessions, auditStore, cfg.SecureCookie())
|
||||
@@ -278,11 +278,11 @@ func runServer() {
|
||||
// is the follow-up (M5 partial).
|
||||
w.Header().Set("Content-Security-Policy",
|
||||
"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; "+
|
||||
"img-src 'self' data: https:; "+
|
||||
"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.Write([]byte(`<!doctype html><html><head><title>API</title>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
|
||||
+26
-7
@@ -15,6 +15,7 @@ import (
|
||||
// itself.
|
||||
type WhoamiInput struct {
|
||||
SessionID string `cookie:"nadir_session_id"`
|
||||
Auth string `header:"Authorization"`
|
||||
}
|
||||
|
||||
// WhoamiBody reports who the caller is and, per module, which permissions they
|
||||
@@ -30,7 +31,7 @@ type WhoamiOutput struct{ Body WhoamiBody }
|
||||
// RegisterWhoami adds the current-user endpoint. It resolves the caller's
|
||||
// concrete grants by asking the RBAC store about each module's permissions,
|
||||
// so "*" wildcards in roles are expanded for free.
|
||||
func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC, mods []module.Module) {
|
||||
func RegisterWhoami(api huma.API, sessions *auth.SessionStore, tokens *auth.TokenAuth, roles *rbac.RBAC, mods []module.Module) {
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "whoami",
|
||||
Method: "GET",
|
||||
@@ -40,18 +41,35 @@ func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC,
|
||||
"permissions the caller holds (wildcards resolved). Pair with " +
|
||||
"/api/_modules to render the full permission matrix.",
|
||||
Tags: []string{"Meta"},
|
||||
Errors: []int{401},
|
||||
Errors: []int{401, 429},
|
||||
}, func(ctx context.Context, in *WhoamiInput) (*WhoamiOutput, error) {
|
||||
sess, ok := sessions.GetByToken(in.SessionID)
|
||||
if !ok {
|
||||
return nil, huma.Error401Unauthorized("unauthorized")
|
||||
var username string
|
||||
|
||||
if raw, isBearer := auth.BearerToken(in.Auth); isBearer {
|
||||
if tokens == nil {
|
||||
return nil, huma.Error401Unauthorized("unauthorized")
|
||||
}
|
||||
name, ok, throttled := tokens.Verify(auth.ClientIP(ctx), raw)
|
||||
if throttled {
|
||||
return nil, huma.Error429TooManyRequests("too many failed token attempts; wait a minute")
|
||||
}
|
||||
if !ok {
|
||||
return nil, huma.Error401Unauthorized("unauthorized")
|
||||
}
|
||||
username = name
|
||||
} else {
|
||||
sess, ok := sessions.GetByToken(in.SessionID)
|
||||
if !ok {
|
||||
return nil, huma.Error401Unauthorized("unauthorized")
|
||||
}
|
||||
username = sess.Username
|
||||
}
|
||||
|
||||
held := make(map[string][]string)
|
||||
for _, m := range mods {
|
||||
var perms []string
|
||||
for _, p := range m.Permissions() {
|
||||
if roles.Can(sess.Username, m.ID(), p) {
|
||||
if roles.Can(username, m.ID(), p) {
|
||||
perms = append(perms, string(p))
|
||||
}
|
||||
}
|
||||
@@ -61,7 +79,8 @@ func RegisterWhoami(api huma.API, sessions *auth.SessionStore, roles *rbac.RBAC,
|
||||
}
|
||||
|
||||
out := &WhoamiOutput{}
|
||||
out.Body = WhoamiBody{Username: sess.Username, Permissions: held}
|
||||
out.Body = WhoamiBody{Username: username, Permissions: held}
|
||||
return out, nil
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package meta
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"nadir/internal/auth"
|
||||
"nadir/internal/module"
|
||||
"nadir/internal/rbac"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/danielgtaylor/huma/v2/adapters/humago"
|
||||
"github.com/danielgtaylor/huma/v2/humatest"
|
||||
)
|
||||
|
||||
type dummyModule struct {
|
||||
id string
|
||||
perms []rbac.Permission
|
||||
}
|
||||
|
||||
func (m *dummyModule) ID() string { return m.id }
|
||||
func (m *dummyModule) Name() string { return m.id }
|
||||
func (m *dummyModule) Permissions() []rbac.Permission { return m.perms }
|
||||
func (m *dummyModule) Register(api huma.API) {}
|
||||
|
||||
func TestWhoami(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
sessions, err := auth.NewSessionStore(filepath.Join(tempDir, "sessions.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tokenStore, err := auth.NewTokenStore(filepath.Join(tempDir, "tokens.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tokenStore.Close()
|
||||
tokenAuth := auth.NewTokenAuth(tokenStore)
|
||||
|
||||
roles := rbac.New()
|
||||
roles.DefineRole(rbac.Role{
|
||||
Name: "admin-role",
|
||||
ModuleGrants: map[string][]rbac.Permission{
|
||||
"system": {rbac.Read},
|
||||
},
|
||||
})
|
||||
roles.AssignRole("admin", "admin-role")
|
||||
|
||||
mods := []module.Module{
|
||||
&dummyModule{
|
||||
id: "system",
|
||||
perms: []rbac.Permission{rbac.Read, rbac.Write},
|
||||
},
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
|
||||
RegisterWhoami(api, sessions, tokenAuth, roles, mods)
|
||||
|
||||
// 1. Unauthorized request (no token, no session)
|
||||
resp := api.Get("/api/whoami")
|
||||
if resp.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", resp.Code)
|
||||
}
|
||||
|
||||
// 2. Cookie session request
|
||||
sessToken, err := sessions.Create("admin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp = api.Get("/api/whoami", "Cookie: nadir_session_id="+sessToken)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", resp.Code)
|
||||
}
|
||||
var body WhoamiBody
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body.Username != "admin" {
|
||||
t.Errorf("expected username admin, got %q", body.Username)
|
||||
}
|
||||
if !slices.Contains(body.Permissions["system"], "read") {
|
||||
t.Errorf("expected system read permission, got %v", body.Permissions["system"])
|
||||
}
|
||||
|
||||
// 3. Token request
|
||||
bearerToken, err := tokenStore.Create("api-user")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
roles.DefineRole(rbac.Role{
|
||||
Name: "api-role",
|
||||
ModuleGrants: map[string][]rbac.Permission{
|
||||
"system": {rbac.Write},
|
||||
},
|
||||
})
|
||||
roles.AssignRole("api-user", "api-role")
|
||||
|
||||
resp = api.Get("/api/whoami", "Authorization: Bearer "+bearerToken)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", resp.Code)
|
||||
}
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body.Username != "api-user" {
|
||||
t.Errorf("expected username api-user, got %q", body.Username)
|
||||
}
|
||||
if !slices.Contains(body.Permissions["system"], "write") {
|
||||
t.Errorf("expected system write permission, got %v", body.Permissions["system"])
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ func (m *Module) Permissions() []rbac.Permission {
|
||||
}
|
||||
|
||||
func (m *Module) Register(api huma.API) {
|
||||
registerReads(api)
|
||||
registerReads(api, m)
|
||||
registerWrites(api, m)
|
||||
registerHosts(api)
|
||||
}
|
||||
|
||||
@@ -87,6 +87,30 @@ func TestNetworkingHandlers(t *testing.T) {
|
||||
t.Errorf("list interfaces: got %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
// 1b. Test GET /api/networking/interfaces/{name} (used by edit-form prefill).
|
||||
// Asserts the backend's Snapshot output is returned verbatim as the body, so
|
||||
// the same shape can feed straight into PUT.
|
||||
resp = api.Get("/api/networking/interfaces/eth0")
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("get interface: got %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
var ifaceRes GetInterfaceConfigOutput
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &ifaceRes.Body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ifaceRes.Body.Method != "dhcp" || ifaceRes.Body.Address != "192.168.1.10/24" {
|
||||
t.Errorf("get interface: got %+v, want snapshot result", ifaceRes.Body)
|
||||
}
|
||||
|
||||
// Same endpoint with no backend should return 501.
|
||||
noBackend := &Module{}
|
||||
noBackendMux := http.NewServeMux()
|
||||
noBackendAPI := humatest.Wrap(t, humago.New(noBackendMux, huma.DefaultConfig("Test", "1.0.0")))
|
||||
noBackend.Register(noBackendAPI)
|
||||
if got := noBackendAPI.Get("/api/networking/interfaces/eth0").Code; got != http.StatusNotImplemented {
|
||||
t.Errorf("get interface without backend: got %d, want 501", got)
|
||||
}
|
||||
|
||||
// 2. Test GET /api/networking/routes
|
||||
resp = api.Get("/api/networking/routes")
|
||||
if resp.Code != http.StatusOK {
|
||||
@@ -388,3 +412,69 @@ func TestBackendImplementations(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetInterfaceConfigAugment(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
api := humatest.Wrap(t, humago.New(mux, huma.DefaultConfig("Test", "1.0.0")))
|
||||
|
||||
be := &mockBackend{
|
||||
name: "mockbe",
|
||||
snapshotResult: IfaceConfig{
|
||||
Method: "dhcp",
|
||||
},
|
||||
}
|
||||
m := &Module{be: be}
|
||||
m.Register(api)
|
||||
|
||||
tempResolv := filepath.Join(t.TempDir(), "resolv.conf")
|
||||
if err := os.WriteFile(tempResolv, []byte("nameserver 1.1.1.1\nnameserver 8.8.8.8\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldResolv := resolvConf
|
||||
resolvConf = tempResolv
|
||||
defer func() { resolvConf = oldResolv }()
|
||||
|
||||
oscmd.SetMock("ip", func(args []string) oscmd.MockCommand {
|
||||
argStr := strings.Join(args, " ")
|
||||
if strings.Contains(argStr, "addr show") {
|
||||
out := `[{"ifname": "eth0", "operstate": "UP", "address": "aa:bb:cc:dd:ee:ff", "mtu": 1500, "addr_info": [{"family": "inet", "local": "192.168.1.10", "prefixlen": 24}, {"family": "inet6", "local": "2001:db8::10", "prefixlen": 64}]}]`
|
||||
return oscmd.MockCommand{Stdout: out, ExitCode: 0}
|
||||
}
|
||||
if strings.Contains(argStr, "route show") && !strings.Contains(argStr, "-6") {
|
||||
out := `[{"dst": "default", "gateway": "192.168.1.1", "dev": "eth0"}]`
|
||||
return oscmd.MockCommand{Stdout: out, ExitCode: 0}
|
||||
}
|
||||
if strings.Contains(argStr, "-6") && strings.Contains(argStr, "route show") {
|
||||
out := `[{"dst": "default", "gateway": "2001:db8::1", "dev": "eth0"}]`
|
||||
return oscmd.MockCommand{Stdout: out, ExitCode: 0}
|
||||
}
|
||||
return oscmd.MockCommand{ExitCode: 1}
|
||||
})
|
||||
defer oscmd.ClearMocks()
|
||||
|
||||
resp := api.Get("/api/networking/interfaces/eth0")
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Errorf("get interface: got %d, want %d", resp.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
var ifaceRes GetInterfaceConfigOutput
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &ifaceRes.Body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if ifaceRes.Body.Method != "dhcp" {
|
||||
t.Errorf("expected Method to be dhcp, got %s", ifaceRes.Body.Method)
|
||||
}
|
||||
if ifaceRes.Body.Address != "192.168.1.10" || ifaceRes.Body.Prefix != 24 {
|
||||
t.Errorf("expected augmented Address 192.168.1.10/24, got %s/%d", ifaceRes.Body.Address, ifaceRes.Body.Prefix)
|
||||
}
|
||||
if ifaceRes.Body.Gateway != "192.168.1.1" {
|
||||
t.Errorf("expected augmented Gateway 192.168.1.1, got %s", ifaceRes.Body.Gateway)
|
||||
}
|
||||
if len(ifaceRes.Body.DNS) != 2 || ifaceRes.Body.DNS[0] != "1.1.1.1" || ifaceRes.Body.DNS[1] != "8.8.8.8" {
|
||||
t.Errorf("expected augmented DNS [1.1.1.1, 8.8.8.8], got %v", ifaceRes.Body.DNS)
|
||||
}
|
||||
if ifaceRes.Body.IPv6 == nil || ifaceRes.Body.IPv6.Method != "auto" || ifaceRes.Body.IPv6.Address != "2001:db8::10" || ifaceRes.Body.IPv6.Prefix != 64 || ifaceRes.Body.IPv6.Gateway != "2001:db8::1" {
|
||||
t.Errorf("expected augmented IPv6, got %+v", ifaceRes.Body.IPv6)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,11 +46,19 @@ func (b *nmcliBackend) Snapshot(ctx context.Context, iface string) (IfaceConfig,
|
||||
return IfaceConfig{Method: "dhcp"}, nil
|
||||
}
|
||||
|
||||
// nmcli's `con show <NAME>` parser does NOT honor `--` as an end-of-options
|
||||
// separator; passing it makes nmcli look for a connection literally named
|
||||
// "--" and fail. `conn` comes from nmcli's own active-connections list (see
|
||||
// connForIface), so it's already validated — no shell-metacharacter risk.
|
||||
// Same applies to con up / con down / con modify below.
|
||||
out, err := oscmd.RunContext(ctx, "nmcli", "-t", "-f",
|
||||
"ipv4.method,ipv4.addresses,ipv4.gateway,ipv4.dns,ipv4.routes,ipv6.method,ipv6.addresses,ipv6.gateway",
|
||||
"con", "show", "--", conn)
|
||||
"con", "show", conn)
|
||||
if err != nil {
|
||||
return IfaceConfig{}, fmt.Errorf("nmcli con show %s: %w", conn, err)
|
||||
// nmcli can refuse the read (connection state odd, permission, terse-mode
|
||||
// quirks). Fall back to DHCP defaults so the prefill endpoint still
|
||||
// returns a usable form, mirroring the networkd / ifupdown fallback.
|
||||
return IfaceConfig{Method: "dhcp"}, nil
|
||||
}
|
||||
|
||||
return parseNmcliSnapshot(out), nil
|
||||
@@ -159,9 +167,9 @@ func (b *nmcliBackend) Apply(ctx context.Context, iface string, cfg IfaceConfig)
|
||||
return fmt.Errorf("cannot apply: %w", err)
|
||||
}
|
||||
|
||||
// Build the nmcli con modify arguments. Note: conn is safe to place after
|
||||
// -- since it comes from nmcli output, not directly from the user.
|
||||
args := []string{"con", "modify", "--", conn}
|
||||
// conn comes from nmcli's own active list (connForIface), not user input.
|
||||
// nmcli's con subcommands don't honor "--" as an end-of-options separator.
|
||||
args := []string{"con", "modify", conn}
|
||||
|
||||
switch cfg.Method {
|
||||
case "static":
|
||||
@@ -222,7 +230,7 @@ func (b *nmcliBackend) Apply(ctx context.Context, iface string, cfg IfaceConfig)
|
||||
}
|
||||
|
||||
// Bring the connection up to apply changes.
|
||||
if _, err := oscmd.RunContext(ctx, "nmcli", "con", "up", "--", conn); err != nil {
|
||||
if _, err := oscmd.RunContext(ctx, "nmcli", "con", "up", conn); err != nil {
|
||||
return fmt.Errorf("nmcli con up: %w", err)
|
||||
}
|
||||
return nil
|
||||
@@ -235,7 +243,7 @@ func (b *nmcliBackend) SetLinkUp(ctx context.Context, iface string) error {
|
||||
_, err = oscmd.RunContext(ctx, "ip", "link", "set", "--", iface, "up")
|
||||
return err
|
||||
}
|
||||
_, err = oscmd.RunContext(ctx, "nmcli", "con", "up", "--", conn)
|
||||
_, err = oscmd.RunContext(ctx, "nmcli", "con", "up", conn)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -245,7 +253,7 @@ func (b *nmcliBackend) SetLinkDown(ctx context.Context, iface string) error {
|
||||
_, err = oscmd.RunContext(ctx, "ip", "link", "set", "--", iface, "down")
|
||||
return err
|
||||
}
|
||||
_, err = oscmd.RunContext(ctx, "nmcli", "con", "down", "--", conn)
|
||||
_, err = oscmd.RunContext(ctx, "nmcli", "con", "down", conn)
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ package networking
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -53,7 +55,48 @@ type DNSOutput struct {
|
||||
}
|
||||
}
|
||||
|
||||
func registerReads(api huma.API) {
|
||||
// GetInterfaceConfigInput carries the path param; matches the PUT endpoint's
|
||||
// IfacePathInput so the frontend can use the same path for both verbs.
|
||||
type GetInterfaceConfigInput struct {
|
||||
Name string `path:"name" example:"eth0" doc:"Interface name"`
|
||||
}
|
||||
|
||||
// GetInterfaceConfigOutput returns the same IfaceConfig shape that PUT
|
||||
// accepts, so the form can be pre-filled directly from this response.
|
||||
type GetInterfaceConfigOutput struct {
|
||||
Body IfaceConfig
|
||||
}
|
||||
|
||||
func registerReads(api huma.API, m *Module) {
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "networking-get-interface",
|
||||
Method: "GET",
|
||||
Path: "/api/networking/interfaces/{name}",
|
||||
Summary: "Get an interface's current configuration",
|
||||
Description: "Returns the IfaceConfig the backend currently has for this " +
|
||||
"interface (method, address/prefix, gateway, DNS, IPv6). Same schema as " +
|
||||
"PUT /api/networking/interfaces/{name}, so the frontend can prefill an " +
|
||||
"edit form from this response directly. Returns 501 when no backend was " +
|
||||
"detected (nmcli / networkd / ifupdown).",
|
||||
Tags: []string{tagNetworking},
|
||||
Metadata: op("read"),
|
||||
Errors: readErrors,
|
||||
}, func(ctx context.Context, in *GetInterfaceConfigInput) (*GetInterfaceConfigOutput, error) {
|
||||
if m.be == nil {
|
||||
return nil, huma.Error501NotImplemented("", errNoBackend)
|
||||
}
|
||||
if err := validateIface(in.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg, err := m.be.Snapshot(ctx, in.Name)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("snapshot failed", err)
|
||||
}
|
||||
augmentWithLiveState(ctx, in.Name, &cfg)
|
||||
return &GetInterfaceConfigOutput{Body: cfg}, nil
|
||||
})
|
||||
|
||||
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "networking-list-interfaces",
|
||||
Method: "GET",
|
||||
@@ -209,3 +252,113 @@ func parseResolv(text string) []string {
|
||||
}
|
||||
return servers
|
||||
}
|
||||
|
||||
func getLiveInterface(ctx context.Context, iface string) (*Interface, error) {
|
||||
out, err := oscmd.RunContext(ctx, "ip", "-j", "addr", "show", "--", iface)
|
||||
if err != nil {
|
||||
out, err = oscmd.RunContext(ctx, "ip", "-j", "addr")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
ifaces, err := parseInterfaces(out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range ifaces {
|
||||
if ifaces[i].Name == iface {
|
||||
return &ifaces[i], nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("interface %s not found in ip addr output", iface)
|
||||
}
|
||||
|
||||
func getLiveGateway(ctx context.Context, iface string) string {
|
||||
routeOut, err := oscmd.RunContext(ctx, "ip", "-j", "route", "show", "dev", "--", iface)
|
||||
if err != nil {
|
||||
routeOut, err = oscmd.RunContext(ctx, "ip", "-j", "route")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
routes, err := parseRoutes(routeOut)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, r := range routes {
|
||||
if r.Destination == "default" && (r.Interface == iface || r.Interface == "") && r.Gateway != "" {
|
||||
return r.Gateway
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func getLiveIPv6Gateway(ctx context.Context, iface string) string {
|
||||
routeOut, err := oscmd.RunContext(ctx, "ip", "-6", "-j", "route", "show", "dev", "--", iface)
|
||||
if err != nil {
|
||||
routeOut, err = oscmd.RunContext(ctx, "ip", "-6", "-j", "route")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
routes, err := parseRoutes(routeOut)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, r := range routes {
|
||||
if r.Destination == "default" && (r.Interface == iface || r.Interface == "") && r.Gateway != "" {
|
||||
return r.Gateway
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func augmentWithLiveState(ctx context.Context, iface string, cfg *IfaceConfig) {
|
||||
liveIface, err := getLiveInterface(ctx, iface)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Prefill IPv4 address and prefix if empty
|
||||
if cfg.Address == "" && len(liveIface.IPv4) > 0 {
|
||||
addr, prefix := splitCIDR(liveIface.IPv4[0])
|
||||
if addr != "" {
|
||||
cfg.Address = addr
|
||||
cfg.Prefix = prefix
|
||||
}
|
||||
}
|
||||
|
||||
// Prefill Gateway if empty
|
||||
if cfg.Gateway == "" {
|
||||
cfg.Gateway = getLiveGateway(ctx, iface)
|
||||
}
|
||||
|
||||
// Prefill DNS if empty
|
||||
if len(cfg.DNS) == 0 {
|
||||
if data, err := os.ReadFile(resolvConf); err == nil {
|
||||
cfg.DNS = parseResolv(string(data))
|
||||
}
|
||||
}
|
||||
|
||||
// Prefill IPv6 if present and method is not ignore
|
||||
if cfg.IPv6 == nil {
|
||||
cfg.IPv6 = &IPv6Config{Method: "auto"}
|
||||
}
|
||||
if cfg.IPv6.Method != "ignore" {
|
||||
// Capture first global IPv6 if address is empty
|
||||
if cfg.IPv6.Address == "" {
|
||||
for _, c := range liveIface.IPv6 {
|
||||
addr, prefix := splitCIDR(c)
|
||||
if ip, err := netip.ParseAddr(addr); err == nil && !ip.IsLinkLocalUnicast() {
|
||||
cfg.IPv6.Address = addr
|
||||
cfg.IPv6.Prefix = prefix
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
// Capture IPv6 default gateway if empty
|
||||
if cfg.IPv6.Gateway == "" {
|
||||
cfg.IPv6.Gateway = getLiveIPv6Gateway(ctx, iface)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,11 +283,11 @@ func result(pm manager, pkgs []Package) *ListOutput {
|
||||
func (m manager) installArgs(name string) (string, []string) {
|
||||
switch m.name {
|
||||
case "dnf":
|
||||
return "dnf", []string{"install", "-y", "--", name}
|
||||
return "dnf", []string{"install", "-y", name}
|
||||
case "apt":
|
||||
return "apt-get", []string{"install", "-y", "--", name}
|
||||
return "apt-get", []string{"install", "-y", name}
|
||||
case "pacman":
|
||||
return "pacman", []string{"-S", "--noconfirm", "--", name}
|
||||
return "pacman", []string{"-S", "--noconfirm", name}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
@@ -295,11 +295,11 @@ func (m manager) installArgs(name string) (string, []string) {
|
||||
func (m manager) removeArgs(name string) (string, []string) {
|
||||
switch m.name {
|
||||
case "dnf":
|
||||
return "dnf", []string{"remove", "-y", "--", name}
|
||||
return "dnf", []string{"remove", "-y", name}
|
||||
case "apt":
|
||||
return "apt-get", []string{"remove", "-y", "--", name}
|
||||
return "apt-get", []string{"remove", "-y", name}
|
||||
case "pacman":
|
||||
return "pacman", []string{"-R", "--noconfirm", "--", name}
|
||||
return "pacman", []string{"-R", "--noconfirm", name}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
@@ -322,11 +322,11 @@ func (m manager) upgradeArgs() (string, []string) {
|
||||
func (m manager) upgradeOneArgs(name string) (string, []string) {
|
||||
switch m.name {
|
||||
case "dnf":
|
||||
return "dnf", []string{"upgrade", "-y", "--", name}
|
||||
return "dnf", []string{"upgrade", "-y", name}
|
||||
case "apt":
|
||||
return "apt-get", []string{"install", "--only-upgrade", "-y", "--", name}
|
||||
return "apt-get", []string{"install", "--only-upgrade", "-y", name}
|
||||
case "pacman":
|
||||
return "pacman", []string{"-S", "--noconfirm", "--", name}
|
||||
return "pacman", []string{"-S", "--noconfirm", name}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
@@ -3,14 +3,22 @@ package services
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"nadir/internal/oscmd"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
)
|
||||
|
||||
// selfUnit is nadir's own systemd unit name. Acting on it via the normal
|
||||
// synchronous path would have systemd SIGTERM the very process serving the
|
||||
// request, so the client sees a dropped connection / 500 even though the
|
||||
// action succeeded. We detach those calls into a Setsid subprocess instead.
|
||||
const selfUnit = "nadir"
|
||||
|
||||
const tagServices = "Services"
|
||||
|
||||
var (
|
||||
@@ -136,6 +144,9 @@ func registerServices(api huma.API) {
|
||||
if err := ensureExists(in.Unit); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if isSelf(in.Unit) {
|
||||
return runDetached(c.action, in.Unit)
|
||||
}
|
||||
if _, err := oscmd.Run("systemctl", c.action, "--", in.Unit); err != nil {
|
||||
return nil, huma.Error500InternalServerError("systemctl "+c.action+" failed", err)
|
||||
}
|
||||
@@ -144,6 +155,27 @@ func registerServices(api huma.API) {
|
||||
}
|
||||
}
|
||||
|
||||
// isSelf reports whether unit names nadir's own service, with or without the
|
||||
// .service suffix.
|
||||
func isSelf(unit string) bool {
|
||||
return unit == selfUnit || unit == selfUnit+".service"
|
||||
}
|
||||
|
||||
// runDetached fires systemctl in a new session so a "systemctl restart nadir"
|
||||
// (or stop) doesn't kill its own caller before the HTTP response is written.
|
||||
// Returns success once the subprocess has *started* — the actual systemd
|
||||
// operation may complete after the response is sent, which is the whole point.
|
||||
func runDetached(action, unit string) (*oscmd.StatusOutput, error) {
|
||||
cmd := exec.Command("systemctl", action, "--", unit)
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, huma.Error500InternalServerError("could not start detached systemctl", err)
|
||||
}
|
||||
// Reap in the background so the child doesn't become a zombie.
|
||||
go cmd.Wait()
|
||||
return oscmd.OK(), nil
|
||||
}
|
||||
|
||||
// validateUnit guards against empty, flag-like, or malformed unit names.
|
||||
func validateUnit(unit string) error {
|
||||
if unit == "" || strings.HasPrefix(unit, "-") || !unitNameRe.MatchString(unit) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ func TestOpenAPISchemaNoCollisions(t *testing.T) {
|
||||
}
|
||||
meta.Register(api, mods)
|
||||
meta.RegisterHealth(api, sessions)
|
||||
meta.RegisterWhoami(api, sessions, roles, mods)
|
||||
meta.RegisterWhoami(api, sessions, nil, roles, mods)
|
||||
auth.RegisterLogin(api, sessions, auditStore, true)
|
||||
auth.RegisterLogout(api, sessions, true)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user