Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Keep agent runtime fixtures out of service-owned state
pulse-triage[bot]a0a9d3b6b3c3
diff --git a/cmd/pulse-agent/main_test.go b/cmd/pulse-agent/main_test.goindex 7dc0380157..080c11dd00 100644--- a/cmd/pulse-agent/main_test.go+++ b/cmd/pulse-agent/main_test.go@@ -1434,7 +1434,7 @@ func TestRun(t *testing.T) {t.Run("self-test", func(t *testing.T) {ctx := context.Background()- err := run(ctx, []string{"-self-test"}, func(s string) string { return "" })+ err := run(ctx, []string{"-state-dir", t.TempDir(), "-self-test"}, func(s string) string { return "" })if err != nil {t.Fatal(err)}@@ -1442,7 +1442,7 @@ func TestRun(t *testing.T) {t.Run("invalid config", func(t *testing.T) {ctx := context.Background()- err := run(ctx, []string{"-interval", "invalid"}, func(s string) string { return "" })+ err := run(ctx, []string{"-state-dir", t.TempDir(), "-interval", "invalid"}, func(s string) string { return "" })if err == nil {t.Fatal("expected error for invalid config")}@@ -1450,7 +1450,7 @@ func TestRun(t *testing.T) {t.Run("version exits cleanly", func(t *testing.T) {ctx := context.Background()- err := run(ctx, []string{"-version"}, func(s string) string { return "" })+ err := run(ctx, []string{"-state-dir", t.TempDir(), "-version"}, func(s string) string { return "" })if err != flag.ErrHelp {t.Fatalf("expected flag.ErrHelp for -version, got %v", err)}@@ -1465,7 +1465,7 @@ func TestRun(t *testing.T) {}()// Use minimal config, no agents- err := run(ctx, []string{"-token", "T", "-enable-host=false", "-enable-docker=false", "-enable-kubernetes=false", "-health-addr", "127.0.0.1:0"}, func(s string) string { return "" })+ err := run(ctx, []string{"-state-dir", t.TempDir(), "-token", "T", "-enable-host=false", "-enable-docker=false", "-enable-kubernetes=false", "-health-addr", "127.0.0.1:0"}, func(s string) string { return "" })if err != nil && err != context.Canceled {t.Errorf("expected nil or context.Canceled, got %v", err)}@@ -1492,7 +1492,7 @@ func TestRun(t *testing.T) {}()// Enable everything, but they will fail to init and log warnings, which is fine for coverage of run's branches- err := run(ctx, []string{"-token", "T", "-enable-host", "-enable-docker", "-enable-kubernetes", "-health-addr", "127.0.0.1:0"}, func(s string) string { return "" })+ err := run(ctx, []string{"-state-dir", t.TempDir(), "-token", "T", "-enable-host", "-enable-docker", "-enable-kubernetes", "-health-addr", "127.0.0.1:0"}, func(s string) string { return "" })if err != nil && err != context.Canceled && !strings.Contains(err.Error(), "disabled for test") {t.Errorf("expected nil or context.Canceled or disabled for test, got %v", err)}@@ -1510,7 +1510,7 @@ func TestRun(t *testing.T) {ctx, cancel := context.WithCancel(context.Background())cancel()- _ = run(ctx, []string{"-token", "T", "-enable-host=false"}, func(s string) string { return "" })+ _ = run(ctx, []string{"-state-dir", t.TempDir(), "-token", "T", "-enable-host=false"}, func(s string) string { return "" })})t.Run("auto-detect podman", func(t *testing.T) {@@ -1525,7 +1525,7 @@ func TestRun(t *testing.T) {ctx, cancel := context.WithCancel(context.Background())cancel()- _ = run(ctx, []string{"-token", "T", "-enable-host=false"}, func(s string) string { return "" })+ _ = run(ctx, []string{"-state-dir", t.TempDir(), "-token", "T", "-enable-host=false"}, func(s string) string { return "" })})t.Run("goroutine error", func(t *testing.T) {@@ -1566,7 +1566,7 @@ func TestDockerAutoDetectHonorsExplicitDisable(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)defer cancel()- err := run(ctx, []string{"-enable-host=false", "-enable-docker=false", "-enable-kubernetes=false", "-health-addr", ""}, func(s string) string { return "" })+ err := run(ctx, []string{"-state-dir", t.TempDir(), "-enable-host=false", "-enable-docker=false", "-enable-kubernetes=false", "-health-addr", ""}, func(s string) string { return "" })if err != nil && err != context.Canceled && err != context.DeadlineExceeded {t.Fatalf("run returned unexpected error: %v", err)}@@ -1681,10 +1681,12 @@ func TestRun_Success(t *testing.T) {defer cancel()// Run in a separate goroutine so we can wait for it+ stateDir := t.TempDir()errCh := make(chan error)go func() {// Enable all agentserrCh <- run(ctx, []string{+ "-state-dir", stateDir,"-token", "T","-enable-host=true","-enable-docker=true",@@ -1730,6 +1732,7 @@ func TestRun_PassesStateDirToUpdaterAndHostAgent(t *testing.T) {return &mockRunnable{}, nil}+ stateDir := filepath.Join(t.TempDir(), "share", "CACHEDEV1_DATA", ".pulse-agent")ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)defer cancel()@@ -1737,17 +1740,17 @@ func TestRun_PassesStateDirToUpdaterAndHostAgent(t *testing.T) {"-token", "deadbeef","-enable-docker=false","-enable-kubernetes=false",- "-state-dir", "/share/CACHEDEV1_DATA/.pulse-agent",+ "-state-dir", stateDir,}, func(string) string { return "" })if err != nil && err != context.Canceled && err != context.DeadlineExceeded {t.Fatalf("run returned error: %v", err)}- if updaterCfg.StateDir != "/share/CACHEDEV1_DATA/.pulse-agent" {- t.Fatalf("updater state dir = %q, want %q", updaterCfg.StateDir, "/share/CACHEDEV1_DATA/.pulse-agent")+ if updaterCfg.StateDir != stateDir {+ t.Fatalf("updater state dir = %q, want %q", updaterCfg.StateDir, stateDir)}- if hostCfg.StateDir != "/share/CACHEDEV1_DATA/.pulse-agent" {- t.Fatalf("host agent state dir = %q, want %q", hostCfg.StateDir, "/share/CACHEDEV1_DATA/.pulse-agent")+ if hostCfg.StateDir != stateDir {+ t.Fatalf("host agent state dir = %q, want %q", hostCfg.StateDir, stateDir)}}@@ -2383,7 +2386,7 @@ func TestRun_AgentFailure(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)defer cancel()- err := run(ctx, []string{"-token", "T", "-enable-docker=true", "-enable-host=false"}, func(s string) string { return "" })+ err := run(ctx, []string{"-state-dir", t.TempDir(), "-token", "T", "-enable-docker=true", "-enable-host=false"}, func(s string) string { return "" })if err == nil {t.Fatal("expected error, got nil")}@@ -2418,6 +2421,7 @@ func TestRun_PropagatesDisableCephToHostAgent(t *testing.T) {defer cancel()err := run(ctx, []string{+ "-state-dir", t.TempDir(),"-token", "T","-enable-host=true","-enable-docker=false",@@ -2726,7 +2730,7 @@ func TestRun_WindowsServiceError(t *testing.T) {}ctx := context.Background()- err := run(ctx, []string{"-token", "T"}, func(s string) string { return "" })+ err := run(ctx, []string{"-state-dir", t.TempDir(), "-token", "T"}, func(s string) string { return "" })if err == nil {t.Fatal("expected error, got nil")}@@ -2761,9 +2765,10 @@ func TestRun_DockerRetry(t *testing.T) {server := httptest.NewServer(http.NotFoundHandler())defer server.Close()+ stateDir := t.TempDir()errCh := make(chan error)go func() {- errCh <- run(ctx, []string{"-token", "T", "-url", server.URL, "-enable-docker=true", "-enable-host=false"}, func(s string) string { return "" })+ errCh <- run(ctx, []string{"-state-dir", stateDir, "-token", "T", "-url", server.URL, "-enable-docker=true", "-enable-host=false"}, func(s string) string { return "" })}()select {@@ -2865,10 +2870,11 @@ func TestRun_KubeRetry(t *testing.T) {server := httptest.NewServer(http.NotFoundHandler())defer server.Close()+ stateDir := t.TempDir()errCh := make(chan error)go func() {// Only enable kubernetes- errCh <- run(ctx, []string{"-token", "T", "-url", server.URL, "-enable-kubernetes=true", "-enable-host=false", "-enable-docker=false"}, func(s string) string { return "" })+ errCh <- run(ctx, []string{"-state-dir", stateDir, "-token", "T", "-url", server.URL, "-enable-kubernetes=true", "-enable-host=false", "-enable-docker=false"}, func(s string) string { return "" })}()select {diff --git a/cmd/pulse-agent/run_fixture_state_test.go b/cmd/pulse-agent/run_fixture_state_test.gonew file mode 100644index 0000000000..020f7b88f0--- /dev/null+++ b/cmd/pulse-agent/run_fixture_state_test.go@@ -0,0 +1,176 @@+package main++import (+ "go/ast"+ "go/parser"+ "go/token"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "testing"+)++// Startup secures (and can create) the service's real state directory even+// with mocked modules or a cancelled context. Runtime unit fixtures must own+// their state; otherwise native Windows tests pre-seed ProgramData\Pulse and+// correctly fail the later clean-runner service-lifecycle admission.+func unsafeAgentRunFixtures(source []byte) ([]int, error) {+ fset := token.NewFileSet()+ file, err := parser.ParseFile(fset, "fixture_test.go", source, 0)+ if err != nil {+ return nil, err+ }+ var unsafe []int+ for _, decl := range file.Decls {+ fn, ok := decl.(*ast.FuncDecl)+ if !ok || fn.Body == nil {+ continue+ }+ // An identifier is owned only when all its assignments derive from a+ // test temporary directory. Reject fixed paths and unknown provenance.+ values := make(map[string][]ast.Expr)+ ast.Inspect(fn.Body, func(node ast.Node) bool {+ if assign, ok := node.(*ast.AssignStmt); ok && len(assign.Lhs) == len(assign.Rhs) {+ for i, lhs := range assign.Lhs {+ if id, ok := lhs.(*ast.Ident); ok {+ values[id.Name] = append(values[id.Name], assign.Rhs[i])+ }+ }+ }+ return true+ })+ var temporary func(ast.Expr, map[string]bool) bool+ temporary = func(expr ast.Expr, visiting map[string]bool) bool {+ switch expr := expr.(type) {+ case *ast.CallExpr:+ if selector, ok := expr.Fun.(*ast.SelectorExpr); ok {+ if receiver, ok := selector.X.(*ast.Ident); ok {+ if receiver.Name == "t" && selector.Sel.Name == "TempDir" && len(expr.Args) == 0 {+ return true+ }+ if receiver.Name == "filepath" && selector.Sel.Name == "Join" && len(expr.Args) > 0 {+ for _, suffix := range expr.Args[1:] {+ text, ok := suffix.(*ast.BasicLit)+ if !ok || text.Kind != token.STRING {+ return false+ }+ path, err := strconv.Unquote(text.Value)+ if err != nil || strings.ContainsAny(path, `/\:`) || path == ".." {+ return false+ }+ }+ return temporary(expr.Args[0], visiting)+ }+ }+ }+ case *ast.Ident:+ if visiting[expr.Name] || len(values[expr.Name]) == 0 {+ return false+ }+ visiting[expr.Name] = true+ defer delete(visiting, expr.Name)+ for _, value := range values[expr.Name] {+ if !temporary(value, visiting) {+ return false+ }+ }+ return true+ }+ return false+ }+ ast.Inspect(fn.Body, func(node ast.Node) bool {+ call, ok := node.(*ast.CallExpr)+ if !ok {+ return true+ }+ name, ok := call.Fun.(*ast.Ident)+ if !ok || name.Name != "run" {+ return true+ }+ owned := false+ stateFlags := 0+ if len(call.Args) == 3 {+ if args, ok := call.Args[1].(*ast.CompositeLit); ok {+ for i, arg := range args.Elts {+ if text, ok := arg.(*ast.BasicLit); ok && text.Kind == token.STRING {+ flag, _ := strconv.Unquote(text.Value)+ if flag == "-state-dir" || flag == "--state-dir" {+ stateFlags+++ owned = i+1 < len(args.Elts) && temporary(args.Elts[i+1], make(map[string]bool))+ }+ }+ }+ }+ }+ if !owned || stateFlags != 1 {+ unsafe = append(unsafe, fset.Position(call.Pos()).Line)+ }+ return true+ })+ }+ return unsafe, nil+}++func TestAgentRunFixturesOwnTheirState(t *testing.T) {+ files, err := filepath.Glob("*_test.go")+ if err != nil || len(files) == 0 {+ t.Fatalf("discover agent test fixtures: %v", err)+ }+ for _, file := range files {+ source, err := os.ReadFile(file)+ if err != nil {+ t.Fatal(err)+ }+ unsafe, err := unsafeAgentRunFixtures(source)+ if err != nil {+ t.Fatalf("parse %s: %v", file, err)+ }+ if len(unsafe) != 0 {+ t.Errorf("%s run fixtures need explicit temporary state at lines %v", file, unsafe)+ }+ }+}++func TestAgentRunFixtureStateGuard(t *testing.T) {+ for _, tc := range []struct {+ name, setup, args string+ owned bool+ }{+ {"default", "", `"-token", "fixture"`, false},+ {"empty", "", `"-state-dir", ""`, false},+ {"service path", "", `"-state-dir", "/var/lib/pulse-agent"`, false},+ {"fixed variable", `stateDir := "/service-state"`, `"-state-dir", stateDir`, false},+ {"unknown variable", "", `"-state-dir", stateDir`, false},+ {"reassigned", `stateDir := t.TempDir(); stateDir = "/service-state"`, `"-state-dir", stateDir`, false},+ {"duplicate flag", "", `"-state-dir", t.TempDir(), "-state-dir", t.TempDir()`, false},+ {"parent traversal", "", `"-state-dir", filepath.Join(t.TempDir(), "..", "service-state")`, false},+ {"absolute suffix", "", `"-state-dir", filepath.Join(t.TempDir(), "/service-state")`, false},+ {"temporary", "", `"-state-dir", t.TempDir()`, true},+ {"long flag", "", `"--state-dir", t.TempDir()`, true},+ {"temporary variable", `stateDir := t.TempDir()`, `"-state-dir", stateDir`, true},+ {"custom temporary path", `root := t.TempDir(); stateDir := filepath.Join(root, "share", ".pulse-agent")`, `"-state-dir", stateDir`, true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ source := "package main\nfunc fixture() { " + tc.setup + "; run(ctx, []string{" + tc.args + "}, getenv) }"+ unsafe, err := unsafeAgentRunFixtures([]byte(source))+ if err != nil {+ t.Fatal(err)+ }+ if (len(unsafe) == 0) != tc.owned {+ t.Fatalf("unsafe lines = %v, owned = %v", unsafe, tc.owned)+ }+ })+ }+ if path := os.Getenv("PULSE_AGENT_RUN_FIXTURE_PARENT"); path != "" {+ source, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ unsafe, err := unsafeAgentRunFixtures(source)+ if err != nil || len(unsafe) != 15 {+ t.Fatalf("original parent: unsafe run lines = %v, error = %v; want 14 default paths and one fixed NAS path", unsafe, err)+ }+ t.Logf("original parent rejected at all 15 unowned run calls: %v", unsafe)+ }+}