Enforce monitoring-only ceilings and bound oversized Docker reports

Wire MonitoringOnly into the Docker agent module from both foreground
and Windows service runtimes so legacy update_container and update_all
commands are rejected under monitoring-only authority. Forward
CommandAuthorityProfile, DisableUpdateChecks, and
DisableRegistryCredentials in the Windows service runtime to match
foreground behavior.

Ignore unsigned commandsEnabled overrides from report responses when
remote configuration signatures are required. Shed oversized Docker
object metadata and container port/mount attachments before delivery
when a report exceeds the shared size limit, and drop HTTP 413
responses without buffering so one oversized container cannot stall
host telemetry.

Contract-Neutral: Security hardening for agent monitoring-only enforcement, remote config signature verification, and oversized Docker report delivery without changing public API contracts.
This commit is contained in:
rcourtman
2026-11-24 11:02:15 +00:00
parent 321a7f95c9
commit 5590bb7725
9 changed files with 720 additions and 11 deletions

View File

@@ -799,6 +799,7 @@ func run(ctx context.Context, args []string, getenv func(string) string) error {
Targets: dockerReportTargets(cfg),
HelperInventory: helperContainerInventory,
HelperOperationStatus: privilegeHelperStatus,
MonitoringOnly: cfg.CommandAuthorityProfile == hostagent.CommandAuthorityMonitoringOnly,
}
dockerAgent, err = newDockerAgent(dockerCfg)

View File

