Warn about container SSH only when ssh really runs

The warning that direct SSH from a container is insecure ran before the
collector checked for a key, so every Docker install logged it for each
node on each poll even though no SSH would ever happen. Two nodes with no
key produced 118 lines in 10 minutes, which buries real warnings in a
support bundle and tells the reader something false.

Emit it from runSSHCommand, right before ssh is executed, and only once
per host. A missing key, a refused host key or an active backoff now log
nothing about it. The dev override's info line moves with it, for the
same reason. The notice is keyed on the host because that is the SSH
target: same-named machines are still separate targets.

Contract-Neutral: log placement and frequency only; key handling, host-key trust, SSH collection and API contracts are unchanged
This commit is contained in:
rcourtman
2026-11-05 19:27:05 +00:00
parent a15c274156
commit 878840f637
2 changed files with 120 additions and 23 deletions

View File

@@ -19,9 +19,16 @@ func (f containerSSHFixtureRunner) Run(ctx context.Context, name string, args ..
return f(ctx, name, args...)
}
const (
containerSSHNoticePhrase = "using direct SSH"
containerSSHInsecureNotice = "This is insecure for production deployments."
containerSSHDevNotice = "dev mode override active"
)
// The runner and keyscan are both synthetic: never contact a real SSH host.
// Default container mode warns, but an existing key still reaches the normal
// host-key and strict SSH path. Missing keys and host-key failures still refuse.
// Default container mode warns when ssh really runs, and an existing key still
// reaches the normal host-key and strict SSH path. Missing keys and host-key
// failures still refuse, and refuse quietly because no ssh ran.
func TestContainerSSHCollectionWarnsWithoutBypassingKeyOrHostTrust(t *testing.T) {
for _, state := range []string{"missing_key", "existing_key", "host_key_refused"} {
t.Run(state, func(t *testing.T) {
@@ -60,13 +67,14 @@ func TestContainerSSHCollectionWarnsWithoutBypassingKeyOrHostTrust(t *testing.T)
temperature, err := collector.CollectTemperature(context.Background(), "container-ssh.invalid", "synthetic-node")
require.NoError(t, err)
require.NotNil(t, temperature)
require.Contains(t, logs.String(), "This is insecure for production deployments.")
if state == "existing_key" {
require.Contains(t, logs.String(), containerSSHInsecureNotice)
require.True(t, temperature.Available)
require.Equal(t, 44.0, temperature.CPUPackage)
require.Equal(t, 1, keyscans)
require.Equal(t, 1, commands)
} else {
require.NotContains(t, logs.String(), containerSSHNoticePhrase)
require.False(t, temperature.Available)
require.Zero(t, commands, "missing key or failed host-key trust must not reach SSH execution")
if state == "missing_key" {
@@ -84,3 +92,87 @@ func TestContainerSSHCollectionWarnsWithoutBypassingKeyOrHostTrust(t *testing.T)
})
}
}
// A Docker install polls every node on every cycle, so the notice has to follow
// real ssh runs and not the poll. Both nodes share a name because the SSH target
// is the host: same-named machines are still separate targets.
func TestContainerSSHNoticeFollowsRealSSHOncePerNode(t *testing.T) {
nodes := []string{"https://alpha.invalid:8006", "https://beta.invalid:8006"}
const polls = 3
cases := []struct {
name string
keyPath func(home string) string
devMode string
wantNotice string // logged once per node; empty means no notice at all
wantRuns int
}{
{
name: "no_key_configured",
keyPath: func(string) string { return "" },
},
{
name: "key_file_missing",
keyPath: func(home string) string { return filepath.Join(home, "absent-key") },
},
{
name: "key_used",
keyPath: func(home string) string { return filepath.Join(home, "synthetic-key") },
wantNotice: containerSSHInsecureNotice,
wantRuns: polls * len(nodes),
},
{
name: "key_used_with_dev_override",
keyPath: func(home string) string { return filepath.Join(home, "synthetic-key") },
devMode: "true",
wantNotice: containerSSHDevNotice,
wantRuns: polls * len(nodes),
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("PULSE_DOCKER", "true")
t.Setenv("PULSE_DEV_ALLOW_CONTAINER_SSH", tc.devMode)
if tc.wantRuns > 0 {
require.NoError(t, os.WriteFile(tc.keyPath(home), []byte("synthetic key"), 0600))
}
runs := 0
collector := &TemperatureCollector{
sshUser: "fixture", sshKeyPath: tc.keyPath(home), sshPort: 2222,
runner: containerSSHFixtureRunner(func(context.Context, string, ...string) ([]byte, error) {
runs++
return []byte(`{"coretemp-isa-0000":{"Package id 0":{"temp1_input":44}}}`), nil
}),
}
logs := newMonitoringLogCapture(t)
for poll := 0; poll < polls; poll++ {
for _, node := range nodes {
_, err := collector.CollectTemperature(context.Background(), node, "pve")
require.NoError(t, err)
}
}
require.Equal(t, tc.wantRuns, runs)
var notices []string
for _, line := range strings.Split(logs.String(), "\n") {
if strings.Contains(line, containerSSHNoticePhrase) {
notices = append(notices, line)
}
}
if tc.wantNotice == "" {
require.Empty(t, notices, "no ssh ran, so the log must not claim it did")
return
}
require.Len(t, notices, len(nodes), "one notice per node across every poll")
require.Contains(t, notices[0], "alpha.invalid")
require.Contains(t, notices[1], "beta.invalid")
for _, notice := range notices {
require.Contains(t, notice, tc.wantNotice)
}
})
}
}

View File

@@ -88,6 +88,7 @@ type TemperatureCollector struct {
sshPort int // SSH port (default 22)
hostKeys KnownHostsManager
missingKeyWarned atomic.Bool
containerSSHSeen sync.Map // Hosts already assessed by noteContainerSSHUse
runner CommandRunner
sshFailureMu sync.Mutex
sshFailures map[string]*temperatureSSHFailure
@@ -263,26 +264,6 @@ func (tc *TemperatureCollector) CollectTemperature(ctx context.Context, nodeHost
// Extract hostname/IP from the host URL (might be https://hostname:8006)
host := extractHostname(nodeHost)
// SECURITY: Warn about legacy SSH collection in containers; this is not a block.
// Container compromise = SSH key compromise = root access to infrastructure
devModeAllowSSH := os.Getenv("PULSE_DEV_ALLOW_CONTAINER_SSH") == "true"
isContainer := os.Getenv("PULSE_DOCKER") == "true" || system.InContainer()
if isContainer && devModeAllowSSH {
// Log when dev override is active so operators understand the security posture
log.Info().
Str("node", nodeName).
Msg("Temperature collection using direct SSH (dev mode override active - not for production)")
}
if isContainer && !devModeAllowSSH {
// Warn but allow if key is present (legacy behavior restoration)
// We don't return here, allowing the code to fall through to the SSH key check
log.Warn().
Str("node", nodeName).
Msg("Temperature collection using direct SSH from container. This is insecure for production deployments.")
}
if strings.TrimSpace(tc.sshKeyPath) == "" {
tc.logMissingSSHKey(nil)
return &models.Temperature{Available: false}, nil
@@ -386,6 +367,28 @@ func (tc *TemperatureCollector) logSkippedSSHAttempt(outcome sshFailureOutcome,
event.Msg("Abandoning SSH temperature collection after the collection deadline expired")
}
// noteContainerSSHUse tells the operator that ssh is about to run from inside a
// container. It is a warning, not a block: container compromise means SSH key
// compromise, which means root access to the infrastructure. A host is only
// assessed once, so the line cannot repeat on every poll cycle.
func (tc *TemperatureCollector) noteContainerSSHUse(host string) {
if _, seen := tc.containerSSHSeen.LoadOrStore(host, struct{}{}); seen {
return
}
if os.Getenv("PULSE_DOCKER") != "true" && !system.InContainer() {
return
}
if os.Getenv("PULSE_DEV_ALLOW_CONTAINER_SSH") == "true" {
log.Info().
Str("host", host).
Msg("Temperature collection using direct SSH (dev mode override active - not for production)")
return
}
log.Warn().
Str("host", host).
Msg("Temperature collection using direct SSH from container. This is insecure for production deployments.")
}
func (tc *TemperatureCollector) runSSHCommand(ctx context.Context, host, command string) (string, error) {
if err := tc.validateSSHKeyPath(); err != nil {
return "", err
@@ -432,6 +435,8 @@ func (tc *TemperatureCollector) runSSHCommand(ctx context.Context, host, command
// Add user@host and command
sshArgs = append(sshArgs, fmt.Sprintf("%s@%s", tc.sshUser, host), command)
tc.noteContainerSSHUse(host)
output, err := tc.runner.Run(runCtx, "ssh", sshArgs...)
if err != nil {
if errors.Is(err, errTemperatureCommandOutputTooLarge) {