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.

feat(patrol): verify Docker actions independently

rcourtman6163a2a5645b
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index ff1fbca173..fb01c38102 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -1671,6 +1671,16 @@ the intentionally sparse public response.
It may render only the strict redacted projection produced by the matching
managed-runtime run and must reject missing or mismatched proposal, action,
attempt, receipt, finding, and evidence identities.
+ Unified Agent registration separately advertises the versioned, read-only
+ Docker observation protocol. `docker_container_observe` is not an action,
+ preflight grant, or durable operation: it accepts only an action-bound
+ digest, runtime enum, and immutable container ID, invokes the fixed local
+ Docker/Podman lifecycle inspector, and returns either one bounded snapshot
+ or a typed inconclusive reason. It must never enter the operation receipt
+ store, execute a mutation, accept command text, or infer action truth. The
+ server validates freshness and correlation and owns all evidence-class and
+ verification projection. Older agents advertise version zero and therefore
+ fail closed without receiving an unsupported request.
RG-06 has a separate mutation harness at
`scripts/intelligence_lab/patrol_autonomy_colima.py` and
`internal/api/patrol_autonomy_colima_real_lab_test.go`. It must run from a
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 07388d1d90..aa45a7eb16 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -7258,6 +7258,17 @@ and terminal push copy stays explicitly inconclusive. This keeps legacy
single-outcome consumers conservative while `ActionDisposition.ActionResultV2`
retains both truth axes and the evidence source.
+The production Docker/Podman Patrol action path now supplies the independent
+postcondition that this rule requires. After a successful typed lifecycle or
+update receipt, the API executor performs a separate action-bound daemon
+observation through the versioned read-only Unified Agent protocol. Only a
+fresh, identity-matched daemon snapshot from the distinct daemon observer
+trust domain can project to `fix_verified`; unsupported older agents,
+inspection failure, stale facts, or mismatched identities remain
+`fix_verification_unknown`. The mutation receipt's own same-agent readback
+continues to project only `agent_attested` evidence, so adding the production
+observer does not loosen the verification rule.
+
### Proxmox guest lifecycle Patrol detector floor
`internal/ai/findings_proxmox_lifecycle.go` owns the deterministic production
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 5a3f85ad61..15de29c53c 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -8935,6 +8935,21 @@ the action, subject, observation and receipt times, before/after facts, and
canonical evidence digest. It is independent operational evidence, not a
cryptographic attestation.
+Production Docker and Podman lifecycle execution must install that observer,
+not leave it as a real-lab-only seam. After the typed mutation receipt returns,
+the API executor issues one separate, bounded `docker_container_observe`
+request through the authenticated Unified Agent session. The request contains
+only an action ID, immutable container ID, runtime enum, protocol version and
+canonical digest; it carries no operation verb, command, approval, dispatch
+lease, or mutation authority. The agent transports a fresh fixed daemon
+inspection but does not author action truth. The API validates the action and
+subject binding, freshness, protocol version and digest, assigns the daemon
+observer trust domain, and alone projects the observation into
+`ActionResultV2`. Missing support, inspection failure, disconnect, timeout,
+stale evidence, or identity drift retains the original agent-attested or
+inconclusive result. It must never downgrade execution success or fabricate
+independence.
+
Proxmox VM and LXC lifecycle execution now consumes that same two-axis truth
contract in production. The node agent remains the executor, while the API
composition root injects the tenant-scoped monitoring client as a direct
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 974b5885ba..42ef1efc12 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -2400,6 +2400,16 @@ not-attempted or inconclusive verification remains verification unknown. A
successful execution never overwrites contradictory verification. Task 11
still owns browser wording and proof for the distinct terminal states.
+Docker/Podman Patrol remediation must have a production post-action observer,
+not only a qualification-lab injection. The canonical action executor issues a
+separate versioned, action-bound daemon observation after the typed mutation
+receipt. Only fresh independent daemon evidence may advance the originating
+investigation and finding to `fix_verified`; older agents, observation errors,
+stale snapshots, digest or subject mismatch, and same-agent receipt evidence
+remain verification unknown. This closes the prior structural dead end where
+an unhealthy-container restart could execute in production but the executor
+had no observer capable of satisfying Patrol's verified-outcome contract.
+
Patrol now consumes the server-derived effective Autopilot mode. Requested
`full` is admitted only with a current persisted human acknowledgement and
exact activation for the same actor credential and organization; legacy
diff --git a/internal/agentexec/docker_observation_codec.go b/internal/agentexec/docker_observation_codec.go
new file mode 100644
index 0000000000..bd73ff79b3
--- /dev/null
+++ b/internal/agentexec/docker_observation_codec.go
@@ -0,0 +1,137 @@
+package agentexec
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"
+)
+
+const DockerContainerObservationProtocolVersion = 1
+
+const dockerContainerObservationMaxClockSkew = 5 * time.Minute
+
+func DecodeDockerContainerObservationPayload(data []byte) (DockerContainerObservationPayload, error) {
+ var payload DockerContainerObservationPayload
+ if err := decodeStrictDockerLifecycle(data, &payload); err != nil {
+ return DockerContainerObservationPayload{}, err
+ }
+ if err := ValidateDockerContainerObservationPayload(&payload); err != nil {
+ return DockerContainerObservationPayload{}, err
+ }
+ return payload, nil
+}
+
+func DecodeDockerContainerObservationResultPayload(data []byte) (DockerContainerObservationResultPayload, error) {
+ var result DockerContainerObservationResultPayload
+ if err := decodeStrictDockerLifecycle(data, &result); err != nil {
+ return DockerContainerObservationResultPayload{}, err
+ }
+ if err := ValidateDockerContainerObservationResultPayload(&result); err != nil {
+ return DockerContainerObservationResultPayload{}, err
+ }
+ return result, nil
+}
+
+func BindDockerContainerObservationPayload(payload *DockerContainerObservationPayload) error {
+ if payload == nil {
+ return fmt.Errorf("docker container observation payload is required")
+ }
+ payload.ProtocolVersion = DockerContainerObservationProtocolVersion
+ digest, err := dockerContainerObservationRequestDigest(*payload)
+ if err != nil {
+ return err
+ }
+ payload.RequestDigest = digest
+ return nil
+}
+
+func dockerContainerObservationRequestDigest(payload DockerContainerObservationPayload) (string, error) {
+ return operationreceipt.DigestCanonicalJSON(struct {
+ ActionID string `json:"action_id"`
+ ProtocolVersion int `json:"protocol_version"`
+ Runtime string `json:"runtime"`
+ ContainerID string `json:"container_id"`
+ }{strings.TrimSpace(payload.ActionID), payload.ProtocolVersion, strings.ToLower(strings.TrimSpace(payload.Runtime)), strings.ToLower(strings.TrimSpace(payload.ContainerID))})
+}
+
+func ValidateDockerContainerObservationPayload(payload *DockerContainerObservationPayload) error {
+ if payload == nil {
+ return fmt.Errorf("docker container observation payload is required")
+ }
+ payload.RequestID = strings.TrimSpace(payload.RequestID)
+ payload.ActionID = strings.TrimSpace(payload.ActionID)
+ payload.RequestDigest = strings.TrimSpace(payload.RequestDigest)
+ payload.Runtime = strings.ToLower(strings.TrimSpace(payload.Runtime))
+ payload.ContainerID = strings.ToLower(strings.TrimSpace(payload.ContainerID))
+ if payload.RequestID == "" || len(payload.RequestID) > maxRequestIDLength || payload.ActionID == "" || len(payload.ActionID) > maxRequestIDLength {
+ return fmt.Errorf("invalid docker observation request identity")
+ }
+ if payload.ProtocolVersion != DockerContainerObservationProtocolVersion {
+ return fmt.Errorf("unsupported docker observation protocol version %d", payload.ProtocolVersion)
+ }
+ if payload.Runtime != "docker" && payload.Runtime != "podman" {
+ return fmt.Errorf("unsupported container runtime %q", payload.Runtime)
+ }
+ if !dockerContainerIDPattern.MatchString(payload.ContainerID) {
+ return fmt.Errorf("container id must be an immutable hexadecimal id")
+ }
+ digest, err := dockerContainerObservationRequestDigest(*payload)
+ if err != nil {
+ return err
+ }
+ if payload.RequestDigest != digest {
+ return fmt.Errorf("docker observation request digest mismatch")
+ }
+ return nil
+}
+
+func ValidateDockerContainerObservationResultPayload(result *DockerContainerObservationResultPayload) error {
+ if result == nil {
+ return fmt.Errorf("docker container observation result is required")
+ }
+ result.RequestID = strings.TrimSpace(result.RequestID)
+ result.ActionID = strings.TrimSpace(result.ActionID)
+ result.RequestDigest = strings.TrimSpace(result.RequestDigest)
+ result.ReasonCode = strings.TrimSpace(result.ReasonCode)
+ result.Snapshot.ContainerID = strings.ToLower(strings.TrimSpace(result.Snapshot.ContainerID))
+ result.Snapshot.State = strings.ToLower(strings.TrimSpace(result.Snapshot.State))
+ result.Snapshot.ObservedAt = result.Snapshot.ObservedAt.UTC()
+ result.Snapshot.StartedAt = result.Snapshot.StartedAt.UTC()
+ if result.RequestID == "" || len(result.RequestID) > maxRequestIDLength || result.ActionID == "" || len(result.ActionID) > maxRequestIDLength {
+ return fmt.Errorf("invalid docker observation result identity")
+ }
+ if result.ProtocolVersion != DockerContainerObservationProtocolVersion || !hostUpdateInventoryHashPattern.MatchString(result.RequestDigest) {
+ return fmt.Errorf("invalid docker observation result binding")
+ }
+ if !result.Observed {
+ if !IsActionRefusalReasonCode(result.ReasonCode) || result.Snapshot.ContainerID != "" || result.Snapshot.State != "" || result.Snapshot.Running || !result.Snapshot.StartedAt.IsZero() || result.Snapshot.RestartCount != 0 || !result.Snapshot.ObservedAt.IsZero() {
+ return fmt.Errorf("inconclusive docker observation requires a bounded reason and no snapshot")
+ }
+ return nil
+ }
+ if result.ReasonCode != "" || !dockerContainerIDPattern.MatchString(result.Snapshot.ContainerID) || result.Snapshot.State == "" || len(result.Snapshot.State) > 32 || result.Snapshot.RestartCount < 0 || result.Snapshot.ObservedAt.IsZero() {
+ return fmt.Errorf("invalid docker observation snapshot")
+ }
+ return nil
+}
+
+func ValidateDockerContainerObservationResultForRequest(req DockerContainerObservationPayload, result DockerContainerObservationResultPayload, receivedAt time.Time) error {
+ if err := ValidateDockerContainerObservationPayload(&req); err != nil {
+ return err
+ }
+ if err := ValidateDockerContainerObservationResultPayload(&result); err != nil {
+ return err
+ }
+ if result.RequestID != req.RequestID || result.ActionID != req.ActionID || result.ProtocolVersion != req.ProtocolVersion || result.RequestDigest != req.RequestDigest || (result.Observed && result.Snapshot.ContainerID != req.ContainerID) {
+ return fmt.Errorf("docker observation result identity mismatch")
+ }
+ if !result.Observed {
+ return nil
+ }
+ if receivedAt.IsZero() || result.Snapshot.ObservedAt.After(receivedAt.UTC().Add(dockerContainerObservationMaxClockSkew)) || result.Snapshot.ObservedAt.Before(receivedAt.UTC().Add(-15*time.Minute)) {
+ return fmt.Errorf("docker observation result is stale or clock-skewed")
+ }
+ return nil
+}
diff --git a/internal/agentexec/docker_observation_codec_test.go b/internal/agentexec/docker_observation_codec_test.go
new file mode 100644
index 0000000000..0d79315f03
--- /dev/null
+++ b/internal/agentexec/docker_observation_codec_test.go
@@ -0,0 +1,58 @@
+package agentexec
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestDockerContainerObservationContractBindsRequestAndFreshResult(t *testing.T) {
+ now := time.Now().UTC()
+ req := DockerContainerObservationPayload{
+ RequestID: "observe-1", ActionID: "action-1", Runtime: "docker", ContainerID: strings.Repeat("a", 64),
+ }
+ if err := BindDockerContainerObservationPayload(&req); err != nil {
+ t.Fatal(err)
+ }
+ encoded, err := json.Marshal(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ decoded, err := DecodeDockerContainerObservationPayload(encoded)
+ if err != nil {
+ t.Fatal(err)
+ }
+ result := DockerContainerObservationResultPayload{
+ RequestID: decoded.RequestID, ActionID: decoded.ActionID, ProtocolVersion: decoded.ProtocolVersion, RequestDigest: decoded.RequestDigest,
+ Observed: true,
+ Snapshot: DockerContainerLifecycleSnapshot{ContainerID: decoded.ContainerID, State: "running", Running: true, ObservedAt: now},
+ }
+ if err := ValidateDockerContainerObservationResultForRequest(decoded, result, now); err != nil {
+ t.Fatalf("fresh bound result rejected: %v", err)
+ }
+
+ tampered := result
+ tampered.ActionID = "different-action"
+ if err := ValidateDockerContainerObservationResultForRequest(decoded, tampered, now); err == nil {
+ t.Fatal("cross-action observation result was accepted")
+ }
+ stale := result
+ stale.Snapshot.ObservedAt = now.Add(-16 * time.Minute)
+ if err := ValidateDockerContainerObservationResultForRequest(decoded, stale, now); err == nil {
+ t.Fatal("stale observation result was accepted")
+ }
+}
+
+func TestDockerContainerObservationWireCarriesFactsNotActionTruth(t *testing.T) {
+ payload, err := json.Marshal(DockerContainerObservationResultPayload{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ encoded := string(payload)
+ for _, forbidden := range []string{`"success"`, `"verification"`, `"evidence"`, `"independent"`, `"command"`, `"operation"`, `"approval"`} {
+ if strings.Contains(encoded, forbidden) {
+ t.Fatalf("observation wire contains forbidden action-truth or authority field %s: %s", forbidden, encoded)
+ }
+ }
+}
diff --git a/internal/agentexec/server.go b/internal/agentexec/server.go
index ad9e30c520..87c37c4ce8 100644
--- a/internal/agentexec/server.go
+++ b/internal/agentexec/server.go
@@ -61,29 +61,30 @@ var hostStorageCleanupFingerprintPattern = regexp.MustCompile(`^sha256:[a-f0-9]{
// Server manages WebSocket connections from agents
type Server struct {
- mu sync.RWMutex
- agents map[string]*agentConn // organizationID + agentID -> connection
- pendingReqs map[string]chan CommandResultPayload // scoped request key -> response channel
- pendingHostStorageCleanups map[string]chan HostStorageCleanupResultPayload // scoped request key -> typed storage-cleanup response
- pendingHostUpdates map[string]chan HostUpdateResultPayload // scoped request key -> typed host-update response
- pendingDockerContainerLifecycles map[string]chan DockerContainerLifecycleResultPayload
- pendingDockerContainerUpdates map[string]chan DockerContainerUpdateResultPayload
- pendingActionPreflights map[string]chan ActionPreflightResultPayload
- pendingHostOperations map[string]pendingHostOperation // scoped request key -> exact typed APT operation/query identity
- pendingOperationQueries map[string]pendingOperationQuery
- deploySubs map[string]chan DeployProgressPayload // deploySubKey(agentID, jobID) -> progress subscriber
- admitToken AgentRegistrationValidator
- validateSession AgentSessionValidator
- commandPolicy *CommandPolicy
- ipConnCounts map[string]int
- maxConnsPerIP int
- shutdown chan struct{}
- shutdownOnce sync.Once
- pingInterval time.Duration
- commandAuthorizationVerifier func(CommandAuthorizationRequest) error
- newCommandApprovalGrant func([]byte, string, ExecuteCommandPayload, time.Time, time.Duration) (*CommandApprovalGrant, error)
- now func() time.Time
- agentRegisteredNotifier func(AgentAdmission)
+ mu sync.RWMutex
+ agents map[string]*agentConn // organizationID + agentID -> connection
+ pendingReqs map[string]chan CommandResultPayload // scoped request key -> response channel
+ pendingHostStorageCleanups map[string]chan HostStorageCleanupResultPayload // scoped request key -> typed storage-cleanup response
+ pendingHostUpdates map[string]chan HostUpdateResultPayload // scoped request key -> typed host-update response
+ pendingDockerContainerLifecycles map[string]chan DockerContainerLifecycleResultPayload
+ pendingDockerContainerUpdates map[string]chan DockerContainerUpdateResultPayload
+ pendingDockerContainerObservations map[string]chan DockerContainerObservationResultPayload
+ pendingActionPreflights map[string]chan ActionPreflightResultPayload
+ pendingHostOperations map[string]pendingHostOperation // scoped request key -> exact typed APT operation/query identity
+ pendingOperationQueries map[string]pendingOperationQuery
+ deploySubs map[string]chan DeployProgressPayload // deploySubKey(agentID, jobID) -> progress subscriber
+ admitToken AgentRegistrationValidator
+ validateSession AgentSessionValidator
+ commandPolicy *CommandPolicy
+ ipConnCounts map[string]int
+ maxConnsPerIP int
+ shutdown chan struct{}
+ shutdownOnce sync.Once
+ pingInterval time.Duration
+ commandAuthorizationVerifier func(CommandAuthorizationRequest) error
+ newCommandApprovalGrant func([]byte, string, ExecuteCommandPayload, time.Time, time.Duration) (*CommandApprovalGrant, error)
+ now func() time.Time
+ agentRegisteredNotifier func(AgentAdmission)
}
const defaultOrganizationID = "default"
@@ -190,25 +191,26 @@ func NewServerWithAdmissionValidator(admit AgentRegistrationValidator, validateS
}
return &Server{
- agents: make(map[string]*agentConn),
- pendingReqs: make(map[string]chan CommandResultPayload),
- pendingHostStorageCleanups: make(map[string]chan HostStorageCleanupResultPayload),
- pendingHostUpdates: make(map[string]chan HostUpdateResultPayload),
- pendingDockerContainerLifecycles: make(map[string]chan DockerContainerLifecycleResultPayload),
- pendingDockerContainerUpdates: make(map[string]chan DockerContainerUpdateResultPayload),
- pendingActionPreflights: make(map[string]chan ActionPreflightResultPayload),
- pendingHostOperations: make(map[string]pendingHostOperation),
- pendingOperationQueries: make(map[string]pendingOperationQuery),
- deploySubs: make(map[string]chan DeployProgressPayload),
- admitToken: admit,
- validateSession: validateSession,
- commandPolicy: DefaultPolicy(),
- ipConnCounts: make(map[string]int),
- maxConnsPerIP: defaultMaxWebSocketConnectionsPerIP,
- shutdown: make(chan struct{}),
- pingInterval: defaultPingInterval,
- newCommandApprovalGrant: NewCommandApprovalGrant,
- now: time.Now,
+ agents: make(map[string]*agentConn),
+ pendingReqs: make(map[string]chan CommandResultPayload),
+ pendingHostStorageCleanups: make(map[string]chan HostStorageCleanupResultPayload),
+ pendingHostUpdates: make(map[string]chan HostUpdateResultPayload),
+ pendingDockerContainerLifecycles: make(map[string]chan DockerContainerLifecycleResultPayload),
+ pendingDockerContainerUpdates: make(map[string]chan DockerContainerUpdateResultPayload),
+ pendingDockerContainerObservations: make(map[string]chan DockerContainerObservationResultPayload),
+ pendingActionPreflights: make(map[string]chan ActionPreflightResultPayload),
+ pendingHostOperations: make(map[string]pendingHostOperation),
+ pendingOperationQueries: make(map[string]pendingOperationQuery),
+ deploySubs: make(map[string]chan DeployProgressPayload),
+ admitToken: admit,
+ validateSession: validateSession,
+ commandPolicy: DefaultPolicy(),
+ ipConnCounts: make(map[string]int),
+ maxConnsPerIP: defaultMaxWebSocketConnectionsPerIP,
+ shutdown: make(chan struct{}),
+ pingInterval: defaultPingInterval,
+ newCommandApprovalGrant: NewCommandApprovalGrant,
+ now: time.Now,
}
}
@@ -967,16 +969,17 @@ func (s *Server) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
ac := &agentConn{
conn: conn,
agent: ConnectedAgent{
- OrganizationID: admission.OrganizationID,
- TokenID: admission.TokenID,
- AgentID: admission.AgentID,
- Hostname: admission.Hostname,
- Version: reg.Version,
- Platform: reg.Platform,
- Tags: reg.Tags,
- ConnectedAt: time.Now(),
- OperationReceiptVersion: reg.OperationReceiptVersion,
- ActionPreflightVersion: reg.ActionPreflightVersion,
+ OrganizationID: admission.OrganizationID,
+ TokenID: admission.TokenID,
+ AgentID: admission.AgentID,
+ Hostname: admission.Hostname,
+ Version: reg.Version,
+ Platform: reg.Platform,
+ Tags: reg.Tags,
+ ConnectedAt: time.Now(),
+ OperationReceiptVersion: reg.OperationReceiptVersion,
+ ActionPreflightVersion: reg.ActionPreflightVersion,
+ DockerObservationVersion: reg.DockerObservationVersion,
},
admission: admission,
sessionKey: agentSessionKey(admission.OrganizationID, admission.AgentID),
@@ -1264,6 +1267,23 @@ func (s *Server) readLoop(ac *agentConn) {
}
}
+ case MsgTypeDockerContainerObserveResult:
+ result, decodeErr := DecodeDockerContainerObservationResultPayload(msg.Payload)
+ if decodeErr != nil {
+ log.Warn().Err(decodeErr).Str("agent_id", ac.agent.AgentID).Msg("Dropping invalid docker container observation result")
+ continue
+ }
+ s.mu.RLock()
+ ch, ok := s.pendingDockerContainerObservations[pendingRequestKey(connectionSessionKey(ac), result.RequestID)]
+ s.mu.RUnlock()
+ if ok {
+ select {
+ case ch <- result:
+ default:
+ log.Warn().Str("agent_id", ac.agent.AgentID).Str("request_id", result.RequestID).Msg("Docker observation result channel full, dropping")
+ }
+ }
+
case MsgTypeHostStorageCleanupResult:
result, decodeErr := DecodeHostStorageCleanupResultPayload(msg.Payload)
if decodeErr != nil {
@@ -1893,6 +1913,76 @@ func (s *Server) PreflightAction(ctx context.Context, agentID string, req Action
}
}
+// ObserveDockerContainer asks the current Unified Agent for a fresh read-only
+// Docker/Podman daemon observation. It is a separate request from the mutation
+// receipt and carries no dispatch authority.
+func (s *Server) ObserveDockerContainer(ctx context.Context, agentID string, req DockerContainerObservationPayload) (*DockerContainerObservationResultPayload, error) {
+ if s == nil {
+ return nil, fmt.Errorf("agent execution server is unavailable")
+ }
+ agentID = strings.TrimSpace(agentID)
+ if agentID == "" {
+ return nil, fmt.Errorf("agent id is required")
+ }
+ if strings.TrimSpace(req.RequestID) == "" {
+ req.RequestID = uuid.NewString()
+ }
+ if err := BindDockerContainerObservationPayload(&req); err != nil {
+ return nil, err
+ }
+ if err := ValidateDockerContainerObservationPayload(&req); err != nil {
+ return nil, err
+ }
+ ac, ok := s.connectionForContext(ctx, agentID)
+ if !ok {
+ return nil, fmt.Errorf("agent %s not connected", agentID)
+ }
+ if ac.agent.DockerObservationVersion != DockerContainerObservationProtocolVersion {
+ return nil, fmt.Errorf("agent does not support docker observation protocol")
+ }
+ ch := make(chan DockerContainerObservationResultPayload, 1)
+ key := pendingRequestKey(connectionSessionKey(ac), req.RequestID)
+ s.mu.Lock()
+ if _, exists := s.pendingDockerContainerObservations[key]; exists {
+ s.mu.Unlock()
+ return nil, fmt.Errorf("docker observation request %q is already pending", req.RequestID)
+ }
+ s.pendingDockerContainerObservations[key] = ch
+ s.mu.Unlock()
+ defer func() {
+ s.mu.Lock()
+ delete(s.pendingDockerContainerObservations, key)
+ s.mu.Unlock()
+ }()
+ msg, err := NewMessage(MsgTypeDockerContainerObserve, req.RequestID, req)
+ if err != nil {
+ return nil, err
+ }
+ ac.writeMu.Lock()
+ err = s.sendMessage(ac.conn, msg)
+ ac.writeMu.Unlock()
+ if err != nil {
+ return nil, fmt.Errorf("failed to send docker observation request: %w", err)
+ }
+ timer := time.NewTimer(20 * time.Second)
+ defer timer.Stop()
+ select {
+ case result := <-ch:
+ if err := ValidateDockerContainerObservationResultForRequest(req, result, s.currentTime()); err != nil {
+ return nil, fmt.Errorf("docker observation result validation failed: %w", err)
+ }
+ return &result, nil
+ case <-timer.C:
+ return nil, fmt.Errorf("docker observation timed out")
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-ac.done:
+ return nil, fmt.Errorf("agent %s disconnected before docker observation result", agentID)
+ case <-s.shutdown:
+ return nil, errServerShuttingDown
+ }
+}
+
// ExecuteHostStorageCleanup dispatches the closed package-cache cleanup
// operation. No command text, path, package selector, or removal policy crosses
// the server/agent boundary.
diff --git a/internal/agentexec/server_websocket_test.go b/internal/agentexec/server_websocket_test.go
index 92907e890f..c4fba9f0eb 100644
--- a/internal/agentexec/server_websocket_test.go
+++ b/internal/agentexec/server_websocket_test.go
@@ -749,6 +749,83 @@ func TestActionPreflightRoundTripIsReadOnlyAndDigestBound(t *testing.T) {
}
}
+func TestDockerContainerObservationRoundTripIsReadOnlyAndActionBound(t *testing.T) {
+ s := NewServer(allowAllTestTokens)
+ ts := newWSServer(t, s)
+ defer ts.Close()
+ conn, _, err := dialAgentExecWebSocket(t, ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{
+ AgentID: "docker-observer", Hostname: "host1", Version: "6", Platform: "linux", Token: "any",
+ DockerObservationVersion: DockerContainerObservationProtocolVersion,
+ }))
+ _ = wsReadRegisteredPayload(t, conn)
+ containerID := strings.Repeat("a", 64)
+ agentErr := make(chan error, 1)
+ go func() {
+ msg, readErr := wsReadRawMessageWithTimeout(conn, 2*time.Second)
+ if readErr != nil {
+ agentErr <- readErr
+ return
+ }
+ if msg.Type != MsgTypeDockerContainerObserve || bytes.Contains(*msg.Payload, []byte(`"command"`)) || bytes.Contains(*msg.Payload, []byte(`"operation"`)) {
+ agentErr <- fmt.Errorf("unexpected docker observation envelope: %#v", msg)
+ return
+ }
+ payload, decodeErr := DecodeDockerContainerObservationPayload(*msg.Payload)
+ if decodeErr != nil {
+ agentErr <- decodeErr
+ return
+ }
+ result := DockerContainerObservationResultPayload{
+ RequestID: payload.RequestID, ActionID: payload.ActionID, ProtocolVersion: payload.ProtocolVersion, RequestDigest: payload.RequestDigest,
+ Observed: true,
+ Snapshot: DockerContainerLifecycleSnapshot{ContainerID: payload.ContainerID, State: "running", Running: true, ObservedAt: time.Now().UTC()},
+ }
+ agentErr <- conn.WriteJSON(mustNewMessage(t, MsgTypeDockerContainerObserveResult, payload.RequestID, result))
+ }()
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ result, err := s.ObserveDockerContainer(ctx, "docker-observer", DockerContainerObservationPayload{ActionID: "action-1", Runtime: "docker", ContainerID: containerID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.ActionID != "action-1" || result.Snapshot.ContainerID != containerID || !result.Snapshot.Running {
+ t.Fatalf("result=%#v", result)
+ }
+ if err := <-agentErr; err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDockerContainerObservationRejectsUnsupportedAgentBeforeDispatch(t *testing.T) {
+ s := NewServer(allowAllTestTokens)
+ ts := newWSServer(t, s)
+ defer ts.Close()
+ conn, _, err := dialAgentExecWebSocket(t, ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{
+ AgentID: "older-agent", Hostname: "host1", Version: "6.3", Platform: "linux", Token: "any",
+ }))
+ _ = wsReadRegisteredPayload(t, conn)
+ started := time.Now()
+ _, err = s.ObserveDockerContainer(context.Background(), "older-agent", DockerContainerObservationPayload{
+ ActionID: "action-1", Runtime: "docker", ContainerID: strings.Repeat("a", 64),
+ })
+ if err == nil || !strings.Contains(err.Error(), "does not support docker observation protocol") {
+ t.Fatalf("error=%v", err)
+ }
+ if time.Since(started) > time.Second {
+ t.Fatalf("unsupported agent rejection was not immediate: %s", time.Since(started))
+ }
+}
+
func TestValidateHostUpdatePayloadRejectsOpenEndedAuthority(t *testing.T) {
for _, req := range []HostUpdatePayload{
{RequestID: "r1", ActionID: "a1", Operation: "run_command", ExpectedInventoryHash: "sha256:" + strings.Repeat("a", 64)},
diff --git a/internal/agentexec/types.go b/internal/agentexec/types.go
index b951d760ed..014dcf9abc 100644
--- a/internal/agentexec/types.go
+++ b/internal/agentexec/types.go
@@ -19,6 +19,7 @@ const (
MsgTypeHostUpdateResult MessageType = "host_update_result"
MsgTypeDockerContainerLifecycleResult MessageType = "docker_container_lifecycle_result"
MsgTypeDockerContainerUpdateResult MessageType = "docker_container_update_result"
+ MsgTypeDockerContainerObserveResult MessageType = "docker_container_observe_result"
MsgTypeActionPreflightResult MessageType = "action_preflight_result"
MsgTypeOperationQueryResult MessageType = "agent_operation_query_result"
@@ -31,6 +32,7 @@ const (
MsgTypeHostUpdate MessageType = "host_update"
MsgTypeDockerContainerLifecycle MessageType = "docker_container_lifecycle"
MsgTypeDockerContainerUpdate MessageType = "docker_container_update"
+ MsgTypeDockerContainerObserve MessageType = "docker_container_observe"
MsgTypeActionPreflight MessageType = "action_preflight"
MsgTypeOperationQuery MessageType = "agent_operation_query"
MsgTypeDeployPreflight MessageType = "deploy_preflight"
@@ -88,14 +90,15 @@ func (m Message) DecodePayload(target any) error {
// AgentRegisterPayload is sent by agent on connection
type AgentRegisterPayload struct {
- AgentID string `json:"agent_id"`
- Hostname string `json:"hostname"`
- Version string `json:"version"`
- Platform string `json:"platform"` // "linux", "windows", "darwin"
- Tags []string `json:"tags,omitempty"`
- Token string `json:"token"` // API token for authentication
- OperationReceiptVersion int `json:"operation_receipt_version,omitempty"`
- ActionPreflightVersion int `json:"action_preflight_version,omitempty"`
+ AgentID string `json:"agent_id"`
+ Hostname string `json:"hostname"`
+ Version string `json:"version"`
+ Platform string `json:"platform"` // "linux", "windows", "darwin"
+ Tags []string `json:"tags,omitempty"`
+ Token string `json:"token"` // API token for authentication
+ OperationReceiptVersion int `json:"operation_receipt_version,omitempty"`
+ ActionPreflightVersion int `json:"action_preflight_version,omitempty"`
+ DockerObservationVersion int `json:"docker_observation_version,omitempty"`
}
// RegisteredPayload is sent by server after successful registration
@@ -205,6 +208,29 @@ type DockerContainerLifecycleSnapshot struct {
ObservedAt time.Time `json:"observed_at"`
}
+// DockerContainerObservationPayload is a server-initiated, read-only daemon
+// observation made after a typed mutation has returned. It is deliberately a
+// separate protocol from the mutation receipt so verification is not authored
+// by the executor result.
+type DockerContainerObservationPayload struct {
+ RequestID string `json:"request_id"`
+ ActionID string `json:"action_id"`
+ ProtocolVersion int `json:"protocol_version"`
+ RequestDigest string `json:"request_digest"`
+ Runtime string `json:"runtime"`
+ ContainerID string `json:"container_id"`
+}
+
+type DockerContainerObservationResultPayload struct {
+ RequestID string `json:"request_id"`
+ ActionID string `json:"action_id"`
+ ProtocolVersion int `json:"protocol_version"`
+ RequestDigest string `json:"request_digest"`
+ Observed bool `json:"observed"`
+ ReasonCode string `json:"reason_code,omitempty"`
+ Snapshot DockerContainerLifecycleSnapshot `json:"snapshot"`
+}
+
type DockerContainerLifecycleResultPayload struct {
RequestID string `json:"request_id"`
ActionID string `json:"action_id"`
@@ -480,16 +506,17 @@ func IsActionRefusalReasonCode(code string) bool {
// ConnectedAgent represents an agent connected via WebSocket
type ConnectedAgent struct {
- OrganizationID string
- TokenID string
- AgentID string
- Hostname string
- Version string
- Platform string
- Tags []string
- ConnectedAt time.Time
- OperationReceiptVersion int
- ActionPreflightVersion int
+ OrganizationID string
+ TokenID string
+ AgentID string
+ Hostname string
+ Version string
+ Platform string
+ Tags []string
+ ConnectedAt time.Time
+ OperationReceiptVersion int
+ ActionPreflightVersion int
+ DockerObservationVersion int
}
// --- Deploy protocol payloads ---
diff --git a/internal/api/docker_container_action_executor.go b/internal/api/docker_container_action_executor.go
index 8b1750e5d5..edd415a949 100644
--- a/internal/api/docker_container_action_executor.go
+++ b/internal/api/docker_container_action_executor.go
@@ -34,7 +34,34 @@ type dockerContainerPostconditionObservation struct {
}
type dockerContainerPostconditionObserver interface {
- ObserveDockerContainer(context.Context, string, string) (dockerContainerPostconditionObservation, error)
+ ObserveDockerContainer(context.Context, string, string, string, string) (dockerContainerPostconditionObservation, error)
+}
+
+type dockerContainerObservationCommander interface {
+ ObserveDockerContainer(context.Context, string, agentexec.DockerContainerObservationPayload) (*agentexec.DockerContainerObservationResultPayload, error)
+}
+
+type agentDockerContainerPostconditionObserver struct {
+ commander dockerContainerObservationCommander
+}
+
+func (o agentDockerContainerPostconditionObserver) ObserveDockerContainer(ctx context.Context, actionID, agentID, runtime, containerID string) (dockerContainerPostconditionObservation, error) {
+ result, err := o.commander.ObserveDockerContainer(ctx, agentID, agentexec.DockerContainerObservationPayload{
+ ActionID: actionID, Runtime: runtime, ContainerID: containerID,
+ })
+ if err != nil {
+ return dockerContainerPostconditionObservation{}, err
+ }
+ if result == nil {
+ return dockerContainerPostconditionObservation{}, fmt.Errorf("docker daemon observation unavailable")
+ }
+ if !result.Observed {
+ return dockerContainerPostconditionObservation{}, fmt.Errorf("docker daemon observation unavailable: %s", strings.TrimSpace(result.ReasonCode))
+ }
+ return dockerContainerPostconditionObservation{
+ ObserverID: "docker-daemon:" + agentID, TrustDomain: "docker-daemon:" + agentID,
+ Method: "typed_docker_daemon_observation", Snapshot: result.Snapshot, ReceivedAt: time.Now().UTC(),
+ }, nil
}
type dockerContainerLifecycleAgentCommander interface {
@@ -106,7 +133,11 @@ func newDockerContainerActionExecutor(resources *ResourceHandlers, agents action
if resources == nil || agents == nil {
return nil
}
- return dockerContainerActionExecutor{resources: resources, agents: agents}
+ executor := dockerContainerActionExecutor{resources: resources, agents: agents}
+ if commander, ok := agents.(dockerContainerObservationCommander); ok {
+ executor.observer = agentDockerContainerPostconditionObserver{commander: commander}
+ }
+ return executor
}
func (e dockerContainerActionExecutor) ActionHandlerNames() []string {
@@ -183,7 +214,7 @@ func (e dockerContainerActionExecutor) ExecuteAction(ctx context.Context, record
}
var independent *dockerContainerPostconditionObservation
if e.observer != nil {
- if observation, observeErr := e.observer.ObserveDockerContainer(ctx, record.ID, req.ContainerID); observeErr == nil {
+ if observation, observeErr := e.observer.ObserveDockerContainer(ctx, record.ID, agentID, runtime, req.ContainerID); observeErr == nil {
independent = &observation
}
}
@@ -231,7 +262,7 @@ func (e dockerContainerActionExecutor) executeDockerContainerUpdate(ctx context.
}
var independent *dockerContainerPostconditionObservation
if e.observer != nil && result.NewContainerID != "" {
- if observation, observeErr := e.observer.ObserveDockerContainer(ctx, record.ID, result.NewContainerID); observeErr == nil {
+ if observation, observeErr := e.observer.ObserveDockerContainer(ctx, record.ID, agentID, runtime, result.NewContainerID); observeErr == nil {
independent = &observation
}
}
@@ -287,7 +318,7 @@ func (e dockerContainerActionExecutor) ReconcileActionDispatch(ctx context.Conte
}
var independent *dockerContainerPostconditionObservation
if e.observer != nil && result.NewContainerID != "" {
- if observation, observeErr := e.observer.ObserveDockerContainer(ctx, record.ID, result.NewContainerID); observeErr == nil {
+ if observation, observeErr := e.observer.ObserveDockerContainer(ctx, record.ID, attempt.AgentID, e.dockerObservationRuntime(ctx, record), result.NewContainerID); observeErr == nil {
independent = &observation
}
}
@@ -305,7 +336,7 @@ func (e dockerContainerActionExecutor) ReconcileActionDispatch(ctx context.Conte
req := agentexec.DockerContainerLifecyclePayload{RequestID: attempt.ID, ActionID: record.ID, Operation: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, Runtime: "docker", ContainerID: result.ContainerID, ExpectedState: result.Before.State, ExpectedStartedAt: result.Before.StartedAt}
var independent *dockerContainerPostconditionObservation
if e.observer != nil {
- if observation, observeErr := e.observer.ObserveDockerContainer(ctx, record.ID, result.ContainerID); observeErr == nil {
+ if observation, observeErr := e.observer.ObserveDockerContainer(ctx, record.ID, attempt.AgentID, e.dockerObservationRuntime(ctx, record), result.ContainerID); observeErr == nil {
independent = &observation
}
}
@@ -317,6 +348,22 @@ func (e dockerContainerActionExecutor) ReconcileActionDispatch(ctx context.Conte
return execution, receipt, true, nil
}
+func (e dockerContainerActionExecutor) dockerObservationRuntime(ctx context.Context, record unified.ActionAuditRecord) string {
+ if e.resources != nil {
+ if registry, err := e.resources.buildRegistry(GetOrgID(ctx)); err == nil {
+ if resource, ok := registry.Get(record.Request.ResourceID); ok && resource != nil {
+ if runtime, runtimeErr := dockerContainerRuntime(*resource); runtimeErr == nil {
+ return runtime
+ }
+ }
+ }
+ }
+ // Older durable attempts did not retain runtime separately. Docker is the
+ // compatibility default; a Podman target with no current resource fails
+ // the observation safely and retains agent-attested truth.
+ return "docker"
+}
+
func (e dockerContainerActionExecutor) CheckActionAvailable(ctx context.Context, req unified.ActionRequest, resource unified.Resource) unified.ResourceActionReadiness {
operation := strings.TrimSpace(req.CapabilityName)
capability, ok := findDockerLifecycleCapability(resource.Capabilities, operation)
diff --git a/internal/api/docker_container_action_executor_test.go b/internal/api/docker_container_action_executor_test.go
index 3b0c018902..e2040e5197 100644
--- a/internal/api/docker_container_action_executor_test.go
+++ b/internal/api/docker_container_action_executor_test.go
@@ -37,6 +37,23 @@ type scopedFakeDockerActionAgentCommander struct {
lastOrg string
}
+type observingDockerActionAgentCommander struct {
+ *fakeDockerActionAgentCommander
+ observations []agentexec.DockerContainerObservationPayload
+}
+
+func (f *observingDockerActionAgentCommander) ObserveDockerContainer(_ context.Context, _ string, req agentexec.DockerContainerObservationPayload) (*agentexec.DockerContainerObservationResultPayload, error) {
+ if err := agentexec.BindDockerContainerObservationPayload(&req); err != nil {
+ return nil, err
+ }
+ f.observations = append(f.observations, req)
+ return &agentexec.DockerContainerObservationResultPayload{
+ RequestID: req.RequestID, ActionID: req.ActionID, ProtocolVersion: req.ProtocolVersion, RequestDigest: req.RequestDigest,
+ Observed: true,
+ Snapshot: agentexec.DockerContainerLifecycleSnapshot{ContainerID: req.ContainerID, State: "running", Running: true, StartedAt: time.Now().UTC(), ObservedAt: time.Now().UTC()},
+ }, nil
+}
+
func (f *scopedFakeDockerActionAgentCommander) IsAgentConnectedForOrganization(organizationID, agentID string) bool {
f.lastOrg = organizationID
return f.IsAgentConnected(agentID)
@@ -221,6 +238,35 @@ func TestDockerContainerActionExecutorDispatchesPodmanRestartAndVerification(t *
}
}
+func TestDockerContainerActionExecutorUsesProductionDaemonObservationForIndependentTruth(t *testing.T) {
+ now := time.Now().UTC()
+ h := newActionTestResourceHandlers(t, &config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(resourceUnifiedSeedProvider{
+ snapshot: models.StateSnapshot{LastUpdate: now},
+ resources: []unified.Resource{dockerContainerActionResource("app-container:api", "docker", "running", now)},
+ })
+ agents := &observingDockerActionAgentCommander{fakeDockerActionAgentCommander: &fakeDockerActionAgentCommander{}}
+ executor := newDockerContainerActionExecutor(h, agents).(dockerContainerActionExecutor)
+ if executor.observer == nil {
+ t.Fatal("production constructor did not wire the typed daemon observer")
+ }
+ record := dockerContainerActionRecord("act_container", "app-container:api", "restart")
+ result, err := executor.ExecuteAction(dockerActionDispatchContext(t, executor, record), record)
+ if err != nil {
+ t.Fatalf("ExecuteAction: %v", err)
+ }
+ if len(agents.observations) != 1 || agents.observations[0].ActionID != record.ID {
+ t.Fatalf("observations=%#v", agents.observations)
+ }
+ truth := result.ActionResultV2
+ if truth == nil || truth.Execution.Status != unified.ActionExecutionSucceeded || truth.Verification.Status != unified.ActionVerificationConfirmed || truth.Verification.EvidenceClass != unified.ActionEvidenceIndependent {
+ t.Fatalf("canonical truth=%#v", truth)
+ }
+ if len(truth.Verification.Evidence) != 1 || truth.Verification.Evidence[0].ObserverTrustDomain == truth.Verification.Evidence[0].ExecutorTrustDomain {
+ t.Fatalf("verification evidence=%#v", truth.Verification.Evidence)
+ }
+}
+
func TestDockerContainerActionExecutorResolvesCommandAgentByDockerHostname(t *testing.T) {
now := time.Now().UTC()
resource := dockerContainerActionResource("app-container:api", "docker", "running", now)
diff --git a/internal/api/docker_restart_colima_real_lab_test.go b/internal/api/docker_restart_colima_real_lab_test.go
index e55be18138..4da42dba75 100644
--- a/internal/api/docker_restart_colima_real_lab_test.go
+++ b/internal/api/docker_restart_colima_real_lab_test.go
@@ -246,7 +246,7 @@ type dockerRestartLabNotification struct {
type colimaDirectObserver struct{}
-func (colimaDirectObserver) ObserveDockerContainer(ctx context.Context, actionID, containerID string) (dockerContainerPostconditionObservation, error) {
+func (colimaDirectObserver) ObserveDockerContainer(ctx context.Context, actionID, _, _, containerID string) (dockerContainerPostconditionObservation, error) {
snapshot, err := observeColimaContainer(ctx, containerID)
return dockerContainerPostconditionObservation{ObserverID: "task06-colima-direct", TrustDomain: "daemon:colima-direct", Method: "docker_context_colima_inspect", Snapshot: snapshot, ReceivedAt: time.Now().UTC()}, err
}
diff --git a/internal/hostagent/commands.go b/internal/hostagent/commands.go
index 0e4f9191ae..fae70a110c 100644
--- a/internal/hostagent/commands.go
+++ b/internal/hostagent/commands.go
@@ -205,6 +205,8 @@ const (
msgTypeDockerContainerLifecycleResult messageType = "docker_container_lifecycle_result"
msgTypeDockerContainerUpdate messageType = "docker_container_update"
msgTypeDockerContainerUpdateResult messageType = "docker_container_update_result"
+ msgTypeDockerContainerObserve messageType = "docker_container_observe"
+ msgTypeDockerContainerObserveResult messageType = "docker_container_observe_result"
msgTypeActionPreflight messageType = "action_preflight"
msgTypeActionPreflightResult messageType = "action_preflight_result"
msgTypeOperationQuery messageType = "agent_operation_query"
@@ -224,14 +226,15 @@ type wsMessage struct {
}
type registerPayload struct {
- AgentID string `json:"agent_id"`
- Hostname string `json:"hostname"`
- Version string `json:"version"`
- Platform string `json:"platform"`
- Tags []string `json:"tags,omitempty"`
- Token string `json:"token"`
- OperationReceiptVersion int `json:"operation_receipt_version,omitempty"`
- ActionPreflightVersion int `json:"action_preflight_version,omitempty"`
+ AgentID string `json:"agent_id"`
+ Hostname string `json:"hostname"`
+ Version string `json:"version"`
+ Platform string `json:"platform"`
+ Tags []string `json:"tags,omitempty"`
+ Token string `json:"token"`
+ OperationReceiptVersion int `json:"operation_receipt_version,omitempty"`
+ ActionPreflightVersion int `json:"action_preflight_version,omitempty"`
+ DockerObservationVersion int `json:"docker_observation_version,omitempty"`
}
type registeredPayload struct {
@@ -457,13 +460,14 @@ func (c *CommandClient) buildWebSocketOrigin() (string, error) {
func (c *CommandClient) sendRegistration(conn *websocket.Conn) error {
payload, err := json.Marshal(registerPayload{
- AgentID: c.agentID,
- Hostname: c.hostname,
- Version: c.version,
- Platform: c.platform,
- Token: c.apiToken,
- OperationReceiptVersion: c.operationReceiptVersion(),
- ActionPreflightVersion: agentexec.ActionPreflightProtocolVersion,
+ AgentID: c.agentID,
+ Hostname: c.hostname,
+ Version: c.version,
+ Platform: c.platform,
+ Token: c.apiToken,
+ OperationReceiptVersion: c.operationReceiptVersion(),
+ ActionPreflightVersion: agentexec.ActionPreflightProtocolVersion,
+ DockerObservationVersion: agentexec.DockerContainerObservationProtocolVersion,
})
if err != nil {
return fmt.Errorf("marshal registration payload: %w", err)
@@ -601,6 +605,14 @@ func (c *CommandClient) handleMessages(ctx context.Context, conn *websocket.Conn
}
go c.handleActionPreflight(ctx, conn, payload)
+ case msgTypeDockerContainerObserve:
+ payload, err := agentexec.DecodeDockerContainerObservationPayload(msg.Payload)
+ if err != nil {
+ c.logger.Warn().Err(err).Msg("Dropping invalid docker container observation request")
+ continue
+ }
+ go c.handleDockerContainerObservation(ctx, conn, payload)
+
case msgTypeHostStorageCleanup:
payload, err := agentexec.DecodeHostStorageCleanupPayload(msg.Payload)
if err != nil {
@@ -726,6 +738,38 @@ func (c *CommandClient) handleActionPreflight(ctx context.Context, conn *websock
}
}
+func (c *CommandClient) handleDockerContainerObservation(ctx context.Context, conn *websocket.Conn, payload agentexec.DockerContainerObservationPayload) {
+ observeCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
+ defer cancel()
+ observer, ok := c.dockerLifecycle.(interface {
+ Observe(context.Context, string, string) (agentexec.DockerContainerLifecycleSnapshot, error)
+ })
+ result := agentexec.DockerContainerObservationResultPayload{
+ RequestID: payload.RequestID, ActionID: payload.ActionID, ProtocolVersion: payload.ProtocolVersion,
+ RequestDigest: payload.RequestDigest,
+ }
+ if !ok || observer == nil {
+ result.ReasonCode = agentexec.ActionRefusalCapabilityUnavailable
+ } else if snapshot, err := observer.Observe(observeCtx, payload.Runtime, payload.ContainerID); err != nil {
+ result.ReasonCode = agentexec.ActionRefusalTargetInspectionUnavailable
+ c.logger.Debug().Err(err).Str("request_id", payload.RequestID).Msg("Docker container observation failed")
+ } else {
+ result.Observed = true
+ result.Snapshot = snapshot
+ }
+ encoded, err := json.Marshal(result)
+ if err != nil {
+ return
+ }
+ msg := wsMessage{Type: msgTypeDockerContainerObserveResult, ID: result.RequestID, Timestamp: time.Now(), Payload: encoded}
+ c.connMu.Lock()
+ err = conn.WriteJSON(msg)
+ c.connMu.Unlock()
+ if err != nil {
+ c.logger.Debug().Err(err).Str("request_id", result.RequestID).Msg("Failed to send docker container observation result")
+ }
+}
+
func (c *CommandClient) preflightHostUpdate(ctx context.Context, payload agentexec.HostUpdatePayload) (bool, string) {
if c.packageUpdates == nil {
return false, agentexec.ActionRefusalCapabilityUnavailable
diff --git a/internal/hostagent/commands_registration_test.go b/internal/hostagent/commands_registration_test.go
index eadd7b92bd..4a0445381e 100644
--- a/internal/hostagent/commands_registration_test.go
+++ b/internal/hostagent/commands_registration_test.go
@@ -105,6 +105,9 @@ func TestCommandClient_sendRegistration_WritesExpectedPayload(t *testing.T) {
if payload.Token != "token-1" {
t.Fatalf("payload.Token = %q, want %q", payload.Token, "token-1")
}
+ if payload.DockerObservationVersion != 1 {
+ t.Fatalf("payload.DockerObservationVersion = %d, want 1", payload.DockerObservationVersion)
+ }
}
func TestCommandClient_waitForRegistration_AcceptsSuccess(t *testing.T) {
diff --git a/internal/hostagent/docker_lifecycle.go b/internal/hostagent/docker_lifecycle.go
index ffb25b4dcd..b3439f3290 100644
--- a/internal/hostagent/docker_lifecycle.go
+++ b/internal/hostagent/docker_lifecycle.go
@@ -21,6 +21,10 @@ type dockerLifecycleManager interface {
Preflight(context.Context, agentexec.DockerContainerLifecyclePayload) (bool, string)
}
+func (m *localDockerLifecycleManager) Observe(ctx context.Context, runtime, containerID string) (agentexec.DockerContainerLifecycleSnapshot, error) {
+ return m.inspect(ctx, runtime, containerID)
+}
+
// DockerContainerLifecycleOperator is the narrow bridge from the host command
// channel to the unified agent's connected Docker / Podman module. It keeps
// lifecycle execution on the daemon API and avoids requiring a second runtime
diff --git a/internal/hostagent/docker_lifecycle_test.go b/internal/hostagent/docker_lifecycle_test.go
index f38aab4fd6..399052dccd 100644
--- a/internal/hostagent/docker_lifecycle_test.go
+++ b/internal/hostagent/docker_lifecycle_test.go
@@ -58,6 +58,24 @@ func TestDockerLifecycleManagerUsesConnectedModuleWithoutExternalCLI(t *testing.
}
}
+func TestDockerLifecycleManagerObservationIsReadOnly(t *testing.T) {
+ now := time.Now().UTC()
+ operator := &stubDockerLifecycleOperator{snapshots: []agentexec.DockerContainerLifecycleSnapshot{{
+ ContainerID: dockerLifecycleTestContainerID, State: "running", Running: true, ObservedAt: now,
+ }}}
+ manager := newLocalDockerLifecycleManager(operator)
+ manager.run = func(context.Context, string, ...string) ([]byte, error) {
+ return nil, fmt.Errorf("external runtime CLI must not be called")
+ }
+ snapshot, err := manager.Observe(context.Background(), "docker", dockerLifecycleTestContainerID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if snapshot.ContainerID != dockerLifecycleTestContainerID || !snapshot.Running || len(operator.mutations) != 0 {
+ t.Fatalf("snapshot=%#v mutations=%v", snapshot, operator.mutations)
+ }
+}
+
func TestDockerLifecycleManagerRestartPerformsOneMutationAndBoundedReadback(t *testing.T) {
t.Setenv("DOCKER_CONTEXT", "")
before := time.Now().UTC().Add(-time.Minute).Truncate(time.Nanosecond)
diff --git a/internal/mutationregistry/runtime_surface_audit_test.go b/internal/mutationregistry/runtime_surface_audit_test.go
index f36904affa..d814c0530d 100644
--- a/internal/mutationregistry/runtime_surface_audit_test.go
+++ b/internal/mutationregistry/runtime_surface_audit_test.go
@@ -164,6 +164,7 @@ func TestTransportCommandCatalogsResolveToRegistry(t *testing.T) {
"MsgTypeHostStorageCleanupResult": {Role: TransportRoleOperationResult}, "MsgTypeHostUpdateResult": {Role: TransportRoleOperationResult},
"MsgTypeDockerContainerLifecycleResult": {Role: TransportRoleOperationResult},
"MsgTypeDockerContainerUpdateResult": {Role: TransportRoleOperationResult},
+ "MsgTypeDockerContainerObserveResult": {Role: TransportRoleOperationResult},
"MsgTypeOperationQueryResult": {Role: TransportRoleOperationReceipt},
"MsgTypeRegistered": {Role: TransportRoleProtocol}, "MsgTypePong": {Role: TransportRoleProtocol},
"MsgTypeExecuteCmd": {Role: TransportRoleMutationRequest, MutationID: "transport.agent.raw-command", DurableAuthorityID: "assistant.resource-action"},
@@ -173,6 +174,7 @@ func TestTransportCommandCatalogsResolveToRegistry(t *testing.T) {
"MsgTypeHostUpdate": {Role: TransportRoleMutationRequest, MutationID: "transport.agent.host-package-update", DurableAuthorityID: "resource.host.package-update"},
"MsgTypeDockerContainerLifecycle": {Role: TransportRoleMutationRequest, MutationID: "transport.agent.docker-container-lifecycle", DurableAuthorityID: "resource.docker.container-lifecycle"},
"MsgTypeDockerContainerUpdate": {Role: TransportRoleMutationRequest, MutationID: "transport.agent.docker-container-update", DurableAuthorityID: "resource.docker.container-update"},
+ "MsgTypeDockerContainerObserve": {Role: TransportRoleOperationQuery},
"MsgTypeOperationQuery": {Role: TransportRoleOperationQuery},
"MsgTypeActionPreflight": {Role: TransportRoleOperationQuery},
"MsgTypeActionPreflightResult": {Role: TransportRoleOperationResult},