daemon: split owner daemon from root helper

Move the supported systemd path to two services: an owner-user bangerd for
orchestration and a narrow root helper for bridge/tap, NAT/resolver, dm/loop,
and Firecracker ownership. This removes repeated sudo from daily vm and image
flows without leaving the general daemon running as root.

Add install metadata, system install/status/restart/uninstall commands, and a
system-owned runtime layout. Keep user SSH/config material in the owner home,
lock file_sync to the owner home, and move daemon known_hosts handling out of
the old root-owned control path.

Route privileged lifecycle steps through typed privilegedOps calls, harden the
two systemd units, and rewrite smoke plus docs around the supported service
model.

Verified with make build, make test, make lint, and make smoke on the
supported systemd host path.
This commit is contained in:
Thales Maciel 2026-04-26 12:43:17 -03:00
parent 3edd7c6de7
commit 59e48e830b
No known key found for this signature in database
GPG key ID: 33112E6833C34679
53 changed files with 3239 additions and 726 deletions

View file

@ -52,6 +52,18 @@ type vmDefaultsFile struct {
}
func Load(layout paths.Layout) (model.DaemonConfig, error) {
home, err := os.UserHomeDir()
if err != nil {
return model.DaemonConfig{}, err
}
return load(layout, home, true)
}
func LoadDaemon(layout paths.Layout, ownerHome string) (model.DaemonConfig, error) {
return load(layout, ownerHome, false)
}
func load(layout paths.Layout, home string, ensureDefaultSSHKey bool) (model.DaemonConfig, error) {
cfg := model.DaemonConfig{
LogLevel: "info",
AutoStopStaleAfter: 0,
@ -62,6 +74,7 @@ func Load(layout paths.Layout) (model.DaemonConfig, error) {
TapPoolSize: 4,
DefaultDNS: model.DefaultDNS,
DefaultImageName: "debian-bookworm",
HostHomeDir: home,
}
var file fileConfig
@ -122,14 +135,14 @@ func Load(layout paths.Layout) (model.DaemonConfig, error) {
cfg.LogLevel = value
}
sshKeyPath, err := resolveSSHKeyPath(layout, file.SSHKeyPath)
sshKeyPath, err := resolveSSHKeyPath(layout, file.SSHKeyPath, home, ensureDefaultSSHKey)
if err != nil {
return cfg, err
}
cfg.SSHKeyPath = sshKeyPath
for i, entry := range file.FileSync {
validated, err := validateFileSyncEntry(entry)
validated, err := validateFileSyncEntry(entry, home)
if err != nil {
return cfg, fmt.Errorf("file_sync[%d]: %w", i, err)
}
@ -179,9 +192,9 @@ func parseVMDefaults(file vmDefaultsFile) (model.VMDefaultsOverride, error) {
// validateFileSyncEntry normalises a single `[[file_sync]]` entry
// and rejects anything the operator would regret later: empty
// paths, unsupported leading characters, path traversal, or
// non-absolute guest targets.
func validateFileSyncEntry(entry fileSyncEntryFile) (model.FileSyncEntry, error) {
// paths, unsupported leading characters, path traversal, host paths
// outside the owner home, or non-absolute guest targets.
func validateFileSyncEntry(entry fileSyncEntryFile, home string) (model.FileSyncEntry, error) {
host := strings.TrimSpace(entry.Host)
guest := strings.TrimSpace(entry.Guest)
if host == "" {
@ -190,7 +203,7 @@ func validateFileSyncEntry(entry fileSyncEntryFile) (model.FileSyncEntry, error)
if guest == "" {
return model.FileSyncEntry{}, fmt.Errorf("guest path is required")
}
if err := validateFileSyncPath("host", host, true); err != nil {
if _, err := ResolveFileSyncHostPath(host, home); err != nil {
return model.FileSyncEntry{}, err
}
if err := validateFileSyncPath("guest", guest, true); err != nil {
@ -211,6 +224,57 @@ func validateFileSyncEntry(entry fileSyncEntryFile) (model.FileSyncEntry, error)
return model.FileSyncEntry{Host: host, Guest: guest, Mode: mode}, nil
}
// ResolveFileSyncHostPath expands a configured [[file_sync]].host path
// against the owner home and rejects anything that lands outside that
// home. Both config.Load and the root daemon use this so policy cannot
// drift between startup-time validation and runtime file reads.
func ResolveFileSyncHostPath(raw, home string) (string, error) {
raw = strings.TrimSpace(raw)
if err := validateFileSyncPath("host", raw, true); err != nil {
return "", err
}
home = strings.TrimSpace(home)
if home == "" {
return "", fmt.Errorf("host path %q: owner home is required", raw)
}
if !filepath.IsAbs(home) {
return "", fmt.Errorf("host path %q: owner home %q must be absolute", raw, home)
}
candidate := raw
if strings.HasPrefix(raw, "~/") {
candidate = filepath.Join(home, strings.TrimPrefix(raw, "~/"))
}
candidate = filepath.Clean(candidate)
if !filepath.IsAbs(candidate) {
return "", fmt.Errorf("host path %q: resolved path %q must be absolute", raw, candidate)
}
if err := ensurePathWithinRoot(candidate, home); err != nil {
return "", fmt.Errorf("host path %q: %w", raw, err)
}
return candidate, nil
}
// ResolveExistingFileSyncHostPath resolves a configured
// [[file_sync]].host path to its real on-disk target. This is the
// runtime companion to ResolveFileSyncHostPath: once os.Stat succeeds,
// the daemon uses this to ensure a top-level symlink still points
// inside the owner home before it reads from the path as root.
func ResolveExistingFileSyncHostPath(raw, home string) (string, error) {
candidate, err := ResolveFileSyncHostPath(raw, home)
if err != nil {
return "", err
}
resolved, err := filepath.EvalSymlinks(candidate)
if err != nil {
return "", fmt.Errorf("host path %q: resolve symlinks: %w", raw, err)
}
resolved = filepath.Clean(resolved)
if err := ensurePathWithinRoot(resolved, home); err != nil {
return "", fmt.Errorf("host path %q: resolved symlink target %q: %w", raw, resolved, err)
}
return resolved, nil
}
// validateFileSyncPath rejects relative paths (other than a leading
// "~/"), "..", empty segments, and "~user/..." forms banger doesn't
// expand. Absolute paths and home-anchored paths pass through — the
@ -240,6 +304,19 @@ func validateFileSyncPath(label, raw string, allowHome bool) error {
return nil
}
func ensurePathWithinRoot(candidate, root string) error {
root = filepath.Clean(strings.TrimSpace(root))
candidate = filepath.Clean(strings.TrimSpace(candidate))
rel, err := filepath.Rel(root, candidate)
if err != nil {
return fmt.Errorf("compare against owner home %q: %w", root, err)
}
if rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
return fmt.Errorf("must stay under owner home %q", root)
}
return nil
}
// validateFileSyncMode accepts three- or four-digit octal strings.
// Three-digit modes like "600" are auto-prefixed with a leading 0
// when parsed by the consumer.
@ -255,10 +332,10 @@ func validateFileSyncMode(mode string) error {
return nil
}
func resolveSSHKeyPath(layout paths.Layout, configured string) (string, error) {
func resolveSSHKeyPath(layout paths.Layout, configured, home string, ensureDefault bool) (string, error) {
configured = strings.TrimSpace(configured)
if configured != "" {
return normalizeSSHKeyPath(configured)
return normalizeSSHKeyPath(configured, home)
}
// Key lives under the state dir, not the config dir. The daemon's
// ensureVMSSHClientConfig scrubs ConfigDir/ssh on every Open as
@ -272,7 +349,11 @@ func resolveSSHKeyPath(layout paths.Layout, configured string) (string, error) {
if !filepath.IsAbs(sshDir) {
return "", fmt.Errorf("ssh key dir must be absolute; got %q (check paths.Resolve populated SSHDir / StateDir)", sshDir)
}
return ensureDefaultSSHKey(filepath.Join(sshDir, "id_ed25519"))
defaultPath := filepath.Join(sshDir, "id_ed25519")
if ensureDefault {
return ensureDefaultSSHKey(defaultPath)
}
return defaultPath, nil
}
// normalizeSSHKeyPath validates and canonicalises a user-configured
@ -289,7 +370,7 @@ func resolveSSHKeyPath(layout paths.Layout, configured string) (string, error) {
// ambiguous because the daemon's cwd isn't the user's shell cwd,
// and readers in internal/guest + internal/cli do raw os.ReadFile
// on the path without re-resolving against a known anchor
func normalizeSSHKeyPath(raw string) (string, error) {
func normalizeSSHKeyPath(raw, home string) (string, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", nil
@ -301,9 +382,9 @@ func normalizeSSHKeyPath(raw string) (string, error) {
return "", fmt.Errorf("ssh_key_path %q: only '~/' is expanded, not '~user/'", raw)
}
if strings.HasPrefix(raw, "~/") {
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("ssh_key_path %q: expand ~/: %w", raw, err)
home = strings.TrimSpace(home)
if home == "" {
return "", fmt.Errorf("ssh_key_path %q: no home directory available for ~ expansion", raw)
}
raw = filepath.Join(home, strings.TrimPrefix(raw, "~/"))
}

View file

@ -70,6 +70,25 @@ func TestLoadSSHKeyPathExpandsHomeAnchored(t *testing.T) {
}
}
func TestLoadDaemonDoesNotGenerateDefaultSSHKey(t *testing.T) {
ownerHome := t.TempDir()
sshDir := filepath.Join(t.TempDir(), "daemon-ssh")
cfg, err := LoadDaemon(paths.Layout{ConfigDir: t.TempDir(), SSHDir: sshDir}, ownerHome)
if err != nil {
t.Fatalf("LoadDaemon: %v", err)
}
wantKey := filepath.Join(sshDir, "id_ed25519")
if cfg.SSHKeyPath != wantKey {
t.Fatalf("SSHKeyPath = %q, want %q", cfg.SSHKeyPath, wantKey)
}
if cfg.HostHomeDir != ownerHome {
t.Fatalf("HostHomeDir = %q, want %q", cfg.HostHomeDir, ownerHome)
}
if _, err := os.Stat(wantKey); !os.IsNotExist(err) {
t.Fatalf("LoadDaemon created %s, want no key material on daemon config load", wantKey)
}
}
// TestLoadNormalizesAbsoluteSSHKeyPath pins filepath.Clean behaviour
// for configured paths: trailing slashes and duplicate slashes are
// flattened so downstream path comparisons don't see two spellings
@ -245,15 +264,19 @@ func TestLoadAppliesLogLevelEnvOverride(t *testing.T) {
}
func TestLoadAcceptsFileSyncEntries(t *testing.T) {
homeDir := t.TempDir()
t.Setenv("HOME", homeDir)
configDir := t.TempDir()
hostsFile := filepath.Join(homeDir, ".config", "gh", "hosts.yml")
data := []byte(`
[[file_sync]]
host = "~/.aws"
guest = "~/.aws"
[[file_sync]]
host = "/etc/resolv.conf"
guest = "/root/.config/resolv.conf"
host = "` + hostsFile + `"
guest = "/root/.config/gh/hosts.yml"
mode = "0644"
`)
if err := os.WriteFile(filepath.Join(configDir, "config.toml"), data, 0o644); err != nil {
@ -269,11 +292,42 @@ mode = "0644"
if cfg.FileSync[0].Host != "~/.aws" || cfg.FileSync[0].Guest != "~/.aws" {
t.Fatalf("entry[0] = %+v", cfg.FileSync[0])
}
if cfg.FileSync[1].Host != hostsFile || cfg.FileSync[1].Guest != "/root/.config/gh/hosts.yml" {
t.Fatalf("entry[1] = %+v", cfg.FileSync[1])
}
if cfg.FileSync[1].Mode != "0644" {
t.Fatalf("entry[1] mode = %q", cfg.FileSync[1].Mode)
}
}
func TestLoadDaemonAcceptsFileSyncPathUnderOwnerHome(t *testing.T) {
ownerHome := t.TempDir()
t.Setenv("HOME", t.TempDir())
configDir := t.TempDir()
allowed := filepath.Join(ownerHome, ".config", "gh", "hosts.yml")
data := []byte(`
[[file_sync]]
host = "` + allowed + `"
guest = "~/.config/gh/hosts.yml"
`)
if err := os.WriteFile(filepath.Join(configDir, "config.toml"), data, 0o644); err != nil {
t.Fatal(err)
}
cfg, err := LoadDaemon(paths.Layout{ConfigDir: configDir, SSHDir: t.TempDir()}, ownerHome)
if err != nil {
t.Fatalf("LoadDaemon: %v", err)
}
got, err := ResolveFileSyncHostPath(cfg.FileSync[0].Host, cfg.HostHomeDir)
if err != nil {
t.Fatalf("ResolveFileSyncHostPath: %v", err)
}
if got != allowed {
t.Fatalf("resolved host path = %q, want %q", got, allowed)
}
}
func TestLoadRejectsInvalidFileSyncEntries(t *testing.T) {
cases := []struct {
name string
@ -333,6 +387,51 @@ func TestLoadRejectsInvalidFileSyncEntries(t *testing.T) {
}
}
func TestLoadRejectsFileSyncHostOutsideHome(t *testing.T) {
homeDir := t.TempDir()
t.Setenv("HOME", homeDir)
configDir := t.TempDir()
data := []byte(`
[[file_sync]]
host = "/etc/resolv.conf"
guest = "~/resolv.conf"
`)
if err := os.WriteFile(filepath.Join(configDir, "config.toml"), data, 0o644); err != nil {
t.Fatal(err)
}
_, err := Load(paths.Layout{ConfigDir: configDir, SSHDir: t.TempDir()})
if err == nil {
t.Fatal("Load: want error for host path outside home")
}
if !strings.Contains(err.Error(), "owner home") {
t.Fatalf("Load error = %v, want owner-home diagnostic", err)
}
}
func TestLoadDaemonRejectsFileSyncHostOutsideOwnerHome(t *testing.T) {
ownerHome := t.TempDir()
t.Setenv("HOME", t.TempDir())
configDir := t.TempDir()
outside := filepath.Join(t.TempDir(), "secret.txt")
data := []byte(`
[[file_sync]]
host = "` + outside + `"
guest = "~/secret.txt"
`)
if err := os.WriteFile(filepath.Join(configDir, "config.toml"), data, 0o644); err != nil {
t.Fatal(err)
}
_, err := LoadDaemon(paths.Layout{ConfigDir: configDir, SSHDir: t.TempDir()}, ownerHome)
if err == nil {
t.Fatal("LoadDaemon: want error for host path outside owner home")
}
if !strings.Contains(err.Error(), "owner home") {
t.Fatalf("LoadDaemon error = %v, want owner-home diagnostic", err)
}
}
func TestLoadAcceptsVMDefaults(t *testing.T) {
configDir := t.TempDir()
data := []byte(`