@@ -916,6 +916,49 @@ func TestApplyInitialRemoteCommandAuthority(t *testing.T) {
}
}
// The Docker module takes commands from its own report response, outside the
// host module's command channel, so it needs the local ceiling handed to it.
func TestRunCarriesCommandAuthorityCeilingIntoDockerModule(t *testing.T) {
for _, tc := range []struct {
profile hostagent.CommandAuthorityProfile
wantMonitoringOnly bool
}{
{profile: hostagent.CommandAuthorityMonitoringOnly, wantMonitoringOnly: true},
{profile: hostagent.CommandAuthorityCommandCapable},
{profile: hostagent.CommandAuthorityLegacy},
} {
t.Run(string(tc.profile), func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/agents/agent/lookup" {
http.NotFound(w, r)
return
}
// A server asking for commands must not lift the ceiling.
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"success":true,"config":{"commandsEnabled":true}}`)
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
evidence := spyIdentityStartup(t, cancel)
err := run(ctx, []string{
"--url", server.URL, "--state-dir", t.TempDir(), "--token", "synthetic-primary-token",
"--hostname", "synthetic-fixture-host", "--enable-host", "--enable-docker", "--enable-kubernetes",
"--disable-auto-update", "--health-addr", "", "--command-authority", string(tc.profile),
}, func(string) string { return "" })
if err != nil {
t.Fatalf("startup failed: %v", err)
}
if evidence.host.CommandAuthorityProfile != tc.profile {
t.Fatalf("host module authority = %q, want %q", evidence.host.CommandAuthorityProfile, tc.profile)
}
if evidence.docker.MonitoringOnly != tc.wantMonitoringOnly {
t.Fatalf("docker module MonitoringOnly = %v under %q, want %v", evidence.docker.MonitoringOnly, tc.profile, tc.wantMonitoringOnly)
}
})
}
}
func TestResolveToken(t *testing.T) {
customStateDir := filepath.Join(string(filepath.Separator), "custom", "pulse-agent")
fakeReadFile := func(path string) ([]byte, error) {
@@ -2988,6 +3031,29 @@ func TestWindowsServiceRuntimeStartsHealthServer(t *testing.T) {
}
}
// The Windows service builds its own module configs. Restrictions the operator
// set locally must reach the modules as they do in the foreground runtime: a
// dropped command authority profile is read as legacy, which lets server
// configuration enable commands on a monitoring-only service.
func TestWindowsServiceRuntimeKeepsLocalRestrictions(t *testing.T) {
source, err := os.ReadFile("service_windows.go")
if err != nil {
t.Fatalf("read pulse-agent service_windows.go: %v", err)
}
text := strings.Join(strings.Fields(string(source)), " ")
required := []string{
`CommandAuthorityProfile: ws.cfg.CommandAuthorityProfile,`,
`DisableUpdateChecks: ws.cfg.DisableDockerUpdateChecks,`,
`DisableRegistryCredentials: ws.cfg.DisableRegistryCredentials,`,
}
for _, want := range required {
if !strings.Contains(text, want) {
t.Fatalf("expected Windows service runtime to include %q", want)
}
}
}
func TestRunSharesPrivilegeHelperStatusAcrossHostAndDocker(t *testing.T) {
source, err := os.ReadFile("main.go")
if err != nil {

View File

@@ -105,6 +105,12 @@ func (ws *windowsService) Execute(args []string, r <-chan svc.ChangeRequest, cha
UpdateStatus: updater.Snapshot,
ModuleStatus: runtimeStatus.moduleStatuses,
Observers: hostObserverTargets(ws.cfg.Observers),
// Carry the installer's local command ceiling into the host module,
// as the foreground runtime does. hostagent.New reads an absent
// profile as legacy, which follows the server's desired command
// state and would let it enable commands on a monitoring-only service.
CommandAuthorityProfile: ws.cfg.CommandAuthorityProfile,
}
agent, err := hostagent.New(hostCfg)
if err != nil {
@@ -150,6 +156,11 @@ func (ws *windowsService) Execute(args []string, r <-chan svc.ChangeRequest, cha
IncludeTasks: true,
CollectDiskMetrics: true,
Targets: dockerReportTargets(ws.cfg),
MonitoringOnly: ws.cfg.CommandAuthorityProfile == hostagent.CommandAuthorityMonitoringOnly,
// Local opt-outs restrict the service as they do the foreground runtime.
DisableUpdateChecks: ws.cfg.DisableDockerUpdateChecks,
DisableRegistryCredentials: ws.cfg.DisableRegistryCredentials,
}
agent, err := dockeragent.New(dockerCfg)

View File

@@ -85,6 +85,11 @@ type Config struct {
// HelperOperationStatus records source-classified typed-helper health. It
// must classify raw operation errors before they reach report state.
HelperOperationStatus HelperOperationStatusRecorder
// MonitoringOnly carries the local command-authority ceiling into this
// module. When the operator installed the agent as monitoring-only, no
// command in a report response may change a container, whatever the
// server sends.
MonitoringOnly bool
}
// HelperOperationStatusRecorder receives typed-helper operation outcomes.
@@ -215,6 +220,17 @@ type inactiveContainerInspectCacheEntry struct {
// ErrStopRequested indicates the agent should terminate gracefully after acknowledging a stop command.
var ErrStopRequested = errors.New("docker host stop requested")
// errReportTooLarge marks a report that a destination refused for its size.
// Sending the same report again gets the same answer, so it is never replayed.
var errReportTooLarge = errors.New("report exceeds the size the destination accepts")
// reportMetadataShedSteps are the per-object sizes of free-form metadata
// (labels, driver options, environment) above which deliverReport sends an
// object without that metadata when the report would otherwise exceed the
// shared size contract. They are tried in order until the report fits; the
// last step withholds all of it.
var reportMetadataShedSteps = []int{32 * 1024, 4 * 1024, 0}
const (
manualUpdateCheckResultTTL = 10 * time.Minute
manualUpdateCheckResultLimit = 64
@@ -1206,20 +1222,25 @@ func (a *Agent) flushBuffer(ctx context.Context) {
func (a *Agent) deliverReport(ctx context.Context, report agentsdocker.Report) error {
a.ensureReportBuffers()
payload, err := json.Marshal(report)
report, payload, compressed, err := a.encodeReportWithinSizeLimit(report)
if err != nil {
return fmt.Errorf("marshal report: %w", err)
}
compressed, err := utils.CompressJSON(payload)
if err != nil {
return fmt.Errorf("compress report: %w", err)
return err
}
a.logReportSize(len(report.Containers), int64(len(compressed)), int64(len(payload)))
for _, target := range a.targets {
if err := a.sendReportToTarget(ctx, target, compressed, len(report.Containers)); err != nil {
agenttarget.MarkDelivery("docker", target.Name, targetRole(target), false)
if errors.Is(err, ErrStopRequested) && target.Authoritative {
return nil
}
if errors.Is(err, errReportTooLarge) {
// Buffering it would replay a report that is refused every
// time and hold back whatever is queued behind it.
a.logger.Error().Err(err).Str("destination", target.Name).
Bool("authoritative", target.Authoritative).
Msg("Docker report was refused as too large and is not buffered for this destination")
continue
}
if report.InventoryComplete == nil || *report.InventoryComplete {
a.reportBuffers[target.Name].Push(report)
}
@@ -1235,6 +1256,164 @@ func (a *Agent) deliverReport(ctx context.Context, report agentsdocker.Report) e
return nil
}
func encodeReport(report agentsdocker.Report) (payload, compressed []byte, err error) {
payload, err = json.Marshal(report)
if err != nil {
return nil, nil, fmt.Errorf("marshal report: %w", err)
}
compressed, err = utils.CompressJSON(payload)
if err != nil {
return nil, nil, fmt.Errorf("compress report: %w", err)
}
return payload, compressed, nil
}
// encodeReportWithinSizeLimit encodes a report for delivery. The server
// refuses a whole host's report above the shared size contract, and whoever
// builds an image or starts a container chooses its labels and environment, so
// a report over the contract is sent without the free-form metadata of its
// heaviest objects rather than not at all: container state, health and metrics
// must not depend on that text. It returns the report as encoded.
func (a *Agent) encodeReportWithinSizeLimit(report agentsdocker.Report) (agentsdocker.Report, []byte, []byte, error) {
payload, compressed, err := encodeReport(report)
if err != nil {
return report, nil, nil, err
}
for _, limit := range reportMetadataShedSteps {
if !agentsdocker.AssessReportSize(int64(len(compressed)), int64(len(payload))).ExceedsLimit() {
break
}
trimmed, withheld := withholdReportMetadata(report, limit)
if withheld == 0 {
continue
}
a.logger.Warn().
Int("objects", withheld).
Int("objectMetadataLimitBytes", limit).
Int("reportEncodedBytes", len(compressed)).
Int("reportDecodedBytes", len(payload)).
Msg("Docker / Podman report exceeds the server size limit, sending objects over the metadata limit without their labels, options and environment")
report = trimmed
if payload, compressed, err = encodeReport(report); err != nil {
return report, nil, nil, err
}
}
for _, limit := range []int{64, 0} {
if !agentsdocker.AssessReportSize(int64(len(compressed)), int64(len(payload))).ExceedsLimit() {
break
}
trimmed, withheld := withholdReportAttachments(report, limit)
if withheld == 0 {
continue
}
a.logger.Warn().
Int("containers", withheld).
Int("containerAttachmentLimit", limit).
Int("reportEncodedBytes", len(compressed)).
Int("reportDecodedBytes", len(payload)).
Msg("Docker / Podman report still exceeds the server size limit, sending containers over the attachment limit without their ports and mounts")
report = trimmed
if payload, compressed, err = encodeReport(report); err != nil {
return report, nil, nil, err
}
}
return report, payload, compressed, nil
}
func withholdReportAttachments(report agentsdocker.Report, limit int) (agentsdocker.Report, int) {
withheld := 0
report.Containers = append([]agentsdocker.Container(nil), report.Containers...)
for i := range report.Containers {
container := &report.Containers[i]
if len(container.Ports)+len(container.Mounts) > limit {
container.Ports = nil
container.Mounts = nil
withheld++
}
}
return report, withheld
}
// withholdReportMetadata returns a copy of report in which every object whose
// labels, options and environment exceed limit bytes carries none of them, and
// the number of such objects. Values derived from a withheld container's or
// service's labels go with them. The caller's report is not modified.
func withholdReportMetadata(report agentsdocker.Report, limit int) (agentsdocker.Report, int) {
size := func(maps ...map[string]string) int {
total := 0
for _, m := range maps {
for k, v := range m {
total += len(k) + len(v)
}
}
return total
}
withheld := 0
report.Containers = append([]agentsdocker.Container(nil), report.Containers...)
for i := range report.Containers {
container := &report.Containers[i]
total := size(container.Labels)
for _, entry := range container.Env {
total += len(entry)
}
if total > limit {
container.Labels, container.Env, container.Podman = nil, nil, nil
withheld++
}
}
report.Images = append([]agentsdocker.Image(nil), report.Images...)
for i := range report.Images {
if size(report.Images[i].Labels) > limit {
report.Images[i].Labels = nil
withheld++
}
}
report.Volumes = append([]agentsdocker.Volume(nil), report.Volumes...)
for i := range report.Volumes {
if size(report.Volumes[i].Labels, report.Volumes[i].Options) > limit {
report.Volumes[i].Labels, report.Volumes[i].Options = nil, nil
withheld++
}
}
report.Networks = append([]agentsdocker.Network(nil), report.Networks...)
for i := range report.Networks {
if size(report.Networks[i].Labels, report.Networks[i].Options) > limit {
report.Networks[i].Labels, report.Networks[i].Options = nil, nil
withheld++
}
}
report.Services = append([]agentsdocker.Service(nil), report.Services...)
for i := range report.Services {
if size(report.Services[i].Labels) > limit {
report.Services[i].Labels, report.Services[i].Stack = nil, ""
withheld++
}
}
report.Nodes = append([]agentsdocker.Node(nil), report.Nodes...)
for i := range report.Nodes {
if size(report.Nodes[i].Labels, report.Nodes[i].EngineLabels) > limit {
report.Nodes[i].Labels, report.Nodes[i].EngineLabels = nil, nil
withheld++
}
}
report.Secrets = append([]agentsdocker.Secret(nil), report.Secrets...)
for i := range report.Secrets {
if size(report.Secrets[i].Labels) > limit {
report.Secrets[i].Labels = nil
withheld++
}
}
report.Configs = append([]agentsdocker.Config(nil), report.Configs...)
for i := range report.Configs {
if size(report.Configs[i].Labels) > limit {
report.Configs[i].Labels = nil
withheld++
}
}
return report, withheld
}
func targetRole(target TargetConfig) string {
if target.Authoritative {
return "primary"
@@ -1262,7 +1441,9 @@ func (a *Agent) flushTargetBuffer(ctx context.Context, target TargetConfig) {
if err != nil {
return
}
if err := a.sendReportToTarget(ctx, target, compressed, len(report.Containers)); err != nil {
// A buffered report refused as too large is dropped like a delivered
// one: it can never be replayed and blocks the reports behind it.
if err := a.sendReportToTarget(ctx, target, compressed, len(report.Containers)); err != nil && !errors.Is(err, errReportTooLarge) {
return
}
queue.Pop()
@@ -1426,6 +1607,9 @@ func (a *Agent) sendReportToTarget(ctx context.Context, target TargetConfig, pay
"Each Docker host requires its own unique token. " +
"Generate a new token in Pulse Settings > Agents and reinstall with the new token.")
}
if resp.StatusCode == http.StatusRequestEntityTooLarge {
return fmt.Errorf("target %s: %w: pulse responded %s: %s", target.URL, errReportTooLarge, resp.Status, errMsg)
}
return fmt.Errorf("target %s: pulse responded %s: %s", target.URL, resp.Status, errMsg)
}
@@ -1466,6 +1650,17 @@ func (a *Agent) sendReportToTarget(ctx context.Context, target TargetConfig, pay
func (a *Agent) handleCommand(ctx context.Context, target TargetConfig, command agentsdocker.Command) error {
commandType := strings.ToLower(command.Type)
if a.cfg.MonitoringOnly {
// Report responses are server-controlled, and these legacy commands
// do not travel over the host module's command channel, where the
// ceiling is otherwise enforced. Refuse them here so a server cannot
// update containers on an install that never granted that authority.
switch commandType {
case agentsdocker.CommandTypeUpdateContainer, agentsdocker.CommandTypeUpdateAll:
a.rejectMonitoringOnlyCommand(ctx, target, command)
return nil
}
}
if a.cfg.HelperInventory != nil {
switch commandType {
case agentsdocker.CommandTypeUpdateContainer, agentsdocker.CommandTypeUpdateAll, agentsdocker.CommandTypeCheckUpdates:

View File

@@ -13,6 +13,7 @@ import (
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"time"
@@ -676,6 +677,119 @@ func TestMonitoringOnlyCollectorRejectsForgedReportCommand(t *testing.T) {
}
}
// A monitoring-only install that reaches the runtime directly has no typed
// helper, so the local ceiling is all that stands between a report response
// and the legacy update handlers.
func TestMonitoringOnlyAuthorityRejectsReportResponseUpdateCommands(t *testing.T) {
for _, tc := range []struct {
name string
monitoringOnly bool
}{
{name: "monitoring-only ceiling", monitoringOnly: true},
{name: "no local ceiling", monitoringOnly: false},
} {
t.Run(tc.name, func(t *testing.T) {
var mu sync.Mutex
acks := make(map[string][]agentsdocker.CommandAck)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/report") {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"commands":[` +
`{"id":"forged-update","type":"update_container","payload":{"containerId":"container-1"}},` +
`{"id":"forged-update-all","type":"UPDATE_ALL","payload":{"containerIds":["container-1","container-2"]}}]}`))
return
}
for _, id := range []string{"forged-update", "forged-update-all"} {
if strings.HasSuffix(r.URL.Path, "/commands/"+id+"/ack") {
var ack agentsdocker.CommandAck
if err := json.NewDecoder(r.Body).Decode(&ack); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
mu.Lock()
acks[id] = append(acks[id], ack)
mu.Unlock()
w.WriteHeader(http.StatusNoContent)
return
}
}
http.NotFound(w, r)
}))
defer server.Close()
runtimeCalls := 0
agent := &Agent{
cfg: Config{MonitoringOnly: tc.monitoringOnly},
hostID: "direct-host",
docker: &fakeDockerClient{
containerInspectFn: func(context.Context, string) (containertypes.InspectResponse, error) {
runtimeCalls++
return containertypes.InspectResponse{}, errors.New("inspect refused")
},
},
httpClients: map[bool]*http.Client{false: server.Client()},
logger: zerolog.Nop(),
}
target := TargetConfig{Name: "primary", URL: server.URL, Token: "token", Authoritative: true}
if err := agent.sendReportToTarget(context.Background(), target, []byte("ignored"), 0); err != nil {
t.Fatalf("report response: %v", err)
}
mu.Lock()
defer mu.Unlock()
if !tc.monitoringOnly {
// The ceiling is the only gate: without it the same response
// still reaches the runtime for both commands.
if runtimeCalls != 3 {
t.Fatalf("legacy update commands reached the runtime %d times, want 3", runtimeCalls)
}
return
}
if runtimeCalls != 0 {
t.Fatalf("forged report commands reached the direct runtime %d times", runtimeCalls)
}
for _, id := range []string{"forged-update", "forged-update-all"} {
if len(acks[id]) != 1 || acks[id][0].Status != agentsdocker.CommandStatusFailed || !strings.Contains(acks[id][0].Message, "Monitoring-only collector") {
t.Fatalf("rejected %s acknowledgements = %+v", id, acks[id])
}
}
})
}
}
// The ceiling covers commands that change containers. A registry re-check
// changes nothing on the host and stays available to a monitoring-only install.
func TestMonitoringOnlyAuthorityStillServesCheckUpdates(t *testing.T) {
registryChecker := NewRegistryChecker(zerolog.Nop())
registryChecker.MarkChecked()
agent := &Agent{
cfg: Config{MonitoringOnly: true},
logger: zerolog.Nop(),
hostID: "direct-host",
registryChecker: registryChecker,
manualCheckCollect: func(context.Context) (agentsdocker.Report, error) {
return agentsdocker.Report{}, nil
},
}
t.Cleanup(func() { _ = agent.Close() })
err := agent.handleCommand(context.Background(), TargetConfig{URL: "http://example.com/\x7f", Token: "token"}, agentsdocker.Command{
ID: "check-1",
Type: agentsdocker.CommandTypeCheckUpdates,
})
if err != nil {
t.Fatalf("check updates command: %v", err)
}
registryChecker.mu.RLock()
lastFullCheck := registryChecker.lastFullCheck
registryChecker.mu.RUnlock()
if !lastFullCheck.IsZero() {
t.Fatalf("monitoring-only ceiling blocked the registry re-check, lastFullCheck = %s", lastFullCheck)
}
}
func TestHandleStopCommand(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("systemd stop-command behavior is not available on Windows")

View File

@@ -2,10 +2,19 @@ package dockeragent
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"io"
"math/rand"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/utils"
agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker"
"github.com/rs/zerolog"
)
@@ -121,3 +130,244 @@ func TestLogDockerReportSizeUsesSharedContract(t *testing.T) {
})
}
}
// reportSizeContractServer answers like the Pulse report endpoint: 413 for a
// body over the shared size contract, 200 otherwise. It records every report
// it accepts.
type reportSizeContractServer struct {
*httptest.Server
mu sync.Mutex
accepted []agentsdocker.Report
}
func newReportSizeContractServer(t *testing.T) *reportSizeContractServer {
t.Helper()
server := &reportSizeContractServer{}
server.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
encoded, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
decoded, err := agentsdocker.DecodeReportBody(encoded, r.Header.Get("Content-Encoding"))
var sizeErr *agentsdocker.ReportSizeError
if errors.As(err, &sizeErr) {
w.WriteHeader(http.StatusRequestEntityTooLarge)
_, _ = w.Write([]byte(`{"error":"report exceeds the server size limit","code":"report_too_large"}`))
return
}
var report agentsdocker.Report
if err != nil || json.Unmarshal(decoded, &report) != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
server.mu.Lock()
server.accepted = append(server.accepted, report)
server.mu.Unlock()
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(server.Close)
return server
}
func (s *reportSizeContractServer) acceptedReports() []agentsdocker.Report {
s.mu.Lock()
defer s.mu.Unlock()
return append([]agentsdocker.Report(nil), s.accepted...)
}
// incompressibleText returns text that gzip cannot shrink by much.
func incompressibleText(size int) string {
noise := make([]byte, size)
rand.New(rand.NewSource(1)).Read(noise)
return base64.StdEncoding.EncodeToString(noise)[:size]
}
func TestDeliverReportWithholdsMetadataOfOversizedObjects(t *testing.T) {
server := newReportSizeContractServer(t)
var output bytes.Buffer
agent := &Agent{
logger: zerolog.New(&output),
targets: []TargetConfig{{URL: server.URL, Token: "token"}},
httpClients: map[bool]*http.Client{false: server.Client()},
reportBuffer: utils.New[agentsdocker.Report](5),
}
noise := incompressibleText(4 * 1024 * 1024)
report := agentsdocker.Report{
Agent: agentsdocker.AgentInfo{ID: "host"},
Containers: []agentsdocker.Container{
{ID: "web", State: "exited", Labels: map[string]string{"com.docker.compose.project": "shop"}, Env: []string{"TZ=UTC"}},
{ID: "batch-job", State: "running", Labels: map[string]string{"notes": noise}, Env: []string{"TZ=UTC"}},
},
}
if err := agent.deliverReport(context.Background(), report); err != nil {
t.Fatalf("deliver report: %v", err)
}
if buffered := agent.bufferedReports(); buffered != 0 {
t.Fatalf("buffered %d reports, want none", buffered)
}
accepted := server.acceptedReports()
if len(accepted) != 1 || len(accepted[0].Containers) != 2 {
t.Fatalf("expected the server to accept one report with both containers, got %d reports", len(accepted))
}
web, batchJob := accepted[0].Containers[0], accepted[0].Containers[1]
if web.State != "exited" || web.Labels["com.docker.compose.project"] != "shop" || len(web.Env) != 1 {
t.Fatalf("ordinary container changed: state=%q labels=%d env=%d", web.State, len(web.Labels), len(web.Env))
}
if batchJob.State != "running" || len(batchJob.Labels) != 0 || len(batchJob.Env) != 0 {
t.Fatalf("oversized container: state=%q labels=%d env=%d, want state without metadata", batchJob.State, len(batchJob.Labels), len(batchJob.Env))
}
if len(report.Containers[1].Labels) != 1 {
t.Fatal("the caller's report must not be modified")
}
if !strings.Contains(output.String(), `"objectMetadataLimitBytes":32768`) {
t.Fatalf("expected a diagnostic naming the metadata limit, got %s", output.String())
}
}
func TestWithholdReportMetadata(t *testing.T) {
small := map[string]string{"tier": "web"}
large := map[string]string{"notes": strings.Repeat("x", 40*1024)}
report := agentsdocker.Report{
Containers: []agentsdocker.Container{
{ID: "small", Labels: small, Env: []string{"TZ=UTC"}},
{ID: "large-labels", Labels: large, Podman: &agentsdocker.PodmanContainer{PodName: "pod"}},
{ID: "large-env", Env: []string{"BLOB=" + large["notes"]}},
},
Images: []agentsdocker.Image{{ID: "small", Labels: small}, {ID: "large", Labels: large}},
Volumes: []agentsdocker.Volume{{Name: "small", Labels: small}, {Name: "large", Options: large}},
Networks: []agentsdocker.Network{{ID: "small", Options: small}, {ID: "large", Labels: large}},
Services: []agentsdocker.Service{{ID: "small", Labels: small, Stack: "shop"}, {ID: "large", Labels: large, Stack: "shop"}},
Nodes: []agentsdocker.Node{{ID: "small", Labels: small}, {ID: "large", EngineLabels: large}},
Secrets: []agentsdocker.Secret{{ID: "small", Labels: small}, {ID: "large", Labels: large}},
Configs: []agentsdocker.Config{{ID: "small", Labels: small}, {ID: "large", Labels: large}},
}
trimmed, withheld := withholdReportMetadata(report, 32*1024)
if withheld != 9 {
t.Fatalf("withheld metadata of %d objects, want 9", withheld)
}
if c := trimmed.Containers; c[0].Labels["tier"] != "web" || len(c[0].Env) != 1 ||
c[1].Labels != nil || c[1].Podman != nil || c[2].Env != nil {
t.Fatalf("unexpected containers: %d/%d labels, %d env", len(c[0].Labels), len(c[1].Labels), len(c[2].Env))
}
if trimmed.Images[0].Labels == nil || trimmed.Images[1].Labels != nil ||
trimmed.Volumes[0].Labels == nil || trimmed.Volumes[1].Options != nil ||
trimmed.Networks[0].Options == nil || trimmed.Networks[1].Labels != nil ||
trimmed.Nodes[0].Labels == nil || trimmed.Nodes[1].EngineLabels != nil ||
trimmed.Secrets[0].Labels == nil || trimmed.Secrets[1].Labels != nil ||
trimmed.Configs[0].Labels == nil || trimmed.Configs[1].Labels != nil {
t.Fatal("expected only the objects over the limit to lose their metadata")
}
if s := trimmed.Services; s[0].Stack != "shop" || s[0].Labels == nil || s[1].Stack != "" || s[1].Labels != nil {
t.Fatalf("unexpected services: %+v", s)
}
if report.Containers[1].Labels == nil || report.Services[1].Stack != "shop" {
t.Fatal("the caller's report must not be modified")
}
if _, withheld := withholdReportMetadata(trimmed, 0); withheld != 8 {
t.Fatalf("last step withheld metadata of %d objects, want the 8 that still carry some", withheld)
}
}
func TestDeliverReportDoesNotBufferReportRefusedAsTooLarge(t *testing.T) {
server := newReportSizeContractServer(t)
var output bytes.Buffer
agent := &Agent{
logger: zerolog.New(&output),
targets: []TargetConfig{{URL: server.URL, Token: "token"}},
httpClients: map[bool]*http.Client{false: server.Client()},
reportBuffer: utils.New[agentsdocker.Report](5),
}
// No metadata to withhold: the report stays over the limit.
oversized := agentsdocker.Report{
Agent: agentsdocker.AgentInfo{ID: "oversized"},
Containers: []agentsdocker.Container{{ID: "container-1", Status: incompressibleText(4 * 1024 * 1024)}},
}
if err := agent.deliverReport(context.Background(), oversized); err != nil {
t.Fatalf("deliver oversized report: %v", err)
}
if buffered := agent.bufferedReports(); buffered != 0 {
t.Fatalf("buffered %d reports the server can never accept", buffered)
}
if !strings.Contains(output.String(), `"reportEncodedLimitExceeded":true`) {
t.Fatal("expected the size diagnostic before the report was sent")
}
if err := agent.deliverReport(context.Background(), agentsdocker.Report{Agent: agentsdocker.AgentInfo{ID: "ordinary"}}); err != nil {
t.Fatalf("deliver ordinary report: %v", err)
}
if accepted := server.acceptedReports(); len(accepted) != 1 || accepted[0].Agent.ID != "ordinary" {
t.Fatalf("accepted %d reports, want only the ordinary one", len(accepted))
}
}
func TestFlushBufferDropsReportRefusedAsTooLarge(t *testing.T) {
server := newReportSizeContractServer(t)
agent := &Agent{
logger: zerolog.Nop(),
targets: []TargetConfig{{URL: server.URL, Token: "token"}},
httpClients: map[bool]*http.Client{false: server.Client()},
reportBuffer: utils.New[agentsdocker.Report](5),
}
agent.reportBuffer.Push(agentsdocker.Report{
Agent: agentsdocker.AgentInfo{ID: "oversized"},
Containers: []agentsdocker.Container{{ID: "container-1", Status: incompressibleText(4 * 1024 * 1024)}},
})
agent.reportBuffer.Push(agentsdocker.Report{Agent: agentsdocker.AgentInfo{ID: "queued"}})
agent.flushBuffer(context.Background())
if agent.reportBuffer.Len() != 0 {
t.Fatalf("expected the buffer to drain, %d reports remain", agent.reportBuffer.Len())
}
if accepted := server.acceptedReports(); len(accepted) != 1 || accepted[0].Agent.ID != "queued" {
t.Fatalf("accepted %d reports, want the one queued behind the oversized report", len(accepted))
}
}
func TestDeliverReportWithholdsOversizedPortsWhenOverLimit(t *testing.T) {
server := newReportSizeContractServer(t)
agent := &Agent{
logger: zerolog.Nop(),
targets: []TargetConfig{{URL: server.URL, Token: "token"}},
httpClients: map[bool]*http.Client{false: server.Client()},
reportBuffer: utils.New[agentsdocker.Report](5),
}
ports := make([]agentsdocker.ContainerPort, 0, 200000)
for i := 0; i < 200000; i++ {
ports = append(ports, agentsdocker.ContainerPort{
PrivatePort: i%65535 + 1,
PublicPort: i%65535 + 1,
Protocol: "tcp",
IP: "0.0.0.0",
})
}
report := agentsdocker.Report{
Agent: agentsdocker.AgentInfo{ID: "many-ports"},
Containers: []agentsdocker.Container{
{ID: "heavy", Name: "heavy", State: "running", Ports: ports},
{ID: "normal", Name: "normal", State: "running", Ports: []agentsdocker.ContainerPort{{PrivatePort: 80, PublicPort: 8080, Protocol: "tcp"}}},
},
}
if err := agent.deliverReport(context.Background(), report); err != nil {
t.Fatalf("deliver report with oversized ports: %v", err)
}
accepted := server.acceptedReports()
if len(accepted) != 1 {
t.Fatalf("accepted %d reports, want 1", len(accepted))
}
if len(accepted[0].Containers) != 2 {
t.Fatalf("accepted %d containers, want 2", len(accepted[0].Containers))
}
if len(accepted[0].Containers[0].Ports) != 0 {
t.Fatalf("expected oversized container ports to be withheld, got %d", len(accepted[0].Containers[0].Ports))
}
if len(accepted[0].Containers[1].Ports) != 1 {
t.Fatalf("expected normal container ports to remain intact, got %d", len(accepted[0].Containers[1].Ports))
}
}

