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.

fix(agentexec): reserve registration acknowledgement before dispatch

pulse-triage[bot]03dcabdf873f
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 38af7e1ffb..516b1bdc1a 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -8002,3 +8002,20 @@ trust suite verifies every consumer pin, absence of the affected auth assumption
workflow trust controls and the retained native Windows command/lifecycle proof
steps. Native Windows execution remains a hosted check, not a local Linux claim.
This upgrade is independent of the grouped signing/Docker/Tailscale updates.
+
+### Command-channel registration frame ordering
+
+The server reserves each new session's write lock while still holding the
+session-map lock, before dispatchers can discover it. Registration success
+must be the first frame: the unified client rejects a command received instead
+of the acknowledgement. Serializing individual writes after publication is
+insufficient because a dispatcher could win the lock first. The lock is on a
+new, unpublished connection, not an existing session. Rejection, replacement,
+pending activation and token admission semantics remain unchanged.
+
+`TestRegistrationReservesFirstFrameBeforePublishingSession` in
+`internal/agentexec/server_websocket_test.go` probes the publication-to-ack
+window deterministically and checks the first wire frame. It joins the handler
+before restoring its test logger. Real unified-agent receipt replay tests cover
+APT, cleanup and Docker mutation-once behaviour, and Proxmox cancellation/reconnect.
+This is synthetic transport proof, not installed delivery or CI qualification.
diff --git a/internal/agentexec/server.go b/internal/agentexec/server.go
index f838fd0469..41473283ff 100644
--- a/internal/agentexec/server.go
+++ b/internal/agentexec/server.go
@@ -1478,6 +1478,10 @@ func (s *Server) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
}
s.agents[ac.sessionKey] = ac
}
+ // Reserve the first frame before publishing the session to dispatchers.
+ // Clients require registered before any command; merely serializing the
+ // writes below does not guarantee that the acknowledgement wins the race.
+ ac.writeMu.Lock()
s.mu.Unlock()
if replaced != nil && replaced != ac {
log.Info().
@@ -1506,10 +1510,10 @@ func (s *Server) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
ackMsg, ackErr := NewMessage(MsgTypeRegistered, "", RegisteredPayload{Success: true, Message: "Registered"})
if ackErr != nil {
log.Warn().Err(ackErr).Str("agent_id", reg.AgentID).Msg("Failed to encode registration ack")
+ ac.writeMu.Unlock()
conn.Close()
return
}
- ac.writeMu.Lock()
if sendErr := s.sendMessage(conn, ackMsg); sendErr != nil {
log.Warn().
Err(sendErr).
diff --git a/internal/agentexec/server_websocket_test.go b/internal/agentexec/server_websocket_test.go
index 0d3988dc7d..c002260215 100644
--- a/internal/agentexec/server_websocket_test.go
+++ b/internal/agentexec/server_websocket_test.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"net/http"
"net/http/httptest"
"strings"
@@ -15,6 +16,8 @@ import (
"github.com/gorilla/websocket"
"github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"
"github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
+ "github.com/rs/zerolog"
+ "github.com/rs/zerolog/log"
)
type wsRawMessage struct {
@@ -2138,3 +2141,54 @@ func TestTypedOperation_TimeoutSendsCancelAndExpiredContextNeverDispatches(t *te
}
})
}
+
+// Probe the scheduling window after publication but before the registration
+// acknowledgement. No sleeps or repeated runs are needed to expose this order.
+func TestRegistrationReservesFirstFrameBeforePublishingSession(t *testing.T) {
+ server := NewServer(allowAllTestTokens)
+ original := log.Logger
+ checked := make(chan bool, 1)
+ log.Logger = zerolog.New(io.Discard).Hook(zerolog.HookFunc(func(_ *zerolog.Event, _ zerolog.Level, message string) {
+ if message != "Agent connected" {
+ return
+ }
+ server.mu.RLock()
+ ac := server.agents[agentSessionKey(defaultOrganizationID, "registration-order")]
+ server.mu.RUnlock()
+ if ac == nil {
+ checked <- false
+ return
+ }
+ // A dispatcher acquiring this lock here can send a command as the first
+ // frame. CommandClient.waitForRegistration rejects that frame and exits.
+ available := ac.writeMu.TryLock()
+ if available {
+ ac.writeMu.Unlock()
+ }
+ checked <- !available
+ }))
+ defer func() { log.Logger = original }()
+ handlerDone := make(chan struct{})
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer close(handlerDone)
+ server.HandleWebSocket(w, r)
+ }))
+ defer ts.Close()
+ defer server.Shutdown()
+ conn, _, err := dialAgentExecWebSocket(t, ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() {
+ _ = conn.Close()
+ <-handlerDone
+ }()
+ wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{AgentID: "registration-order", Hostname: "host", Token: "ok"}))
+ first := wsReadRawMessage(t, conn)
+ if first.Type != MsgTypeRegistered {
+ t.Fatalf("first frame = %s, want registered", first.Type)
+ }
+ if !<-checked {
+ t.Fatal("published session permits command writes before registration acknowledgement")
+ }
+}