Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Contain typed action subprocesses with systemd

rcourtmanf9ae289bd509
diff --git a/cmd/pulse-agent-runner/main.go b/cmd/pulse-agent-runner/main.go
index e3ed691997..44cf0f49b0 100644
--- a/cmd/pulse-agent-runner/main.go
+++ b/cmd/pulse-agent-runner/main.go
@@ -106,6 +106,12 @@ func run() error {
if err != nil {
return err
}
+ reconcileCtx, reconcileCancel := context.WithTimeout(context.Background(), 30*time.Second)
+ err = actionrunner.ReconcileTypedActionUnits(reconcileCtx)
+ reconcileCancel()
+ if err != nil {
+ return fmt.Errorf("reconcile typed action containment: %w", err)
+ }
token, err := readPrivateValue(config.TokenFile, "runner token")
if err != nil {
return err
@@ -264,6 +270,9 @@ func readPrivateValue(path, label string) (string, error) {
}
func main() {
+ if len(os.Args) > 1 && os.Args[1] == "__pulse_typed_action_launcher" {
+ os.Exit(actionrunner.RunTypedActionLauncher(os.Args[2:]))
+ }
var err error
if len(os.Args) > 1 && (os.Args[1] == "cancel-pending-credential" || os.Args[1] == "revoke-credential") {
err = runCredentialLifecycleCommand(os.Args[1], os.Args[2:])
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 280f9e19b7..66e384b1ef 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -1288,6 +1288,25 @@ so Pulse must re-plan against the widened or changed set. A reboot-required
marker is reported as state, never acted upon by this capability. Generic
agent command execution, Patrol prose, lifecycle UI, and external agents must
not reconstruct or bypass this typed operation.
+Every fixed-catalog package and Proxmox guest invocation runs inside a
+cryptographically named transient systemd service. PID 1 starts a hidden
+runner launcher that revalidates the closed tool/argument/environment catalog,
+mirrors the runner sandbox, caps output, and records direct-process and cgroup
+inspection state through a root-private atomic sideband. `KillMode=control-group`
+and bounded TERM-to-KILL escalation own cancellation; disappearance of the
+exact transient unit, never a PID/PGID observation or pipe close, is the sole
+authority to release the shared typed-action gate and package-manager lease.
+The runner reconciles stale private units and executes a harmless containment
+probe before registering. Missing systemd features, manager-query ambiguity,
+launcher inspection failure, or a direct process exiting with descendants is
+indeterminate and fail-closed; failed adopted workers remain indeterminate even
+after they exit. Package interruption sets recovery-required,
+and indeterminate Proxmox dispatch requires target-state recovery inspection.
+The package unit alone permits setuid/setgid file creation and kernel-package
+payload writes because apt/dpkg legitimately require them; every other runner
+hardening property and the exact package command catalog remain enforced.
+Docker/Podman lifecycle remains on the already-connected daemon API operator;
+the action runner does not fall back to a killable external runtime CLI.
Host storage-pressure cleanup is a second closed agent operation. The report
may expose only the bounded `apt-package-cache` provider, its reclaimable byte
count, freshness, and a SHA-256 fingerprint; cache entry names and paths remain
diff --git a/internal/actionrunner/transport.go b/internal/actionrunner/transport.go
index 281d66c973..6ab0d1ae6c 100644
--- a/internal/actionrunner/transport.go
+++ b/internal/actionrunner/transport.go
@@ -23,6 +23,14 @@ func RevokeCredential(ctx context.Context, config CredentialLifecycleConfig, hos
return hostagent.RevokeActionRunnerCredential(ctx, config, hostID, hostname)
}
+func RunTypedActionLauncher(args []string) int {
+ return hostagent.RunTypedActionLauncher(args)
+}
+
+func ReconcileTypedActionUnits(ctx context.Context) error {
+ return hostagent.ReconcileTypedActionUnits(ctx)
+}
+
// Client is the action-runner-owned facade over the existing typed action
// codecs and executors. The hostagent implementation remains an internal
// compatibility detail while the collector continues its legacy migration.
diff --git a/internal/hostagent/action_runner_client.go b/internal/hostagent/action_runner_client.go
index e1c459ee52..520d1ea177 100644
--- a/internal/hostagent/action_runner_client.go
+++ b/internal/hostagent/action_runner_client.go
@@ -188,6 +188,12 @@ func NewActionRunnerClient(config ActionRunnerClientConfig, agentID, hostname, v
client.actionRunnerOnly = true
client.runtimeRole = agentexec.RuntimeRoleActionRunner
client.actionCapability = agentexec.ActionCapabilityTypedV1
+ if config.DockerContainerLifecycleOperator == nil {
+ // The privileged runner never falls back to a Docker/Podman CLI. A
+ // daemon may already have accepted a mutation after its CLI exits, so
+ // process containment cannot establish the operation's terminal state.
+ client.dockerLifecycle = nil
+ }
client.healthPath = strings.TrimSpace(config.HealthPath)
client.actionActivationNonce = strings.TrimSpace(config.ActivationNonce)
client.healthCapabilities = []string{
diff --git a/internal/hostagent/action_runner_client_test.go b/internal/hostagent/action_runner_client_test.go
index 3fa9fe4c30..d45e4946f4 100644
--- a/internal/hostagent/action_runner_client_test.go
+++ b/internal/hostagent/action_runner_client_test.go
@@ -49,6 +49,14 @@ func TestNewActionRunnerClientIsTypedOnlyAndEmitsExplicitRole(t *testing.T) {
}
}
+func TestActionRunnerWithoutConnectedContainerOperatorHasNoCLIFallback(t *testing.T) {
+ client := NewActionRunnerClient(ActionRunnerClientConfig{StateDir: t.TempDir()}, "host-1", "node-1", "test")
+ t.Cleanup(func() { _ = client.Close() })
+ if client.dockerLifecycle != nil {
+ t.Fatal("action runner exposed a Docker/Podman CLI fallback without a connected daemon operator")
+ }
+}
+
func TestActionRunnerTransportRequiresTLSExceptLoopback(t *testing.T) {
logger := zerolog.Nop()
for _, test := range []struct {
diff --git a/internal/hostagent/package_updates.go b/internal/hostagent/package_updates.go
index cc1a91a256..5901ba9d74 100644
--- a/internal/hostagent/package_updates.go
+++ b/internal/hostagent/package_updates.go
@@ -5,7 +5,6 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
- "errors"
"os"
"os/exec"
"sort"
@@ -22,9 +21,8 @@ const (
)
var (
- packageUpdateCommandContext = exec.CommandContext
- packageUpdateLookPath = exec.LookPath
- packageUpdateStat = os.Stat
+ packageUpdateLookPath = exec.LookPath
+ packageUpdateStat = os.Stat
)
// packageUpdateManager owns both host package telemetry and the only command
@@ -288,26 +286,10 @@ type packageUpdateCommandResult struct {
}
func runPackageUpdateCommand(ctx context.Context, env []string, name string, args ...string) packageUpdateCommandResult {
- cmd := packageUpdateCommandContext(ctx, name, args...)
- if len(env) > 0 {
- cmd.Env = append(os.Environ(), env...)
- }
- stdout := newCappedBuffer(maxCommandOutputSize)
- stderr := newCappedBuffer(maxCommandOutputSize)
- cmd.Stdout = stdout
- cmd.Stderr = stderr
- err := cmd.Run()
- result := packageUpdateCommandResult{stdout: stdout.String(), stderr: stderr.String(), err: err}
- if err == nil {
- return result
- }
- var exitErr *exec.ExitError
- if errors.As(err, &exitErr) {
- result.exitCode = exitErr.ExitCode()
- } else {
- result.exitCode = -1
+ result := runTypedActionCommand(ctx, env, typedActionCatalogPackage, name, args...)
+ return packageUpdateCommandResult{
+ stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode, err: result.err,
}
- return result
}
func parseAPTSimulatedUpgrades(output string) []agentexec.HostPackageUpdate {
diff --git a/internal/hostagent/proxmox_guest_lifecycle.go b/internal/hostagent/proxmox_guest_lifecycle.go
index df8f397773..edf5bacf34 100644
--- a/internal/hostagent/proxmox_guest_lifecycle.go
+++ b/internal/hostagent/proxmox_guest_lifecycle.go
@@ -3,8 +3,8 @@ package hostagent
import (
"context"
"encoding/json"
+ "errors"
"fmt"
- "os/exec"
"strconv"
"strings"
"time"
@@ -24,7 +24,8 @@ type proxmoxGuestLifecycleManager struct {
func newProxmoxGuestLifecycleManager() *proxmoxGuestLifecycleManager {
return &proxmoxGuestLifecycleManager{
run: func(ctx context.Context, name string, args ...string) ([]byte, error) {
- return exec.CommandContext(ctx, name, args...).CombinedOutput()
+ result := runTypedActionCommand(ctx, nil, typedActionCatalogProxmox, name, args...)
+ return []byte(result.stdout), result.err
},
now: time.Now,
}
@@ -59,7 +60,11 @@ func (m *proxmoxGuestLifecycleManager) Apply(ctx context.Context, req agentexec.
}
// This is the entire mutation catalog: fixed tool, fixed verb, decimal VMID.
if _, err := m.run(ctx, tool, req.Operation, strconv.Itoa(req.VMID)); err != nil {
- result.Error = "Proxmox guest lifecycle mutation did not complete"
+ if ctx.Err() != nil || errors.Is(err, errTypedActionContainmentIndeterminate) {
+ result.Error = "Proxmox guest lifecycle mutation was interrupted after dispatch; target state requires recovery inspection"
+ } else {
+ result.Error = "Proxmox guest lifecycle mutation did not complete"
+ }
return result
}
result.MutationCompleted, result.ExecutionPhase = true, agentexec.ProxmoxGuestPhaseVerify
diff --git a/internal/hostagent/typed_action_command.go b/internal/hostagent/typed_action_command.go
new file mode 100644
index 0000000000..121b8b8acc
--- /dev/null
+++ b/internal/hostagent/typed_action_command.go
@@ -0,0 +1,90 @@
+package hostagent
+
+import (
+ "context"
+ "errors"
+ "fmt"
+)
+
+type typedActionCatalog string
+
+const (
+ typedActionCatalogPackage typedActionCatalog = "package"
+ typedActionCatalogProxmox typedActionCatalog = "proxmox"
+ typedActionCatalogProbe typedActionCatalog = "probe"
+)
+
+const (
+ typedActionLauncherCommand = "__pulse_typed_action_launcher"
+ typedActionLauncherDescendantExit = 200
+ typedActionLauncherInspectionFailureExit = 201
+ typedActionLauncherStartFailureExit = 202
+ typedActionLauncherSupervisorFailureExit = 203
+)
+
+var (
+ errTypedActionContainmentUnavailable = errors.New("typed action systemd containment unavailable")
+ errTypedActionContainmentIndeterminate = errors.New("typed action containment is indeterminate")
+)
+
+type typedActionCommandResult struct {
+ stdout string
+ stderr string
+ exitCode int
+ err error
+}
+
+// runTypedActionCommand is the single subprocess boundary for fixed-catalog
+// privileged actions. Linux runs the closed invocation inside a transient
+// systemd service and does not return until PID 1 has collected that unit.
+func runTypedActionCommand(ctx context.Context, env []string, catalog typedActionCatalog, name string, args ...string) typedActionCommandResult {
+ if err := validateTypedActionInvocation(catalog, name, args); err != nil {
+ return typedActionCommandResult{exitCode: -1, err: err}
+ }
+ return runTypedActionCommandPlatform(ctx, env, catalog, name, args...)
+}
+
+func validateTypedActionInvocation(catalog typedActionCatalog, name string, args []string) error {
+ switch catalog {
+ case typedActionCatalogPackage:
+ if name == "dpkg" && len(args) == 1 && args[0] == "--audit" {
+ return nil
+ }
+ if name == "apt-get" {
+ switch fmt.Sprint(args) {
+ case "[-s -o Debug::NoLocking=1 upgrade]", "[update]", "[-y --no-remove -o Dpkg::Options::=--force-confold upgrade]", "[clean]":
+ return nil
+ }
+ }
+ case typedActionCatalogProxmox:
+ if (name == "qm" || name == "pct") && len(args) == 2 && isProxmoxLifecycleVerb(args[0]) && isPositiveDecimalID(args[1]) {
+ return nil
+ }
+ case typedActionCatalogProbe:
+ if name == "true" && len(args) == 0 {
+ return nil
+ }
+ }
+ return fmt.Errorf("typed action invocation is outside the closed %s catalog", catalog)
+}
+
+func isProxmoxLifecycleVerb(value string) bool {
+ switch value {
+ case "status", "start", "stop", "reboot":
+ return true
+ default:
+ return false
+ }
+}
+
+func isPositiveDecimalID(value string) bool {
+ if value == "" || len(value) > 10 || value == "0" || value[0] == '0' {
+ return false
+ }
+ for _, char := range value {
+ if char < '0' || char > '9' {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/hostagent/typed_action_command_linux.go b/internal/hostagent/typed_action_command_linux.go
new file mode 100644
index 0000000000..445cf6a2a2
--- /dev/null
+++ b/internal/hostagent/typed_action_command_linux.go
@@ -0,0 +1,558 @@
+//go:build linux
+
+package hostagent
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+const (
+ typedActionUnitPrefix = "pulse-agent-action-"
+ typedActionUnitSuffix = ".service"
+ typedActionResultVersion = 1
+ typedActionSystemdStopGrace = "10s"
+ typedActionRuntimeMaximum = "20m"
+)
+
+var typedActionSystemdGate = make(chan struct{}, 1)
+
+var (
+ typedActionResolveSystemdTool = trustedSystemdTool
+ typedActionCurrentExecutable = os.Executable
+ typedActionQueryUnitLoadState = typedActionUnitLoadState
+ typedActionStopUnit = requestTypedActionUnitStop
+ typedActionResolveTarget = resolveTypedActionTarget
+ typedActionBecomeSubreaper = becomeTypedActionSubreaper
+ typedActionInspectDescendants = typedActionHasLiveDescendants
+ typedActionWait4 = syscall.Wait4
+)
+
+type typedActionLauncherResult struct {
+ Version int `json:"version"`
+ TargetStarted bool `json:"target_started"`
+ ExitCode int `json:"exit_code"`
+ Signal int `json:"signal,omitempty"`
+ ScanComplete bool `json:"scan_complete"`
+ DescendantsObserved bool `json:"descendants_observed"`
+ Error string `json:"error,omitempty"`
+}
+
+type typedActionWaitResult struct {
+ err error
+}
+
+func runTypedActionCommandPlatform(ctx context.Context, env []string, catalog typedActionCatalog, name string, args ...string) typedActionCommandResult {
+ select {
+ case typedActionSystemdGate <- struct{}{}:
+ defer func() { <-typedActionSystemdGate }()
+ case <-ctx.Done():
+ return typedActionCommandResult{exitCode: -1, err: ctx.Err()}
+ }
+
+ systemdRun, err := typedActionResolveSystemdTool("systemd-run")
+ if err != nil {
+ return typedActionCommandResult{exitCode: -1, err: err}
+ }
+ systemctl, err := typedActionResolveSystemdTool("systemctl")
+ if err != nil {
+ return typedActionCommandResult{exitCode: -1, err: err}
+ }
+ runnerPath, err := typedActionCurrentExecutable()
+ if err != nil {
+ return typedActionCommandResult{exitCode: -1, err: fmt.Errorf("resolve action-runner executable: %w", err)}
+ }
+ runnerPath, err = filepath.EvalSymlinks(runnerPath)
+ if err != nil || !filepath.IsAbs(runnerPath) {
+ return typedActionCommandResult{exitCode: -1, err: fmt.Errorf("resolve absolute action-runner executable: %w", err)}
+ }
+ if err := validateTrustedExecutable(runnerPath, uint32(os.Geteuid())); err != nil {
+ return typedActionCommandResult{exitCode: -1, err: fmt.Errorf("validate action-runner executable: %w", err)}
+ }
+ unit, err := newTypedActionUnitName()
+ if err != nil {
+ return typedActionCommandResult{exitCode: -1, err: err}
+ }
+ resultPath, err := prepareTypedActionResultPath(unit)
+ if err != nil {
+ return typedActionCommandResult{exitCode: -1, err: err}
+ }
+ defer os.Remove(resultPath)
+
+ commandArgs, err := typedActionSystemdRunArgs(unit, runnerPath, resultPath, env, catalog, name, args)
+ if err != nil {
+ return typedActionCommandResult{exitCode: -1, err: err}
+ }
+ cmd := exec.Command(systemdRun, commandArgs...)
+ cmd.WaitDelay = 5 * time.Second
+ stdout := newCappedBuffer(maxCommandOutputSize)
+ stderr := newCappedBuffer(maxCommandOutputSize)
+ cmd.Stdout, cmd.Stderr = stdout, stderr
+ if err := cmd.Start(); err != nil {
+ return typedActionCommandResult{exitCode: -1, err: fmt.Errorf("start typed action transient service: %w", err)}
+ }
+ waited := make(chan typedActionWaitResult, 1)
+ go func() { waited <- typedActionWaitResult{err: cmd.Wait()} }()
+
+ var waitResult typedActionWaitResult
+ collected := false
+ select {
+ case waitResult = <-waited:
+ case <-ctx.Done():
+ waitResult = waitForTypedActionUnitCollection(systemctl, unit, waited, true)
+ collected = true
+ }
+ if !collected {
+ waitResult = waitForTypedActionUnitCollection(systemctl, unit, completedTypedActionWait(waitResult), ctx.Err() != nil || waitResult.err != nil)
+ }
+
+ launcherResult, resultErr := readTypedActionLauncherResult(resultPath)
+ result := typedActionCommandResult{stdout: stdout.String(), stderr: stderr.String(), exitCode: -1}
+ if ctxErr := ctx.Err(); ctxErr != nil {
+ result.err = errors.Join(errTypedActionContainmentIndeterminate, fmt.Errorf("typed action command interrupted after authoritative unit cleanup: %w", ctxErr))
+ return result
+ }
+ if resultErr != nil {
+ result.err = errors.Join(errTypedActionContainmentIndeterminate, waitResult.err, fmt.Errorf("typed action launcher result unavailable: %w", resultErr))
+ return result
+ }
+ result.exitCode = launcherResult.ExitCode
+ if !launcherResult.TargetStarted || !launcherResult.ScanComplete || launcherResult.Error != "" {
+ result.err = errors.Join(errTypedActionContainmentIndeterminate, waitResult.err, fmt.Errorf("typed action launcher could not establish terminal state: %s", launcherResult.Error))
+ result.exitCode = -1
+ return result
+ }
+ if launcherResult.DescendantsObserved {
+ result.err = errors.Join(errTypedActionContainmentIndeterminate, waitResult.err, errors.New("typed action direct process did not establish clean descendant completion"))
+ result.exitCode = -1
+ return result
+ }
+ if launcherResult.Signal != 0 {
+ result.err = errors.Join(waitResult.err, fmt.Errorf("typed action terminated by signal %d", launcherResult.Signal))
+ return result
+ }
+ if launcherResult.ExitCode != 0 {
+ result.err = errors.Join(waitResult.err, fmt.Errorf("typed action exited with status %d", launcherResult.ExitCode))
+ return result
+ }
+ if waitResult.err != nil {
+ result.err = errors.Join(errTypedActionContainmentIndeterminate, fmt.Errorf("typed action supervisor failed: %w", waitResult.err))
+ result.exitCode = -1
+ }
+ return result
+}
+
+func completedTypedActionWait(result typedActionWaitResult) <-chan typedActionWaitResult {
+ ch := make(chan typedActionWaitResult, 1)
+ ch <- result
+ return ch
+}
+
+func waitForTypedActionUnitCollection(systemctl, unit string, waited <-chan typedActionWaitResult, requestStop bool) typedActionWaitResult {
+ var result typedActionWaitResult
+ waitComplete := false
+ for {
+ select {
+ case result = <-waited:
+ waitComplete = true
+ default:
+ }
+ loadState, queryErr := typedActionQueryUnitLoadState(systemctl, unit)
+ if queryErr == nil && loadState == "not-found" && waitComplete {
+ return result
+ }
+ if requestStop || waitComplete {
+ _ = typedActionStopUnit(systemctl, unit)
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+}
+
+func typedActionUnitLoadState(systemctl, unit string) (string, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ output, err := exec.CommandContext(ctx, systemctl, "--no-ask-password", "show", "--property=LoadState", "--value", unit).CombinedOutput()
+ if err != nil {
+ return "", fmt.Errorf("query transient unit: %w", err)
+ }
+ state := strings.TrimSpace(string(output))
+ if state == "" {
+ return "", errors.New("query transient unit returned no load state")
+ }
+ return state, nil
+}
+
+func requestTypedActionUnitStop(systemctl, unit string) error {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ return exec.CommandContext(ctx, systemctl, "--no-ask-password", "--no-block", "stop", unit).Run()
+}
+
+func typedActionSystemdRunArgs(unit, runnerPath, resultPath string, env []string, catalog typedActionCatalog, name string, args []string) ([]string, error) {
+ if err := validateTypedActionEnvironment(catalog, env); err != nil {
+ return nil, err
+ }
+ restrictSUIDSGID := "yes"
+ protectKernelModules := "yes"
+ if catalog == typedActionCatalogPackage {
+ // apt/dpkg must be able to install setuid/setgid files and kernel
+ // package payloads. This relaxation remains inside the exact closed
+ // package catalog and the systemd-owned transient service.
+ restrictSUIDSGID = "no"
+ protectKernelModules = "no"
+ }
+ result := []string{
+ "--no-ask-password", "--quiet", "--wait", "--pipe", "--collect", "--service-type=exec", "--unit=" + unit,
+ "--property=User=root", "--property=Group=root", "--property=UMask=0077", "--property=Restart=no",
+ "--property=KillMode=control-group", "--property=KillSignal=SIGTERM", "--property=SendSIGKILL=yes", "--property=FinalKillSignal=SIGKILL",
+ "--property=TimeoutStopSec=" + typedActionSystemdStopGrace, "--property=RuntimeMaxSec=" + typedActionRuntimeMaximum,
+ "--property=BindsTo=pulse-agent-runner.service", "--property=After=pulse-agent-runner.service", "--property=PartOf=pulse-agent-runner.service",
+ "--property=NoNewPrivileges=yes", "--property=PrivateTmp=yes", "--property=ProtectHome=yes", "--property=ProtectSystem=no",
+ "--property=ProtectKernelTunables=yes", "--property=ProtectKernelModules=" + protectKernelModules, "--property=ProtectControlGroups=yes",
+ "--property=LockPersonality=yes", "--property=RestrictSUIDSGID=" + restrictSUIDSGID, "--property=RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6",
+ "--property=SystemCallArchitectures=native", "--property=WorkingDirectory=/",
+ "--setenv=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "--setenv=LC_ALL=C",
+ }
+ for _, value := range env {
+ result = append(result, "--setenv="+value)
+ }
+ result = append(result, "--", runnerPath, typedActionLauncherCommand, "--catalog", string(catalog), "--result-file", resultPath, "--", name)
+ return append(result, args...), nil
+}
+
+func validateTypedActionEnvironment(catalog typedActionCatalog, env []string) error {
+ if catalog != typedActionCatalogPackage && len(env) != 0 {
+ return errors.New("typed action environment is not allowed for this catalog")
+ }
+ allowed := map[string]bool{"DEBIAN_FRONTEND=noninteractive": true, "APT_LISTCHANGES_FRONTEND=none": true, "NEEDRESTART_MODE=a": true}
+ for _, value := range env {
+ if !allowed[value] {
+ return fmt.Errorf("typed package environment is outside the closed catalog")
+ }
+ }
+ return nil
+}
+
+func newTypedActionUnitName() (string, error) {
+ var id [16]byte
+ if _, err := rand.Read(id[:]); err != nil {
+ return "", fmt.Errorf("generate typed action unit identity: %w", err)
+ }
+ return typedActionUnitPrefix + hex.EncodeToString(id[:]) + typedActionUnitSuffix, nil
+}
+
+func prepareTypedActionResultPath(unit string) (string, error) {
+ stateDir := strings.TrimSpace(os.Getenv("PULSE_AGENT_RUNNER_STATE_DIR"))
+ if !filepath.IsAbs(stateDir) {
+ return "", errors.New("PULSE_AGENT_RUNNER_STATE_DIR must be absolute for typed action containment")
+ }
+ dir := filepath.Join(stateDir, "typed-actions")
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return "", fmt.Errorf("create typed action result directory: %w", err)
+ }
+ if err := validatePrivateDirectory(dir); err != nil {
+ return "", err
+ }
+ resultPath := filepath.Join(dir, strings.TrimSuffix(unit, typedActionUnitSuffix)+".json")
+ if _, err := os.Lstat(resultPath); err == nil {
+ return "", errors.New("typed action result identity collision")
+ } else if !errors.Is(err, fs.ErrNotExist) {
+ return "", err
+ }
+ return resultPath, nil
+}
+
+func validatePrivateDirectory(path string) error {
+ info, err := os.Lstat(path)
+ if err != nil {
+ return err
+ }
+ stat, ok := info.Sys().(*syscall.Stat_t)
+ if !ok || !info.IsDir() || info.Mode().Perm()&0o077 != 0 || stat.Uid != uint32(os.Geteuid()) {
+ return fmt.Errorf("typed action state directory must be a private directory owned by the runner")
+ }
+ return nil
+}
+
+func readTypedActionLauncherResult(path string) (typedActionLauncherResult, error) {
+ fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0)
+ if err != nil {
+ return typedActionLauncherResult{}, err
+ }
+ file := os.NewFile(uintptr(fd), path)
+ if file == nil {
+ _ = unix.Close(fd)
+ return typedActionLauncherResult{}, errors.New("open typed action result file")
+ }
+ defer file.Close()
+ var stat unix.Stat_t
+ if err := unix.Fstat(fd, &stat); err != nil {
+ return typedActionLauncherResult{}, err
+ }
+ if stat.Mode&unix.S_IFMT != unix.S_IFREG || fs.FileMode(stat.Mode).Perm() != 0o600 || stat.Uid != uint32(os.Geteuid()) || stat.Size <= 0 || stat.Size > 4096 {
+ return typedActionLauncherResult{}, errors.New("typed action result file failed ownership, mode, type, or size validation")
+ }
+ data, err := io.ReadAll(io.LimitReader(file, 4097))
+ if err != nil {
+ return typedActionLauncherResult{}, err
+ }
+ if len(data) == 0 || len(data) > 4096 {
+ return typedActionLauncherResult{}, errors.New("typed action result file exceeded its bound")
+ }
+ var result typedActionLauncherResult
+ if err := json.Unmarshal(data, &result); err != nil || result.Version != typedActionResultVersion {
+ return typedActionLauncherResult{}, errors.New("typed action result file is malformed")
+ }
+ return result, nil
+}
+
+func trustedSystemdTool(name string) (string, error) {
+ for _, candidate := range []string{filepath.Join("/usr/bin", name), filepath.Join("/bin", name)} {
+ resolved, err := filepath.EvalSymlinks(candidate)
+ if err == nil && validateTrustedExecutable(resolved, 0) == nil {
+ return resolved, nil
+ }
+ }
+ return "", fmt.Errorf("trusted %s is required for typed action containment", name)
+}
+
+func validateTrustedExecutable(path string, owner uint32) error {
+ info, err := os.Lstat(path)
+ if err != nil {
+ return err
+ }
+ stat, ok := info.Sys().(*syscall.Stat_t)
+ if !ok || !info.Mode().IsRegular() || info.Mode().Perm()&0o022 != 0 || info.Mode().Perm()&0o111 == 0 || stat.Uid != owner {
+ return errors.New("executable must be a regular owner-controlled file")
+ }
+ return nil
+}
+
+func RunTypedActionLauncher(args []string) int {
+ catalog, resultPath, name, commandArgs, err := parseTypedActionLauncherArgs(args)
+ if err != nil {
+ return typedActionLauncherSupervisorFailureExit
+ }
+ result := typedActionLauncherResult{Version: typedActionResultVersion, ExitCode: -1}
+ if err := typedActionBecomeSubreaper(); err != nil {
+ result.Error = "establish typed action child subreaper"
+ _ = writeTypedActionLauncherResult(resultPath, result)
+ return typedActionLauncherSupervisorFailureExit
+ }
+ target, err := typedActionResolveTarget(catalog, name)
+ if err != nil {
+ result.Error = err.Error()
+ _ = writeTypedActionLauncherResult(resultPath, result)
+ return typedActionLauncherStartFailureExit
+ }
+ cmd := exec.Command(target, commandArgs...)
+ cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
+ cmd.Env = os.Environ()
+ if err := cmd.Start(); err != nil {
+ result.Error = "start fixed-catalog target"
+ _ = writeTypedActionLauncherResult(resultPath, result)
+ return typedActionLauncherStartFailureExit
+ }
+ result.TargetStarted = true
+ waitErr := cmd.Wait()
+ result.ExitCode = 0
+ if waitErr != nil {
+ var exitErr *exec.ExitError
+ if errors.As(waitErr, &exitErr) {
+ status, _ := exitErr.Sys().(syscall.WaitStatus)
+ result.ExitCode = status.ExitStatus()
+ if status.Signaled() {
+ result.ExitCode = -1
+ result.Signal = int(status.Signal())
+ }
+ } else {
+ result.ExitCode = -1
+ result.Error = "wait for fixed-catalog target"
+ }
+ }
+ descendants, scanErr := typedActionInspectDescendants()
+ if scanErr != nil {
+ result.Error = "inspect transient service cgroup"
+ } else {
+ result.ScanComplete = true
+ result.DescendantsObserved = descendants
+ }
+ if err := writeTypedActionLauncherResult(resultPath, result); err != nil {
+ return typedActionLauncherSupervisorFailureExit
+ }
+ if scanErr != nil {
+ return typedActionLauncherInspectionFailureExit
+ }
+ if descendants {
+ return typedActionLauncherDescendantExit
+ }
+ if result.Signal != 0 || result.ExitCode < 0 {
+ return typedActionLauncherSupervisorFailureExit
+ }
+ return result.ExitCode
+}
+
+func parseTypedActionLauncherArgs(args []string) (typedActionCatalog, string, string, []string, error) {
+ if len(args) < 6 || args[0] != "--catalog" || args[2] != "--result-file" || args[4] != "--" {
+ return "", "", "", nil, errors.New("invalid typed action launcher arguments")
+ }
+ catalog := typedActionCatalog(args[1])
+ resultPath, name, commandArgs := args[3], args[5], args[6:]
+ if !filepath.IsAbs(resultPath) || filepath.Base(resultPath) == "." {
+ return "", "", "", nil, errors.New("invalid typed action result path")
+ }
+ if err := validateTypedActionInvocation(catalog, name, commandArgs); err != nil {
+ return "", "", "", nil, err
+ }
+ return catalog, resultPath, name, commandArgs, nil
+}
+
+func resolveTypedActionTarget(catalog typedActionCatalog, name string) (string, error) {
+ allowed := map[typedActionCatalog]map[string][]string{
+ typedActionCatalogPackage: {"apt-get": {"/usr/bin/apt-get"}, "dpkg": {"/usr/bin/dpkg"}},
+ typedActionCatalogProxmox: {"qm": {"/usr/sbin/qm", "/usr/bin/qm"}, "pct": {"/usr/sbin/pct", "/usr/bin/pct"}},
+ typedActionCatalogProbe: {"true": {"/usr/bin/true", "/bin/true"}},
+ }
+ for _, candidate := range allowed[catalog][name] {
+ resolved, err := filepath.EvalSymlinks(candidate)
+ if err == nil && validateTrustedExecutable(resolved, 0) == nil {
+ return resolved, nil
+ }
+ }
+ return "", fmt.Errorf("fixed-catalog executable %s is unavailable", name)
+}
+
+func becomeTypedActionSubreaper() error {
+ return unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0)
+}
+
+func typedActionHasLiveDescendants() (bool, error) {
+ failedAdoptedChild := false
+ for {
+ var status syscall.WaitStatus
+ pid, err := typedActionWait4(-1, &status, syscall.WNOHANG, nil)
+ switch {
+ case err == nil && pid > 0:
+ // Reap an adopted descendant that already exited, then establish
+ // whether any live descendants remain. A failed adopted worker is
+ // terminally indeterminate even after it has exited.
+ if !status.Exited() || status.ExitStatus() != 0 {
+ failedAdoptedChild = true
+ }
+ continue
+ case err == nil && pid == 0:
+ return true, nil
+ case errors.Is(err, syscall.EINTR):
+ continue
+ case errors.Is(err, syscall.ECHILD):
+ return failedAdoptedChild, nil
+ default:
+ return false, err
+ }
+ }
+}
+
+func writeTypedActionLauncherResult(path string, result typedActionLauncherResult) error {
+ data, err := json.Marshal(result)
+ if err != nil || len(data) > 4096 {
+ return errors.New("encode typed action result")
+ }
+ tmp, err := os.CreateTemp(filepath.Dir(path), ".typed-action-result-")
+ if err != nil {
+ return err
+ }
+ tmpPath := tmp.Name()
+ defer os.Remove(tmpPath)
+ if err := tmp.Chmod(0o600); err == nil {
+ _, err = tmp.Write(data)
+ }
+ if err == nil {
+ err = tmp.Sync()
+ }
+ closeErr := tmp.Close()
+ if err == nil {
+ err = closeErr
+ }
+ if err == nil {
+ err = os.Rename(tmpPath, path)
+ }
+ if err != nil {
+ return err
+ }
+ dir, err := os.Open(filepath.Dir(path))
+ if err != nil {
+ return err
+ }
+ err = dir.Sync()
+ closeErr = dir.Close()
+ if err != nil {
+ return err
+ }
+ return closeErr
+}
+
+var typedActionReconcileMu sync.Mutex
+
+func ReconcileTypedActionUnits(ctx context.Context) error {
+ typedActionReconcileMu.Lock()
+ defer typedActionReconcileMu.Unlock()
+ if _, err := typedActionResolveSystemdTool("systemd-run"); err != nil {
+ return err
+ }
+ systemctl, err := typedActionResolveSystemdTool("systemctl")
+ if err != nil {
+ return err
+ }
+ output, err := exec.CommandContext(ctx, systemctl, "--no-ask-password", "list-units", "--all", "--full", "--plain", "--no-legend", typedActionUnitPrefix+"*"+typedActionUnitSuffix).CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("enumerate stale typed action units: %w", err)
+ }
+ for _, line := range strings.Split(string(output), "\n") {
+ fields := strings.Fields(line)
+ if len(fields) == 0 || !validTypedActionUnitName(fields[0]) {
+ continue
+ }
+ unit := fields[0]
+ for {
+ state, queryErr := typedActionQueryUnitLoadState(systemctl, unit)
+ if queryErr == nil && state == "not-found" {
+ break
+ }
+ _ = typedActionStopUnit(systemctl, unit)
+ select {
+ case <-ctx.Done():
+ return fmt.Errorf("reconcile stale typed action unit %s: %w", unit, ctx.Err())
+ case <-time.After(100 * time.Millisecond):
+ }
+ }
+ }
+ probe := runTypedActionCommand(ctx, nil, typedActionCatalogProbe, "true")
+ if probe.err != nil || probe.exitCode != 0 {
+ return fmt.Errorf("qualify typed action systemd containment: %w", probe.err)
+ }
+ return nil
+}
+
+func validTypedActionUnitName(unit string) bool {
+ value := strings.TrimSuffix(strings.TrimPrefix(unit, typedActionUnitPrefix), typedActionUnitSuffix)
+ if len(value) != 32 || typedActionUnitPrefix+value+typedActionUnitSuffix != unit {
+ return false
+ }
+ _, err := hex.DecodeString(value)
+ return err == nil
+}
diff --git a/internal/hostagent/typed_action_command_linux_test.go b/internal/hostagent/typed_action_command_linux_test.go
new file mode 100644
index 0000000000..a7b5bfa489
--- /dev/null
+++ b/internal/hostagent/typed_action_command_linux_test.go
@@ -0,0 +1,612 @@
+//go:build linux
+
+package hostagent
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "syscall"
+ "testing"
+ "time"
+)
+
+func TestMain(m *testing.M) {
+ if len(os.Args) > 1 && os.Args[1] == typedActionLauncherCommand {
+ if target := os.Getenv("PULSE_TEST_TYPED_ACTION_TARGET"); target != "" {
+ typedActionResolveTarget = func(typedActionCatalog, string) (string, error) { return target, nil }
+ }
+ os.Exit(RunTypedActionLauncher(os.Args[2:]))
+ }
+ os.Exit(m.Run())
+}
+
+func withTypedActionLinuxHooks(t *testing.T) {
+ t.Helper()
+ oldTool := typedActionResolveSystemdTool
+ oldExecutable := typedActionCurrentExecutable
+ oldQuery := typedActionQueryUnitLoadState
+ oldStop := typedActionStopUnit
+ oldTarget := typedActionResolveTarget
+ oldSubreaper := typedActionBecomeSubreaper
+ oldInspect := typedActionInspectDescendants
+ oldWait4 := typedActionWait4
+ t.Cleanup(func() {
+ typedActionResolveSystemdTool = oldTool
+ typedActionCurrentExecutable = oldExecutable
+ typedActionQueryUnitLoadState = oldQuery
+ typedActionStopUnit = oldStop
+ typedActionResolveTarget = oldTarget
+ typedActionBecomeSubreaper = oldSubreaper
+ typedActionInspectDescendants = oldInspect
+ typedActionWait4 = oldWait4
+ })
+}
+
+func TestTypedActionSystemdArgumentsAreHardenedAndTerminateOptions(t *testing.T) {
+ args, err := typedActionSystemdRunArgs(
+ "pulse-agent-action-0123456789abcdef0123456789abcdef.service",
+ "/usr/local/bin/pulse-agent-runner", "/var/lib/pulse-agent-runner/typed-actions/result.json",
+ []string{"DEBIAN_FRONTEND=noninteractive"}, typedActionCatalogPackage, "apt-get", []string{"update"},
+ )
+ if err != nil {
+ t.Fatal(err)
+ }
+ joined := strings.Join(args, "\n")
+ for _, required := range []string{
+ "--property=KillMode=control-group", "--property=SendSIGKILL=yes", "--property=ProtectControlGroups=yes",
+ "--property=BindsTo=pulse-agent-runner.service", "--property=PartOf=pulse-agent-runner.service",
+ "--property=NoNewPrivileges=yes", "--property=RuntimeMaxSec=20m", "--property=RestrictSUIDSGID=no",
+ "--property=ProtectKernelModules=no", "--collect", "--pipe", "--wait",
+ } {
+ if !strings.Contains(joined, required) {
+ t.Fatalf("systemd arguments missing %q:\n%s", required, joined)
+ }
+ }
+ separator := -1
+ for index, value := range args {
+ if value == "--" {
+ separator = index
+ break
+ }
+ }
+ if separator < 0 || args[separator+1] != "/usr/local/bin/pulse-agent-runner" || args[separator+2] != typedActionLauncherCommand {
+ t.Fatalf("systemd option terminator/launcher binding is wrong: %v", args)
+ }
+}
+
+func TestTypedActionNonPackageCatalogKeepsKernelAndSUIDRestrictions(t *testing.T) {
+ args, err := typedActionSystemdRunArgs(
+ "pulse-agent-action-0123456789abcdef0123456789abcdef.service",
+ "/usr/local/bin/pulse-agent-runner", "/var/lib/pulse-agent-runner/typed-actions/result.json",
+ nil, typedActionCatalogProxmox, "qm", []string{"status", "100"},
+ )
+ if err != nil {
+ t.Fatal(err)
+ }
+ joined := strings.Join(args, "\n")
+ for _, required := range []string{"--property=RestrictSUIDSGID=yes", "--property=ProtectKernelModules=yes"} {
+ if !strings.Contains(joined, required) {
+ t.Fatalf("Proxmox transient service missing %q:\n%s", required, joined)
+ }
+ }
+}
+
+func TestTypedActionLauncherSidebandDisambiguatesReservedExitAndDescendants(t *testing.T) {
+ withTypedActionLinuxHooks(t)
+ tmp := t.TempDir()
+ target := filepath.Join(tmp, "target.sh")
+ if err := os.WriteFile(target, []byte("#!/bin/sh\nexit 200\n"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ typedActionResolveTarget = func(typedActionCatalog, string) (string, error) { return target, nil }
+ typedActionBecomeSubreaper = func() error { return nil }
+ typedActionInspectDescendants = func() (bool, error) { return false, nil }
+ resultPath := filepath.Join(tmp, "result.json")
+ exitCode := RunTypedActionLauncher([]string{"--catalog", "package", "--result-file", resultPath, "--", "apt-get", "update"})
+ if exitCode != 200 {
+ t.Fatalf("launcher exit=%d want target's reserved-value exit", exitCode)
+ }
+ result, err := readTypedActionLauncherResult(resultPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.DescendantsObserved || !result.ScanComplete || result.ExitCode != 200 {
+ t.Fatalf("sideband did not preserve target result: %#v", result)
+ }
+
+ typedActionInspectDescendants = func() (bool, error) { return true, nil }
+ resultPath = filepath.Join(tmp, "descendant.json")
+ exitCode = RunTypedActionLauncher([]string{"--catalog", "package", "--result-file", resultPath, "--", "apt-get", "update"})
+ result, err = readTypedActionLauncherResult(resultPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if exitCode != typedActionLauncherDescendantExit || !result.DescendantsObserved || result.ExitCode != 200 {
+ t.Fatalf("descendant sideband=%#v launcher_exit=%d", result, exitCode)
+ }
+}
+
+func TestTypedActionLauncherInspectionFailureIsIndeterminate(t *testing.T) {
+ withTypedActionLinuxHooks(t)
+ tmp := t.TempDir()
+ target := filepath.Join(tmp, "target.sh")
+ if err := os.WriteFile(target, []byte("#!/bin/sh\nexit 0\n"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ typedActionResolveTarget = func(typedActionCatalog, string) (string, error) { return target, nil }
+ typedActionBecomeSubreaper = func() error { return nil }
+ typedActionInspectDescendants = func() (bool, error) { return false, errors.New("wait unavailable") }
+ resultPath := filepath.Join(tmp, "result.json")
+ if got := RunTypedActionLauncher([]string{"--catalog", "package", "--result-file", resultPath, "--", "apt-get", "update"}); got != typedActionLauncherInspectionFailureExit {
+ t.Fatalf("launcher exit=%d", got)
+ }
+ result, err := readTypedActionLauncherResult(resultPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.ScanComplete || result.Error == "" {
+ t.Fatalf("inspection failure sideband=%#v", result)
+ }
+}
+
+func TestTypedActionAdoptedChildFailureIsIndeterminate(t *testing.T) {
+ withTypedActionLinuxHooks(t)
+ for _, test := range []struct {
+ name string
+ status syscall.WaitStatus
+ want bool
+ }{
+ {name: "zero exit is reaped", status: syscall.WaitStatus(0), want: false},
+ {name: "nonzero exit is indeterminate", status: syscall.WaitStatus(42 << 8), want: true},
+ {name: "signal is indeterminate", status: syscall.WaitStatus(syscall.SIGTERM), want: true},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ calls := 0
+ typedActionWait4 = func(_ int, status *syscall.WaitStatus, _ int, _ *syscall.Rusage) (int, error) {
+ calls++
+ if calls == 1 {
+ *status = test.status
+ return 123, nil
+ }
+ return -1, syscall.ECHILD
+ }
+ got, err := typedActionHasLiveDescendants()
+ if err != nil || got != test.want {
+ t.Fatalf("adopted child status=%#x got=%v err=%v want=%v", uint32(test.status), got, err, test.want)
+ }
+ })
+ }
+}
+
+func TestValidateTrustedExecutableRequiresControlledExecutableFile(t *testing.T) {
+ valid := filepath.Join(t.TempDir(), "valid")
+ if err := os.WriteFile(valid, []byte("binary"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := validateTrustedExecutable(valid, uint32(os.Geteuid())); err != nil {
+ t.Fatalf("valid executable rejected: %v", err)
+ }
+ nonExecutable := filepath.Join(t.TempDir(), "non-executable")
+ if err := os.WriteFile(nonExecutable, []byte("binary"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := validateTrustedExecutable(nonExecutable, uint32(os.Geteuid())); err == nil {
+ t.Fatal("non-executable file was trusted")
+ }
+ writable := filepath.Join(t.TempDir(), "group-writable")
+ if err := os.WriteFile(writable, []byte("binary"), 0o720); err != nil {
+ t.Fatal(err)
+ }
+ if err := validateTrustedExecutable(writable, uint32(os.Geteuid())); err == nil {
+ t.Fatal("group-writable executable was trusted")
+ }
+ symlink := filepath.Join(t.TempDir(), "symlink")
+ if err := os.Symlink(valid, symlink); err != nil {
+ t.Fatal(err)
+ }
+ if err := validateTrustedExecutable(symlink, uint32(os.Geteuid())); err == nil {
+ t.Fatal("symlink was trusted without resolution at the boundary")
+ }
+ if err := validateTrustedExecutable(t.TempDir(), uint32(os.Geteuid())); err == nil {
+ t.Fatal("directory was trusted as an executable")
+ }
+}
+
+func TestTypedActionWaitsForUnitAbsenceBeforeReturning(t *testing.T) {
+ withTypedActionLinuxHooks(t)
+ tmp := t.TempDir()
+ t.Setenv("PULSE_AGENT_RUNNER_STATE_DIR", tmp)
+ fakeRun := filepath.Join(tmp, "systemd-run")
+ script := `#!/bin/sh
+result=""
+previous=""
+for arg in "$@"; do
+ if [ "$previous" = "--result-file" ]; then result="$arg"; break; fi
+ previous="$arg"
+done
+printf '%s' '{"version":1,"target_started":true,"exit_code":0,"scan_complete":true,"descendants_observed":false}' > "$result"
+chmod 600 "$result"
+`
+ if err := os.WriteFile(fakeRun, []byte(script), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ typedActionResolveSystemdTool = func(string) (string, error) { return fakeRun, nil }
+ typedActionCurrentExecutable = func() (string, error) { return fakeRun, nil }
+ var queries atomic.Int32
+ releaseQuery := make(chan struct{})
+ typedActionQueryUnitLoadState = func(string, string) (string, error) {
+ queries.Add(1)
+ select {
+ case <-releaseQuery:
+ return "not-found", nil
+ default:
+ return "loaded", nil
+ }
+ }
+ typedActionStopUnit = func(string, string) error { return nil }
+ done := make(chan typedActionCommandResult, 1)
+ go func() {
+ done <- runTypedActionCommand(context.Background(), nil, typedActionCatalogPackage, "apt-get", "update")
+ }()
+ deadline := time.Now().Add(2 * time.Second)
+ for queries.Load() == 0 && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ select {
+ case result := <-done:
+ t.Fatalf("command returned before unit collection: %#v", result)
+ default:
+ }
+ close(releaseQuery)
+ select {
+ case result := <-done:
+ if result.err != nil || result.exitCode != 0 {
+ t.Fatalf("command result=%#v", result)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("command did not return after unit collection")
+ }
+}
+
+func TestTypedActionCancellationBeforeUnitCreationStillStopsLateUnit(t *testing.T) {
+ withTypedActionLinuxHooks(t)
+ tmp := t.TempDir()
+ t.Setenv("PULSE_AGENT_RUNNER_STATE_DIR", tmp)
+ startedPath := filepath.Join(tmp, "started")
+ releasePath := filepath.Join(tmp, "release")
+ fakeRun := filepath.Join(tmp, "systemd-run")
+ script := "#!/bin/sh\n: > " + startedPath + "\nwhile [ ! -f " + releasePath + " ]; do sleep 0.01; done\n"
+ if err := os.WriteFile(fakeRun, []byte(script), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ typedActionResolveSystemdTool = func(string) (string, error) { return fakeRun, nil }
+ typedActionCurrentExecutable = func() (string, error) { return fakeRun, nil }
+ var queries atomic.Int32
+ var stops atomic.Int32
+ typedActionQueryUnitLoadState = func(string, string) (string, error) {
+ query := queries.Add(1)
+ if query == 1 {
+ return "not-found", nil
+ }
+ if _, err := os.Stat(releasePath); err == nil {
+ return "not-found", nil
+ }
+ return "loaded", nil
+ }
+ typedActionStopUnit = func(string, string) error {
+ if stops.Add(1) == 1 {
+ return errors.New("unit not created yet")
+ }
+ return os.WriteFile(releasePath, []byte("release"), 0o600)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan typedActionCommandResult, 1)
+ go func() {
+ done <- runTypedActionCommand(ctx, nil, typedActionCatalogPackage, "apt-get", "update")
+ }()
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ if _, err := os.Stat(startedPath); err == nil {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("fake systemd-run did not start")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ cancel()
+ select {
+ case result := <-done:
+ if !errors.Is(result.err, context.Canceled) {
+ t.Fatalf("canceled result=%#v", result)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("canceled command did not finish after the late unit was stopped")
+ }
+ if stops.Load() < 2 || queries.Load() < 3 {
+ t.Fatalf("creation race was not retried: queries=%d stops=%d", queries.Load(), stops.Load())
+ }
+}
+
+func TestPackageLeaseRemainsHeldUntilTypedActionUnitIsAbsent(t *testing.T) {
+ withTypedActionLinuxHooks(t)
+ tmp := t.TempDir()
+ t.Setenv("PULSE_AGENT_RUNNER_STATE_DIR", tmp)
+ fakeRun := filepath.Join(tmp, "systemd-run")
+ script := `#!/bin/sh
+result=""
+previous=""
+for arg in "$@"; do
+ if [ "$previous" = "--result-file" ]; then result="$arg"; break; fi
+ previous="$arg"
+done
+printf '%s' '{"version":1,"target_started":true,"exit_code":0,"scan_complete":true,"descendants_observed":false}' > "$result"
+chmod 600 "$result"
+`
+ if err := os.WriteFile(fakeRun, []byte(script), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ typedActionResolveSystemdTool = func(string) (string, error) { return fakeRun, nil }
+ typedActionCurrentExecutable = func() (string, error) { return fakeRun, nil }
+ unitAbsent := make(chan struct{})
+ queried := make(chan struct{}, 1)
+ typedActionQueryUnitLoadState = func(string, string) (string, error) {
+ select {
+ case queried <- struct{}{}:
+ default:
+ }
+ select {
+ case <-unitAbsent:
+ return "not-found", nil
+ default:
+ return "loaded", nil
+ }
+ }
+ typedActionStopUnit = func(string, string) error { return nil }
+ lease := newPackageManagerLease()
+ release, err := lease.acquire(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ done := make(chan typedActionCommandResult, 1)
+ go func() {
+ result := runTypedActionCommand(context.Background(), nil, typedActionCatalogPackage, "apt-get", "update")
+ release()
+ done <- result
+ }()
+ select {
+ case <-queried:
+ case <-time.After(2 * time.Second):
+ t.Fatal("typed action never reached the unit-collection fence")
+ }
+ blockedCtx, blockedCancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ defer blockedCancel()
+ if acquired, err := lease.acquire(blockedCtx); !errors.Is(err, context.DeadlineExceeded) {
+ if acquired != nil {
+ acquired()
+ }
+ t.Fatalf("package lease released before unit absence: %v", err)
+ }
+ close(unitAbsent)
+ select {
+ case result := <-done:
+ if result.err != nil {
+ t.Fatalf("typed action result=%#v", result)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("typed action did not release after unit absence")
+ }
+ postCtx, postCancel := context.WithTimeout(context.Background(), time.Second)
+ defer postCancel()
+ postRelease, err := lease.acquire(postCtx)
+ if err != nil {
+ t.Fatalf("package lease remained fenced after unit absence: %v", err)
+ }
+ postRelease()
+}
+
+func TestTypedActionManagerQueryFailureKeepsGlobalGateFenced(t *testing.T) {
+ withTypedActionLinuxHooks(t)
+ tmp := t.TempDir()
+ t.Setenv("PULSE_AGENT_RUNNER_STATE_DIR", tmp)
+ fakeRun := filepath.Join(tmp, "systemd-run")
+ script := `#!/bin/sh
+result=""
+previous=""
+for arg in "$@"; do
+ if [ "$previous" = "--result-file" ]; then result="$arg"; break; fi
+ previous="$arg"
+done
+printf '%s' '{"version":1,"target_started":true,"exit_code":0,"scan_complete":true,"descendants_observed":false}' > "$result"
+chmod 600 "$result"
+`
+ if err := os.WriteFile(fakeRun, []byte(script), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ typedActionResolveSystemdTool = func(string) (string, error) { return fakeRun, nil }
+ typedActionCurrentExecutable = func() (string, error) { return fakeRun, nil }
+ recoverManager := make(chan struct{})
+ queried := make(chan struct{}, 1)
+ typedActionQueryUnitLoadState = func(string, string) (string, error) {
+ select {
+ case queried <- struct{}{}:
+ default:
+ }
+ select {
+ case <-recoverManager:
+ return "not-found", nil
+ default:
+ return "", errors.New("system manager unavailable")
+ }
+ }
+ typedActionStopUnit = func(string, string) error { return errors.New("system manager unavailable") }
+ firstDone := make(chan typedActionCommandResult, 1)
+ go func() {
+ firstDone <- runTypedActionCommand(context.Background(), nil, typedActionCatalogPackage, "apt-get", "update")
+ }()
+ select {
+ case <-queried:
+ case <-time.After(2 * time.Second):
+ t.Fatal("typed action did not reach manager verification")
+ }
+ blockedCtx, blockedCancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ defer blockedCancel()
+ blocked := runTypedActionCommand(blockedCtx, nil, typedActionCatalogPackage, "apt-get", "update")
+ if !errors.Is(blocked.err, context.DeadlineExceeded) {
+ t.Fatalf("global gate admitted overlapping work while manager state was unknown: %#v", blocked)
+ }
+ select {
+ case result := <-firstDone:
+ t.Fatalf("first action returned while manager state was unknown: %#v", result)
+ default:
+ }
+ close(recoverManager)
+ select {
+ case result := <-firstDone:
+ if result.err != nil {
+ t.Fatalf("first action did not recover after authoritative absence: %#v", result)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("first action remained fenced after manager recovery")
+ }
+}
+
+func TestTypedActionRealSystemdContainmentProbe(t *testing.T) {
+ if os.Getenv("PULSE_TEST_SYSTEMD_TYPED_ACTION") != "1" {
+ t.Skip("set PULSE_TEST_SYSTEMD_TYPED_ACTION=1 inside a root systemd host")
+ }
+ if os.Geteuid() != 0 {
+ t.Fatal("real transient-service proof must run as root")
+ }
+ withTypedActionLinuxHooks(t)
+ stateDir, err := os.MkdirTemp("/run", "pulse-agent-runner-test-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.RemoveAll(stateDir) })
+ t.Setenv("PULSE_AGENT_RUNNER_STATE_DIR", stateDir)
+ self, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ runnerPath := filepath.Join(stateDir, "pulse-agent-runner-test")
+ binary, err := os.ReadFile(self)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(runnerPath, binary, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ typedActionCurrentExecutable = func() (string, error) { return runnerPath, nil }
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ result := runTypedActionCommand(ctx, nil, typedActionCatalogProbe, "true")
+ if result.err != nil || result.exitCode != 0 {
+ t.Fatalf("real systemd containment probe exit=%d err=%v stderr=%q", result.exitCode, result.err, result.stderr)
+ }
+}
+
+func TestTypedActionRealSystemdKillsDetachedDescendantBeforeReturn(t *testing.T) {
+ if os.Getenv("PULSE_TEST_SYSTEMD_TYPED_ACTION") != "1" {
+ t.Skip("set PULSE_TEST_SYSTEMD_TYPED_ACTION=1 inside a root systemd host")
+ }
+ if os.Geteuid() != 0 {
+ t.Fatal("real transient-service proof must run as root")
+ }
+ withTypedActionLinuxHooks(t)
+ stateDir, err := os.MkdirTemp("/run", "pulse-agent-runner-test-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.RemoveAll(stateDir) })
+ t.Setenv("PULSE_AGENT_RUNNER_STATE_DIR", stateDir)
+ self, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ testBinary := filepath.Join(stateDir, "hostagent.test")
+ binary, err := os.ReadFile(self)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(testBinary, binary, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ pidFile := filepath.Join(stateDir, "descendant.pid")
+ target := filepath.Join(stateDir, "detached-target.sh")
+ targetScript := "#!/bin/sh\nsh -c 'sleep 300 >/dev/null 2>&1 & echo $! > \"$1\"; exit 0' child " + pidFile + " &\nwait\nexit 0\n"
+ if err := os.WriteFile(target, []byte(targetScript), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ runnerPath := filepath.Join(stateDir, "pulse-agent-runner-test")
+ runnerScript := "#!/bin/sh\nexport PULSE_TEST_TYPED_ACTION_TARGET=" + target + "\nexec " + testBinary + " \"$@\"\n"
+ if err := os.WriteFile(runnerPath, []byte(runnerScript), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ typedActionCurrentExecutable = func() (string, error) { return runnerPath, nil }
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ result := runTypedActionCommand(ctx, nil, typedActionCatalogProbe, "true")
+ if !errors.Is(result.err, errTypedActionContainmentIndeterminate) || result.exitCode != -1 {
+ t.Fatalf("detached descendant result exit=%d err=%v stderr=%q", result.exitCode, result.err, result.stderr)
+ }
+ pid := readPidFile(t, pidFile)
+ waitForProcessGone(t, pid, 5*time.Second)
+}
+
+func TestTypedActionRealSystemdPackageUnitCanInstallSetuidPayload(t *testing.T) {
+ if os.Getenv("PULSE_TEST_SYSTEMD_TYPED_ACTION") != "1" {
+ t.Skip("set PULSE_TEST_SYSTEMD_TYPED_ACTION=1 inside a root systemd host")
+ }
+ if os.Geteuid() != 0 {
+ t.Fatal("real transient-service proof must run as root")
+ }
+ withTypedActionLinuxHooks(t)
+ stateDir, err := os.MkdirTemp("/run", "pulse-agent-runner-test-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.RemoveAll(stateDir) })
+ t.Setenv("PULSE_AGENT_RUNNER_STATE_DIR", stateDir)
+ self, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ testBinary := filepath.Join(stateDir, "hostagent.test")
+ binary, err := os.ReadFile(self)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(testBinary, binary, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ payload := filepath.Join(stateDir, "setuid-payload")
+ target := filepath.Join(stateDir, "package-target.sh")
+ targetScript := "#!/bin/sh\n: > " + payload + "\nchmod 4755 " + payload + "\n"
+ if err := os.WriteFile(target, []byte(targetScript), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ runnerPath := filepath.Join(stateDir, "pulse-agent-runner-test")
+ runnerScript := "#!/bin/sh\nexport PULSE_TEST_TYPED_ACTION_TARGET=" + target + "\nexec " + testBinary + " \"$@\"\n"
+ if err := os.WriteFile(runnerPath, []byte(runnerScript), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ typedActionCurrentExecutable = func() (string, error) { return runnerPath, nil }
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ result := runTypedActionCommand(ctx, nil, typedActionCatalogPackage, "apt-get", "update")
+ if result.err != nil || result.exitCode != 0 {
+ t.Fatalf("package setuid fixture exit=%d err=%v stderr=%q", result.exitCode, result.err, result.stderr)
+ }
+ info, err := os.Stat(payload)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Mode()&os.ModeSetuid == 0 {
+ t.Fatalf("package fixture mode=%v, setuid bit was not preserved", info.Mode())
+ }
+}
diff --git a/internal/hostagent/typed_action_command_other.go b/internal/hostagent/typed_action_command_other.go
new file mode 100644
index 0000000000..956c9f28c8
--- /dev/null
+++ b/internal/hostagent/typed_action_command_other.go
@@ -0,0 +1,17 @@
+//go:build !linux
+
+package hostagent
+
+import "context"
+
+func runTypedActionCommandPlatform(context.Context, []string, typedActionCatalog, string, ...string) typedActionCommandResult {
+ return typedActionCommandResult{exitCode: -1, err: errTypedActionContainmentUnavailable}
+}
+
+func RunTypedActionLauncher([]string) int {
+ return typedActionLauncherSupervisorFailureExit
+}
+
+func ReconcileTypedActionUnits(context.Context) error {
+ return errTypedActionContainmentUnavailable
+}
diff --git a/internal/hostagent/typed_action_command_test.go b/internal/hostagent/typed_action_command_test.go
new file mode 100644
index 0000000000..d30a8731af
--- /dev/null
+++ b/internal/hostagent/typed_action_command_test.go
@@ -0,0 +1,35 @@
+package hostagent
+
+import "testing"
+
+func TestTypedActionCatalogRejectsArgumentInjection(t *testing.T) {
+ tests := []struct {
+ catalog typedActionCatalog
+ name string
+ args []string
+ valid bool
+ }{
+ {typedActionCatalogPackage, "apt-get", []string{"-s", "-o", "Debug::NoLocking=1", "upgrade"}, true},
+ {typedActionCatalogPackage, "apt-get", []string{"update"}, true},
+ {typedActionCatalogPackage, "apt-get", []string{"clean"}, true},
+ {typedActionCatalogPackage, "apt-get", []string{"-y", "--no-remove", "-o", "Dpkg::Options::=--force-confold", "upgrade"}, true},
+ {typedActionCatalogPackage, "dpkg", []string{"--audit"}, true},
+ {typedActionCatalogPackage, "apt-get", []string{"update", ";", "sh"}, false},
+ {typedActionCatalogPackage, "apt-get", []string{"autoclean"}, false},
+ {typedActionCatalogPackage, "apt-get", []string{"clean", "--simulate"}, false},
+ {typedActionCatalogPackage, "/tmp/apt-get", []string{"update"}, false},
+ {typedActionCatalogProxmox, "qm", []string{"status", "100"}, true},
+ {typedActionCatalogProxmox, "pct", []string{"reboot", "2147483647"}, true},
+ {typedActionCatalogProxmox, "qm", []string{"start", "01"}, false},
+ {typedActionCatalogProxmox, "qm", []string{"start", "100", "--skiplock"}, false},
+ {typedActionCatalogProxmox, "sh", []string{"-c", "id"}, false},
+ {typedActionCatalogProbe, "true", nil, true},
+ {typedActionCatalogProbe, "true", []string{"--help"}, false},
+ }
+ for _, test := range tests {
+ err := validateTypedActionInvocation(test.catalog, test.name, test.args)
+ if (err == nil) != test.valid {
+ t.Fatalf("validate %s %s %v: err=%v valid=%v", test.catalog, test.name, test.args, err, test.valid)
+ }
+ }
+}