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.

Add least-privilege SSH deploy mode

rcourtmanb33e21e0e8e1
diff --git a/cmd/pulse-agent/main.go b/cmd/pulse-agent/main.go
index 7d24980452..686a32e9be 100644
--- a/cmd/pulse-agent/main.go
+++ b/cmd/pulse-agent/main.go
@@ -287,6 +287,7 @@ func run(ctx context.Context, args []string, getenv func(string) string) error {
InsecureSkipVerify: cfg.InsecureSkipVerify,
CACertPath: cfg.CACertPath,
ServerFingerprint: cfg.ServerFingerprint,
+ DeploySSHUser: cfg.DeploySSHUser,
LogLevel: cfg.LogLevel,
Logger: &logger,
EnableProxmox: cfg.EnableProxmox,
@@ -528,6 +529,7 @@ type Config struct {
InsecureSkipVerify bool
CACertPath string
ServerFingerprint string
+ DeploySSHUser string
LogLevel zerolog.Level
Logger *zerolog.Logger
@@ -584,6 +586,7 @@ func loadConfig(args []string, getenv func(string) string) (Config, error) {
envInsecure := strings.TrimSpace(getenv("PULSE_INSECURE_SKIP_VERIFY"))
envCACertPath := strings.TrimSpace(getenv("PULSE_CACERT"))
envServerFingerprint := strings.TrimSpace(getenv("PULSE_SERVER_FINGERPRINT"))
+ envDeploySSHUser := strings.TrimSpace(getenv("PULSE_DEPLOY_SSH_USER"))
envTags := strings.TrimSpace(getenv("PULSE_TAGS"))
envLogLevel := strings.TrimSpace(getenv("LOG_LEVEL"))
envEnableHost := strings.TrimSpace(getenv("PULSE_ENABLE_HOST"))
@@ -657,6 +660,7 @@ func loadConfig(args []string, getenv func(string) string) (Config, error) {
insecureFlag := fs.Bool("insecure", utils.ParseBool(envInsecure), "Skip TLS verification")
caCertFlag := fs.String("cacert", envCACertPath, "Path to custom CA bundle for agent HTTPS transport")
serverFingerprintFlag := fs.String("server-fingerprint", envServerFingerprint, "Expected Pulse server TLS certificate fingerprint (SHA256)")
+ deploySSHUserFlag := fs.String("deploy-ssh-user", envDeploySSHUser, "SSH user for peer deploy fan-out (default: root; non-root requires passwordless sudo)")
logLevelFlag := fs.String("log-level", defaultLogLevel(envLogLevel), "Log level")
enableHostFlag := fs.Bool("enable-host", defaultEnableHost, "Enable Host Agent module")
@@ -746,6 +750,10 @@ func loadConfig(args []string, getenv func(string) string) (Config, error) {
if err != nil {
return Config{}, err
}
+ deploySSHUser, err := hostagent.NormalizeDeploySSHUser(*deploySSHUserFlag)
+ if err != nil {
+ return Config{}, err
+ }
tags := gatherTags(envTags, tagFlags)
kubeIncludeNamespaces := gatherCSV(envKubeIncludeNamespaces, kubeIncludeNamespaceFlags)
@@ -772,6 +780,7 @@ func loadConfig(args []string, getenv func(string) string) (Config, error) {
InsecureSkipVerify: *insecureFlag,
CACertPath: strings.TrimSpace(*caCertFlag),
ServerFingerprint: strings.TrimSpace(*serverFingerprintFlag),
+ DeploySSHUser: deploySSHUser,
LogLevel: logLevel,
EnableHost: *enableHostFlag,
EnableDocker: *enableDockerFlag,
diff --git a/cmd/pulse-agent/main_test.go b/cmd/pulse-agent/main_test.go
index 85e9640d64..f4e2028ffa 100644
--- a/cmd/pulse-agent/main_test.go
+++ b/cmd/pulse-agent/main_test.go
@@ -806,6 +806,7 @@ func TestLoadConfig(t *testing.T) {
"PULSE_ENABLE_DOCKER": "true",
"PULSE_CACERT": "/etc/pulse/ca.pem",
"PULSE_SERVER_FINGERPRINT": "aabbccdd",
+ "PULSE_DEPLOY_SSH_USER": "pulse-deploy",
}
cfg, err := loadConfig([]string{}, func(s string) string { return env[s] })
if err != nil {
@@ -829,10 +830,13 @@ func TestLoadConfig(t *testing.T) {
if cfg.ServerFingerprint != "aabbccdd" {
t.Errorf("expected server fingerprint from env, got %s", cfg.ServerFingerprint)
}
+ if cfg.DeploySSHUser != "pulse-deploy" {
+ t.Errorf("expected deploy SSH user from env, got %s", cfg.DeploySSHUser)
+ }
})
t.Run("flag overrides", func(t *testing.T) {
- cfg, err := loadConfig([]string{"-url", "http://flag.example.com", "-token", "flag-token", "-enable-host=false", "-cacert", "/tmp/custom-ca.pem", "-server-fingerprint", "1122"}, func(s string) string { return "" })
+ cfg, err := loadConfig([]string{"-url", "http://flag.example.com", "-token", "flag-token", "-enable-host=false", "-cacert", "/tmp/custom-ca.pem", "-server-fingerprint", "1122", "-deploy-ssh-user", "pulse-deploy"}, func(s string) string { return "" })
if err != nil {
t.Fatal(err)
}
@@ -851,6 +855,9 @@ func TestLoadConfig(t *testing.T) {
if cfg.ServerFingerprint != "1122" {
t.Errorf("expected server fingerprint from flag, got %s", cfg.ServerFingerprint)
}
+ if cfg.DeploySSHUser != "pulse-deploy" {
+ t.Errorf("expected deploy SSH user from flag, got %s", cfg.DeploySSHUser)
+ }
})
t.Run("invalid interval flag", func(t *testing.T) {
@@ -888,6 +895,13 @@ func TestLoadConfig(t *testing.T) {
}
})
+ t.Run("invalid deploy ssh user returns error", func(t *testing.T) {
+ _, err := loadConfig([]string{"-token", "test-token", "-deploy-ssh-user", "bad user"}, func(s string) string { return "" })
+ if err == nil {
+ t.Fatal("expected error for invalid deploy SSH user")
+ }
+ })
+
t.Run("show version", func(t *testing.T) {
_, err := loadConfig([]string{"-version"}, func(s string) string { return "" })
if err != flag.ErrHelp {
diff --git a/cmd/pulse-agent/service_windows.go b/cmd/pulse-agent/service_windows.go
index 0b5adc0458..076903760f 100644
--- a/cmd/pulse-agent/service_windows.go
+++ b/cmd/pulse-agent/service_windows.go
@@ -73,6 +73,7 @@ func (ws *windowsService) Execute(args []string, r <-chan svc.ChangeRequest, cha
InsecureSkipVerify: ws.cfg.InsecureSkipVerify,
CACertPath: ws.cfg.CACertPath,
ServerFingerprint: ws.cfg.ServerFingerprint,
+ DeploySSHUser: ws.cfg.DeploySSHUser,
LogLevel: ws.cfg.LogLevel,
Logger: &ws.logger,
}
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 27c7f2dcb8..bd2dca485c 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -1147,6 +1147,11 @@ keys through the managed `ssh_known_hosts` store before any automated deploy
fan-out writes a bootstrap token or runs the installer on a remote node, keep
`StrictHostKeyChecking=yes`, and fail closed on key mismatch or missing-host-
key state instead of downgrading to unauthenticated SSH during install.
+That same boundary also owns least-privilege peer deploy execution: when
+operators configure a non-root SSH user for deploy fan-out, privileged token
+write and install steps must escalate through non-interactive `sudo` on the
+remote node instead of hard-coding `root@` for every SSH hop or silently
+falling back to a second unaudited privilege path.
That same transport boundary also keeps plaintext Pulse URLs loopback-only.
`internal/securityutil/httpurl.go` owns the canonical Pulse transport
normalization used by `internal/hostagent/agent.go`,
diff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.go
index 3d1f9009e4..fee63fbf87 100644
--- a/internal/hostagent/agent.go
+++ b/internal/hostagent/agent.go
@@ -62,6 +62,9 @@ type Config struct {
// State directory for persistent files (agent-id, proxmox registration, etc.)
StateDir string // Default: /var/lib/pulse-agent
+ // Deploy SSH configuration for peer-node install fan-out.
+ DeploySSHUser string // Default: root. Non-root users must support passwordless sudo for install steps.
+
// Network configuration
ReportIP string // IP address to report instead of auto-detected (for multi-NIC systems)
DisableCeph bool // If true, disables local Ceph status polling
@@ -169,6 +172,11 @@ func New(cfg Config) (*Agent, error) {
return nil, err
}
+ cfg.DeploySSHUser, err = NormalizeDeploySSHUser(cfg.DeploySSHUser)
+ if err != nil {
+ return nil, err
+ }
+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
diff --git a/internal/hostagent/agent_new_test.go b/internal/hostagent/agent_new_test.go
index 8f979c8485..efb32ef1b8 100644
--- a/internal/hostagent/agent_new_test.go
+++ b/internal/hostagent/agent_new_test.go
@@ -177,6 +177,7 @@ func TestNewCommandClient_SetsSecureCommandDefaults(t *testing.T) {
client := NewCommandClient(Config{
PulseURL: "https://pulse.example",
ServerFingerprint: "aabbccdd",
+ DeploySSHUser: "pulse-deploy",
Logger: &logger,
}, "agent-1", "node-1", "linux", "1.0.0")
@@ -189,6 +190,9 @@ func TestNewCommandClient_SetsSecureCommandDefaults(t *testing.T) {
if client.serverFingerprint != "aabbccdd" {
t.Fatalf("serverFingerprint = %q, want %q", client.serverFingerprint, "aabbccdd")
}
+ if client.deploySSHUser != "pulse-deploy" {
+ t.Fatalf("deploySSHUser = %q, want %q", client.deploySSHUser, "pulse-deploy")
+ }
if err := client.authorizeCommand(executeCommandPayload{Command: "systemctl restart nginx"}); err == nil || !strings.Contains(err.Error(), "requires approval") {
t.Fatalf("expected approval-required command to fail closed, got %v", err)
@@ -201,6 +205,24 @@ func TestNewCommandClient_SetsSecureCommandDefaults(t *testing.T) {
}
}
+func TestNewRejectsInvalidDeploySSHUser(t *testing.T) {
+ mc := &mockCollector{
+ hostInfoFn: func(context.Context) (*gohost.InfoStat, error) {
+ return &gohost.InfoStat{Hostname: "host", HostID: "hid", KernelArch: runtime.GOARCH}, nil
+ },
+ }
+
+ _, err := New(Config{
+ APIToken: "token",
+ DeploySSHUser: "bad user",
+ LogLevel: zerolog.InfoLevel,
+ Collector: mc,
+ })
+ if err == nil || !strings.Contains(err.Error(), "invalid deploy SSH user") {
+ t.Fatalf("expected invalid deploy SSH user error, got %v", err)
+ }
+}
+
func TestNewCommandClient_BuildWebSocketOriginFollowsCanonicalPulseURL(t *testing.T) {
logger := zerolog.Nop()
diff --git a/internal/hostagent/commands.go b/internal/hostagent/commands.go
index 2b024978e3..59ee4899b0 100644
--- a/internal/hostagent/commands.go
+++ b/internal/hostagent/commands.go
@@ -95,6 +95,7 @@ type CommandClient struct {
insecureSkipVerify bool
caCertPath string
serverFingerprint string
+ deploySSHUser string
commandPolicy *agentexec.CommandPolicy
sshKnownHosts sshknownhosts.Manager
sshKnownHostsOnce sync.Once
@@ -125,6 +126,7 @@ func NewCommandClient(cfg Config, agentID, hostname, platform, version string) *
insecureSkipVerify: cfg.InsecureSkipVerify,
caCertPath: cfg.CACertPath,
serverFingerprint: cfg.ServerFingerprint,
+ deploySSHUser: cfg.DeploySSHUser,
commandPolicy: agentexec.DefaultPolicy(),
logger: logger,
done: make(chan struct{}),
diff --git a/internal/hostagent/commands_deploy.go b/internal/hostagent/commands_deploy.go
index 3e910685b1..9f2340baca 100644
--- a/internal/hostagent/commands_deploy.go
+++ b/internal/hostagent/commands_deploy.go
@@ -6,6 +6,7 @@ import (
"fmt"
"net"
"os/exec"
+ "regexp"
"strings"
"sync"
"time"
@@ -13,6 +14,8 @@ import (
"github.com/gorilla/websocket"
)
+var deploySSHUserPattern = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._-]{0,63}$`)
+
// --- Agent-side payload types (mirrors agentexec types) ---
type deployPreflightPayload struct {
@@ -265,18 +268,26 @@ func (c *CommandClient) preflightTarget(
}
// 1. SSH reachability check.
+ sshCheckMessage := "Checking SSH connectivity"
+ sshFailureDetail := "SSH connection failed"
+ sshSuccessMessage := "SSH reachable"
+ if c.deployRequiresSudo() {
+ sshCheckMessage = fmt.Sprintf("Checking SSH and sudo connectivity as %s", c.deploySSHUserOrDefault())
+ sshFailureDetail = fmt.Sprintf("SSH or sudo access failed for user %s", c.deploySSHUserOrDefault())
+ sshSuccessMessage = fmt.Sprintf("SSH and sudo reachable as %s", c.deploySSHUserOrDefault())
+ }
c.sendDeployProgress(conn, requestID, jobID, target.TargetID,
- "preflight_ssh", "started", "Checking SSH connectivity", "", false)
+ "preflight_ssh", "started", sshCheckMessage, "", false)
sshOK := c.checkSSH(tctx, target.NodeIP)
if !sshOK {
- data := marshalPreflightResult(false, false, false, "", "SSH connection failed")
+ data := marshalPreflightResult(false, false, false, "", sshFailureDetail)
c.sendDeployProgress(conn, requestID, jobID, target.TargetID,
- "preflight_complete", "failed", "SSH check failed", data, false)
+ "preflight_complete", "failed", sshFailureDetail, data, false)
return false
}
c.sendDeployProgress(conn, requestID, jobID, target.TargetID,
- "preflight_ssh", "ok", "SSH reachable", "", false)
+ "preflight_ssh", "ok", sshSuccessMessage, "", false)
// 2. Architecture detection.
c.sendDeployProgress(conn, requestID, jobID, target.TargetID,
@@ -408,6 +419,38 @@ func (c *CommandClient) installTarget(
// --- SSH helpers ---
+// NormalizeDeploySSHUser validates the optional SSH username used for peer-node
+// deploy fan-out. Empty input means "use the canonical root default".
+func NormalizeDeploySSHUser(raw string) (string, error) {
+ user := strings.TrimSpace(raw)
+ if user == "" {
+ return "", nil
+ }
+ if !deploySSHUserPattern.MatchString(user) {
+ return "", fmt.Errorf("invalid deploy SSH user %q", raw)
+ }
+ return user, nil
+}
+
+func (c *CommandClient) deploySSHUserOrDefault() string {
+ user, err := NormalizeDeploySSHUser(c.deploySSHUser)
+ if err != nil || user == "" {
+ return "root"
+ }
+ return user
+}
+
+func (c *CommandClient) deployRequiresSudo() bool {
+ return c.deploySSHUserOrDefault() != "root"
+}
+
+func (c *CommandClient) sshRemoteShellCommand(command string, privileged bool) string {
+ if privileged && c.deployRequiresSudo() {
+ return "sudo -n bash -lc " + shellescape(command)
+ }
+ return "bash -lc " + shellescape(command)
+}
+
func (c *CommandClient) sshCommand(ctx context.Context, nodeIP string, remoteArgs ...string) (*exec.Cmd, error) {
if err := validateNodeIP(nodeIP); err != nil {
return nil, err
@@ -427,15 +470,23 @@ func (c *CommandClient) sshCommand(ctx context.Context, nodeIP string, remoteArg
"-o", fmt.Sprintf("UserKnownHostsFile=%s", hostKeys.Path()),
"-o", "GlobalKnownHostsFile=/dev/null",
"-o", "ConnectTimeout=10",
- fmt.Sprintf("root@%s", nodeIP),
+ fmt.Sprintf("%s@%s", c.deploySSHUserOrDefault(), nodeIP),
}
args = append(args, remoteArgs...)
return execCommandContext(ctx, "ssh", args...), nil
}
+func (c *CommandClient) sshShellCommand(ctx context.Context, nodeIP, command string, privileged bool) (*exec.Cmd, error) {
+ return c.sshCommand(ctx, nodeIP, c.sshRemoteShellCommand(command, privileged))
+}
+
// checkSSH tests basic SSH connectivity to a peer node.
func (c *CommandClient) checkSSH(ctx context.Context, nodeIP string) bool {
- cmd, err := c.sshCommand(ctx, nodeIP, "true")
+ command := "true"
+ if c.deployRequiresSudo() {
+ command = "sudo -n true"
+ }
+ cmd, err := c.sshShellCommand(ctx, nodeIP, command, false)
if err != nil {
c.logger.Warn().Err(err).Str("node_ip", nodeIP).Msg("SSH connectivity check refused before execution")
return false
@@ -445,7 +496,7 @@ func (c *CommandClient) checkSSH(ctx context.Context, nodeIP string) bool {
// detectArchSSH detects the architecture of a remote node via SSH.
func (c *CommandClient) detectArchSSH(ctx context.Context, nodeIP string) string {
- cmd, err := c.sshCommand(ctx, nodeIP, "uname -m")
+ cmd, err := c.sshShellCommand(ctx, nodeIP, "uname -m", false)
if err != nil {
c.logger.Warn().Err(err).Str("node_ip", nodeIP).Msg("SSH arch detection refused before execution")
return ""
@@ -467,7 +518,7 @@ func (c *CommandClient) detectArchSSH(ctx context.Context, nodeIP string) string
// checkExistingAgentSSH checks if a Pulse agent is already installed on the target.
func (c *CommandClient) checkExistingAgentSSH(ctx context.Context, nodeIP string) bool {
- cmd, err := c.sshCommand(ctx, nodeIP, "systemctl is-active pulse-agent 2>/dev/null || test -f /usr/local/bin/pulse-agent")
+ cmd, err := c.sshShellCommand(ctx, nodeIP, "systemctl is-active pulse-agent 2>/dev/null || test -f /usr/local/bin/pulse-agent", false)
if err != nil {
c.logger.Warn().Err(err).Str("node_ip", nodeIP).Msg("SSH existing-agent check refused before execution")
return false
@@ -478,7 +529,7 @@ func (c *CommandClient) checkExistingAgentSSH(ctx context.Context, nodeIP string
// checkPulseReachabilitySSH checks if the peer can reach the Pulse URL.
func (c *CommandClient) checkPulseReachabilitySSH(ctx context.Context, nodeIP, pulseURL string) bool {
// Use curl with a short timeout to check connectivity.
- cmd, err := c.sshCommand(ctx, nodeIP, fmt.Sprintf("curl -sf --connect-timeout 5 -o /dev/null %s/api/health || wget -q --timeout=5 -O /dev/null %s/api/health 2>/dev/null", shellescape(pulseURL), shellescape(pulseURL)))
+ cmd, err := c.sshShellCommand(ctx, nodeIP, fmt.Sprintf("curl -sf --connect-timeout 5 -o /dev/null %s/api/health || wget -q --timeout=5 -O /dev/null %s/api/health 2>/dev/null", shellescape(pulseURL), shellescape(pulseURL)), false)
if err != nil {
c.logger.Warn().Err(err).Str("node_ip", nodeIP).Msg("SSH Pulse reachability check refused before execution")
return false
@@ -488,7 +539,7 @@ func (c *CommandClient) checkPulseReachabilitySSH(ctx context.Context, nodeIP, p
// writeTokenSSH writes a bootstrap token to a secure path on the target via SSH stdin.
func (c *CommandClient) writeTokenSSH(ctx context.Context, nodeIP, token string) error {
- cmd, err := c.sshCommand(ctx, nodeIP, "mkdir -p /run/pulse-agent && cat > /run/pulse-agent/bootstrap.token && chmod 600 /run/pulse-agent/bootstrap.token")
+ cmd, err := c.sshShellCommand(ctx, nodeIP, "mkdir -p /run/pulse-agent && cat > /run/pulse-agent/bootstrap.token && chmod 600 /run/pulse-agent/bootstrap.token", true)
if err != nil {
return err
}
@@ -514,8 +565,7 @@ func (c *CommandClient) runInstallSSH(ctx context.Context, nodeIP, pulseURL stri
"set -o pipefail; curl -sfL -- %s/install.sh | bash -s -- --non-interactive --token-file /run/pulse-agent/bootstrap.token --pulse-url %s --enroll --enable-commands --enable-proxmox",
escapedURL, escapedURL,
)
- remoteCmd := "bash -c " + shellescape(innerCmd)
- cmd, err := c.sshCommand(ctx, nodeIP, remoteCmd)
+ cmd, err := c.sshShellCommand(ctx, nodeIP, innerCmd, true)
if err != nil {
return -1, "", err
}
diff --git a/internal/hostagent/commands_deploy_test.go b/internal/hostagent/commands_deploy_test.go
index 7f4ad01b5f..41ebec5631 100644
--- a/internal/hostagent/commands_deploy_test.go
+++ b/internal/hostagent/commands_deploy_test.go
@@ -61,6 +61,40 @@ func TestValidateNodeIP(t *testing.T) {
}
}
+func TestNormalizeDeploySSHUser(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ want string
+ wantErr bool
+ }{
+ {name: "empty defaults to root", input: "", want: ""},
+ {name: "trimmed user", input: " pulse-deploy ", want: "pulse-deploy"},
+ {name: "underscore and dot", input: "ec2_user.ops", want: "ec2_user.ops"},
+ {name: "reject host separator", input: "user@example", wantErr: true},
+ {name: "reject option style", input: "-root", wantErr: true},
+ {name: "reject whitespace", input: "bad user", wantErr: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := NormalizeDeploySSHUser(tt.input)
+ if tt.wantErr {
+ if err == nil {
+ t.Fatalf("expected error for %q", tt.input)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("NormalizeDeploySSHUser(%q): %v", tt.input, err)
+ }
+ if got != tt.want {
+ t.Fatalf("NormalizeDeploySSHUser(%q) = %q, want %q", tt.input, got, tt.want)
+ }
+ })
+ }
+}
+
func TestMakeSemaphore(t *testing.T) {
// Zero/negative defaults to 1.
sem := makeSemaphore(0)
@@ -178,6 +212,9 @@ func TestRunInstallSSH_IncludesEnrollAndEnableCommands(t *testing.T) {
if !strings.Contains(joined, "GlobalKnownHostsFile=/dev/null") {
t.Error("SSH install command does not isolate global known_hosts state")
}
+ if !strings.Contains(joined, "[email protected]") {
+ t.Error("SSH install command does not default to root user")
+ }
}
func TestRunInstallSSH_RejectsNonLoopbackPlainHTTP(t *testing.T) {
@@ -190,3 +227,71 @@ func TestRunInstallSSH_RejectsNonLoopbackPlainHTTP(t *testing.T) {
t.Fatal("expected non-loopback plain HTTP Pulse URL to be rejected")
}
}
+
+func TestRunInstallSSH_UsesConfiguredDeploySSHUserWithSudo(t *testing.T) {
+ origExec := execCommandContext
+ defer func() { execCommandContext = origExec }()
+
+ var capturedArgs []string
+ execCommandContext = func(ctx context.Context, name string, args ...string) *exec.Cmd {
+ capturedArgs = append([]string{name}, args...)
+ return exec.Command("true")
+ }
+
+ c := &CommandClient{
+ deploySSHUser: "pulse-deploy",
+ logger: zerolog.New(zerolog.NewTestWriter(t)),
+ sshKnownHosts: stubKnownHostsManager{path: "/tmp/pulse-test-known-hosts"},
+ }
+
+ exitCode, _, err := c.runInstallSSH(context.Background(), "10.0.0.1", "https://10.0.0.1:7655")
+ if err != nil {
+ t.Fatalf("runInstallSSH error: %v", err)
+ }
+ if exitCode != 0 {
+ t.Fatalf("expected exit code 0, got %d", exitCode)
+ }
+
+ joined := strings.Join(capturedArgs, " ")
+ if !strings.Contains(joined, "[email protected]") {
+ t.Fatalf("SSH install command missing configured deploy user: %s", joined)
+ }
+ if strings.Contains(joined, "[email protected]") {
+ t.Fatalf("SSH install command unexpectedly used root user: %s", joined)
+ }
+ if !strings.Contains(joined, "sudo -n bash -lc") {
+ t.Fatalf("SSH install command missing sudo escalation for non-root deploy user: %s", joined)
+ }
+}
+
+func TestWriteTokenSSH_UsesConfiguredDeploySSHUserWithSudo(t *testing.T) {
+ origExec := execCommandContext
+ defer func() { execCommandContext = origExec }()
+
+ var capturedArgs []string
+ execCommandContext = func(ctx context.Context, name string, args ...string) *exec.Cmd {
+ capturedArgs = append([]string{name}, args...)
+ return exec.Command("true")
+ }
+
+ c := &CommandClient{
+ deploySSHUser: "pulse-deploy",
+ logger: zerolog.New(zerolog.NewTestWriter(t)),
+ sshKnownHosts: stubKnownHostsManager{path: "/tmp/pulse-test-known-hosts"},
+ }
+
+ if err := c.writeTokenSSH(context.Background(), "10.0.0.1", "token"); err != nil {
+ t.Fatalf("writeTokenSSH error: %v", err)
+ }
+
+ joined := strings.Join(capturedArgs, " ")
+ if !strings.Contains(joined, "[email protected]") {
+ t.Fatalf("SSH token write missing configured deploy user: %s", joined)
+ }
+ if !strings.Contains(joined, "sudo -n bash -lc") {
+ t.Fatalf("SSH token write missing sudo escalation for non-root deploy user: %s", joined)
+ }
+ if !strings.Contains(joined, "/run/pulse-agent/bootstrap.token") {
+ t.Fatalf("SSH token write missing bootstrap token target path: %s", joined)
+ }
+}