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.

Keep foreign QGA reply payloads behind shared admission

pulse-triage[bot]9b887e78e4df
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index ae36531437..82d8df5a0e 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -1271,6 +1271,31 @@ last-known with their QGA provenance, metadata is not renewed, CPU advances,
and guest metrics are not renewed. This is synthetic source/consuming-surface proof, not attribution of
the original freeze or native thaw/restart recovery.
+The success boundary also checks compatibility with the command sent, before
+postflight lock reads or release of shared admission. Present, non-null fields
+exclusive to another supported command (file content, OS identity, agent command
+catalogue, filesystem capacity or network interfaces), an explicit error payload,
+and list results for the two dictionary-valued information commands retain
+`agent-completion-unverified`. A recognizable network row must not become a
+current filesystem named `eth0`, nor a file/agent-info reply an empty current
+disk inventory. The original one-minute uncertainty fence, alias coordination,
+no-replay transport, credentials and independent live counters are unchanged.
+Empty/null replies, shared `name`/`version` fields, unknown metadata, supported
+object/array inventories, partial rows and completed unusable file measurements
+keep their existing semantics. This is contradiction detection, not proof of
+payload-to-command correlation: replies without discriminating fields remain
+indistinguishable, and native thaw/restart recovery remains unverified.
+
+`TestGuestAgentForeignReplyDefersEveryReader` covers cross-command/error replies
+through all six HTTP readers, with no postflight/follow-up guest request and
+independent PVE/VM controls. Alias/fresh-client/unchanged-expiry/resumption and
+compatible empty/partial-data tests complete the client boundary.
+`TestGuestAgentCommandReplyMonitoringContract` connects three foreign reply
+families through the actual polling builder, state, broadcast and History:
+original disk/memory remain last-known, metadata and measurement times are not
+renewed, and CPU advances. Source and browser fixture proof do not establish a
+native command-ID collision, incident cause, guest liveness or successful thaw.
+
The completed-error boundary uses the actual HTTP status retained by the request
layer, not an `API error` phrase in provider or proxy text. The supported
explicit request/access/command refusals (HTTP 400, 401, 403, 404, 405, 422 and
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index c8ed1c7438..f08101296c 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -3393,6 +3393,13 @@ func TestGuestAgentTypedReplyMonitoringContract(t *testing.T) {
testGuestAgentTransportDeferralKeepsLastKnownHistory(t, "typed result", "typed content", "typed truncated")
}
+func TestGuestAgentCommandReplyMonitoringContract(t *testing.T) {
+ // A complete but recognizably foreign command reply cannot clear a
+ // filesystem request or renew its capacity/History. Keep actual warm
+ // observation origins and live CPU across both deferral polls.
+ testGuestAgentTransportDeferralKeepsLastKnownHistory(t, "foreign file", "foreign network", "foreign version")
+}
+
func TestBackupAlertEvaluationCallersShareFailureVisibility(t *testing.T) {
for path, want := range map[string]int{"monitor_backups.go": 2, "monitor_alerts.go": 1} {
raw, err := os.ReadFile(path)
diff --git a/internal/monitoring/guest_agent_transport_integration_test.go b/internal/monitoring/guest_agent_transport_integration_test.go
index beddf35d73..8a459a7c72 100644
--- a/internal/monitoring/guest_agent_transport_integration_test.go
+++ b/internal/monitoring/guest_agent_transport_integration_test.go
@@ -20,6 +20,7 @@ import (
func testGuestAgentTransportDeferralKeepsLastKnownHistory(t *testing.T, kinds ...string) {
for _, kind := range kinds {
t.Run(kind, func(t *testing.T) {
+ preserveOrigins := strings.HasPrefix(kind, "typed ") || strings.HasPrefix(kind, "foreign ")
const mib = uint64(1024 * 1024)
var phase, calls, redirected atomic.Int32
var lost atomic.Bool
@@ -54,6 +55,15 @@ func testGuestAgentTransportDeferralKeepsLastKnownHistory(t *testing.T, kinds ..
case "typed truncated":
fmt.Fprint(w, `{"data":{"result":[],"truncated":"false"}}`)
return
+ case "foreign file":
+ fmt.Fprint(w, `{"data":{"content":"MemTotal: 8192 kB\nMemAvailable: 8192 kB\n","truncated":false}}`)
+ return
+ case "foreign network":
+ fmt.Fprint(w, `{"data":{"result":[{"name":"eth0","ip-addresses":[]}]}}`)
+ return
+ case "foreign version":
+ fmt.Fprint(w, `{"data":{"result":{"version":"1.0","supported_commands":[]}}}`)
+ return
}
if status := map[string]int{
"server error": http.StatusInternalServerError,
@@ -99,12 +109,18 @@ func testGuestAgentTransportDeferralKeepsLastKnownHistory(t *testing.T, kinds ..
}
}))
defer server.Close()
- client, err := proxmox.NewClient(proxmox.ClientConfig{Host: server.URL, TokenName: "fixture@pve!pulse", TokenValue: "fixture", Timeout: time.Second})
+ host := server.URL
+ timeout := time.Second
+ if strings.HasPrefix(kind, "foreign ") {
+ timeout = 15 * time.Second
+ host += "/command-reply-fixture/" + strings.ReplaceAll(kind, " ", "-")
+ }
+ client, err := proxmox.NewClient(proxmox.ClientConfig{Host: host, TokenName: "fixture@pve!pulse", TokenValue: "fixture", Timeout: timeout})
if err != nil {
t.Fatal(err)
}
m := &Monitor{config: &config.Config{}, rateTracker: NewRateTracker(), metricsHistory: NewMetricsHistory(32, time.Hour), guestMetadataLimiter: make(map[string]time.Time)}
- if strings.HasPrefix(kind, "typed ") {
+ if preserveOrigins {
m.state = models.NewState()
}
res := proxmox.ClusterResource{Type: "qemu", Node: "node", Name: "guest", VMID: 105, Status: "running", MaxMem: 8 * mib, Mem: 8 * mib, MaxDisk: 1000 * mib, CPU: 0.1}
@@ -118,7 +134,7 @@ func testGuestAgentTransportDeferralKeepsLastKnownHistory(t *testing.T, kinds ..
m.recordGuestSnapshot("transport", "qemu", "node", 105, GuestMemorySnapshot{Name: vm.Name, Status: vm.Status, RetrievedAt: at, MemorySource: source, Memory: vm.Memory, Raw: raw, Notes: notes})
m.recordGuestMetrics([]models.VM{vm}, nil, time.Now().Add(-time.Second))
previous = &vm
- if strings.HasPrefix(kind, "typed ") {
+ if preserveOrigins {
// The safe fixture's actual builder/broadcast output is also
// available for consuming browser proof. Do not hand-author a
// fresh/last-known carrier or replace its observation time.
@@ -135,7 +151,11 @@ func testGuestAgentTransportDeferralKeepsLastKnownHistory(t *testing.T, kinds ..
if err != nil {
t.Fatal(err)
}
- t.Logf("TYPED_REPLY_PRODUCER %s", wire)
+ marker := "TYPED_REPLY_PRODUCER"
+ if strings.HasPrefix(kind, "foreign ") {
+ marker = "COMMAND_REPLY_PRODUCER"
+ }
+ t.Logf("%s %s", marker, wire)
}
return vm, source
}
@@ -146,7 +166,7 @@ func testGuestAgentTransportDeferralKeepsLastKnownHistory(t *testing.T, kinds ..
memKey, metadataKey := guestMemoryCacheKey("transport", "node", 105), guestMetadataCacheKey("transport", "node", 105)
memory := m.vmAgentMemCache[memKey]
metadata := m.guestMetadataCache[metadataKey]
- if !strings.HasPrefix(kind, "typed ") {
+ if !preserveOrigins {
memory.fetchedAt = time.Now().Add(-2 * vmAgentMemCacheTTL)
m.vmAgentMemCache[memKey] = memory
metadata.fetchedAt = time.Now().Add(-2 * guestMetadataCacheTTL)
@@ -161,7 +181,7 @@ func testGuestAgentTransportDeferralKeepsLastKnownHistory(t *testing.T, kinds ..
phase.Store(1)
res.CPU = 0.2
wantMemorySource := "previous-snapshot"
- if strings.HasPrefix(kind, "typed ") {
+ if preserveOrigins {
wantMemorySource = "guest-agent-meminfo" // The untouched warm cache retains its actual origin.
}
for i := 0; i < 2; i++ {
@@ -180,7 +200,7 @@ func testGuestAgentTransportDeferralKeepsLastKnownHistory(t *testing.T, kinds ..
if deferred.ID != initial.ID || deferred.GuestAgentStatus != "deferred" || deferred.DiskStatusReason != wantReason || deferred.Memory.Used != initial.Memory.Used || source != wantMemorySource || deferred.Disk.Used != initial.Disk.Used || !reflect.DeepEqual(deferred.NetworkInterfaces, initial.NetworkInterfaces) {
t.Fatalf("uncertain command lost truthful continuity: source=%s vm=%+v", source, deferred)
}
- if strings.HasPrefix(kind, "typed ") && (deferred.Memory.Observation.State != "last-known" || !deferred.Memory.Observation.ObservedAt.Equal(initial.Memory.Observation.ObservedAt)) {
+ if preserveOrigins && (deferred.Memory.Observation.State != "last-known" || !deferred.Memory.Observation.ObservedAt.Equal(initial.Memory.Observation.ObservedAt)) {
t.Fatal("typed reply renewed or promoted the original memory observation")
}
if !reflect.DeepEqual(m.vmAgentMemCache[memKey], memory) || !reflect.DeepEqual(m.guestMetadataCache[metadataKey], metadata) {
diff --git a/pkg/proxmox/guest_agent_command_response_test.go b/pkg/proxmox/guest_agent_command_response_test.go
new file mode 100644
index 0000000000..4e40cca38a
--- /dev/null
+++ b/pkg/proxmox/guest_agent_command_response_test.go
@@ -0,0 +1,213 @@
+package proxmox
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func commandReplyTestClient(t *testing.T, host string) *Client {
+ t.Helper()
+ c := backupTestClient(t, host)
+ // This fixture checks request counts and admission, not listener latency.
+ c.httpClient.Timeout = 15 * time.Second
+ t.Cleanup(c.httpClient.CloseIdleConnections)
+ return c
+}
+
+func guestReplyFamily(reader string) string {
+ switch reader {
+ case "os":
+ return "os"
+ case "version":
+ return "version"
+ case "filesystem":
+ return "filesystem"
+ case "network":
+ return "network"
+ default:
+ return "file"
+ }
+}
+
+// These are valid, synthetic replies for another existing command, not a
+// native command-ID collision replay. A generic type/envelope check accepts
+// them; the actual HTTP reader must retain uncertainty before releasing work.
+func TestGuestAgentForeignReplyDefersEveryReader(t *testing.T) {
+ replies := map[string]string{
+ "os": `{"data":{"id":"linux","name":"Linux"}}`,
+ "version": `{"data":{"result":{"version":"1.0","supported_commands":[]}}}`,
+ "filesystem": `{"data":{"result":[{"name":"root","mountpoint":"/","total-bytes":1024,"used-bytes":512}]}}`,
+ "network": `{"data":{"result":[{"name":"eth0","hardware-address":"02:00:00:00:00:01","ip-addresses":[]}]}}`,
+ "file": `{"data":{"content":"MemTotal: 1024 kB\nMemAvailable: 512 kB\n","truncated":false}}`,
+ "error": `{"data":{"error":{"class":"GenericError","desc":"synthetic error"}}}`,
+ }
+ for reader, read := range backupAgentReads() {
+ for family, body := range replies {
+ if guestReplyFamily(reader) == family {
+ continue
+ }
+ t.Run(reader+"/"+family, func(t *testing.T) {
+ if !guestAgentSuccessResponse([]byte(body)) {
+ t.Fatal("control is not a valid generic reply")
+ }
+ var commands, configs atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/config"):
+ configs.Add(1)
+ fmt.Fprint(w, `{"data":{}}`)
+ case strings.HasSuffix(r.URL.Path, "/status/current"):
+ fmt.Fprint(w, `{"data":{"status":"running","cpu":0.25,"diskread":4096}}`)
+ default:
+ if commands.Add(1) == 1 {
+ fmt.Fprint(w, body)
+ return
+ }
+ backupAgentPayload(w, r)
+ }
+ }))
+ defer server.Close()
+ // Independent cases must not inherit uncertainty if the kernel
+ // reuses a listener port. Within a case all clients share a key.
+ host := server.URL + "/command-reply-fixture/" + reader + "/" + family
+ c := commandReplyTestClient(t, host)
+ if err := read(context.Background(), c, 105); GuestAgentDeferredReason(err) != "agent-completion-unverified" {
+ t.Fatalf("foreign %s reply released %s admission: %v", family, reader, err)
+ }
+ if commands.Load() != 1 || configs.Load() != 1 {
+ t.Fatal("foreign reply triggered a postflight lock read or replay")
+ }
+ diagnostic := commandReplyTestClient(t, host)
+ for later, next := range backupAgentReads() {
+ if err := next(context.Background(), diagnostic, 105); GuestAgentDeferredReason(err) != "agent-cooldown" {
+ t.Errorf("next %s escaped foreign-reply uncertainty: %v", later, err)
+ }
+ }
+ if commands.Load() != 1 || configs.Load() != 1 {
+ t.Fatal("foreign reply permitted another command or config request")
+ }
+ status, err := c.GetVMStatus(context.Background(), "node", 105)
+ if err != nil || status.CPU != 0.25 || status.DiskRead != 4096 {
+ t.Errorf("independent PVE counters stopped: %+v / %v", status, err)
+ }
+ if _, err := diagnostic.GetVMAgentInfo(context.Background(), "node", 106); err != nil {
+ t.Errorf("another VM was fenced: %v", err)
+ }
+ t.Logf("foreign=%s reader=%s; one original command, six blocked follow-ups, live PVE and independent VM preserved", family, reader)
+ })
+ }
+ }
+}
+
+func TestGuestAgentForeignReplySharesUnrenewedFenceAndResumes(t *testing.T) {
+ var commands atomic.Int32
+ var healthy atomic.Bool
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/nodes"):
+ fmt.Fprint(w, `{"data":[]}`)
+ case strings.HasSuffix(r.URL.Path, "/config"):
+ fmt.Fprint(w, `{"data":{}}`)
+ default:
+ commands.Add(1)
+ if strings.Contains(r.URL.Path, "/qemu/105/") && !healthy.Load() {
+ fmt.Fprint(w, `{"data":{"result":{"qemu-ga":{"version":"1.0"}}}}`)
+ return
+ }
+ backupAgentPayload(w, r)
+ }
+ })
+ a, b, other := httptest.NewServer(handler), httptest.NewServer(handler), httptest.NewServer(handler)
+ defer a.Close()
+ defer b.Close()
+ defer other.Close()
+ hostA, hostB, hostOther := a.URL+"/alias-shape", b.URL+"/alias-shape", other.URL+"/other-shape"
+ cc := NewClusterClient("command-reply-fixture", ClientConfig{Host: hostA, TokenName: "fixture@pve!pulse", TokenValue: "fixture"}, []string{hostA, hostB}, nil)
+ if _, err := commandReplyTestClient(t, hostA).GetVMFSInfo(context.Background(), "node", 105); GuestAgentDeferredReason(err) != "agent-completion-unverified" {
+ t.Fatal(err)
+ }
+ guestAgentGuards.Lock()
+ original := make(map[guestAgentGuardKey]guestAgentGuardEntry)
+ for key, entry := range guestAgentGuards.entries {
+ original[key] = entry
+ }
+ guestAgentGuards.Unlock()
+ if _, err := cc.GetVMNetworkInterfaces(context.Background(), "migrated", 105); GuestAgentDeferredReason(err) != "agent-cooldown" {
+ t.Fatalf("cluster alias bypassed uncertainty: %v", err)
+ }
+ if _, err := commandReplyTestClient(t, hostB).GetVMAgentVersion(context.Background(), "migrated", 105); GuestAgentDeferredReason(err) != "agent-cooldown" {
+ t.Fatalf("fresh alias client bypassed uncertainty: %v", err)
+ }
+ guestAgentGuards.Lock()
+ unchanged := reflect.DeepEqual(original, guestAgentGuards.entries)
+ guestAgentGuards.Unlock()
+ if commands.Load() != 1 || !unchanged {
+ t.Fatal("follow-up dispatched work or renewed the original fence")
+ }
+ if _, err := commandReplyTestClient(t, hostB).GetVMFSInfo(context.Background(), "node", 106); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := commandReplyTestClient(t, hostOther).GetVMAgentVersion(context.Background(), "node", 105); err != nil {
+ t.Fatalf("independent source blocked: %v", err)
+ }
+ // Expire only this fixture's original transport fence. No clock sleep,
+ // re-enactment, guard reset or live/native operation is performed.
+ guestAgentGuards.Lock()
+ for key, entry := range guestAgentGuards.entries {
+ if key.vmid == 105 && (key.endpoint == hostA+"/api2/json" || key.endpoint == hostB+"/api2/json") {
+ entry.until = time.Now().Add(-time.Second)
+ guestAgentGuards.entries[key] = entry
+ }
+ }
+ guestAgentGuards.Unlock()
+ healthy.Store(true)
+ for reader, read := range backupAgentReads() {
+ if err := read(context.Background(), commandReplyTestClient(t, hostB), 105); err != nil {
+ t.Errorf("completed compatible %s read did not resume: %v", reader, err)
+ }
+ }
+}
+
+func TestGuestAgentCommandReplyPreservesCompatibleEmptyAndPartialData(t *testing.T) {
+ replies := map[string][]string{
+ "os": {`{"data":{"name":"Linux","version":"fixture","future":{"enabled":true}}}`, `{"data":{"result":{"id":"linux","version-id":"1"}}}`},
+ "version": {`{"data":{"result":{"version":{"version":"1.0"},"supported_commands":[]}}}`, `{"data":{"result":{"qemu-ga":{"version":"1.0"}}}}`},
+ "filesystem": {`{"data":{"result":{"mountpoint":"/","total-bytes":1024,"used-bytes":0},"future":true}}`, `{"data":{"result":[null,{"mountpoint":"/","used-bytes":512}]}}`},
+ "network": {`{"data":{"result":{"name":"eth0","hardware-address":"02:00:00:00:00:01"}}}`, `{"data":{"result":[null,{"name":"eth0"}],"future":true}}`},
+ "file": {`{"data":{"content":"MemTotal: 1024 kB\nMemAvailable: 0 kB\n","truncated":false}}`, `{"data":{"content":"","truncated":true}}`},
+ }
+ for reader, read := range backupAgentReads() {
+ compatible := append([]string{`{"data":{}}`, `{"data":{"result":null,"content":null,"truncated":null}}`}, replies[guestReplyFamily(reader)]...)
+ for index, body := range compatible {
+ t.Run(fmt.Sprintf("%s/%d", reader, index), func(t *testing.T) {
+ var commands atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "/config") {
+ fmt.Fprint(w, `{"data":{}}`)
+ return
+ }
+ if commands.Add(1) == 1 {
+ fmt.Fprint(w, body)
+ return
+ }
+ backupAgentPayload(w, r)
+ }))
+ defer server.Close()
+ c := commandReplyTestClient(t, server.URL)
+ if err := read(context.Background(), c, 105); GuestAgentDeferredReason(err) != "" {
+ t.Fatalf("compatible reply paused %s: %v", reader, err)
+ }
+ if _, err := c.GetVMAgentInfo(context.Background(), "node", 105); err != nil || commands.Load() != 2 {
+ t.Fatalf("completed empty/partial measurement blocked OS discovery: %v", err)
+ }
+ })
+ }
+ }
+}
diff --git a/pkg/proxmox/guest_agent_guard.go b/pkg/proxmox/guest_agent_guard.go
index 2a5abe14cf..7d2df56b91 100644
--- a/pkg/proxmox/guest_agent_guard.go
+++ b/pkg/proxmox/guest_agent_guard.go
@@ -261,7 +261,7 @@ func (c *Client) getGuestAgent(ctx context.Context, path, node string, vmid int)
// A completed HTTP body is not a completed QGA reply if it is malformed,
// ambiguous, or only a JSON prefix. Validate before releasing admission,
// not in the method decoder after another guest command can be queued.
- if resp.StatusCode != http.StatusOK || !guestAgentSuccessResponse(body) {
+ if resp.StatusCode != http.StatusOK || !guestAgentCommandResponse(path, body) {
uncertain = true
return nil, &guestAgentDeferredError{reason: "agent-completion-unverified"}
}
diff --git a/pkg/proxmox/guest_agent_response.go b/pkg/proxmox/guest_agent_response.go
index 1b7443b566..13bd072acf 100644
--- a/pkg/proxmox/guest_agent_response.go
+++ b/pkg/proxmox/guest_agent_response.go
@@ -119,21 +119,26 @@ func guestAgentErrorMessage(body []byte) (string, bool) {
// envelope or case-insensitive overwrite as a completed reply. This is not
// payload-to-command provenance or proof of native QGA completion/thaw.
func guestAgentSuccessResponse(body []byte) bool {
+ _, valid := guestAgentSuccessData(body)
+ return valid
+}
+
+func guestAgentSuccessData(body []byte) (map[string]json.RawMessage, bool) {
if !utf8.Valid(body) {
- return false
+ return nil, false
}
envelope, ok := guestAgentResponseFields(body, "data")
if !ok {
- return false
+ return nil, false
}
data, ok := guestAgentResponseFields(envelope["data"])
if !ok {
- return false
+ return nil, false
}
for name, value := range data {
for _, canonical := range []string{"result", "content", "truncated"} {
if name != canonical && strings.EqualFold(name, canonical) {
- return false
+ return nil, false
}
}
// A well-formed envelope can still contain an impossible guest reply.
@@ -146,18 +151,105 @@ func guestAgentSuccessResponse(body []byte) bool {
switch name {
case "result":
if !bytes.Equal(value, []byte("null")) && value[0] != '{' && value[0] != '[' {
- return false
+ return nil, false
}
case "content":
if !bytes.Equal(value, []byte("null")) && value[0] != '"' {
- return false
+ return nil, false
}
case "truncated":
if !bytes.Equal(value, []byte("null")) && !bytes.Equal(value, []byte("true")) && !bytes.Equal(value, []byte("false")) {
- return false
+ return nil, false
}
}
}
+ return data, true
+}
+
+// Valid field types alone do not make a reply compatible with the command
+// sent. For example, a file-read body is valid JSON but cannot complete an
+// outstanding filesystem request. Refuse known foreign reply fields before
+// releasing shared admission. This detects contradictory shapes, not native
+// payload provenance: shared fields (name/version), empty/null results and
+// unknown metadata cannot identify the originating command and remain valid.
+func guestAgentCommandResponse(path string, body []byte) bool {
+ data, valid := guestAgentSuccessData(body)
+ if !valid {
+ return false
+ }
+ if _, _, valid := guestAgentPath(path); !valid {
+ return false
+ }
+ command := strings.SplitN(path, "?", 2)[0]
+ command = command[strings.LastIndex(command, "/")+1:]
+ switch command {
+ case "get-osinfo", "info", "get-fsinfo", "network-get-interfaces", "file-read":
+ default:
+ return false
+ }
+ if !guestAgentReplyFieldsCompatible(data, command) {
+ return false
+ }
+ result := bytes.TrimSpace(data["result"])
+ if len(result) == 0 || bytes.Equal(result, []byte("null")) {
+ return true
+ }
+ if command == "file-read" {
+ return false // file-read returns content/truncated, not a result payload.
+ }
+ if result[0] == '{' {
+ fields, valid := guestAgentResponseFields(result)
+ return valid && guestAgentReplyFieldsCompatible(fields, command)
+ }
+ if command == "get-osinfo" || command == "info" {
+ return false // Both information commands return dictionaries, not lists.
+ }
+ decoder := json.NewDecoder(bytes.NewReader(result))
+ if start, err := decoder.Token(); err != nil || start != json.Delim('[') {
+ return false
+ }
+ for decoder.More() {
+ var row json.RawMessage
+ if decoder.Decode(&row) != nil {
+ return false
+ }
+ // Existing inventory decoders own malformed/partial rows. Only a
+ // recognizable foreign dictionary contradicts the command here.
+ fields, valid := guestAgentResponseFields(row)
+ if valid && !guestAgentReplyFieldsCompatible(fields, command) {
+ return false
+ }
+ }
+ end, err := decoder.Token()
+ return err == nil && end == json.Delim(']')
+}
+
+func guestAgentReplyFieldsCompatible(fields map[string]json.RawMessage, command string) bool {
+ for name, value := range fields {
+ // Null foreign fields carry no affirmative payload identity; keep
+ // the established null-field and completed-empty semantics.
+ if bytes.Equal(bytes.TrimSpace(value), []byte("null")) {
+ continue
+ }
+ var owner string
+ switch strings.ToLower(name) {
+ case "content", "truncated":
+ owner = "file-read"
+ case "id", "kernel-release", "kernel-version", "machine", "pretty-name", "version-id":
+ owner = "get-osinfo"
+ case "qemu-ga", "supported-commands", "supported_commands":
+ owner = "info"
+ case "mountpoint", "total-bytes", "total-bytes-privileged", "used-bytes", "disk":
+ owner = "get-fsinfo"
+ case "hardware-address", "ip-addresses", "statistics", "has-ipv4-synth-gateway", "has-ipv6-synth-gateway":
+ owner = "network-get-interfaces"
+ case "error", "errors":
+ return false
+ }
+ if owner != "" && owner != command {
+ return false
+ }
+ }
return true
}