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.

Cap agent exec websocket connections per IP

rcourtmanc1d0d34c1685
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 399bee1c15..ef8e942dd7 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -797,7 +797,9 @@ base URL through `internal/securityutil/websocket_origin.go`, and the agent
receiver must reject missing or cross-host origins before registration.
Runtime command sockets therefore stay on the same fail-closed host/proxy
continuity contract as the browser websocket path instead of accepting
-originless upgrades.
+originless upgrades. That same receiver-owned admission path must also cap
+concurrent websocket connections per client IP before upgrade so one source
+cannot hold unbounded agent command sockets open.
That same shared helper layer also now assumes the Pulse Mobile relay runtime
credential reaches only the explicit backend-owned route inventory, so
lifecycle-adjacent setup and install flows cannot accidentally widen the
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 924b15b45d..05b52e00f2 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -254,7 +254,9 @@ the canonical monitored-system blocked payload.
`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
+ different agent. That same websocket admission path must also cap
+ concurrent connections per client IP before upgrade so one source cannot
+ hold unbounded agent-exec sockets open. 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.
diff --git a/internal/agentexec/server.go b/internal/agentexec/server.go
index cf405619cb..9ae80d7125 100644
--- a/internal/agentexec/server.go
+++ b/internal/agentexec/server.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "net"
"net/http"
"regexp"
"strings"
@@ -41,14 +42,15 @@ var (
const maxWebSocketMessageBytes int64 = 1 << 20 // 1 MiB
const (
- maxAgentIDLength = 128
- maxRequestIDLength = 128
- maxExecuteCommandLength = 32 * 1024
- maxTargetIDLength = 256
- maxExecuteCommandTimeoutSeconds = 3600
- defaultReadFileMaxBytes int64 = 1 << 20 // 1 MiB
- maxReadFileMaxBytes int64 = 10 << 20 // 10 MiB
- maxReadFilePathLength = 4096
+ maxAgentIDLength = 128
+ maxRequestIDLength = 128
+ maxExecuteCommandLength = 32 * 1024
+ maxTargetIDLength = 256
+ maxExecuteCommandTimeoutSeconds = 3600
+ defaultMaxWebSocketConnectionsPerIP = 128
+ defaultReadFileMaxBytes int64 = 1 << 20 // 1 MiB
+ maxReadFileMaxBytes int64 = 10 << 20 // 10 MiB
+ maxReadFilePathLength = 4096
)
var safeTargetIDPattern = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
@@ -61,6 +63,8 @@ type Server struct {
deploySubs map[string]chan DeployProgressPayload // deploySubKey(agentID, jobID) -> progress subscriber
validateToken func(token string, agentID string) bool
commandPolicy *CommandPolicy
+ ipConnCounts map[string]int
+ maxConnsPerIP int
shutdown chan struct{}
shutdownOnce sync.Once
pingInterval time.Duration
@@ -96,6 +100,8 @@ func NewServer(validateToken func(token string, agentID string) bool) *Server {
deploySubs: make(map[string]chan DeployProgressPayload),
validateToken: validateToken,
commandPolicy: DefaultPolicy(),
+ ipConnCounts: make(map[string]int),
+ maxConnsPerIP: defaultMaxWebSocketConnectionsPerIP,
shutdown: make(chan struct{}),
pingInterval: defaultPingInterval,
}
@@ -237,14 +243,71 @@ func isAllowedWebSocketOrigin(r *http.Request) bool {
return securityutil.SameHostWebSocketOrigin(origin, r.Host)
}
+func normalizeWebSocketRemoteIP(remoteAddr string) string {
+ remoteAddr = strings.TrimSpace(remoteAddr)
+ if remoteAddr == "" {
+ return ""
+ }
+
+ host, _, err := net.SplitHostPort(remoteAddr)
+ if err == nil {
+ return strings.Trim(host, "[]")
+ }
+
+ return strings.Trim(remoteAddr, "[]")
+}
+
+func (s *Server) acquireWebSocketIPSlot(remoteIP string) bool {
+ if s == nil || s.maxConnsPerIP <= 0 || remoteIP == "" {
+ return true
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.ipConnCounts[remoteIP] >= s.maxConnsPerIP {
+ return false
+ }
+
+ s.ipConnCounts[remoteIP]++
+ return true
+}
+
+func (s *Server) releaseWebSocketIPSlot(remoteIP string) {
+ if s == nil || s.maxConnsPerIP <= 0 || remoteIP == "" {
+ return
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ count := s.ipConnCounts[remoteIP]
+ if count <= 1 {
+ delete(s.ipConnCounts, remoteIP)
+ return
+ }
+
+ s.ipConnCounts[remoteIP] = count - 1
+}
+
// HandleWebSocket handles incoming WebSocket connections from agents
func (s *Server) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
remoteAddr := r.RemoteAddr
+ remoteIP := normalizeWebSocketRemoteIP(remoteAddr)
if s.isShuttingDown() {
http.Error(w, "agent execution server is shutting down", http.StatusServiceUnavailable)
return
}
+ if !s.acquireWebSocketIPSlot(remoteIP) {
+ log.Warn().
+ Str("remote_ip", remoteIP).
+ Int("max_connections_per_ip", s.maxConnsPerIP).
+ Msg("Rejected agent websocket upgrade due to per-IP connection cap")
+ http.Error(w, "Too many agent websocket connections from this IP", http.StatusTooManyRequests)
+ return
+ }
+ defer s.releaseWebSocketIPSlot(remoteIP)
// CRITICAL: Clear http.Server deadlines BEFORE WebSocket upgrade.
// The http.Server.ReadTimeout sets a deadline on the underlying connection when
diff --git a/internal/agentexec/server_websocket_test.go b/internal/agentexec/server_websocket_test.go
index 692e58259c..df28787932 100644
--- a/internal/agentexec/server_websocket_test.go
+++ b/internal/agentexec/server_websocket_test.go
@@ -168,6 +168,64 @@ func TestHandleWebSocket_RejectsMissingOrigin(t *testing.T) {
}
}
+func TestHandleWebSocket_RejectsPerIPConnectionFlood(t *testing.T) {
+ s := NewServer(allowAllTestTokens)
+ s.maxConnsPerIP = 1
+ ts := newWSServer(t, s)
+ defer ts.Close()
+
+ firstConn, _, err := dialAgentExecWebSocket(t, ts.URL)
+ if err != nil {
+ t.Fatalf("Dial first connection: %v", err)
+ }
+ defer firstConn.Close()
+
+ wsWriteMessage(t, firstConn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{
+ AgentID: "a1",
+ Hostname: "host1",
+ Version: "1.2.3",
+ Platform: "linux",
+ Token: "any",
+ }))
+ reg := wsReadRegisteredPayload(t, firstConn)
+ if !reg.Success {
+ t.Fatalf("first registration failed: %q", reg.Message)
+ }
+
+ secondConn, resp, err := dialAgentExecWebSocket(t, ts.URL)
+ if err == nil {
+ secondConn.Close()
+ t.Fatalf("expected second websocket upgrade to be rejected")
+ }
+ if resp == nil {
+ t.Fatalf("expected HTTP response for rejected websocket upgrade")
+ }
+ if resp.StatusCode != http.StatusTooManyRequests {
+ t.Fatalf("expected %d, got %d", http.StatusTooManyRequests, resp.StatusCode)
+ }
+
+ firstConn.Close()
+ waitFor(t, 2*time.Second, func() bool { return !s.IsAgentConnected("a1") })
+
+ thirdConn, _, err := dialAgentExecWebSocket(t, ts.URL)
+ if err != nil {
+ t.Fatalf("Dial third connection after release: %v", err)
+ }
+ defer thirdConn.Close()
+
+ wsWriteMessage(t, thirdConn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{
+ AgentID: "a2",
+ Hostname: "host2",
+ Version: "1.2.3",
+ Platform: "linux",
+ Token: "any",
+ }))
+ reg = wsReadRegisteredPayload(t, thirdConn)
+ if !reg.Success {
+ t.Fatalf("third registration failed after slot release: %q", reg.Message)
+ }
+}
+
func TestHandleWebSocket_InvalidTokenRejected(t *testing.T) {
s := NewServer(func(string, string) bool { return false })
ts := newWSServer(t, s)