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.

Harden agent command and deploy trust boundaries

rcourtman3ec2c0779e06
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index fe425e9264..3feba168b9 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -1081,6 +1081,12 @@ runtime may not keep `.bootstrap_token` as an unstructured plaintext secret
file after startup. Canonical persistence must encrypt the bootstrap token at
rest and rewrite any legacy plaintext bootstrap-token file immediately into
the encrypted canonical format on load.
+That same deploy/install runtime boundary also owns peer-node SSH trust.
+`internal/hostagent/commands_deploy.go` must resolve and persist peer host
+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 shared `internal/api/` lifecycle boundary also assumes tenant-scoped
resource helpers stay on canonical unified-resource seeds: adjacent fleet and
install surfaces may not revive raw tenant `StateSnapshot` fallback through
@@ -1979,6 +1985,13 @@ enables insecure TLS mode or Pulse command execution, the PowerShell path must
carry `PULSE_INSECURE_SKIP_VERIFY` and `PULSE_ENABLE_COMMANDS` through to the
installer where those settings apply, so Windows agents do not diverge from the
governed shell transport.
+That same command-enabled lifecycle path must still enforce the shared command
+policy on the agent itself. `internal/hostagent/commands.go` may accept the
+installed command-execution capability, but it must re-evaluate
+`internal/agentexec/policy.go` immediately before `sh -c`, reject
+`PolicyBlock` commands regardless of caller, and require a consumed approval
+identifier before executing any `PolicyRequireApproval` command so a missed
+control-plane gate cannot silently turn into host-level RCE.
That same copied install transport must also normalize canonical base URLs
before composing installer asset paths: when operators enter a trailing-slash
Pulse URL, shell and PowerShell install commands must trim it before appending
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index f5f3738160..d7966eb6b4 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -360,6 +360,13 @@ was disabled at process boot. The approval cleanup loop must follow owned AI
runtime lifetime rather than an HTTP request context, and approval persistence
may fail closed only when AI is actually disabled instead of because runtime
enablement happened after startup.
+That same approval boundary also owns approved command execution. When
+`internal/api/ai_handlers.go`, `internal/ai/service.go`, or
+`internal/ai/tools/action_audit.go` consume a governed approval record, the
+runtime must carry that approval identifier into the final
+`agentexec.ExecuteCommandPayload` so the host agent can re-check the shared
+command policy locally and fail closed on blocked or still-unapproved commands
+instead of treating control-plane approval as an implicit bypass.
The same ownership includes the Pulse query tool schema under
`internal/ai/tools/`: topology-query input names must stay canonical inside
the AI runtime itself, so new tool arguments such as `max_proxmox_nodes`
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 232e487392..d168b9852e 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -228,6 +228,15 @@ the canonical monitored-system blocked payload.
target. When an explicit `targetHost` misses that canonical match, the
shared relay adapter must keep the result empty instead of silently
falling back to the lone connected agent.
+ That same shared runtime-token boundary also owns agent-exec binding.
+ `internal/api/deploy_handlers.go`, `internal/api/router.go`, and
+ `internal/api/contract_test.go` must mint agent-exec-capable runtime
+ tokens with a server-owned `bound_agent_id` and reject websocket
+ registration when the token is missing binding metadata or names a
+ different agent. Legacy `bound_hostname` metadata may be normalized only
+ as compatibility input into that same canonical `agent-<hostname>`
+ binding, and unbound agent-exec tokens must fail closed instead of being
+ treated as global command authority.
21. Keep hosted billing-state quickstart payload fields on the shared API contract: `internal/api/hosted_entitlement_refresh.go`, `internal/api/subscription_state_handlers.go`, and `internal/api/contract_test.go` must preserve `quickstart_credits_granted`, `quickstart_credits_used`, and `quickstart_credits_granted_at` through hosted signup, hosted lease refresh, and billing-state reads instead of letting lease rewrites silently erase seeded quickstart inventory.
22. Keep hosted AI settings bootstrap on the shared API contract: `internal/api/ai_hosted_runtime.go`, `internal/api/ai_handlers.go`, `internal/api/ai_handler.go`, and `internal/api/contract_test.go` must treat a missing `ai.enc` in hosted mode as a canonical bootstrap condition, persist one machine-owned quickstart-backed AI config with the Pulse-owned alias `quickstart:pulse-hosted` when hosted entitlements grant AI capability, and preserve that configured settings payload as the same public contract that Chat, Patrol, and AI Settings consume instead of embedding a third-party model ID in the transport contract.
That same hosted bootstrap surface must also preserve the secure quickstart-identity contract: hosted or trial-backed AI settings reads and enablement may bootstrap Patrol quickstart from the effective signed entitlement lease when no self-hosted installation token exists, but they must not fabricate installation-scoped activation state or anonymous client identity to satisfy `/v1/quickstart/bootstrap`.
diff --git a/internal/agentexec/server.go b/internal/agentexec/server.go
index 9153e8bffa..f2f2a24be8 100644
--- a/internal/agentexec/server.go
+++ b/internal/agentexec/server.go
@@ -61,6 +61,7 @@ type Server struct {
pendingReqs map[string]chan CommandResultPayload // scoped request key -> response channel
deploySubs map[string]chan DeployProgressPayload // deploySubKey(agentID, jobID) -> progress subscriber
validateToken func(token string, agentID string) bool
+ commandPolicy *CommandPolicy
shutdown chan struct{}
shutdownOnce sync.Once
pingInterval time.Duration
@@ -86,11 +87,16 @@ func (ac *agentConn) signalDone() {
// NewServer creates a new agent execution server
func NewServer(validateToken func(token string, agentID string) bool) *Server {
+ if validateToken == nil {
+ panic("agentexec: validateToken is required")
+ }
+
return &Server{
agents: make(map[string]*agentConn),
pendingReqs: make(map[string]chan CommandResultPayload),
deploySubs: make(map[string]chan DeployProgressPayload),
validateToken: validateToken,
+ commandPolicy: DefaultPolicy(),
shutdown: make(chan struct{}),
pingInterval: defaultPingInterval,
}
@@ -148,6 +154,7 @@ func validateExecuteCommandPayload(cmd *ExecuteCommandPayload) error {
if strings.TrimSpace(cmd.Command) == "" {
return fmt.Errorf("command is required")
}
+ cmd.ApprovalID = strings.TrimSpace(cmd.ApprovalID)
if len(cmd.Command) > maxExecuteCommandLength {
return fmt.Errorf("command exceeds %d characters", maxExecuteCommandLength)
}
@@ -169,6 +176,23 @@ func validateExecuteCommandPayload(cmd *ExecuteCommandPayload) error {
return nil
}
+func (s *Server) authorizeCommandPayload(cmd ExecuteCommandPayload) error {
+ if s == nil || s.commandPolicy == nil {
+ return nil
+ }
+
+ switch s.commandPolicy.Evaluate(cmd.Command) {
+ case PolicyBlock:
+ return fmt.Errorf("command blocked by policy")
+ case PolicyRequireApproval:
+ if cmd.ApprovalID == "" {
+ return fmt.Errorf("command requires approval")
+ }
+ }
+
+ return nil
+}
+
func validateReadFilePayload(req *ReadFilePayload) error {
if req == nil {
return fmt.Errorf("read file payload is required")
@@ -353,7 +377,7 @@ func (s *Server) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
}
// Validate token
- if s.validateToken != nil && !s.validateToken(reg.Token, reg.AgentID) {
+ if !s.validateToken(reg.Token, reg.AgentID) {
log.Warn().Str("agent_id", reg.AgentID).Msg("Agent registration rejected: invalid token")
rejectedMsg, err := NewMessage(MsgTypeRegistered, "", RegisteredPayload{Success: false, Message: "Invalid token"})
if err != nil {
@@ -777,6 +801,9 @@ func (s *Server) ExecuteCommand(ctx context.Context, agentID string, cmd Execute
Msg("Execute command requested for disconnected agent")
return nil, fmt.Errorf("agent %s not connected", agentID)
}
+ if err := s.authorizeCommandPayload(cmd); err != nil {
+ return nil, err
+ }
execLog := log.With().
Str("agent_id", agentID).
diff --git a/internal/agentexec/server_coverage_test.go b/internal/agentexec/server_coverage_test.go
index 4336d7cf95..d6b2131113 100644
--- a/internal/agentexec/server_coverage_test.go
+++ b/internal/agentexec/server_coverage_test.go
@@ -65,13 +65,13 @@ func newConnPair(t *testing.T) (*websocket.Conn, *websocket.Conn, func()) {
}
func TestHandleWebSocket_UpgradeFailureAndDeadlineErrors(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
req := httptest.NewRequest(http.MethodGet, "http://example/ws", nil)
s.HandleWebSocket(&noHijackResponseWriter{header: make(http.Header)}, req)
}
func TestHandleWebSocket_RegistrationReadError(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
@@ -83,7 +83,7 @@ func TestHandleWebSocket_RegistrationReadError(t *testing.T) {
}
func TestHandleWebSocket_RegistrationMessageJSONError(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
@@ -104,7 +104,7 @@ func TestHandleWebSocket_RegistrationMessageJSONError(t *testing.T) {
}
func TestHandleWebSocket_RegistrationPayloadMissing(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
@@ -123,7 +123,7 @@ func TestHandleWebSocket_RegistrationPayloadMissing(t *testing.T) {
}
func TestHandleWebSocket_RegistrationPayloadUnmarshalError(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
@@ -180,7 +180,7 @@ func TestHandleWebSocket_RegistrationAckSendFailure(t *testing.T) {
return errors.New("write failure")
}
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
@@ -208,7 +208,7 @@ func TestHandleWebSocket_RegistrationAckSendFailure(t *testing.T) {
}
func TestHandleWebSocket_PongHandler(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
@@ -234,7 +234,7 @@ func TestHandleWebSocket_PongHandler(t *testing.T) {
}
func TestReadLoopDone(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
serverConn, clientConn, cleanup := newConnPair(t)
defer cleanup()
@@ -258,7 +258,7 @@ func TestReadLoopDone(t *testing.T) {
}
func TestReadLoopUnexpectedCloseError(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
serverConn, clientConn, cleanup := newConnPair(t)
defer cleanup()
@@ -292,7 +292,7 @@ func TestReadLoopUnexpectedCloseError(t *testing.T) {
}
func TestReadLoopCommandResultBranches(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
serverConn, clientConn, cleanup := newConnPair(t)
defer cleanup()
@@ -338,7 +338,7 @@ func TestReadLoopAgentPingPongSendFailure(t *testing.T) {
return errors.New("write failure")
}
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
serverConn, clientConn, cleanup := newConnPair(t)
defer cleanup()
@@ -381,7 +381,7 @@ func TestReadLoopAgentPingPongSendFailure(t *testing.T) {
}
func TestPingLoopSuccessAndStop(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
s.pingInterval = 5 * time.Millisecond
serverConn, _, cleanup := newConnPair(t)
defer cleanup()
@@ -410,7 +410,7 @@ func TestPingLoopSuccessAndStop(t *testing.T) {
}
func TestPingLoopFailuresClose(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
s.pingInterval = 5 * time.Millisecond
serverConn, _, cleanup := newConnPair(t)
defer cleanup()
@@ -438,14 +438,14 @@ func TestPingLoopFailuresClose(t *testing.T) {
}
func TestSendMessageMarshalError(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
if err := s.sendMessage(nil, Message{Payload: json.RawMessage("{")}); err == nil {
t.Fatalf("expected marshal error")
}
}
func TestExecuteCommandSendError(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
serverConn, _, cleanup := newConnPair(t)
defer cleanup()
@@ -461,9 +461,10 @@ func TestExecuteCommandSendError(t *testing.T) {
s.mu.Unlock()
_, err := s.ExecuteCommand(context.Background(), "a1", ExecuteCommandPayload{
- RequestID: "r1",
- Command: "echo ok",
- Timeout: 1,
+ RequestID: "r1",
+ Command: "echo ok",
+ ApprovalID: "approval-1",
+ Timeout: 1,
})
if err == nil {
t.Fatalf("expected send error")
@@ -471,7 +472,7 @@ func TestExecuteCommandSendError(t *testing.T) {
}
func TestExecuteCommandTimeoutAndCancel(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
serverConn, _, cleanup := newConnPair(t)
defer cleanup()
@@ -485,9 +486,10 @@ func TestExecuteCommandTimeoutAndCancel(t *testing.T) {
s.mu.Unlock()
_, err := s.ExecuteCommand(context.Background(), "a1", ExecuteCommandPayload{
- RequestID: "r-timeout",
- Command: "echo ok",
- Timeout: 1,
+ RequestID: "r-timeout",
+ Command: "echo ok",
+ ApprovalID: "approval-1",
+ Timeout: 1,
})
if err == nil || !strings.Contains(err.Error(), "timed out") {
t.Fatalf("expected timeout error, got %v", err)
@@ -496,9 +498,10 @@ func TestExecuteCommandTimeoutAndCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err = s.ExecuteCommand(ctx, "a1", ExecuteCommandPayload{
- RequestID: "r-cancel",
- Command: "echo ok",
- Timeout: 1,
+ RequestID: "r-cancel",
+ Command: "echo ok",
+ ApprovalID: "approval-1",
+ Timeout: 1,
})
if err == nil {
t.Fatalf("expected cancel error")
@@ -506,7 +509,7 @@ func TestExecuteCommandTimeoutAndCancel(t *testing.T) {
}
func TestExecuteCommandDefaultTimeout(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
serverConn, _, cleanup := newConnPair(t)
defer cleanup()
@@ -533,8 +536,9 @@ func TestExecuteCommandDefaultTimeout(t *testing.T) {
}()
result, err := s.ExecuteCommand(context.Background(), "a1", ExecuteCommandPayload{
- RequestID: "r-default",
- Command: "echo ok",
+ RequestID: "r-default",
+ Command: "echo ok",
+ ApprovalID: "approval-1",
})
if err != nil || result == nil || !result.Success {
t.Fatalf("expected success, got result=%v err=%v", result, err)
@@ -542,7 +546,7 @@ func TestExecuteCommandDefaultTimeout(t *testing.T) {
}
func TestReadFileRoundTrip(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
@@ -603,7 +607,7 @@ func TestReadFileTimeoutCancelAndSendError(t *testing.T) {
t.Cleanup(func() { readFileTimeout = origTimeout })
readFileTimeout = 10 * time.Millisecond
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
serverConn, _, cleanup := newConnPair(t)
defer cleanup()
@@ -642,7 +646,7 @@ func TestReadFileTimeoutCancelAndSendError(t *testing.T) {
}
func TestShutdownRejectsNewWebSocketConnections(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
s.Shutdown()
ts := newWSServer(t, s)
defer ts.Close()
@@ -664,7 +668,7 @@ func TestShutdownRejectsNewWebSocketConnections(t *testing.T) {
}
func TestShutdownClosesActiveConnectionsAndIsIdempotent(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
@@ -698,7 +702,7 @@ func TestShutdownClosesActiveConnectionsAndIsIdempotent(t *testing.T) {
func TestExecuteCommandAndReadFileReturnShutdownError(t *testing.T) {
t.Run("execute_command", func(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
serverConn, _, cleanup := newConnPair(t)
defer cleanup()
@@ -713,7 +717,7 @@ func TestExecuteCommandAndReadFileReturnShutdownError(t *testing.T) {
errCh := make(chan error, 1)
go func() {
- _, err := s.ExecuteCommand(context.Background(), "a1", ExecuteCommandPayload{RequestID: "r-shutdown", Command: "echo test", Timeout: 60})
+ _, err := s.ExecuteCommand(context.Background(), "a1", ExecuteCommandPayload{RequestID: "r-shutdown", Command: "echo test", ApprovalID: "approval-1", Timeout: 60})
errCh <- err
}()
@@ -731,7 +735,7 @@ func TestExecuteCommandAndReadFileReturnShutdownError(t *testing.T) {
})
t.Run("read_file", func(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
serverConn, _, cleanup := newConnPair(t)
defer cleanup()
diff --git a/internal/agentexec/server_test.go b/internal/agentexec/server_test.go
index e709bc0ece..038a18101a 100644
--- a/internal/agentexec/server_test.go
+++ b/internal/agentexec/server_test.go
@@ -7,8 +7,20 @@ import (
"time"
)
+func allowAllTestTokens(string, string) bool { return true }
+
+func TestNewServerRequiresValidateToken(t *testing.T) {
+ defer func() {
+ if recover() == nil {
+ t.Fatal("expected panic when validateToken is nil")
+ }
+ }()
+
+ _ = NewServer(nil)
+}
+
func TestExecuteCommandAgentNotConnected(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
_, err := s.ExecuteCommand(context.Background(), "missing", ExecuteCommandPayload{RequestID: "r1", Timeout: 1})
if err == nil {
t.Fatalf("expected error when agent not connected")
@@ -16,7 +28,7 @@ func TestExecuteCommandAgentNotConnected(t *testing.T) {
}
func TestReadFileAgentNotConnected(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
_, err := s.ReadFile(context.Background(), "missing", ReadFilePayload{RequestID: "r1"})
if err == nil {
t.Fatalf("expected error when agent not connected")
@@ -24,7 +36,7 @@ func TestReadFileAgentNotConnected(t *testing.T) {
}
func TestExecuteCommandValidation(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
if _, err := s.ExecuteCommand(context.Background(), "", ExecuteCommandPayload{RequestID: "r1"}); err == nil {
t.Fatalf("expected empty agent id error")
}
@@ -34,7 +46,7 @@ func TestExecuteCommandValidation(t *testing.T) {
}
func TestExecuteCommandSecurityValidation(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
cases := []struct {
name string
@@ -131,8 +143,32 @@ func TestExecuteCommandSecurityValidation(t *testing.T) {
}
}
+func TestExecuteCommandSecurityValidation_RequiresApprovalIDWhenPolicyRequiresApproval(t *testing.T) {
+ s := NewServer(allowAllTestTokens)
+ serverConn, _, cleanup := newConnPair(t)
+ defer cleanup()
+
+ ac := &agentConn{
+ conn: serverConn,
+ agent: ConnectedAgent{AgentID: "a1"},
+ done: make(chan struct{}),
+ }
+ s.mu.Lock()
+ s.agents["a1"] = ac
+ s.mu.Unlock()
+
+ _, err := s.ExecuteCommand(context.Background(), "a1", ExecuteCommandPayload{
+ RequestID: "r1",
+ Command: "echo ok",
+ Timeout: 1,
+ })
+ if err == nil || !strings.Contains(err.Error(), "requires approval") {
+ t.Fatalf("expected approval-required error, got %v", err)
+ }
+}
+
func TestReadFileValidation(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
if _, err := s.ReadFile(context.Background(), "", ReadFilePayload{RequestID: "r1"}); err == nil {
t.Fatalf("expected empty agent id error")
}
@@ -142,7 +178,7 @@ func TestReadFileValidation(t *testing.T) {
}
func TestReadFileSecurityValidation(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
cases := []struct {
name string
@@ -232,7 +268,7 @@ func TestReadFileSecurityValidation(t *testing.T) {
}
func TestConnectedAgentLookups(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
now := time.Now().Add(-1 * time.Minute)
s.mu.Lock()
@@ -262,7 +298,7 @@ func TestConnectedAgentLookups(t *testing.T) {
}
func TestGetAgentForHostNormalizesFQDNAndCase(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
now := time.Now().Add(-1 * time.Minute)
s.mu.Lock()
@@ -283,7 +319,7 @@ func TestGetAgentForHostNormalizesFQDNAndCase(t *testing.T) {
}
func TestGetAgentForHostKeepsDistinctFQDNsSeparate(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
now := time.Now().Add(-1 * time.Minute)
s.mu.Lock()
diff --git a/internal/agentexec/server_websocket_test.go b/internal/agentexec/server_websocket_test.go
index 0eca3df58e..a305be0d8d 100644
--- a/internal/agentexec/server_websocket_test.go
+++ b/internal/agentexec/server_websocket_test.go
@@ -165,7 +165,7 @@ func TestHandleWebSocket_InvalidTokenRejected(t *testing.T) {
}
func TestHandleWebSocket_MissingAgentIDRejected(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
@@ -196,7 +196,7 @@ func TestHandleWebSocket_MissingAgentIDRejected(t *testing.T) {
}
func TestHandleWebSocket_FirstMessageMustBeRegister(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
@@ -216,7 +216,7 @@ func TestHandleWebSocket_FirstMessageMustBeRegister(t *testing.T) {
}
func TestHandleWebSocket_RejectsOversizedRegistrationMessage(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
@@ -239,7 +239,7 @@ func TestHandleWebSocket_RejectsOversizedRegistrationMessage(t *testing.T) {
}
func TestHandleWebSocket_AgentPingRespondsWithPong(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
@@ -267,7 +267,7 @@ func TestHandleWebSocket_AgentPingRespondsWithPong(t *testing.T) {
}
func TestExecuteCommand_RoundTripViaWebSocket(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
@@ -328,9 +328,10 @@ func TestExecuteCommand_RoundTripViaWebSocket(t *testing.T) {
defer cancel()
result, err := s.ExecuteCommand(ctx, "a1", ExecuteCommandPayload{
- RequestID: "req1",
- Command: "echo ok",
- Timeout: 1,
+ RequestID: "req1",
+ Command: "echo ok",
+ ApprovalID: "approval-1",
+ Timeout: 1,
})
if err != nil {
t.Fatalf("ExecuteCommand: %v", err)
@@ -351,7 +352,7 @@ func TestExecuteCommand_RoundTripViaWebSocket(t *testing.T) {
}
func TestHandleWebSocket_ReconnectSameAgentIDClosesOldConnection(t *testing.T) {
- s := NewServer(nil)
+ s := NewServer(allowAllTestTokens)
ts := newWSServer(t, s)
defer ts.Close()
diff --git a/internal/agentexec/types.go b/internal/agentexec/types.go
index 1c242e3b57..73f680ff2c 100644
--- a/internal/agentexec/types.go
+++ b/internal/agentexec/types.go
@@ -92,6 +92,7 @@ type RegisteredPayload struct {
type ExecuteCommandPayload struct {
RequestID string `json:"request_id"`
Command string `json:"command"`
+ ApprovalID string `json:"approval_id,omitempty"`
TargetType string `json:"target_type"` // "agent", "container", "vm"
TargetID string `json:"target_id,omitempty"` // VMID for container/VM
Timeout int `json:"timeout,omitempty"` // seconds, 0 = default
diff --git a/internal/ai/discovery_adapter_test.go b/internal/ai/discovery_adapter_test.go
index 25774eb368..9d00631739 100644
--- a/internal/ai/discovery_adapter_test.go
+++ b/internal/ai/discovery_adapter_test.go
@@ -50,7 +50,7 @@ func TestDiscoveryCommandAdapter_NilServer(t *testing.T) {
}
func TestDiscoveryCommandAdapter_ExecuteCommandNotConnected(t *testing.T) {
- server := agentexec.NewServer(nil)
+ server := agentexec.NewServer(func(string, string) bool { return true })
adapter := newDiscoveryCommandAdapter(server)
cmd := servicediscovery.ExecuteCommandPayload{
@@ -76,7 +76,7 @@ func TestDiscoveryCommandAdapter_ExecuteCommandNotConnected(t *testing.T) {
}
func TestDiscoveryCommandAdapter_ConnectedAgentsAndLookup(t *testing.T) {
- server := agentexec.NewServer(nil)
+ server := agentexec.NewServer(func(string, string) bool { return true })
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
server.HandleWebSocket(w, r)
}))
@@ -153,7 +153,7 @@ func TestDiscoveryCommandAdapter_ConnectedAgentsAndLookup(t *testing.T) {
}
func TestDiscoveryCommandAdapter_ExecuteCommandSuccess(t *testing.T) {
- server := agentexec.NewServer(nil)
+ server := agentexec.NewServer(func(string, string) bool { return true })
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
server.HandleWebSocket(w, r)
}))
diff --git a/internal/ai/patrol_prober_test.go b/internal/ai/patrol_prober_test.go
index 8fde611d0d..de652306b9 100644
--- a/internal/ai/patrol_prober_test.go
+++ b/internal/ai/patrol_prober_test.go
@@ -82,7 +82,7 @@ func TestAgentExecProber_PingGuestsNilServer(t *testing.T) {
}
func TestAgentExecProber_PingGuestsEmptyIPs(t *testing.T) {
- prober := NewAgentExecProber(agentexec.NewServer(nil))
+ prober := NewAgentExecProber(agentexec.NewServer(func(string, string) bool { return true }))
results, err := prober.PingGuests(context.Background(), "agent-1", nil)
if err != nil {
t.Fatalf("PingGuests with empty ips returned error: %v", err)
@@ -93,7 +93,7 @@ func TestAgentExecProber_PingGuestsEmptyIPs(t *testing.T) {
}
func TestAgentExecProber_RoundTripViaAgentExecServer(t *testing.T) {
- server := agentexec.NewServer(nil)
+ server := agentexec.NewServer(func(string, string) bool { return true })
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
server.HandleWebSocket(w, r)
}))
diff --git a/internal/ai/service.go b/internal/ai/service.go
index cbf14ac71d..671bee9d72 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -3911,6 +3911,10 @@ func extractVMIDFromContext(ctx map[string]interface{}) (string, bool) {
// executeOnAgent executes a command via the agent WebSocket
func (s *Service) executeOnAgent(ctx context.Context, req ExecuteRequest, command string) (string, error) {
+ return s.executeOnAgentWithApproval(ctx, req, command, "")
+}
+
+func (s *Service) executeOnAgentWithApproval(ctx context.Context, req ExecuteRequest, command, approvalID string) (string, error) {
if s.agentServer == nil {
return "", fmt.Errorf("agent server not available")
}
@@ -3984,6 +3988,7 @@ func (s *Service) executeOnAgent(ctx context.Context, req ExecuteRequest, comman
cmd := agentexec.ExecuteCommandPayload{
RequestID: requestID,
Command: command,
+ ApprovalID: strings.TrimSpace(approvalID),
TargetType: dispatchTargetType,
TargetID: targetID,
Timeout: 300, // 5 minutes - commands like du, backups, etc. can take a while
@@ -4064,7 +4069,7 @@ func (s *Service) RunCommand(ctx context.Context, req RunCommandRequest) (*RunCo
Msg("RunCommand using explicit target_host for routing")
}
- output, err := s.executeOnAgent(ctx, execReq, req.Command)
+ output, err := s.executeOnAgentWithApproval(ctx, execReq, req.Command, req.ApprovalID)
if err != nil {
return &RunCommandResponse{
Success: false,
diff --git a/internal/ai/service_extended_test.go b/internal/ai/service_extended_test.go
index b00e799e37..e0f4ed049f 100644
--- a/internal/ai/service_extended_test.go
+++ b/internal/ai/service_extended_test.go
@@ -292,14 +292,20 @@ func TestService_RunCommandExtended(t *testing.T) {
AgentID: "agent-1",
Hostname: "node-1",
}
+ var executed agentexec.ExecuteCommandPayload
mockServer := &mockAgentServer{
agents: []agentexec.ConnectedAgent{mockAgent},
+ executeFunc: func(ctx context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error) {
+ executed = cmd
+ return &agentexec.CommandResultPayload{Success: true, Stdout: "Mock output"}, nil
+ },
}
svc := NewService(nil, mockServer)
// Successful run
resp, err := svc.RunCommand(context.Background(), RunCommandRequest{
Command: "uptime",
+ ApprovalID: "approval-1",
TargetType: "agent",
TargetHost: "node-1",
})
@@ -312,6 +318,9 @@ func TestService_RunCommandExtended(t *testing.T) {
if resp.Output != "Mock output" {
t.Errorf("Unexpected output: %s", resp.Output)
}
+ if executed.ApprovalID != "approval-1" {
+ t.Errorf("expected approval id to propagate, got %q", executed.ApprovalID)
+ }
// Failure (routing)
resp, err = svc.RunCommand(context.Background(), RunCommandRequest{
diff --git a/internal/ai/tools/action_audit.go b/internal/ai/tools/action_audit.go
index 430ace8c37..1c58c24301 100644
--- a/internal/ai/tools/action_audit.go
+++ b/internal/ai/tools/action_audit.go
@@ -101,6 +101,7 @@ func (e *PulseToolExecutor) executeCommandWithAudit(
e.recordActionLifecycle(actionID, unifiedresources.ActionStateExecuting, requestedBy, fmt.Sprintf("dispatching command to agent %s", agentID))
e.recordActionAudit(record)
+ payload.ApprovalID = strings.TrimSpace(approvalID)
result, err := e.agentServer.ExecuteCommand(ctx, agentID, payload)
finalState := unifiedresources.ActionStateCompleted
finalMessage := "command completed"
diff --git a/internal/ai/tools/control_run_command_test.go b/internal/ai/tools/control_run_command_test.go
index b210e6c074..92b686d523 100644
--- a/internal/ai/tools/control_run_command_test.go
+++ b/internal/ai/tools/control_run_command_test.go
@@ -147,7 +147,10 @@ func TestPulseToolExecutor_ExecuteRunCommand(t *testing.T) {
{AgentID: "agent-1", Hostname: "tower"},
}).Maybe()
agentSrv.On("ExecuteCommand", mock.Anything, "agent-1", mock.MatchedBy(func(payload agentexec.ExecuteCommandPayload) bool {
- return payload.Command == "uptime" && payload.TargetType == "agent" && payload.TargetID == ""
+ return payload.Command == "uptime" &&
+ payload.ApprovalID == "approval-1" &&
+ payload.TargetType == "agent" &&
+ payload.TargetID == ""
})).Return(&agentexec.CommandResultPayload{
Stdout: "ok",
ExitCode: 0,
diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.go
index 1aab881e2d..ebfa39b35c 100644
--- a/internal/api/ai_handlers_test.go
+++ b/internal/api/ai_handlers_test.go
@@ -1826,7 +1826,7 @@ func TestHandleRunCommand_ConsumesApproval(t *testing.T) {
tmp := t.TempDir()
cfg := &config.Config{DataPath: tmp}
persistence := config.NewConfigPersistence(tmp)
- handler := newTestAISettingsHandler(cfg, persistence, agentexec.NewServer(nil))
+ handler := newTestAISettingsHandler(cfg, persistence, agentexec.NewServer(func(string, string) bool { return true }))
store, err := approval.NewStore(approval.StoreConfig{
DataDir: tmp,
@@ -1862,7 +1862,7 @@ func TestHandleRunCommand_RejectsCommandMismatch(t *testing.T) {
tmp := t.TempDir()
cfg := &config.Config{DataPath: tmp}
persistence := config.NewConfigPersistence(tmp)
- handler := newTestAISettingsHandler(cfg, persistence, agentexec.NewServer(nil))
+ handler := newTestAISettingsHandler(cfg, persistence, agentexec.NewServer(func(string, string) bool { return true }))
store, err := approval.NewStore(approval.StoreConfig{
DataDir: tmp,
@@ -1898,7 +1898,7 @@ func TestHandleRunCommand_RejectsUnsupportedTargetType(t *testing.T) {
tmp := t.TempDir()
cfg := &config.Config{DataPath: tmp}
persistence := config.NewConfigPersistence(tmp)
- handler := newTestAISettingsHandler(cfg, persistence, agentexec.NewServer(nil))
+ handler := newTestAISettingsHandler(cfg, persistence, agentexec.NewServer(func(string, string) bool { return true }))
store, err := approval.NewStore(approval.StoreConfig{
DataDir: tmp,
@@ -1935,7 +1935,7 @@ func TestHandleRunCommand_RejectsCrossOrgApproval(t *testing.T) {
tmp := t.TempDir()
cfg := &config.Config{DataPath: tmp}
persistence := config.NewConfigPersistence(tmp)
- handler := newTestAISettingsHandler(cfg, persistence, agentexec.NewServer(nil))
+ handler := newTestAISettingsHandler(cfg, persistence, agentexec.NewServer(func(string, string) bool { return true }))
store, err := approval.NewStore(approval.StoreConfig{
DataDir: tmp,
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 080872872b..cba280dea6 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -9956,6 +9956,76 @@ func TestContract_ResourceCapabilitiesJSONSnapshot(t *testing.T) {
assertJSONSnapshot(t, got, want)
}
+func TestContract_AgentExecWebSocketRejectsUnboundToken(t *testing.T) {
+ rawToken := "contract-agent-unbound-token.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentExec}, nil)
+ cfg := newTestConfigWithTokens(t, record)
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+
+ ts := newIPv4HTTPServer(t, router.Handler())
+ defer ts.Close()
+
+ conn, _, err := websocket.DefaultDialer.Dial(wsURLForHTTP(ts.URL)+"/api/agent/ws", nil)
+ if err != nil {
+ t.Fatalf("Dial: %v", err)
+ }
+ defer conn.Close()
+
+ regMsg, err := agentexec.NewMessage(agentexec.MsgTypeAgentRegister, "", agentexec.AgentRegisterPayload{
+ AgentID: "agent-node-1",
+ Hostname: "node-1",
+ Version: "1.0.0",
+ Platform: "linux",
+ Token: rawToken,
+ })
+ if err != nil {
+ t.Fatalf("NewMessage: %v", err)
+ }
+ if err := conn.WriteJSON(regMsg); err != nil {
+ t.Fatalf("WriteJSON: %v", err)
+ }
+
+ reg := readRegisteredPayload(t, conn)
+ if reg.Success {
+ t.Fatalf("expected unbound agent exec token registration to fail closed")
+ }
+}
+
+func TestContract_AgentExecWebSocketAcceptsLegacyHostnameBinding(t *testing.T) {
+ rawToken := "contract-agent-legacy-token.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentExec}, map[string]string{"bound_hostname": "node-1"})
+ cfg := newTestConfigWithTokens(t, record)
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+
+ ts := newIPv4HTTPServer(t, router.Handler())
+ defer ts.Close()
+
+ conn, _, err := websocket.DefaultDialer.Dial(wsURLForHTTP(ts.URL)+"/api/agent/ws", nil)
+ if err != nil {
+ t.Fatalf("Dial: %v", err)
+ }
+ defer conn.Close()
+
+ regMsg, err := agentexec.NewMessage(agentexec.MsgTypeAgentRegister, "", agentexec.AgentRegisterPayload{
+ AgentID: "agent-node-1",
+ Hostname: "node-1",
+ Version: "1.0.0",
+ Platform: "linux",
+ Token: rawToken,
+ })
+ if err != nil {
+ t.Fatalf("NewMessage: %v", err)
+ }
+ if err := conn.WriteJSON(regMsg); err != nil {
+ t.Fatalf("WriteJSON: %v", err)
+ }
+
+ reg := readRegisteredPayload(t, conn)
+ if !reg.Success {
+ t.Fatalf("expected legacy hostname binding to resolve to canonical agent binding, got %q", reg.Message)
+ }
+}
+
func TestContract_ResourceRelationshipsJSONSnapshot(t *testing.T) {
now := time.Date(2026, 3, 18, 17, 0, 0, 0, time.UTC)
payload := struct {
diff --git a/internal/api/deploy_handlers.go b/internal/api/deploy_handlers.go
index dd221ab2a5..4db02451b6 100644
--- a/internal/api/deploy_handlers.go
+++ b/internal/api/deploy_handlers.go
@@ -897,7 +897,9 @@ func (h *DeployHandlers) HandleEnroll(w http.ResponseWriter, r *http.Request) {
return
}
runtimeRecord.OrgID = bootstrapToken.OrgID
+ canonicalAgentID := fmt.Sprintf("agent-%s", req.Hostname)
runtimeRecord.Metadata = map[string]string{
+ "bound_agent_id": canonicalAgentID,
"bound_hostname": req.Hostname,
"deploy_job_id": jobID,
}
@@ -931,7 +933,6 @@ func (h *DeployHandlers) HandleEnroll(w http.ResponseWriter, r *http.Request) {
h.broadcastSSE(jobID, enrollEvt)
// 12. Return runtime token + config to agent.
- canonicalAgentID := fmt.Sprintf("agent-%s", req.Hostname)
resp := map[string]any{
"agentId": canonicalAgentID,
"runtimeToken": runtimeRaw,
diff --git a/internal/api/deploy_handlers_test.go b/internal/api/deploy_handlers_test.go
index 7f9e8a4076..ff8b26ca39 100644
--- a/internal/api/deploy_handlers_test.go
+++ b/internal/api/deploy_handlers_test.go
@@ -901,6 +901,9 @@ func TestHandleEnroll_CommandsEnabledAddsAgentExecScope(t *testing.T) {
if !hasManage {
t.Errorf("expected runtime token to have %s scope, got scopes: %v", config.ScopeAgentManage, found.Scopes)
}
+ if got := found.Metadata["bound_agent_id"]; got != "agent-cmd-host" {
+ t.Errorf("runtime token bound_agent_id = %q, want %q", got, "agent-cmd-host")
+ }
}
func TestHandleEnroll_CommandsDisabledNoAgentExecScope(t *testing.T) {
diff --git a/internal/api/router.go b/internal/api/router.go
index 736412538a..2a7da1d74b 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -492,17 +492,26 @@ func (r *Router) setupRoutes() {
return false
}
- // SECURITY: Check if token is bound to a specific agent
- if boundID, ok := record.Metadata["bound_agent_id"]; ok && boundID != "" {
- if boundID != agentID {
- log.Warn().
- Str("token_id", record.ID).
- Str("bound_id", boundID).
- Str("requested_id", agentID).
- Msg("Agent token mismatch: token is bound to a different agent ID")
- return false
+ boundID := strings.TrimSpace(record.Metadata["bound_agent_id"])
+ if boundID == "" {
+ if legacyHost := strings.TrimSpace(record.Metadata["bound_hostname"]); legacyHost != "" {
+ boundID = fmt.Sprintf("agent-%s", legacyHost)
}
}
+ if boundID == "" {
+ log.Warn().
+ Str("token_id", record.ID).
+ Msg("Agent exec token missing binding metadata")
+ return false
+ }
+ if boundID != agentID {
+ log.Warn().
+ Str("token_id", record.ID).
+ Str("bound_id", boundID).
+ Str("requested_id", agentID).
+ Msg("Agent token mismatch: token is bound to a different agent ID")
+ return false
+ }
return true
}
diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.go
index 31e8e54ad4..78e2acbdda 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -536,6 +536,43 @@ func TestAgentExecTokenBindingEnforced(t *testing.T) {
conn.Close()
}
+func TestSecurityTokens_AgentExecRejectsUnboundToken(t *testing.T) {
+ rawToken := "agent-unbound-token-123.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentExec}, nil)
+ cfg := newTestConfigWithTokens(t, record)
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+
+ ts := newIPv4HTTPServer(t, router.Handler())
+ defer ts.Close()
+
+ wsURL := wsURLForHTTP(ts.URL) + "/api/agent/ws"
+ conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
+ if err != nil {
+ t.Fatalf("Dial: %v", err)
+ }
+ regMsg, err := agentexec.NewMessage(agentexec.MsgTypeAgentRegister, "", agentexec.AgentRegisterPayload{
+ AgentID: "agent-1",
+ Hostname: "host-1",
+ Version: "1.0.0",
+ Platform: "linux",
+ Token: rawToken,
+ })
+ if err != nil {
+ conn.Close()
+ t.Fatalf("NewMessage: %v", err)
+ }
+ if err := conn.WriteJSON(regMsg); err != nil {
+ conn.Close()
+ t.Fatalf("WriteJSON: %v", err)
+ }
+ reg := readRegisteredPayload(t, conn)
+ if reg.Success {
+ conn.Close()
+ t.Fatalf("expected registration to be rejected for unbound token")
+ }
+ conn.Close()
+}
+
func TestSecurityTokens_AgentExecRequiresAgentExecScope(t *testing.T) {
rawToken := "agent-scope-token-123.12345678"
record := newTokenRecord(t, rawToken, []string{config.ScopeAIChat}, nil)
diff --git a/internal/hostagent/agent_new_test.go b/internal/hostagent/agent_new_test.go
index b23f164a93..7a6834932c 100644
--- a/internal/hostagent/agent_new_test.go
+++ b/internal/hostagent/agent_new_test.go
@@ -172,6 +172,31 @@ func TestNew_DefaultPulseURL(t *testing.T) {
}
}
+func TestNewCommandClient_SetsSecureCommandDefaults(t *testing.T) {
+ logger := zerolog.Nop()
+ client := NewCommandClient(Config{
+ PulseURL: "https://pulse.example",
+ Logger: &logger,
+ }, "agent-1", "node-1", "linux", "1.0.0")
+
+ if client.commandPolicy == nil {
+ t.Fatalf("expected default command policy to be configured")
+ }
+ if client.stateDir != defaultStateDir {
+ t.Fatalf("stateDir = %q, want %q", client.stateDir, defaultStateDir)
+ }
+
+ 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)
+ }
+ if err := client.authorizeCommand(executeCommandPayload{Command: "systemctl restart nginx", ApprovalID: "approval-1"}); err != nil {
+ t.Fatalf("expected approved command to pass, got %v", err)
+ }
+ if err := client.authorizeCommand(executeCommandPayload{Command: "rm -rf /"}); err == nil || !strings.Contains(err.Error(), "blocked by policy") {
+ t.Fatalf("expected blocked command to be rejected, got %v", err)
+ }
+}
+
func TestNew_ResolvesVendorNASIdentityFromPlatformFiles(t *testing.T) {
t.Run("synology dsm from version file", func(t *testing.T) {
mc := &mockCollector{
diff --git a/internal/hostagent/commands.go b/internal/hostagent/commands.go
index 898e21179c..ca0faaa7d6 100644
--- a/internal/hostagent/commands.go
+++ b/internal/hostagent/commands.go
@@ -11,6 +11,7 @@ import (
"net/url"
"os"
"os/exec"
+ "path/filepath"
"regexp"
"runtime"
"strings"
@@ -18,7 +19,9 @@ import (
"time"
"github.com/gorilla/websocket"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
"github.com/rcourtman/pulse-go-rewrite/internal/agenttls"
+ sshknownhosts "github.com/rcourtman/pulse-go-rewrite/internal/ssh/knownhosts"
"github.com/rcourtman/pulse-go-rewrite/internal/utils"
"github.com/rs/zerolog"
)
@@ -87,8 +90,13 @@ type CommandClient struct {
hostname string
platform string
version string
+ stateDir string
insecureSkipVerify bool
caCertPath string
+ commandPolicy *agentexec.CommandPolicy
+ sshKnownHosts sshknownhosts.Manager
+ sshKnownHostsOnce sync.Once
+ sshKnownHostsErr error
logger zerolog.Logger
conn *websocket.Conn
@@ -99,6 +107,10 @@ type CommandClient struct {
// NewCommandClient creates a new command execution client
func NewCommandClient(cfg Config, agentID, hostname, platform, version string) *CommandClient {
logger := cfg.Logger.With().Str("component", "command-client").Logger()
+ stateDir := strings.TrimSpace(cfg.StateDir)
+ if stateDir == "" {
+ stateDir = defaultStateDir
+ }
return &CommandClient{
pulseURL: strings.TrimRight(cfg.PulseURL, "/"),
@@ -107,8 +119,10 @@ func NewCommandClient(cfg Config, agentID, hostname, platform, version string) *
hostname: hostname,
platform: platform,
version: version,
+ stateDir: stateDir,
insecureSkipVerify: cfg.InsecureSkipVerify,
caCertPath: cfg.CACertPath,
+ commandPolicy: agentexec.DefaultPolicy(),
logger: logger,
done: make(chan struct{}),
}
@@ -166,6 +180,7 @@ type registeredPayload struct {
type executeCommandPayload struct {
RequestID string `json:"request_id"`
Command string `json:"command"`
+ ApprovalID string `json:"approval_id,omitempty"`
TargetType string `json:"target_type"`
TargetID string `json:"target_id,omitempty"`
Timeout int `json:"timeout,omitempty"`
@@ -543,6 +558,7 @@ func (c *CommandClient) handleExecuteCommand(ctx context.Context, conn *websocke
c.logger.Info().
Str("request_id", payload.RequestID).
Str("command", payload.Command).
+ Str("approval_id", payload.ApprovalID).
Str("target_type", payload.TargetType).
Str("target_id", payload.TargetID).
Msg("Executing command")
@@ -621,11 +637,64 @@ func shellQuote(s string) string {
return "'" + escaped + "'"
}
+func (c *CommandClient) currentCommandPolicy() *agentexec.CommandPolicy {
+ if c != nil && c.commandPolicy != nil {
+ return c.commandPolicy
+ }
+ return agentexec.DefaultPolicy()
+}
+
+func (c *CommandClient) authorizeCommand(payload executeCommandPayload) error {
+ switch c.currentCommandPolicy().Evaluate(payload.Command) {
+ case agentexec.PolicyBlock:
+ return fmt.Errorf("command blocked by policy")
+ case agentexec.PolicyRequireApproval:
+ if strings.TrimSpace(payload.ApprovalID) == "" {
+ return fmt.Errorf("command requires approval")
+ }
+ }
+ return nil
+}
+
+func (c *CommandClient) ensureSSHKnownHostsManager() (sshknownhosts.Manager, error) {
+ if c == nil {
+ return nil, fmt.Errorf("command client is nil")
+ }
+
+ c.sshKnownHostsOnce.Do(func() {
+ if c.sshKnownHosts != nil {
+ return
+ }
+
+ stateDir := strings.TrimSpace(c.stateDir)
+ if stateDir == "" {
+ stateDir = defaultStateDir
+ }
+
+ c.sshKnownHosts, c.sshKnownHostsErr = sshknownhosts.NewManager(filepath.Join(stateDir, "ssh_known_hosts"))
+ })
+
+ if c.sshKnownHostsErr != nil {
+ return nil, c.sshKnownHostsErr
+ }
+ if c.sshKnownHosts == nil {
+ return nil, fmt.Errorf("ssh known_hosts manager is not configured")
+ }
+ return c.sshKnownHosts, nil
+}
+
func (c *CommandClient) executeCommand(ctx context.Context, payload executeCommandPayload) commandResultPayload {
result := commandResultPayload{
RequestID: payload.RequestID,
}
+ if err := c.authorizeCommand(payload); err != nil {
+ result.Error = err.Error()
+ result.ExitCode = -1
+ result.Success = false
+ return result
+ }
+
// Determine timeout
timeout := time.Duration(payload.Timeout) * time.Second
if timeout <= 0 {
diff --git a/internal/hostagent/commands_connect_test.go b/internal/hostagent/commands_connect_test.go
index 24fc49c7e8..e93c6e5974 100644
--- a/internal/hostagent/commands_connect_test.go
+++ b/internal/hostagent/commands_connect_test.go
@@ -53,6 +53,7 @@ func TestCommandClient_connectAndHandle_ExecutesCommandAndReturnsResult(t *testi
execPayloadBytes, _ := json.Marshal(executeCommandPayload{
RequestID: "req-1",
Command: "echo hello",
+ ApprovalID: "approval-1",
TargetType: "host",
Timeout: 5,
})
diff --git a/internal/hostagent/commands_coverage_test.go b/internal/hostagent/commands_coverage_test.go
index a4b053e5a2..f3ef9b9db6 100644
--- a/internal/hostagent/commands_coverage_test.go
+++ b/internal/hostagent/commands_coverage_test.go
@@ -36,15 +36,17 @@ func TestCommandClient_LoopsCoverage(t *testing.T) {
// 4. Send an execute_command
cmdPayload, _ := json.Marshal(executeCommandPayload{
- RequestID: "req-1",
- Command: "echo hi",
+ RequestID: "req-1",
+ Command: "echo hi",
+ ApprovalID: "approval-1",
})
_ = conn.WriteJSON(wsMessage{Type: msgTypeExecuteCmd, Payload: cmdPayload})
// 5. Send a read_file
readPayload, _ := json.Marshal(executeCommandPayload{
- RequestID: "req-2",
- Command: "cat /etc/hostname",
+ RequestID: "req-2",
+ Command: "cat /etc/hostname",
+ ApprovalID: "approval-1",
})
_ = conn.WriteJSON(wsMessage{Type: msgTypeReadFile, Payload: readPayload})
diff --git a/internal/hostagent/commands_deploy.go b/internal/hostagent/commands_deploy.go
index 47ea40d7f6..1331486a58 100644
--- a/internal/hostagent/commands_deploy.go
+++ b/internal/hostagent/commands_deploy.go
@@ -394,27 +394,48 @@ func (c *CommandClient) installTarget(
// --- SSH helpers ---
-// checkSSH tests basic SSH connectivity to a peer node.
-func (c *CommandClient) checkSSH(ctx context.Context, nodeIP string) bool {
- cmd := execCommandContext(ctx, "ssh",
+func (c *CommandClient) sshCommand(ctx context.Context, nodeIP string, remoteArgs ...string) (*exec.Cmd, error) {
+ if err := validateNodeIP(nodeIP); err != nil {
+ return nil, err
+ }
+
+ hostKeys, err := c.ensureSSHKnownHostsManager()
+ if err != nil {
+ return nil, fmt.Errorf("initialize SSH known_hosts manager: %w", err)
+ }
+ if err := hostKeys.Ensure(ctx, nodeIP); err != nil {
+ return nil, fmt.Errorf("ensure SSH host key for %s: %w", nodeIP, err)
+ }
+
+ args := []string{
"-o", "BatchMode=yes",
- "-o", "StrictHostKeyChecking=no",
+ "-o", "StrictHostKeyChecking=yes",
+ "-o", fmt.Sprintf("UserKnownHostsFile=%s", hostKeys.Path()),
+ "-o", "GlobalKnownHostsFile=/dev/null",
"-o", "ConnectTimeout=10",
fmt.Sprintf("root@%s", nodeIP),
- "true",
- )
+ }
+ args = append(args, remoteArgs...)
+ return execCommandContext(ctx, "ssh", args...), nil
+}
+
+// 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")
+ if err != nil {
+ c.logger.Warn().Err(err).Str("node_ip", nodeIP).Msg("SSH connectivity check refused before execution")
+ return false
+ }
return cmd.Run() == nil
}
// detectArchSSH detects the architecture of a remote node via SSH.
func (c *CommandClient) detectArchSSH(ctx context.Context, nodeIP string) string {
- cmd := execCommandContext(ctx, "ssh",
- "-o", "BatchMode=yes",
- "-o", "StrictHostKeyChecking=no",
- "-o", "ConnectTimeout=10",
- fmt.Sprintf("root@%s", nodeIP),
- "uname -m",
- )
+ cmd, err := c.sshCommand(ctx, nodeIP, "uname -m")
+ if err != nil {
+ c.logger.Warn().Err(err).Str("node_ip", nodeIP).Msg("SSH arch detection refused before execution")
+ return ""
+ }
out, err := cmd.Output()
if err != nil {
return ""
@@ -432,38 +453,31 @@ 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 := execCommandContext(ctx, "ssh",
- "-o", "BatchMode=yes",
- "-o", "StrictHostKeyChecking=no",
- "-o", "ConnectTimeout=10",
- fmt.Sprintf("root@%s", nodeIP),
- "systemctl is-active pulse-agent 2>/dev/null || test -f /usr/local/bin/pulse-agent",
- )
+ cmd, err := c.sshCommand(ctx, nodeIP, "systemctl is-active pulse-agent 2>/dev/null || test -f /usr/local/bin/pulse-agent")
+ if err != nil {
+ c.logger.Warn().Err(err).Str("node_ip", nodeIP).Msg("SSH existing-agent check refused before execution")
+ return false
+ }
return cmd.Run() == nil
}
// 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 := execCommandContext(ctx, "ssh",
- "-o", "BatchMode=yes",
- "-o", "StrictHostKeyChecking=no",
- "-o", "ConnectTimeout=10",
- fmt.Sprintf("root@%s", 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.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)))
+ if err != nil {
+ c.logger.Warn().Err(err).Str("node_ip", nodeIP).Msg("SSH Pulse reachability check refused before execution")
+ return false
+ }
return cmd.Run() == nil
}
// 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 := execCommandContext(ctx, "ssh",
- "-o", "BatchMode=yes",
- "-o", "StrictHostKeyChecking=no",
- "-o", "ConnectTimeout=10",
- fmt.Sprintf("root@%s", nodeIP),
- "mkdir -p /run/pulse-agent && cat > /run/pulse-agent/bootstrap.token && chmod 600 /run/pulse-agent/bootstrap.token",
- )
+ cmd, err := c.sshCommand(ctx, nodeIP, "mkdir -p /run/pulse-agent && cat > /run/pulse-agent/bootstrap.token && chmod 600 /run/pulse-agent/bootstrap.token")
+ if err != nil {
+ return err
+ }
cmd.Stdin = strings.NewReader(token)
return cmd.Run()
}
@@ -482,13 +496,10 @@ func (c *CommandClient) runInstallSSH(ctx context.Context, nodeIP, pulseURL stri
escapedURL, escapedURL,
)
remoteCmd := "bash -c " + shellescape(innerCmd)
- cmd := execCommandContext(ctx, "ssh",
- "-o", "BatchMode=yes",
- "-o", "StrictHostKeyChecking=no",
- "-o", "ConnectTimeout=10",
- fmt.Sprintf("root@%s", nodeIP),
- remoteCmd,
- )
+ cmd, err := c.sshCommand(ctx, nodeIP, remoteCmd)
+ if err != nil {
+ return -1, "", err
+ }
out, err := cmd.CombinedOutput()
exitCode := 0
diff --git a/internal/hostagent/commands_deploy_test.go b/internal/hostagent/commands_deploy_test.go
index 22374b4724..7589934c9e 100644
--- a/internal/hostagent/commands_deploy_test.go
+++ b/internal/hostagent/commands_deploy_test.go
@@ -6,9 +6,25 @@ import (
"strings"
"testing"
+ sshknownhosts "github.com/rcourtman/pulse-go-rewrite/internal/ssh/knownhosts"
"github.com/rs/zerolog"
)
+type stubKnownHostsManager struct {
+ path string
+}
+
+func (m stubKnownHostsManager) Ensure(context.Context, string) error { return nil }
+func (m stubKnownHostsManager) EnsureWithPort(context.Context, string, int) error {
+ return nil
+}
+func (m stubKnownHostsManager) EnsureWithEntries(context.Context, string, int, [][]byte) error {
+ return nil
+}
+func (m stubKnownHostsManager) Path() string { return m.path }
+
+var _ sshknownhosts.Manager = stubKnownHostsManager{}
+
func TestShellescape(t *testing.T) {
tests := []struct {
input string
@@ -130,7 +146,8 @@ func TestRunInstallSSH_IncludesEnrollAndEnableCommands(t *testing.T) {
}
c := &CommandClient{
- logger: zerolog.New(zerolog.NewTestWriter(t)),
+ logger: zerolog.New(zerolog.NewTestWriter(t)),
+ sshKnownHosts: stubKnownHostsManager{path: "/tmp/pulse-test-known-hosts"},
}
exitCode, _, err := c.runInstallSSH(context.Background(), "10.0.0.1", "http://10.0.0.1:7655")
@@ -152,4 +169,13 @@ func TestRunInstallSSH_IncludesEnrollAndEnableCommands(t *testing.T) {
if !strings.Contains(joined, "--enable-proxmox") {
t.Error("SSH install command does not include --enable-proxmox")
}
+ if !strings.Contains(joined, "StrictHostKeyChecking=yes") {
+ t.Error("SSH install command does not enforce strict host key checking")
+ }
+ if !strings.Contains(joined, "UserKnownHostsFile=/tmp/pulse-test-known-hosts") {
+ t.Error("SSH install command does not use the managed known_hosts file")
+ }
+ if !strings.Contains(joined, "GlobalKnownHostsFile=/dev/null") {
+ t.Error("SSH install command does not isolate global known_hosts state")
+ }
}
diff --git a/internal/hostagent/commands_execute_test.go b/internal/hostagent/commands_execute_test.go
index d39cc017d1..7790bf4328 100644
--- a/internal/hostagent/commands_execute_test.go
+++ b/internal/hostagent/commands_execute_test.go
@@ -69,9 +69,10 @@ func TestCommandClient_executeCommand_Success(t *testing.T) {
c := &CommandClient{}
result := c.executeCommand(context.Background(), executeCommandPayload{
- RequestID: "r1",
- Command: "echo hello",
- Timeout: 5,
+ RequestID: "r1",
+ Command: "echo hello",
+ ApprovalID: "approval-1",
+ Timeout: 5,
})
if !result.Success || result.ExitCode != 0 {
t.Fatalf("expected success, got %#v", result)
@@ -88,9 +89,10 @@ func TestCommandClient_executeCommand_NonZeroExitCode(t *testing.T) {
c := &CommandClient{}
result := c.executeCommand(context.Background(), executeCommandPayload{
- RequestID: "r1",
- Command: "echo err 1>&2; exit 3",
- Timeout: 5,
+ RequestID: "r1",
+ Command: "echo err 1>&2; exit 3",
+ ApprovalID: "approval-1",
+ Timeout: 5,
})
if result.Success {
t.Fatalf("expected failure, got %#v", result)
@@ -111,9 +113,10 @@ func TestCommandClient_executeCommand_TimeoutSetsError(t *testing.T) {
c := &CommandClient{}
start := time.Now()
result := c.executeCommand(context.Background(), executeCommandPayload{
- RequestID: "r1",
- Command: "sleep 2",
- Timeout: 1,
+ RequestID: "r1",
+ Command: "sleep 2",
+ ApprovalID: "approval-1",
+ Timeout: 1,
})
if time.Since(start) > 3*time.Second {
t.Fatalf("timeout path took too long: %v", time.Since(start))
@@ -136,9 +139,10 @@ func TestCommandClient_executeCommand_TruncatesLargeOutput(t *testing.T) {
c := &CommandClient{}
result := c.executeCommand(context.Background(), executeCommandPayload{
- RequestID: "r1",
- Command: "head -c 1048580 /dev/zero | tr '\\0' 'a'",
- Timeout: 5,
+ RequestID: "r1",
+ Command: "head -c 1048580 /dev/zero | tr '\\0' 'a'",
+ ApprovalID: "approval-1",
+ Timeout: 5,
})
if !result.Success {
t.Fatalf("expected success, got %#v", result)
@@ -158,9 +162,10 @@ func TestCommandClient_executeCommand_TruncatesLargeStderr(t *testing.T) {
c := &CommandClient{}
result := c.executeCommand(context.Background(), executeCommandPayload{
- RequestID: "r1",
- Command: "head -c 1048580 /dev/zero | tr '\\0' 'b' 1>&2",
- Timeout: 5,
+ RequestID: "r1",
+ Command: "head -c 1048580 /dev/zero | tr '\\0' 'b' 1>&2",
+ ApprovalID: "approval-1",
+ Timeout: 5,
})
if !result.Success {
t.Fatalf("expected success, got %#v", result)
@@ -172,3 +177,33 @@ func TestCommandClient_executeCommand_TruncatesLargeStderr(t *testing.T) {
t.Fatalf("stderr len=%d, expected <= %d", len(result.Stderr), 1024*1024+64)
}
}
+
+func TestCommandClient_executeCommand_RequiresApprovalForUnknownCommand(t *testing.T) {
+ c := &CommandClient{}
+ result := c.executeCommand(context.Background(), executeCommandPayload{
+ RequestID: "r1",
+ Command: "echo hello",
+ Timeout: 5,
+ })
+ if result.Success {
+ t.Fatalf("expected approval-gated failure, got %#v", result)
+ }
+ if result.Error != "command requires approval" {
+ t.Fatalf("error = %q, want %q", result.Error, "command requires approval")
+ }
+}
+
+func TestCommandClient_executeCommand_BlocksPolicyDeniedCommand(t *testing.T) {
+ c := &CommandClient{}
+ result := c.executeCommand(context.Background(), executeCommandPayload{
+ RequestID: "r1",
+ Command: "rm -rf /",
+ Timeout: 5,
+ })
+ if result.Success {
+ t.Fatalf("expected blocked-command failure, got %#v", result)
+ }
+ if result.Error != "command blocked by policy" {
+ t.Fatalf("error = %q, want %q", result.Error, "command blocked by policy")
+ }
+}
diff --git a/internal/hostagent/commands_test.go b/internal/hostagent/commands_test.go
index f365613db8..468b1bb3c3 100644
--- a/internal/hostagent/commands_test.go
+++ b/internal/hostagent/commands_test.go
@@ -53,9 +53,10 @@ func TestCommandClient_Run(t *testing.T) {
// 3. Send Execute Command
cmdPayload, _ := json.Marshal(executeCommandPayload{
- RequestID: "cmd-1",
- Command: "echo hello",
- Timeout: 5,
+ RequestID: "cmd-1",
+ Command: "echo hello",
+ ApprovalID: "approval-1",
+ Timeout: 5,
})
_ = conn.WriteJSON(wsMessage{
Type: msgTypeExecuteCmd,