banger/internal/cli/daemon_lifecycle_test.go
Thales Maciel cec7291184
Survive banger update with running VMs
Two coupled fixes that together make the daemon-restart path of
`banger update` non-destructive for running guests:

1. Unit templates set `KillMode=process` on bangerd.service and
   bangerd-root.service. The default control-group behaviour sent
   SIGKILL to every process in the cgroup on stop/restart — including
   jailer-spawned firecracker children, since fork/exec doesn't
   escape a systemd cgroup. With process mode only the unit's main
   PID is signalled; FC children stay alive in the (unowned)
   cgroup until the new helper instance starts up and re-claims them.

2. `fcproc.FindPID` falls back to the jailer-written pidfile at
   `<chroot>/firecracker.pid` (sibling of the api-sock target) when
   `pgrep -n -f <api-sock>` doesn't find a match. pgrep can't see
   jailer'd FCs because their cmdline only carries the chroot-relative
   `--api-sock /firecracker.socket`, not the host-side path. The
   pidfile is jailer's actual record of the post-exec FC PID, so
   reconcile can verify the surviving process is the right one
   (comm == "firecracker") and re-seed handles.json without tearing
   down the VM's dm-snapshot.

Verified live on the dev host: started a VM, restarted the helper
unit, restarted the daemon unit, and confirmed the FC PID was
unchanged, vm list still showed the guest as running, and
`banger vm ssh` returned the same boot_id pre and post restart.
The systemd journal now reports "firecracker remains running after
unit stopped" and "Found left-over process X (firecracker) in
control group while starting unit. Ignoring." — exactly the shape
`KillMode=process` is supposed to produce.

Tests cover both the parser (parseVersionOutput from the v0.1.2
fix) and the new pidfile lookup: happy path, missing pidfile,
stale pid, wrong comm, garbage content, non-symlink api-sock,
whitespace tolerance.

CHANGELOG corrects v0.1.0's misleading "daemon restarts do not
interrupt running guests" line and documents the unit-refresh
caveat: existing v0.1.0–v0.1.3 installs need a one-time
`sudo banger system install` after updating to v0.1.4 to pick up
the new KillMode directive (`banger update` swaps binaries, not
unit files).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 17:09:15 -03:00

217 lines
6.3 KiB
Go

