diff --git a/internal/monitoring/container_ssh_collection_test.go b/internal/monitoring/container_ssh_collection_test.go index ea7e822169..47a5dbec0b 100644 --- a/internal/monitoring/container_ssh_collection_test.go +++ b/internal/monitoring/container_ssh_collection_test.go @@ -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) + } + }) + } +} diff --git a/internal/monitoring/temperature.go b/internal/monitoring/temperature.go index c7a0d79b09..557bfe7153 100644 --- a/internal/monitoring/temperature.go +++ b/internal/monitoring/temperature.go @@ -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) {