View File

@@ -1583,9 +1583,17 @@ func (a *Agent) sendReportToDestination(ctx context.Context, report agentshost.R
a.persistAgentID(canonicalAgentID)
}
// Apply server config overrides
// Apply server config overrides. The acknowledgement carries no signature,
// so an agent that requires signed remote config lets it withdraw command
// execution but never grant it: enabling commands is left to the signed
// config endpoint, which the remote config refresh applies.
if reportResp.Config != nil && reportResp.Config.CommandsEnabled != nil {
a.applyRemoteConfig(*reportResp.Config.CommandsEnabled)
commandsEnabled := *reportResp.Config.CommandsEnabled
if commandsEnabled && remoteconfig.SignatureRequired() {
a.logger.Debug().Msg("Ignored unsigned command enablement in report response because signed remote config is required")
} else {
a.applyRemoteConfig(commandsEnabled)
}
}
// Only a real acknowledgement answers for this process's identity: one

View File

@@ -604,3 +604,65 @@ func TestAgentSendReport_RedirectCannotConsumeAcknowledgement(t *testing.T) {
})
}
}
// The report acknowledgement carries no signature. An agent that requires
// signed remote config must not let it turn command execution on; it may still
// withdraw it, and an agent without the requirement keeps following the ack.
func TestAgentSendReport_UnsignedAckCannotEnableCommandsWhenSignatureRequired(t *testing.T) {
for _, test := range []struct {
name string
signatureRequired string
startEnabled bool
ack string
wantEnabled bool
}{
{name: "required refuses enable", signatureRequired: "true", ack: `{"commandsEnabled":true}`},
{name: "required keeps signed enable", signatureRequired: "true", startEnabled: true, ack: `{"commandsEnabled":true}`, wantEnabled: true},
{name: "required honors disable", signatureRequired: "true", startEnabled: true, ack: `{"commandsEnabled":false}`},
{name: "not required follows enable", signatureRequired: "false", ack: `{"commandsEnabled":true}`, wantEnabled: true},
{name: "not required follows disable", signatureRequired: "false", startEnabled: true, ack: `{"commandsEnabled":false}`},
} {
t.Run(test.name, func(t *testing.T) {
t.Setenv("PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED", test.signatureRequired)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"success":true,"agentId":"agent-1","config":`+test.ack+`}`)
}))
defer server.Close()
logger := zerolog.Nop()
agent, err := New(Config{
APIToken: "test-token",
PulseURL: "https://pulse",
AgentID: "agent-1",
EnableCommands: test.startEnabled,
CommandAuthorityProfile: CommandAuthorityLegacy,
StateDir: t.TempDir(),
Collector: &mockCollector{},
Logger: &logger,
})
if err != nil {
t.Fatalf("New: %v", err)
}
t.Cleanup(func() { agent.stopCommandClient(true) })
agent.httpClient = server.Client()
agent.trimmedPulseURL = server.URL
report := agentshost.Report{Agent: agentshost.AgentInfo{ID: "agent-1"}}
if err := agent.sendReport(context.Background(), report); err != nil {
t.Fatalf("sendReport: %v", err)
}
agent.configMu.RLock()
enabled := agent.cfg.EnableCommands
agent.configMu.RUnlock()
agent.commandClientMu.Lock()
hasClient := agent.commandClient != nil
agent.commandClientMu.Unlock()
if enabled != test.wantEnabled || hasClient != test.wantEnabled {
t.Fatalf("after unsigned ack: EnableCommands=%v commandClient=%v, want %v", enabled, hasClient, test.wantEnabled)
}
})
}
}

View File

@@ -131,7 +131,7 @@ func (c *Client) Fetch(ctx context.Context) (map[string]interface{}, *bool, erro
}
logger := c.logger()
signatureRequired := isConfigSignatureRequired()
signatureRequired := SignatureRequired()
agentID := c.cfg.AgentID
if resolved, err := c.resolveAgentID(ctx); err != nil {
return nil, nil, fmt.Errorf("resolve agent ID: %w", err)
@@ -283,7 +283,9 @@ func (c *Client) Fetch(ctx context.Context) (map[string]interface{}, *bool, erro
return configResp.Config.Settings, configResp.Config.CommandsEnabled, nil
}
func isConfigSignatureRequired() bool {
// SignatureRequired reports whether this agent must refuse remote config that
// does not carry a valid signature (PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED).
func SignatureRequired() bool {
return utils.ParseBool(utils.GetenvTrim("PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED"))
}