package cli
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"banger/internal/api"
"banger/internal/installmeta"
)
func TestEnsureDaemonRequiresSystemInstallWhenMetadataMissing(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", filepath.Join(t.TempDir(), "config"))
t.Setenv("XDG_STATE_HOME", filepath.Join(t.TempDir(), "state"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(t.TempDir(), "cache"))
t.Setenv("XDG_RUNTIME_DIR", filepath.Join(t.TempDir(), "run"))
restoreLoad := loadInstallMetadata
restoreUID := currentUID
t.Cleanup(func() {
loadInstallMetadata = restoreLoad
currentUID = restoreUID
})
loadInstallMetadata = func() (installmeta.Metadata, error) {
return installmeta.Metadata{}, os.ErrNotExist
}
currentUID = os.Getuid
d := defaultDeps()
d.daemonPing = func(context.Context, string) (api.PingResult, error) {
return api.PingResult{}, errors.New("dial unix /run/banger/bangerd.sock: no such file")
}
_, _, err := d.ensureDaemon(context.Background())
if err == nil || !strings.Contains(err.Error(), "sudo banger system install") {
t.Fatalf("ensureDaemon error = %v, want install guidance", err)
}
}
func TestEnsureDaemonSuggestsRestartWhenInstalledButUnavailable(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", filepath.Join(t.TempDir(), "config"))
t.Setenv("XDG_STATE_HOME", filepath.Join(t.TempDir(), "state"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(t.TempDir(), "cache"))
t.Setenv("XDG_RUNTIME_DIR", filepath.Join(t.TempDir(), "run"))
restoreLoad := loadInstallMetadata
restoreUID := currentUID
t.Cleanup(func() {
loadInstallMetadata = restoreLoad
currentUID = restoreUID
})
loadInstallMetadata = func() (installmeta.Metadata, error) {
return installmeta.Metadata{
OwnerUser: "tester",
OwnerUID: os.Getuid(),
OwnerGID: os.Getgid(),
OwnerHome: t.TempDir(),
}, nil
}
currentUID = os.Getuid
d := defaultDeps()
d.daemonPing = func(context.Context, string) (api.PingResult, error) {
return api.PingResult{}, errors.New("dial unix /run/banger/bangerd.sock: connection refused")
}
_, _, err := d.ensureDaemon(context.Background())
if err == nil || !strings.Contains(err.Error(), "sudo banger system restart") {
t.Fatalf("ensureDaemon error = %v, want restart guidance", err)
}
}
func TestEnsureDaemonRejectsNonOwnerUser(t *testing.T) {
restoreLoad := loadInstallMetadata
restoreUID := currentUID
t.Cleanup(func() {
loadInstallMetadata = restoreLoad
currentUID = restoreUID
})
loadInstallMetadata = func() (installmeta.Metadata, error) {
return installmeta.Metadata{
OwnerUser: "alice",
OwnerUID: os.Getuid() + 1,
OwnerGID: os.Getgid(),
OwnerHome: t.TempDir(),
}, nil
}
currentUID = os.Getuid
d := defaultDeps()
d.daemonPing = func(context.Context, string) (api.PingResult, error) {
t.Fatal("daemonPing should not be called for a non-owner user")
return api.PingResult{}, nil
}
_, _, err := d.ensureDaemon(context.Background())
if err == nil || !strings.Contains(err.Error(), "installed for alice") {
t.Fatalf("ensureDaemon error = %v, want owner mismatch guidance", err)
}
}
func TestSystemSubcommandFlagsAreScoped(t *testing.T) {
root := NewBangerCommand()
systemCmd, _, err := root.Find([]string{"system"})
if err != nil {
t.Fatalf("find system: %v", err)
}
installCmd, _, err := systemCmd.Find([]string{"install"})
if err != nil {
t.Fatalf("find system install: %v", err)
}
uninstallCmd, _, err := systemCmd.Find([]string{"uninstall"})
if err != nil {
t.Fatalf("find system uninstall: %v", err)
}
if installCmd.Flags().Lookup("owner") == nil {
t.Fatal("system install is missing --owner")
}
if uninstallCmd.Flags().Lookup("purge") == nil {
t.Fatal("system uninstall is missing --purge")
}
}
func TestRenderSystemdUnitIncludesHardeningDirectives(t *testing.T) {
unit := renderSystemdUnit(installmeta.Metadata{
OwnerUser: "alice",
OwnerUID: 1000,
OwnerGID: 1000,
OwnerHome: "/home/alice/dev home",
})
for _, want := range []string{
"ExecStart=/usr/local/bin/bangerd --system",
"User=alice",
"Wants=network-online.target bangerd-root.service",
"After=bangerd-root.service",
"Requires=bangerd-root.service",
"KillMode=process",
"UMask=0077",
"Environment=TMPDIR=/run/banger",
"NoNewPrivileges=yes",
"PrivateMounts=yes",
"ProtectSystem=strict",
"ProtectHome=read-only",
"ProtectControlGroups=yes",
"ProtectKernelLogs=yes",
"ProtectKernelModules=yes",
"ProtectClock=yes",
"ProtectHostname=yes",
"RestrictSUIDSGID=yes",
"LockPersonality=yes",
"SystemCallArchitectures=native",
"RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK AF_VSOCK",
"StateDirectory=banger",
"StateDirectoryMode=0700",
"CacheDirectory=banger",
"CacheDirectoryMode=0700",
"RuntimeDirectory=banger",
"RuntimeDirectoryMode=0700",
`ReadOnlyPaths="/home/alice/dev home"`,
} {
if !strings.Contains(unit, want) {
t.Fatalf("unit = %q, want %q", unit, want)
}
}
}
func TestRenderRootHelperSystemdUnitIncludesRequiredCapabilities(t *testing.T) {
unit := renderRootHelperSystemdUnit()
for _, want := range []string{
"ExecStart=/usr/local/bin/bangerd --root-helper",
"KillMode=process",
"Environment=TMPDIR=/run/banger-root",
"NoNewPrivileges=yes",
"PrivateTmp=yes",
"PrivateMounts=yes",
"ProtectSystem=strict",
"ProtectHome=yes",
"RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK AF_VSOCK",
"CapabilityBoundingSet=CAP_CHOWN CAP_DAC_OVERRIDE CAP_FOWNER CAP_KILL CAP_MKNOD CAP_NET_ADMIN CAP_NET_RAW CAP_SETGID CAP_SETUID CAP_SYS_ADMIN CAP_SYS_CHROOT",
"ReadWritePaths=/var/lib/banger",
"RuntimeDirectory=banger-root",
"RuntimeDirectoryMode=0711",
} {
if !strings.Contains(unit, want) {
t.Fatalf("unit = %q, want %q", unit, want)
}
}
}
func TestRenderSystemdUnitsIncludeOptionalCoverageEnv(t *testing.T) {
t.Setenv(systemCoverDirEnv, "/var/lib/banger")
t.Setenv(rootCoverDirEnv, "/var/lib/banger")
userUnit := renderSystemdUnit(installmeta.Metadata{
OwnerUser: "alice",
OwnerUID: 1000,
OwnerGID: 1000,
OwnerHome: "/home/alice",
})
if !strings.Contains(userUnit, `Environment=GOCOVERDIR="/var/lib/banger"`) {
t.Fatalf("user unit = %q, want GOCOVERDIR env", userUnit)
}
rootUnit := renderRootHelperSystemdUnit()
if !strings.Contains(rootUnit, `Environment=GOCOVERDIR="/var/lib/banger"`) {
t.Fatalf("root unit = %q, want GOCOVERDIR env", rootUnit)
}
}