mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-12-03 18:43:38 +01:00
Reject unsafe agent URLs before startup diagnostics
Reuse private destination-validation errors in host enrollment and replace Docker URL echoes with destination indices. Admit the unified agent's existing primary URL policy before logging, clients or saved-state writes. Preserve the updater's local self-test behavior and cover saved credentials, rejected inputs and accepted transport with registered Go tests. Contract-Neutral: Implement the already-declared safe URL diagnostic boundary before runtime side effects, without changing accepted transport, authority, wire data or configuration formats. Human-held subsystem contract files are unchanged. Change-source: pulse-maintainer
This commit is contained in:
@@ -304,13 +304,16 @@ func run(ctx context.Context, args []string, getenv func(string) string) error {
|
||||
return fmt.Errorf("failed to load unified agent configuration: %w", err)
|
||||
}
|
||||
|
||||
// The installer runs this on the verified staged executable before changing
|
||||
// a service or its saved credentials. Use the modules' primary-destination
|
||||
// policy, without logging, enrollment, identity persistence or listeners.
|
||||
if cfg.ValidateURLOnly {
|
||||
// Refuse an invalid primary destination before logging it, fetching remote
|
||||
// configuration, enrolling or changing saved state. Self-test is deliberately
|
||||
// only a local executable/logger probe: the updater invokes it without the
|
||||
// service's runtime transport flags. --validate-url checks the actual policy.
|
||||
if !cfg.SelfTest || cfg.ValidateURLOnly {
|
||||
if _, err := agenttarget.NormalizePulseURL(cfg.PulseURL, true, cfg.AllowPlaintextHTTP); err != nil {
|
||||
return fmt.Errorf("invalid pulse URL: %w", err)
|
||||
}
|
||||
}
|
||||
if cfg.ValidateURLOnly {
|
||||
fmt.Println("Pulse URL validation passed")
|
||||
return nil
|
||||
}
|
||||
|
||||
150
cmd/pulse-agent/startup_url_privacy_test.go
Normal file
150
cmd/pulse-agent/startup_url_privacy_test.go
Normal file
@@ -0,0 +1,150 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/agentupdate"
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/dockeragent"
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/hostagent"
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/kubernetesagent"
|
||||
"github.com/rcourtman/pulse-go-rewrite/pkg/securityutil"
|
||||
)
|
||||
|
||||
func TestRunRejectsURLBeforeLoggingOrStateChange(t *testing.T) {
|
||||
origHost, origDocker, origKube, origUpdater := newHostAgent, newDockerAgent, newKubeAgent, newUpdater
|
||||
t.Cleanup(func() {
|
||||
newHostAgent, newDockerAgent, newKubeAgent, newUpdater = origHost, origDocker, origKube, origUpdater
|
||||
securityutil.SetOperatorPlaintextHTTPConsent(false)
|
||||
})
|
||||
started := 0
|
||||
newHostAgent = func(hostagent.Config) (Runnable, error) { started++; return &mockRunnable{}, nil }
|
||||
newDockerAgent = func(dockeragent.Config) (RunnableCloser, error) { started++; return &mockRunnableCloser{}, nil }
|
||||
newKubeAgent = func(kubernetesagent.Config) (Runnable, error) { started++; return &mockRunnable{}, nil }
|
||||
newUpdater = func(cfg agentupdate.Config) *agentupdate.Updater {
|
||||
started++
|
||||
cfg.Disabled = true
|
||||
return agentupdate.New(cfg)
|
||||
}
|
||||
for _, enroll := range []bool{false, true} {
|
||||
for _, tc := range []struct{ name, raw string }{
|
||||
{"userinfo", "https://synthetic-user:synthetic-password@private-fixture.invalid"},
|
||||
{"query", "https://private-fixture.invalid/?token=synthetic-query"},
|
||||
{"fragment", "https://private-fixture.invalid/#synthetic-fragment"},
|
||||
{"port", "https://private-fixture.invalid:synthetic-port"},
|
||||
{"escape", "https://private-fixture.invalid/%synthetic-escape"},
|
||||
{"missing-host", "https:///synthetic-path"},
|
||||
{"scheme", "synthetic-scheme://private-fixture.invalid"},
|
||||
{"control", "https://private-fixture.invalid/\nsynthetic-control"},
|
||||
{"public-http", "http://203.0.113.10/synthetic-path"},
|
||||
} {
|
||||
t.Run(tc.name+"/enroll-"+strconv.FormatBool(enroll), func(t *testing.T) {
|
||||
stateDir := t.TempDir()
|
||||
files := map[string]string{"agent-id": "synthetic-saved-id\n", "token": "synthetic-saved-token\n",
|
||||
"runtime.token": "synthetic-saved-runtime\n", "connection.env": "synthetic-saved-connection\n", "install.sh": "synthetic-saved-recovery\n"}
|
||||
modes := make(map[string]os.FileMode)
|
||||
for name, data := range files {
|
||||
path := filepath.Join(stateDir, name)
|
||||
if err := os.WriteFile(path, []byte(data), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
modes[name] = info.Mode()
|
||||
}
|
||||
if err := os.Chmod(stateDir, 0750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := os.Stat(stateDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
started = 0
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel() // Baseline must also finish without contacting a service.
|
||||
err = run(ctx, []string{"--url", tc.raw, "--state-dir", stateDir,
|
||||
"--agent-id", "synthetic-runtime-id", "--token-file", filepath.Join(stateDir, "token"),
|
||||
"--enable-host", "--enable-docker", "--enable-kubernetes", "--disable-auto-update", "--health-addr", "",
|
||||
"--log-file", filepath.Join(stateDir, "unexpected.log"), "--enroll=" + strconv.FormatBool(enroll)}, func(string) string { return "" })
|
||||
if err == nil || !strings.Contains(err.Error(), "invalid pulse URL") {
|
||||
t.Error("startup did not reject the URL with correction context")
|
||||
} else if strings.Contains(err.Error(), "synthetic-") || strings.Contains(err.Error(), "private-fixture.invalid") || strings.Contains(err.Error(), "203.0.113.10") {
|
||||
t.Error("startup refusal disclosed rejected input")
|
||||
}
|
||||
if started != 0 {
|
||||
t.Error("invalid URL reached an updater or module constructor")
|
||||
}
|
||||
entries, err := os.ReadDir(stateDir)
|
||||
if err != nil || len(entries) != len(files) {
|
||||
t.Error("invalid URL created log or state files")
|
||||
}
|
||||
after, err := os.Stat(stateDir)
|
||||
if err != nil || after.Mode() != before.Mode() {
|
||||
t.Error("invalid URL changed state directory permissions")
|
||||
}
|
||||
for name, want := range files {
|
||||
path := filepath.Join(stateDir, name)
|
||||
data, readErr := os.ReadFile(path)
|
||||
info, statErr := os.Stat(path)
|
||||
if readErr != nil || statErr != nil || string(data) != want || info.Mode() != modes[name] {
|
||||
t.Error("invalid URL changed saved identity, credentials, recovery files or permissions")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunURLAdmissionPreservesAcceptedSelfTest(t *testing.T) {
|
||||
t.Cleanup(func() { securityutil.SetOperatorPlaintextHTTPConsent(false) })
|
||||
for _, tc := range []struct {
|
||||
name, raw string
|
||||
plaintext bool
|
||||
}{
|
||||
{"https", " HTTPS://Pulse.Invalid:7655/base/ ", false},
|
||||
{"loopback", "http://127.0.0.1:7655", false},
|
||||
{"private-http", "http://192.168.1.20:7655/base", false},
|
||||
{"explicit-http", "http://203.0.113.10/base", true},
|
||||
{"default", "", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
stateDir := t.TempDir()
|
||||
err := run(context.Background(), []string{"--url", tc.raw, "--self-test", "--state-dir", stateDir,
|
||||
"--allow-plaintext-http=" + strconv.FormatBool(tc.plaintext)}, func(string) string { return "" })
|
||||
if err != nil {
|
||||
t.Fatal("accepted URL no longer passes startup self-test")
|
||||
}
|
||||
entries, err := os.ReadDir(stateDir)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatal("self-test started writing runtime state")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelfTestDoesNotRequireRuntimeURLAdmission(t *testing.T) {
|
||||
// The updater launches this local executable probe without the service's
|
||||
// --allow-plaintext-http flag. It must not become a new transport-policy
|
||||
// gate; the separate --validate-url mode checks that policy.
|
||||
t.Cleanup(func() { securityutil.SetOperatorPlaintextHTTPConsent(false) })
|
||||
for _, raw := range []string{
|
||||
"http://203.0.113.10/synthetic-path",
|
||||
"https://synthetic-user:synthetic-password@private-fixture.invalid",
|
||||
} {
|
||||
stateDir := t.TempDir()
|
||||
err := run(context.Background(), []string{"--self-test", "--url", raw, "--state-dir", stateDir}, func(string) string { return "" })
|
||||
if err != nil {
|
||||
t.Fatal("local self-test acquired a runtime URL requirement")
|
||||
}
|
||||
entries, err := os.ReadDir(stateDir)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatal("local self-test wrote runtime state")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -557,7 +557,7 @@ func normalizeTargets(raw []TargetConfig) ([]TargetConfig, error) {
|
||||
return nil, errors.New("pulse target URL is required")
|
||||
}
|
||||
if token == "" {
|
||||
return nil, fmt.Errorf("pulse target %s is missing API token", targetURL)
|
||||
return nil, fmt.Errorf("pulse target %d is missing API token", index+1)
|
||||
}
|
||||
|
||||
if len(normalized) == 0 && !target.Authoritative {
|
||||
@@ -569,7 +569,7 @@ func normalizeTargets(raw []TargetConfig) ([]TargetConfig, error) {
|
||||
target.AllowPlaintextHTTP,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid pulse target URL %q: %w", targetURL, err)
|
||||
return nil, fmt.Errorf("invalid pulse target %d URL: %w", index+1, err)
|
||||
}
|
||||
|
||||
caCertPath := strings.TrimSpace(target.CACertPath)
|
||||
|
||||
58
internal/dockeragent/startup_url_privacy_test.go
Normal file
58
internal/dockeragent/startup_url_privacy_test.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package dockeragent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDockerTargetRejectionDoesNotDiscloseURL(t *testing.T) {
|
||||
// Synthetic inputs cover the outer wrappers, including the missing-token
|
||||
// branch that runs before shared URL validation and both destination slots.
|
||||
for _, position := range []int{1, 2} {
|
||||
for _, token := range []string{"", "synthetic-runtime-token"} {
|
||||
for _, tc := range []struct{ name, raw string }{
|
||||
{"userinfo", "https://synthetic-user:synthetic-password@private-fixture.invalid"},
|
||||
{"query", "https://private-fixture.invalid/?token=synthetic-query"},
|
||||
{"fragment", "https://private-fixture.invalid/#synthetic-fragment"},
|
||||
{"port", "https://private-fixture.invalid:synthetic-port"},
|
||||
{"escape", "https://private-fixture.invalid/%synthetic-escape"},
|
||||
{"scheme", "synthetic-scheme://private-fixture.invalid"},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("slot-%d/token-%t/%s", position, token != "", tc.name), func(t *testing.T) {
|
||||
targets := []TargetConfig{{URL: tc.raw, Token: token}}
|
||||
if position == 2 {
|
||||
targets = append([]TargetConfig{{URL: "https://primary.invalid", Token: "synthetic-primary-token", Authoritative: true}}, targets...)
|
||||
}
|
||||
normalized, err := normalizeTargets(targets)
|
||||
if err == nil || len(normalized) != 0 {
|
||||
t.Fatal("invalid target was admitted")
|
||||
}
|
||||
if strings.Contains(err.Error(), "synthetic-") || strings.Contains(err.Error(), "private-fixture.invalid") {
|
||||
t.Error("target refusal disclosed the rejected URL")
|
||||
}
|
||||
if !strings.Contains(err.Error(), fmt.Sprintf("target %d", position)) {
|
||||
t.Error("target refusal lost its destination index")
|
||||
}
|
||||
agent, newErr := New(Config{Targets: targets})
|
||||
if newErr == nil || agent != nil {
|
||||
t.Fatal("invalid target produced a Docker module")
|
||||
}
|
||||
if strings.Contains(newErr.Error(), "synthetic-") || strings.Contains(newErr.Error(), "private-fixture.invalid") {
|
||||
t.Error("constructor wrapper disclosed the rejected URL")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDockerLegacyTargetRejectionDoesNotDiscloseURL(t *testing.T) {
|
||||
agent, err := New(Config{PulseURL: "https://synthetic-user:synthetic-password@private-fixture.invalid", APIToken: "synthetic-runtime-token"})
|
||||
if err == nil || agent != nil {
|
||||
t.Fatal("invalid legacy target was admitted")
|
||||
}
|
||||
if strings.Contains(err.Error(), "synthetic-") || strings.Contains(err.Error(), "private-fixture.invalid") {
|
||||
t.Fatal("legacy target wrapper disclosed the rejected URL")
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,6 @@ import (
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/config"
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/platformsupport"
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/remoteconfig"
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/sensors"
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/utils"
|
||||
agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
|
||||
@@ -1857,14 +1856,7 @@ func normaliseRuntimePlatform(goos, reportedPlatform string) string {
|
||||
}
|
||||
|
||||
func normalizePulseURL(rawURL string) (string, error) {
|
||||
parsed, err := securityutil.NormalizePulseHTTPBaseURLWithOptions(rawURL, securityutil.PulseURLValidationOptions{
|
||||
AllowLocalNetworkHTTP: true,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return parsed.String(), nil
|
||||
return agenttarget.NormalizePulseURL(rawURL, true, false)
|
||||
}
|
||||
|
||||
// collectTemperatures attempts to collect temperature data from the local system.
|
||||
|
||||
102
internal/hostagent/startup_url_privacy_test.go
Normal file
102
internal/hostagent/startup_url_privacy_test.go
Normal file
@@ -0,0 +1,102 @@
|
||||
package hostagent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/rcourtman/pulse-go-rewrite/pkg/securityutil"
|
||||
"github.com/rs/zerolog"
|
||||
gohost "github.com/shirou/gopsutil/v4/host"
|
||||
)
|
||||
|
||||
// All URLs and credentials in these tests are synthetic, never reporter data.
|
||||
func TestHostURLRejectionIsPrivateAndReadOnly(t *testing.T) {
|
||||
for _, tc := range []struct{ name, raw string }{
|
||||
{"userinfo", "https://synthetic-user:synthetic-password@private-fixture.invalid"},
|
||||
{"query", "https://private-fixture.invalid/?token=synthetic-query"},
|
||||
{"fragment", "https://private-fixture.invalid/#synthetic-fragment"},
|
||||
{"port", "https://private-fixture.invalid:synthetic-port"},
|
||||
{"escape", "https://private-fixture.invalid/%synthetic-escape"},
|
||||
{"missing-host", "https:///synthetic-path"},
|
||||
{"scheme", "synthetic-scheme://private-fixture.invalid"},
|
||||
{"control", "https://private-fixture.invalid/\nsynthetic-control"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
stateDir := t.TempDir()
|
||||
saved := filepath.Join(stateDir, "runtime.token")
|
||||
if err := os.WriteFile(saved, []byte("synthetic-saved-token\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := os.Stat(saved)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var logs bytes.Buffer
|
||||
logger := zerolog.New(&logs)
|
||||
probes := 0
|
||||
collector := &mockCollector{hostInfoFn: func(context.Context) (*gohost.InfoStat, error) {
|
||||
probes++
|
||||
return nil, errors.New("host discovery must not run")
|
||||
}}
|
||||
agent, newErr := New(Config{PulseURL: tc.raw, APIToken: "synthetic-runtime-token", StateDir: stateDir,
|
||||
Logger: &logger, Collector: collector})
|
||||
if agent != nil {
|
||||
t.Fatal("invalid URL produced a host module")
|
||||
}
|
||||
result, enrollErr := Enroll(context.Background(), EnrollmentConfig{PulseURL: tc.raw,
|
||||
APIToken: "synthetic-bootstrap-token", StateDir: stateDir, Logger: &logger, Collector: collector})
|
||||
if result.APIToken != "" || result.AgentID != "" {
|
||||
t.Fatal("invalid URL produced enrollment credentials")
|
||||
}
|
||||
for _, err := range []error{newErr, enrollErr} {
|
||||
if err == nil || !strings.Contains(err.Error(), "invalid pulse URL") {
|
||||
t.Fatal("URL refusal lost its configuration context")
|
||||
}
|
||||
if strings.Contains(err.Error(), "synthetic-") || strings.Contains(err.Error(), "private-fixture.invalid") {
|
||||
t.Error("URL refusal disclosed rejected input")
|
||||
}
|
||||
}
|
||||
if probes != 0 || logs.Len() != 0 {
|
||||
t.Error("invalid URL reached discovery or logging")
|
||||
}
|
||||
entries, err := os.ReadDir(stateDir)
|
||||
if err != nil || len(entries) != 1 {
|
||||
t.Fatal("URL refusal added saved state")
|
||||
}
|
||||
data, readErr := os.ReadFile(saved)
|
||||
after, statErr := os.Stat(saved)
|
||||
if readErr != nil || statErr != nil || string(data) != "synthetic-saved-token\n" || after.Mode() != before.Mode() {
|
||||
t.Fatal("URL refusal changed saved credentials or permissions")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostURLDiagnosticReusePreservesTransportPolicy(t *testing.T) {
|
||||
t.Cleanup(func() { securityutil.SetOperatorPlaintextHTTPConsent(false) })
|
||||
for _, consent := range []bool{false, true} {
|
||||
securityutil.SetOperatorPlaintextHTTPConsent(consent)
|
||||
for _, raw := range []string{
|
||||
" HTTPS://Pulse.Invalid:7655/base/ ", "https://pulse.invalid/a%2Fb///", "https://pulse.invalid/?",
|
||||
"http://localhost:7655/", "http://127.0.0.1:7655/", "http://[::1]:7655/",
|
||||
"http://192.168.1.20:7655/", "http://pulse:7655/", "http://203.0.113.10/",
|
||||
"https://user:password@pulse.invalid", "https://pulse.invalid/?token=value", "https://pulse.invalid/#fragment",
|
||||
"https://pulse.invalid:0", "https://pulse.invalid:65536", "https://pulse.invalid:bad-port",
|
||||
"ftp://pulse.invalid/", "wss://pulse.invalid/", "https:///missing-host", "pulse.invalid/base", " ",
|
||||
} {
|
||||
want, wantErr := securityutil.NormalizePulseHTTPBaseURLWithOptions(raw, securityutil.PulseURLValidationOptions{AllowLocalNetworkHTTP: true})
|
||||
got, err := normalizePulseURL(raw)
|
||||
if (err != nil) != (wantErr != nil) {
|
||||
t.Fatal("diagnostic reuse changed transport admission")
|
||||
}
|
||||
if err == nil && got != want.String() {
|
||||
t.Fatal("diagnostic reuse changed an accepted URL")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user