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.

Tighten unified agent hardening proof

rcourtmanc51708000f2d
diff --git a/cmd/pulse-agent/main.go b/cmd/pulse-agent/main.go
index 6d54c1ccf7..cd4893c149 100644
--- a/cmd/pulse-agent/main.go
+++ b/cmd/pulse-agent/main.go
@@ -785,8 +785,8 @@ func loadConfig(args []string, getenv func(string) string) (Config, error) {
}
}
- if token == "" && !*selfTest {
- return Config{}, fmt.Errorf("Pulse API token is required (use --token, --token-file, PULSE_TOKEN env, or /var/lib/pulse-agent/token)")
+ if token == "" && *enrollFlag && !*selfTest {
+ return Config{}, fmt.Errorf("Pulse API token is required for enrollment (use --token, --token-file, PULSE_TOKEN env, or /var/lib/pulse-agent/token)")
}
logLevel, err := parseLogLevel(*logLevelFlag)
diff --git a/cmd/pulse-agent/main_test.go b/cmd/pulse-agent/main_test.go
index 1f608085a7..0967997a3c 100644
--- a/cmd/pulse-agent/main_test.go
+++ b/cmd/pulse-agent/main_test.go
@@ -860,6 +860,26 @@ func TestLoadConfig(t *testing.T) {
}
})
+ t.Run("token optional when enrollment disabled", func(t *testing.T) {
+ cfg, err := loadConfig([]string{"-url", "http://token-optional.example.com", "-enable-host"}, func(s string) string { return "" })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cfg.APIToken != "" {
+ t.Fatalf("expected empty token for token-optional config, got %q", cfg.APIToken)
+ }
+ if cfg.Enroll {
+ t.Fatal("expected enrollment to be disabled")
+ }
+ })
+
+ t.Run("enrollment requires token", func(t *testing.T) {
+ _, err := loadConfig([]string{"-url", "http://token-required.example.com", "-enroll"}, func(s string) string { return "" })
+ if err == nil || !strings.Contains(err.Error(), "required for enrollment") {
+ t.Fatalf("expected enrollment token requirement, got %v", err)
+ }
+ })
+
t.Run("invalid interval flag", func(t *testing.T) {
_, err := loadConfig([]string{"-interval", "invalid"}, func(s string) string { return "" })
if err == nil {
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 772d25fbca..f438bfb249 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -201,6 +201,9 @@ an add-only capacity posture.
2. Add or change update continuity and persisted-version handoff through `internal/agentupdate/`.
3. Add or change runtime-side Unified Agent startup, first-report assembly, and enroll/runtime continuity through `internal/hostagent/`.
Proxmox host-agent setup must treat local `proxmox-registered` markers as a cache, not authority: before skipping token setup or node repair, `internal/hostagent/proxmox_setup.go` must revalidate the current type and candidate hosts against Pulse through the canonical auto-register contract.
+ Runtime startup must preserve the token-optional path for already-installed
+ non-enrollment agents; only enrollment mode may fail CLI configuration
+ loading solely because no API token was supplied.
That runtime-side ownership includes local disk telemetry collection in
`internal/hostagent/smartctl.go`. Linux SMART discovery must prefer
`smartctl --scan-open` typed targets before generic block-device fallback so
@@ -235,6 +238,9 @@ an add-only capacity posture.
The same runtime-owned boundary also owns Pulse control-plane URL validation for agent startup, remote config, updater continuity, and command transport. Non-loopback control-plane URLs remain HTTPS/WSS by default, but explicitly insecure agent/dev-runtime flows may use plain HTTP/WS for LAN development control planes; installer-persisted dev URLs must not be accepted by one runtime path and rejected by another.
8. Add or change installer flags, persisted service arguments, or upgrade-safe re-entry behavior through `scripts/install.sh` and `scripts/install.ps1`.
Persistence-sensitive NAS targets must keep one canonical continuity model here: installer-owned bootstraps may use flash-backed or immutable-root launch hooks only as thin trampolines, while the durable wrapper, state, and reboot-surviving binary copy stay in the governed persistent state directory that updater continuity also refreshes.
+ Approval-gated command execution must expose stable rejection reasons for
+ invalid approval grants so fleet operators can distinguish missing, expired,
+ mismatched, and signature-invalid grants through agent metrics.
9. Add or change profile management, the extracted agent profiles runtime owner, the infrastructure source-manager landing, the pure unified-agent inventory/install model, the connections-ledger workspace shell, the unified ConnectionEditor and its per-type credential slots, route model, shared install section owner, the shared direct-node/discovery infrastructure settings owners plus their model, shared frontend install-command assembly, Proxmox setup/install API transport, TrueNAS platform-connection management, VMware platform-connection management, the shared monitored-system admission preview shell for those platform connections, setup-completion install handoff transport, deploy-fallback manual install transport, and fleet-control presentation through `frontend-modern/src/api/agentProfiles.ts`, `frontend-modern/src/api/nodes.ts`, `frontend-modern/src/components/Settings/AgentProfilesPanel.tsx`, `frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts`, `frontend-modern/src/components/Settings/ConnectionsTable.tsx`, `frontend-modern/src/components/Settings/connectionsTableModel.ts`, `frontend-modern/src/components/Settings/useConnectionsLedger.ts`, `frontend-modern/src/components/Settings/useConnectionRowActions.ts`, `frontend-modern/src/components/Settings/ConnectionEditor/ConnectionEditor.tsx`, `frontend-modern/src/components/Settings/ConnectionEditor/AddressProbeStep.tsx`, `frontend-modern/src/components/Settings/ConnectionEditor/useConnectionEditor.ts`, `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/NodeCredentialSlot.tsx`, `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/TrueNASCredentialSlot.tsx`, `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/VMwareCredentialSlot.tsx`, `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx`, `frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx`, `frontend-modern/src/components/Settings/InfrastructureSourceManager.tsx`, `frontend-modern/src/components/Settings/infrastructureWorkspaceModel.ts`, `frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx`, `frontend-modern/src/components/Settings/platformConnectionsModel.ts`, `frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts`, `frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts`, `frontend-modern/src/components/Settings/proxmoxSettingsModel.ts`, `frontend-modern/src/components/Settings/ConfiguredNodeTables.tsx`, `frontend-modern/src/components/Settings/SettingsSectionNav.tsx`, `frontend-modern/src/components/Settings/infrastructureSettingsModel.ts`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts`, `frontend-modern/src/components/Settings/nodeModalModel.ts`, `frontend-modern/src/components/Settings/useNodeModalState.ts`, `frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx`, and `frontend-modern/src/utils/agentInstallCommand.ts`. Phase 9 retired the legacy reporting/inventory surface (InfrastructureOperationsController, InfrastructureInventorySection, InfrastructureActiveRowDetails, InfrastructureIgnoredRowDetails, InfrastructureStopMonitoringDialog, useInfrastructureReportingState) and the per-type shells (PlatformConnectionsWorkspace, ProxmoxSettingsPanel, ProxmoxDirectWorkspace, ProxmoxConfiguredNodesTable, ProxmoxDirectConnectionsCard, ProxmoxDiscoveryResultsCard, ProxmoxDeleteNodeDialog, ProxmoxNodeModalStack, NodeModal shell, TrueNASSettingsPanel, VMwareSettingsPanel, useProxmoxDirectWorkspaceState); lifecycle extensions must route through the unified aggregator ledger, source-manager cards, and ConnectionEditor credential slots rather than reintroducing those retired surfaces.
Those lifecycle-owned settings hooks may consume websocket state only through `frontend-modern/src/contexts/appRuntime.ts`; they must not import `frontend-modern/src/App.tsx` or recreate root-shell providers.
Discovery configuration is part of that same lifecycle-owned workspace boundary. `InfrastructureSourceManager.tsx` must open one canonical discovery editor through `InfrastructureDiscoverySettingsDialog.tsx`, `DiscoverySettingsForm.tsx`, and `discoverySettingsModel.ts`, while the System/Network shell stays limited to network-boundary controls instead of reintroducing a second editable discovery surface. That same workspace boundary now owns the add-flow entry split too: the landing guidance exposes `Detect from address`, `Install Pulse Agent`, and `Choose source type` as first-run actions above the source ledger, while header actions stay limited to ongoing discovery controls. The same landing boundary may surface setup confidence from the unified rows and discovered candidates, including connected-system count, API coverage, agent coverage, discovery review state, and the next setup action, without creating a second inventory model or provider-specific summary fetch.
diff --git a/internal/agentexec/approval_grant.go b/internal/agentexec/approval_grant.go
index fa1770302a..db8f73f34a 100644
--- a/internal/agentexec/approval_grant.go
+++ b/internal/agentexec/approval_grant.go
@@ -19,6 +19,67 @@ const (
DefaultApprovalGrantTTL = 2 * time.Minute
)
+const (
+ ApprovalGrantRejectionUnknown = "unknown"
+ ApprovalGrantRejectionMissing = "missing"
+ ApprovalGrantRejectionKeyUnavailable = "key_unavailable"
+ ApprovalGrantRejectionVersionMismatch = "version_mismatch"
+ ApprovalGrantRejectionApprovalIDMismatch = "approval_id_mismatch"
+ ApprovalGrantRejectionRequestMismatch = "request_mismatch"
+ ApprovalGrantRejectionAgentMismatch = "agent_mismatch"
+ ApprovalGrantRejectionCommandHashMismatch = "command_hash_mismatch"
+ ApprovalGrantRejectionTargetTypeMismatch = "target_type_mismatch"
+ ApprovalGrantRejectionTargetIDMismatch = "target_id_mismatch"
+ ApprovalGrantRejectionExpired = "expired"
+ ApprovalGrantRejectionIssuedAtInvalid = "issued_at_invalid"
+ ApprovalGrantRejectionNonceMissing = "nonce_missing"
+ ApprovalGrantRejectionSignatureInvalid = "signature_invalid"
+)
+
+// ApprovalGrantVerificationError preserves a stable rejection reason for
+// metrics and logs while keeping the human-readable verification error.
+type ApprovalGrantVerificationError struct {
+ Reason string
+ Err error
+}
+
+func (e *ApprovalGrantVerificationError) Error() string {
+ if e == nil || e.Err == nil {
+ return "approval grant verification failed"
+ }
+ return e.Err.Error()
+}
+
+func (e *ApprovalGrantVerificationError) Unwrap() error {
+ if e == nil {
+ return nil
+ }
+ return e.Err
+}
+
+func approvalGrantVerificationError(reason, message string, args ...interface{}) error {
+ if reason == "" {
+ reason = ApprovalGrantRejectionUnknown
+ }
+ return &ApprovalGrantVerificationError{
+ Reason: reason,
+ Err: fmt.Errorf(message, args...),
+ }
+}
+
+// ApprovalGrantVerificationReason returns the stable metric/log label for a
+// verification error. Non-verification errors collapse to "unknown".
+func ApprovalGrantVerificationReason(err error) string {
+ if err == nil {
+ return ""
+ }
+ var verificationErr *ApprovalGrantVerificationError
+ if errors.As(err, &verificationErr) && strings.TrimSpace(verificationErr.Reason) != "" {
+ return verificationErr.Reason
+ }
+ return ApprovalGrantRejectionUnknown
+}
+
// CommandApprovalGrant is a server-issued, token-bound grant that lets an agent
// verify an approval-gated command before executing it.
type CommandApprovalGrant struct {
@@ -90,7 +151,7 @@ func NewCommandApprovalGrant(key []byte, agentID string, cmd ExecuteCommandPaylo
func VerifyCommandApprovalGrant(token string, agentID string, cmd ExecuteCommandPayload, now time.Time) error {
if cmd.ApprovalGrant == nil {
- return errors.New("approval grant is required")
+ return approvalGrantVerificationError(ApprovalGrantRejectionMissing, "approval grant is required")
}
key := DeriveApprovalGrantKey(token)
return VerifyCommandApprovalGrantWithKey(key, agentID, cmd, now)
@@ -99,43 +160,43 @@ func VerifyCommandApprovalGrant(token string, agentID string, cmd ExecuteCommand
func VerifyCommandApprovalGrantWithKey(key []byte, agentID string, cmd ExecuteCommandPayload, now time.Time) error {
grant := cmd.ApprovalGrant
if grant == nil {
- return errors.New("approval grant is required")
+ return approvalGrantVerificationError(ApprovalGrantRejectionMissing, "approval grant is required")
}
if len(key) == 0 {
- return errors.New("approval grant key is unavailable")
+ return approvalGrantVerificationError(ApprovalGrantRejectionKeyUnavailable, "approval grant key is unavailable")
}
if grant.Version != approvalGrantVersion {
- return fmt.Errorf("unsupported approval grant version %d", grant.Version)
+ return approvalGrantVerificationError(ApprovalGrantRejectionVersionMismatch, "unsupported approval grant version %d", grant.Version)
}
if strings.TrimSpace(grant.ApprovalID) == "" || strings.TrimSpace(grant.ApprovalID) != strings.TrimSpace(cmd.ApprovalID) {
- return errors.New("approval grant id does not match command")
+ return approvalGrantVerificationError(ApprovalGrantRejectionApprovalIDMismatch, "approval grant id does not match command")
}
if strings.TrimSpace(grant.RequestID) == "" || strings.TrimSpace(grant.RequestID) != strings.TrimSpace(cmd.RequestID) {
- return errors.New("approval grant request does not match command")
+ return approvalGrantVerificationError(ApprovalGrantRejectionRequestMismatch, "approval grant request does not match command")
}
if strings.TrimSpace(grant.AgentID) == "" || strings.TrimSpace(grant.AgentID) != strings.TrimSpace(agentID) {
- return errors.New("approval grant agent does not match command")
+ return approvalGrantVerificationError(ApprovalGrantRejectionAgentMismatch, "approval grant agent does not match command")
}
if strings.TrimSpace(grant.CommandHash) != ComputeCommandApprovalHash(cmd.Command, cmd.TargetType, cmd.TargetID) {
- return errors.New("approval grant command hash does not match command")
+ return approvalGrantVerificationError(ApprovalGrantRejectionCommandHashMismatch, "approval grant command hash does not match command")
}
if strings.ToLower(strings.TrimSpace(grant.TargetType)) != strings.ToLower(strings.TrimSpace(cmd.TargetType)) {
- return errors.New("approval grant target type does not match command")
+ return approvalGrantVerificationError(ApprovalGrantRejectionTargetTypeMismatch, "approval grant target type does not match command")
}
if strings.TrimSpace(grant.TargetID) != strings.TrimSpace(cmd.TargetID) {
- return errors.New("approval grant target id does not match command")
+ return approvalGrantVerificationError(ApprovalGrantRejectionTargetIDMismatch, "approval grant target id does not match command")
}
if grant.ExpiresAt.IsZero() || now.UTC().After(grant.ExpiresAt.UTC()) {
- return errors.New("approval grant has expired")
+ return approvalGrantVerificationError(ApprovalGrantRejectionExpired, "approval grant has expired")
}
if grant.IssuedAt.IsZero() || grant.IssuedAt.UTC().After(now.UTC().Add(30*time.Second)) {
- return errors.New("approval grant issued_at is invalid")
+ return approvalGrantVerificationError(ApprovalGrantRejectionIssuedAtInvalid, "approval grant issued_at is invalid")
}
if strings.TrimSpace(grant.Nonce) == "" {
- return errors.New("approval grant nonce is required")
+ return approvalGrantVerificationError(ApprovalGrantRejectionNonceMissing, "approval grant nonce is required")
}
if !hmac.Equal([]byte(strings.TrimSpace(grant.Signature)), []byte(signApprovalGrant(key, grant))) {
- return errors.New("approval grant signature is invalid")
+ return approvalGrantVerificationError(ApprovalGrantRejectionSignatureInvalid, "approval grant signature is invalid")
}
return nil
}
diff --git a/internal/agentexec/approval_grant_test.go b/internal/agentexec/approval_grant_test.go
index a89666157d..b736d04d75 100644
--- a/internal/agentexec/approval_grant_test.go
+++ b/internal/agentexec/approval_grant_test.go
@@ -29,6 +29,8 @@ func TestCommandApprovalGrantVerifiesExactCommandAndTarget(t *testing.T) {
tampered.Command = "systemctl restart postgres"
if err := VerifyCommandApprovalGrant("runtime-token", "agent-1", tampered, now.Add(10*time.Second)); err == nil || !strings.Contains(err.Error(), "command hash") {
t.Fatalf("expected command hash rejection, got %v", err)
+ } else if got := ApprovalGrantVerificationReason(err); got != ApprovalGrantRejectionCommandHashMismatch {
+ t.Fatalf("rejection reason = %q, want %q", got, ApprovalGrantRejectionCommandHashMismatch)
}
}
@@ -49,5 +51,37 @@ func TestCommandApprovalGrantExpires(t *testing.T) {
if err := VerifyCommandApprovalGrant("runtime-token", "agent-1", cmd, now.Add(2*time.Second)); err == nil || !strings.Contains(err.Error(), "expired") {
t.Fatalf("expected expiry rejection, got %v", err)
+ } else if got := ApprovalGrantVerificationReason(err); got != ApprovalGrantRejectionExpired {
+ t.Fatalf("rejection reason = %q, want %q", got, ApprovalGrantRejectionExpired)
+ }
+}
+
+func TestCommandApprovalGrantClassifiesMissingAndSignatureRejections(t *testing.T) {
+ cmd := ExecuteCommandPayload{
+ RequestID: "req-1",
+ Command: "systemctl restart nginx",
+ ApprovalID: "approval-1",
+ TargetType: "agent",
+ }
+ now := time.Now()
+
+ if err := VerifyCommandApprovalGrant("runtime-token", "agent-1", cmd, now); err == nil {
+ t.Fatal("expected missing approval grant rejection")
+ } else if got := ApprovalGrantVerificationReason(err); got != ApprovalGrantRejectionMissing {
+ t.Fatalf("missing rejection reason = %q, want %q", got, ApprovalGrantRejectionMissing)
+ }
+
+ key := DeriveApprovalGrantKey("runtime-token")
+ grant, err := NewCommandApprovalGrant(key, "agent-1", cmd, now, time.Minute)
+ if err != nil {
+ t.Fatalf("NewCommandApprovalGrant() error = %v", err)
+ }
+ grant.Signature = "hmac-sha256:invalid"
+ cmd.ApprovalGrant = grant
+
+ if err := VerifyCommandApprovalGrant("runtime-token", "agent-1", cmd, now.Add(10*time.Second)); err == nil {
+ t.Fatal("expected signature rejection")
+ } else if got := ApprovalGrantVerificationReason(err); got != ApprovalGrantRejectionSignatureInvalid {
+ t.Fatalf("signature rejection reason = %q, want %q", got, ApprovalGrantRejectionSignatureInvalid)
}
}
diff --git a/internal/hostagent/agent_new_test.go b/internal/hostagent/agent_new_test.go
index 5eb38322d5..450bd46b55 100644
--- a/internal/hostagent/agent_new_test.go
+++ b/internal/hostagent/agent_new_test.go
@@ -13,6 +13,8 @@ import (
"testing"
"time"
+ "github.com/prometheus/client_golang/prometheus/testutil"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
"github.com/rcourtman/pulse-go-rewrite/internal/hostmetrics"
agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
"github.com/rs/zerolog"
@@ -92,6 +94,34 @@ func TestNew_RequiresAPITokenWhenEnrollmentEnabled(t *testing.T) {
}
}
+func TestCommandApprovalGrantRejectionMetricClassifiesMissingGrant(t *testing.T) {
+ reason := agentexec.ApprovalGrantRejectionMissing
+ before := testutil.ToFloat64(commandApprovalGrantRejectionsTotal.WithLabelValues(reason))
+
+ client := &CommandClient{
+ apiToken: "runtime-token",
+ agentID: "agent-1",
+ }
+ result := client.executeCommand(context.Background(), executeCommandPayload{
+ RequestID: "req-1",
+ Command: "echo hello",
+ ApprovalID: "approval-1",
+ TargetType: "agent",
+ Timeout: 5,
+ })
+ if result.Success {
+ t.Fatalf("expected approval-grant failure, got %#v", result)
+ }
+ if !strings.Contains(result.Error, "approval grant is required") {
+ t.Fatalf("error = %q, want missing approval grant", result.Error)
+ }
+
+ after := testutil.ToFloat64(commandApprovalGrantRejectionsTotal.WithLabelValues(reason))
+ if after != before+1 {
+ t.Fatalf("approval grant rejection metric = %v, want %v", after, before+1)
+ }
+}
+
func TestNew_NormalizesConfigAndTags(t *testing.T) {
mc := &mockCollector{
goos: "darwin",
diff --git a/internal/hostagent/commands.go b/internal/hostagent/commands.go
index 4a445c4967..ec57b14e47 100644
--- a/internal/hostagent/commands.go
+++ b/internal/hostagent/commands.go
@@ -19,6 +19,8 @@ import (
"time"
"github.com/gorilla/websocket"
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/promauto"
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
"github.com/rcourtman/pulse-go-rewrite/internal/agenttls"
"github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
@@ -46,6 +48,11 @@ var (
reconnectMaxDelay = 5 * time.Minute
reconnectJitterRatio = 0.1
reconnectRandFloat64 = rand.Float64
+
+ commandApprovalGrantRejectionsTotal = promauto.NewCounterVec(prometheus.CounterOpts{
+ Name: "pulse_hostagent_command_approval_grant_rejections_total",
+ Help: "Total number of approval-required commands rejected by the host agent due to invalid approval grants.",
+ }, []string{"reason"})
)
type cappedBuffer struct {
@@ -638,6 +645,7 @@ func (c *CommandClient) authorizeCommand(payload executeCommandPayload) error {
return fmt.Errorf("command requires approval")
}
if err := agentexec.VerifyCommandApprovalGrant(c.apiToken, c.agentID, payload.toAgentExecPayload(), time.Now()); err != nil {
+ commandApprovalGrantRejectionsTotal.WithLabelValues(agentexec.ApprovalGrantVerificationReason(err)).Inc()
return fmt.Errorf("command approval grant invalid: %w", err)
}
}
diff --git a/internal/hostagent/commands_execute_test.go b/internal/hostagent/commands_execute_test.go
index 6ba02fb3d6..e0e124ab71 100644
--- a/internal/hostagent/commands_execute_test.go
+++ b/internal/hostagent/commands_execute_test.go
@@ -7,6 +7,7 @@ import (
"testing"
"time"
+ "github.com/prometheus/client_golang/prometheus/testutil"
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
)
@@ -226,6 +227,34 @@ func TestCommandClient_executeCommand_RequiresApprovalForUnknownCommand(t *testi
}
}
+func TestCommandClient_executeCommand_RecordsApprovalGrantRejectionMetric(t *testing.T) {
+ reason := agentexec.ApprovalGrantRejectionMissing
+ before := testutil.ToFloat64(commandApprovalGrantRejectionsTotal.WithLabelValues(reason))
+
+ c := &CommandClient{
+ apiToken: "runtime-token",
+ agentID: "agent-1",
+ }
+ result := c.executeCommand(context.Background(), executeCommandPayload{
+ RequestID: "r1",
+ Command: "echo hello",
+ ApprovalID: "approval-1",
+ TargetType: "agent",
+ Timeout: 5,
+ })
+ if result.Success {
+ t.Fatalf("expected approval-grant failure, got %#v", result)
+ }
+ if !strings.Contains(result.Error, "approval grant is required") {
+ t.Fatalf("error = %q, want missing approval grant", result.Error)
+ }
+
+ after := testutil.ToFloat64(commandApprovalGrantRejectionsTotal.WithLabelValues(reason))
+ if after != before+1 {
+ t.Fatalf("approval grant rejection metric = %v, want %v", after, before+1)
+ }
+}
+
func TestCommandClient_executeCommand_BlocksPolicyDeniedCommand(t *testing.T) {
c := &CommandClient{}
result := c.executeCommand(context.Background(), executeCommandPayload{
diff --git a/scripts/installtests/build_release_assets_test.go b/scripts/installtests/build_release_assets_test.go
index 936b324994..e34381d31c 100644
--- a/scripts/installtests/build_release_assets_test.go
+++ b/scripts/installtests/build_release_assets_test.go
@@ -220,6 +220,13 @@ func TestReleaseValidationRequiresSignedSidecars(t *testing.T) {
`if [ ! -s "${filename}.sshsig" ]; then`,
`error "Missing or empty ${filename}.sshsig"`,
`success "SSH signature sidecars validated"`,
+ `validate_download_binary_headers() {`,
+ `http_header_value "X-Checksum-Sha256"`,
+ `http_header_value "X-Signature-Ed25519"`,
+ `http_header_value "X-Signature-SSHSIG"`,
+ `Install script endpoints returned required signature headers`,
+ `Download endpoints returned binaries with checksum and signature headers for all platforms/architectures`,
+ `Offline self-heal: download endpoint works with checksum and signature headers without outbound network`,
}
for _, needle := range localRequired {
if !strings.Contains(localValidator, needle) {
@@ -270,6 +277,7 @@ func TestReleaseValidationRequiresSignedSidecars(t *testing.T) {
"published artifact or",
"`checksums.txt` is missing its `.sshsig` sidecar",
"release-packet SBOM is absent",
+ "download endpoints must return checksum and signature headers",
}
for _, needle := range contractRequired {
if !strings.Contains(contract, needle) {
diff --git a/scripts/installtests/install_ps1_test.go b/scripts/installtests/install_ps1_test.go
index 523a16e1bf..74984d7563 100644
--- a/scripts/installtests/install_ps1_test.go
+++ b/scripts/installtests/install_ps1_test.go
@@ -2,10 +2,31 @@ package installtests
import (
"os"
+ "os/exec"
"strings"
"testing"
)
+func TestInstallPS1ParsesWithPowerShell(t *testing.T) {
+ pwsh, err := exec.LookPath("pwsh")
+ if err != nil {
+ t.Skip("pwsh not installed")
+ }
+
+ scriptPath := repoFile("scripts", "install.ps1")
+ cmd := exec.Command(pwsh,
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ `$errors = $null; [System.Management.Automation.Language.Parser]::ParseFile($env:PULSE_INSTALL_PS1_PATH, [ref]$null, [ref]$errors) > $null; if ($errors.Count) { $errors | ForEach-Object { Write-Error $_.ToString() }; exit 1 }`,
+ )
+ cmd.Env = append(os.Environ(), "PULSE_INSTALL_PS1_PATH="+scriptPath)
+ if output, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("install.ps1 failed PowerShell parser check: %v\n%s", err, output)
+ }
+}
+
func TestInstallPS1DockerModeDefaultsHostOff(t *testing.T) {
content, err := os.ReadFile(repoFile("scripts", "install.ps1"))
if err != nil {
diff --git a/scripts/tests/test-install-ps1-parser.sh b/scripts/tests/test-install-ps1-parser.sh
new file mode 100755
index 0000000000..ab141f58df
--- /dev/null
+++ b/scripts/tests/test-install-ps1-parser.sh
@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+
+if ! command -v pwsh >/dev/null 2>&1; then
+ if [[ "${GITHUB_ACTIONS:-false}" == "true" || "${PULSE_REQUIRE_PWSH:-false}" == "true" ]]; then
+ echo "pwsh is required for install.ps1 parser validation" >&2
+ exit 1
+ fi
+ echo "SKIP: pwsh not installed"
+ exit 0
+fi
+
+PULSE_INSTALL_PS1_PATH="${ROOT_DIR}/scripts/install.ps1" \
+ pwsh -NoLogo -NoProfile -NonInteractive -Command \
+ '$errors = $null; [System.Management.Automation.Language.Parser]::ParseFile($env:PULSE_INSTALL_PS1_PATH, [ref]$null, [ref]$errors) > $null; if ($errors.Count) { $errors | ForEach-Object { Write-Error $_.ToString() }; exit 1 }'
+
+echo "install.ps1 parses successfully"
diff --git a/scripts/validate-release.sh b/scripts/validate-release.sh
index 6c7c858e24..4dec79cf34 100755
--- a/scripts/validate-release.sh
+++ b/scripts/validate-release.sh
@@ -69,6 +69,73 @@ check_tar_entries_nonempty() {
done
}
+http_header_value() {
+ local header_name="$1"
+ local headers_file="$2"
+ awk -v needle="$(printf '%s' "$header_name" | tr '[:upper:]' '[:lower:]')" '
+ BEGIN { value = "" }
+ {
+ line = $0
+ sub(/\r$/, "", line)
+ sub(/^[[:space:]]+/, "", line)
+ lower = tolower(line)
+ if (index(lower, needle ":") == 1) {
+ sub(/^[^:]*:[[:space:]]*/, "", line)
+ value = line
+ }
+ }
+ END { print value }
+ ' "$headers_file"
+}
+
+validate_download_binary_headers() {
+ local file_path="$1"
+ local headers_path="$2"
+ local label="$3"
+ local checksum_header signature_header ssh_signature_header actual_checksum
+
+ checksum_header="$(http_header_value "X-Checksum-Sha256" "$headers_path")"
+ signature_header="$(http_header_value "X-Signature-Ed25519" "$headers_path")"
+ ssh_signature_header="$(http_header_value "X-Signature-SSHSIG" "$headers_path")"
+
+ if [ -z "$checksum_header" ]; then
+ error "${label} missing X-Checksum-Sha256 header"
+ exit 1
+ fi
+ if [ -z "$signature_header" ]; then
+ error "${label} missing X-Signature-Ed25519 header"
+ exit 1
+ fi
+ if [ -z "$ssh_signature_header" ]; then
+ error "${label} missing X-Signature-SSHSIG header"
+ exit 1
+ fi
+
+ actual_checksum="$(sha256sum "$file_path" | awk '{print $1}')"
+ if [ "$actual_checksum" != "$checksum_header" ]; then
+ error "${label} checksum header mismatch: expected ${checksum_header}, got ${actual_checksum}"
+ exit 1
+ fi
+}
+
+validate_download_script_headers() {
+ local headers_path="$1"
+ local label="$2"
+ local signature_header ssh_signature_header
+
+ signature_header="$(http_header_value "X-Signature-Ed25519" "$headers_path")"
+ ssh_signature_header="$(http_header_value "X-Signature-SSHSIG" "$headers_path")"
+
+ if [ -z "$signature_header" ]; then
+ error "${label} missing X-Signature-Ed25519 header"
+ exit 1
+ fi
+ if [ -z "$ssh_signature_header" ]; then
+ error "${label} missing X-Signature-SSHSIG header"
+ exit 1
+ fi
+}
+
if [ $# -lt 1 ]; then
error "Usage: $0 <pulse-version> [image] [release-dir] [--skip-docker]"
exit 1
@@ -193,13 +260,32 @@ if [ "$SKIP_DOCKER" = false ]; then
"windows 386"
)
+ for script_name in install.sh install.ps1; do
+ url="http://127.0.0.1:${HOST_PORT}/download/${script_name}"
+ tmp_file=$(mktemp)
+ tmp_headers=$(mktemp)
+ if ! curl -fsS -D "$tmp_headers" -o "$tmp_file" "$url"; then
+ docker logs "$SMOKE_CONTAINER" || true
+ error "Download failed for ${script_name}"
+ exit 1
+ fi
+ if [ ! -s "$tmp_file" ]; then
+ error "Downloaded empty ${script_name}"
+ exit 1
+ fi
+ validate_download_script_headers "$tmp_headers" "${script_name}"
+ rm -f "$tmp_file" "$tmp_headers"
+ done
+ success "Install script endpoints returned required signature headers"
+
for entry in "${download_matrix[@]}"; do
set -- $entry
platform=$1
arch=$2
url="http://127.0.0.1:${HOST_PORT}/download/pulse-agent?arch=${platform}-${arch}"
tmp_file=$(mktemp)
- if ! curl -fsS -o "$tmp_file" "$url"; then
+ tmp_headers=$(mktemp)
+ if ! curl -fsS -D "$tmp_headers" -o "$tmp_file" "$url"; then
docker logs "$SMOKE_CONTAINER" || true
error "Download failed for $platform/$arch"
exit 1
@@ -208,9 +294,10 @@ if [ "$SKIP_DOCKER" = false ]; then
error "Downloaded empty binary for $platform/$arch"
exit 1
fi
- rm -f "$tmp_file"
+ validate_download_binary_headers "$tmp_file" "$tmp_headers" "${platform}/${arch}"
+ rm -f "$tmp_file" "$tmp_headers"
done
- success "Download endpoints returned binaries for all platforms/architectures"
+ success "Download endpoints returned binaries with checksum and signature headers for all platforms/architectures"
docker rm -f "$SMOKE_CONTAINER" >/dev/null 2>&1 || true
smoke_container=""
@@ -243,7 +330,8 @@ if [ "$SKIP_DOCKER" = false ]; then
done
offline_tmp=$(mktemp)
- if ! docker exec "$SMOKE_CONTAINER" wget -qO- "http://127.0.0.1:7655/download/pulse-agent?arch=linux-amd64" > "$offline_tmp"; then
+ offline_headers=$(mktemp)
+ if ! docker exec "$SMOKE_CONTAINER" sh -c "headers=\$(mktemp); wget -qS -O- 'http://127.0.0.1:7655/download/pulse-agent?arch=linux-amd64' 2>\"\$headers\"; status=\$?; cat \"\$headers\" >&2; rm -f \"\$headers\"; exit \$status" > "$offline_tmp" 2> "$offline_headers"; then
docker logs "$SMOKE_CONTAINER" || true
error "Offline self-heal failed: download endpoint returned error with no outbound network"
exit 1
@@ -252,8 +340,9 @@ if [ "$SKIP_DOCKER" = false ]; then
error "Offline self-heal failed: downloaded binary is empty"
exit 1
fi
- rm -f "$offline_tmp"
- success "Offline self-heal: download endpoint works without outbound network"
+ validate_download_binary_headers "$offline_tmp" "$offline_headers" "offline linux/amd64"
+ rm -f "$offline_tmp" "$offline_headers"
+ success "Offline self-heal: download endpoint works with checksum and signature headers without outbound network"
docker rm -f "$SMOKE_CONTAINER" >/dev/null 2>&1 || true
smoke_container=""