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.

Cover the missing arms of the SSRF, clone and classifier guards

rcourtmanc035c5b51406
diff --git a/internal/alerts/ack_identity_branchcov0724pm_test.go b/internal/alerts/ack_identity_branchcov0724pm_test.go
new file mode 100644
index 0000000000..2c6c077222
--- /dev/null
+++ b/internal/alerts/ack_identity_branchcov0724pm_test.go
@@ -0,0 +1,111 @@
+package alerts
+
+import (
+ "testing"
+)
+
+// TestBranchcov0724pmCanonicalAckKey raises branch coverage of canonicalAckKey
+// (ack_state.go:5, baseline 80%). The existing suite reaches the canonical-
+// state-present arm and the fallback-with-identity-absent arm, but never the
+// nil-alert early return. These cases drive the nil guard and re-assert the
+// other two arms with concrete, distinct expected values.
+func TestBranchcov0724pmCanonicalAckKey(t *testing.T) {
+ cases := []struct {
+ name string
+ alert *Alert
+ fallback string
+ want string
+ }{
+ {
+ // UNCOVERED arm: nil alert -> fallback returned verbatim.
+ name: "nil_alert_returns_fallback",
+ alert: nil,
+ fallback: "public-id-1",
+ want: "public-id-1",
+ },
+ {
+ // Canonical state present on the alert wins over the fallback.
+ name: "canonical_state_wins_over_fallback",
+ alert: &Alert{CanonicalState: "r1::s1"},
+ fallback: "should-not-be-used",
+ want: "r1::s1",
+ },
+ {
+ // No canonical identity resolvable -> fallback.
+ name: "no_identity_returns_fallback",
+ alert: &Alert{ID: "legacy-only"},
+ fallback: "legacy-only",
+ want: "legacy-only",
+ },
+ {
+ // No identity and empty fallback -> empty string.
+ name: "no_identity_empty_fallback_returns_empty",
+ alert: &Alert{},
+ fallback: "",
+ want: "",
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := canonicalAckKey(tc.alert, tc.fallback); got != tc.want {
+ t.Fatalf("canonicalAckKey want %q, got %q", tc.want, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0724pmAlertMetadataResourceType raises branch coverage of
+// alertMetadataResourceType (active_cleanup.go:219, baseline 80%). The
+// existing suite covers the nil-alert/nil-metadata guard and the
+// resourceType-present-as-string arm. The UNCOVERED arm is the final
+// `return ""` when the key is absent or holds a non-string value. These cases
+// drive that arm and re-assert the trim/lowercase behaviour of the string arm.
+func TestBranchcov0724pmAlertMetadataResourceType(t *testing.T) {
+ cases := []struct {
+ name string
+ alert *Alert
+ want string
+ }{
+ {
+ // Nil alert guard -> "".
+ name: "nil_alert_returns_empty",
+ alert: nil,
+ want: "",
+ },
+ {
+ // Nil metadata guard -> "".
+ name: "nil_metadata_returns_empty",
+ alert: &Alert{Metadata: nil},
+ want: "",
+ },
+ {
+ // UNCOVERED arm: metadata present but key absent -> "".
+ name: "missing_resource_type_key_returns_empty",
+ alert: &Alert{Metadata: map[string]interface{}{"other": 1}},
+ want: "",
+ },
+ {
+ // UNCOVERED arm (same return): key present but not a string -> "".
+ name: "non_string_resource_type_returns_empty",
+ alert: &Alert{Metadata: map[string]interface{}{"resourceType": 42}},
+ want: "",
+ },
+ {
+ // String value is trimmed and lower-cased.
+ name: "string_value_trimmed_and_lowercased",
+ alert: &Alert{Metadata: map[string]interface{}{"resourceType": " Docker "}},
+ want: "docker",
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := alertMetadataResourceType(tc.alert); got != tc.want {
+ t.Fatalf("alertMetadataResourceType want %q, got %q", tc.want, got)
+ }
+ })
+ }
+}
diff --git a/internal/alerts/backup_snapshot_branchcov0724pm_test.go b/internal/alerts/backup_snapshot_branchcov0724pm_test.go
new file mode 100644
index 0000000000..ae083efdb3
--- /dev/null
+++ b/internal/alerts/backup_snapshot_branchcov0724pm_test.go
@@ -0,0 +1,432 @@
+package alerts
+
+import (
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// TestBranchcov0724pmBackupAlertStillTriggered raises branch coverage of
+// backupAlertStillTriggered (backup_snapshot.go:85, baseline 61.1%). The
+// existing suite only reaches the trailing `return false`, so nearly every
+// guard body and both threshold "still triggered" arms are uncovered. These
+// cases drive: the nil-alert guard, the disabled-config guard, the
+// ignored-VMID suppression, the orphaned-but-AlertOrphaned-off suppression,
+// the ageDays-metadata-missing fall-back to alert.Value, the guestVmid-absent
+// fall-back, and the critical/warning trigger arms -- each asserting a
+// concrete, observable boolean.
+//
+// NOTE: the inner `if parsed := metadataIntValue(...); parsed > 0` arm at
+// backup_snapshot.go:92 is provably unreachable (see report) and is therefore
+// not exercised here.
+func TestBranchcov0724pmBackupAlertStillTriggered(t *testing.T) {
+ orphanedOff := false
+ cases := []struct {
+ name string
+ alert *Alert
+ cfg BackupAlertConfig
+ want bool
+ }{
+ {
+ // Nil-alert guard: returns false regardless of cfg.
+ name: "nil_alert_returns_false",
+ alert: nil,
+ cfg: BackupAlertConfig{Enabled: true, WarningDays: 3},
+ want: false,
+ },
+ {
+ // Disabled-config guard: returns false.
+ name: "disabled_cfg_returns_false",
+ alert: &Alert{Metadata: map[string]interface{}{"ageDays": 99.0}},
+ cfg: BackupAlertConfig{Enabled: false, WarningDays: 3},
+ want: false,
+ },
+ {
+ // guestVmid absent -> vmid=="" body is entered (parsed stays 0).
+ // ageDays present (4) over warning threshold (3) -> still triggered.
+ name: "guest_vmid_absent_still_triggers_warning",
+ alert: &Alert{Metadata: map[string]interface{}{"ageDays": 4.0}},
+ cfg: BackupAlertConfig{Enabled: true, WarningDays: 3, CriticalDays: 5},
+ want: true,
+ },
+ {
+ // Ignored VMID suppresses even when age would trigger.
+ name: "ignored_vmid_returns_false",
+ alert: &Alert{Metadata: map[string]interface{}{
+ "guestVmid": "100",
+ "ageDays": 99.0,
+ }},
+ cfg: BackupAlertConfig{Enabled: true, WarningDays: 3, IgnoreVMIDs: []string{"100"}},
+ want: false,
+ },
+ {
+ // Orphaned backup with AlertOrphaned pointing at false is suppressed.
+ name: "orphaned_with_alert_orphaned_off_returns_false",
+ alert: &Alert{Metadata: map[string]interface{}{
+ "guestVmid": "100",
+ "orphaned": true,
+ "ageDays": 99.0,
+ }},
+ cfg: BackupAlertConfig{Enabled: true, WarningDays: 3, AlertOrphaned: &orphanedOff},
+ want: false,
+ },
+ {
+ // ageDays metadata absent -> ageValue falls back to alert.Value (7),
+ // which clears the warning threshold (5) -> still triggered.
+ name: "age_falls_back_to_alert_value_triggers_warning",
+ alert: &Alert{
+ Value: 7.0,
+ Metadata: map[string]interface{}{"guestVmid": "100"},
+ },
+ cfg: BackupAlertConfig{Enabled: true, WarningDays: 5},
+ want: true,
+ },
+ {
+ // Critical arm: ageDays (10) >= CriticalDays (5).
+ name: "critical_threshold_triggers",
+ alert: &Alert{Metadata: map[string]interface{}{
+ "guestVmid": "100",
+ "ageDays": 10.0,
+ }},
+ cfg: BackupAlertConfig{Enabled: true, WarningDays: 3, CriticalDays: 5},
+ want: true,
+ },
+ {
+ // Warning-only arm: ageDays (4) below critical (5) but >= warning (3).
+ name: "warning_threshold_triggers_below_critical",
+ alert: &Alert{Metadata: map[string]interface{}{
+ "guestVmid": "100",
+ "ageDays": 4.0,
+ }},
+ cfg: BackupAlertConfig{Enabled: true, WarningDays: 3, CriticalDays: 5},
+ want: true,
+ },
+ {
+ // Boundary: ageDays (3) below warning threshold (3 fails >=) -> false.
+ name: "below_warning_threshold_returns_false",
+ alert: &Alert{Metadata: map[string]interface{}{
+ "guestVmid": "100",
+ "ageDays": 2.0,
+ }},
+ cfg: BackupAlertConfig{Enabled: true, WarningDays: 3},
+ want: false,
+ },
+ {
+ // No thresholds configured at all -> never triggers.
+ name: "no_thresholds_returns_false",
+ alert: &Alert{Metadata: map[string]interface{}{
+ "guestVmid": "100",
+ "ageDays": 50.0,
+ }},
+ cfg: BackupAlertConfig{Enabled: true},
+ want: false,
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := backupAlertStillTriggered(tc.alert, tc.cfg); got != tc.want {
+ t.Fatalf("backupAlertStillTriggered want %v, got %v", tc.want, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0724pmGuestMatchesBackupType raises branch coverage of
+// guestMatchesBackupType (backup_snapshot.go:191, baseline 80%). The existing
+// suite covers the "guest-type-unknown -> false" and the equality arms but not
+// the "backup-type-unknown -> true" arm. These cases drive the unknown-backup-
+// type arm (with a typed guest, to prove it matches anything), the guest-
+// unknown arm, and both sides of the equality comparison.
+func TestBranchcov0724pmGuestMatchesBackupType(t *testing.T) {
+ cases := []struct {
+ name string
+ guest GuestLookup
+ backupType string
+ want bool
+ }{
+ {
+ // UNCOVERED arm: unknown backup type matches a typed guest.
+ name: "unknown_backup_type_matches_typed_guest",
+ guest: GuestLookup{Type: "qemu"},
+ backupType: "host",
+ want: true,
+ },
+ {
+ // UNCOVERED arm via empty backup type: "" is unknown -> matches.
+ name: "empty_backup_type_matches",
+ guest: GuestLookup{Type: "lxc"},
+ backupType: "",
+ want: true,
+ },
+ {
+ // Guest type unknown, backup typed -> never matches.
+ name: "unknown_guest_type_never_matches_typed_backup",
+ guest: GuestLookup{Type: "storage"},
+ backupType: "qemu",
+ want: false,
+ },
+ {
+ // Same kind (qemu == qemu).
+ name: "same_kind_matches",
+ guest: GuestLookup{Type: "qemu"},
+ backupType: "vm",
+ want: true,
+ },
+ {
+ // Different kind (lxc guest vs qemu backup).
+ name: "different_kind_does_not_match",
+ guest: GuestLookup{Type: "lxc"},
+ backupType: "qemu",
+ want: false,
+ },
+ {
+ // Alias normalisation on both sides (ct == container).
+ name: "alias_normalisation_both_sides",
+ guest: GuestLookup{Type: "ct"},
+ backupType: "container",
+ want: true,
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := guestMatchesBackupType(tc.guest, tc.backupType); got != tc.want {
+ t.Fatalf("guestMatchesBackupType want %v, got %v", tc.want, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0724pmBackupOrphanInventoryReady raises branch coverage of
+// backupOrphanInventoryReady (backup_snapshot.go:217, baseline 77.8%). The
+// existing suite covers the nil-scope and final map-lookup arms. These cases
+// drive the uncovered "non-PVE source -> ready (true)" arm and the
+// "blank-instance/guestType -> not ready (false)" arm, and re-assert the map
+// lookup for both a ready and not-ready inventory entry.
+func TestBranchcov0724pmBackupOrphanInventoryReady(t *testing.T) {
+ readyScope := &BackupInventoryScope{
+ PVEOrphanInventoryReady: map[string]map[string]bool{
+ "pve1": {"qemu": true, "lxc": false},
+ },
+ }
+ cases := []struct {
+ name string
+ scope *BackupInventoryScope
+ record backupRecord
+ want bool
+ }{
+ {
+ // Nil scope -> inventory treated as ready.
+ name: "nil_scope_ready",
+ scope: nil,
+ record: backupRecord{source: "PVE"},
+ want: true,
+ },
+ {
+ // Scope present but map nil -> ready.
+ name: "nil_ready_map_ready",
+ scope: &BackupInventoryScope{},
+ record: backupRecord{source: "PVE"},
+ want: true,
+ },
+ {
+ // UNCOVERED arm: non-PVE source is always ready.
+ name: "non_pve_source_ready",
+ scope: readyScope,
+ record: backupRecord{source: "PBS"},
+ want: true,
+ },
+ {
+ // UNCOVERED arm: PVE source but blank instance -> not ready.
+ name: "pve_blank_instance_not_ready",
+ scope: readyScope,
+ record: backupRecord{source: "PVE", instance: " ", subjectType: "qemu"},
+ want: false,
+ },
+ {
+ // UNCOVERED arm: PVE source but blank guest type -> not ready.
+ name: "pve_blank_guest_type_not_ready",
+ scope: readyScope,
+ record: backupRecord{source: "PVE", instance: "pve1", subjectType: "host"},
+ want: false,
+ },
+ {
+ // PVE source, inventory marks qemu ready -> true.
+ name: "pve_inventory_ready_true",
+ scope: readyScope,
+ record: backupRecord{source: "PVE", instance: "pve1", subjectType: "qemu"},
+ want: true,
+ },
+ {
+ // PVE source, inventory marks lxc not ready -> false.
+ name: "pve_inventory_ready_false",
+ scope: readyScope,
+ record: backupRecord{source: "PVE", instance: "pve1", node: "n1", subjectType: "lxc"},
+ want: false,
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := backupOrphanInventoryReady(tc.scope, tc.record); got != tc.want {
+ t.Fatalf("backupOrphanInventoryReady want %v, got %v", tc.want, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0724pmBackupMatchesKnownPVETemplate raises branch coverage of
+// backupMatchesKnownPVETemplate (backup_snapshot.go:232, baseline 80%). The
+// existing suite covers the top guard and the final exists lookup. These cases
+// drive the uncovered "unparseable/non-positive vmID -> false" arm and the
+// "built subject key is empty -> false" arm, and re-assert a positive and a
+// negative exists lookup against a real key.
+func TestBranchcov0724pmBackupMatchesKnownPVETemplate(t *testing.T) {
+ // Construct the exact key the implementation builds for a qemu template.
+ qemuKey := BuildBackupPVETemplateSubjectKey("pve1", "qemu", "node1", 100)
+ if qemuKey == "" {
+ t.Fatalf("test setup: expected non-empty template subject key")
+ }
+ scope := &BackupInventoryScope{
+ PVETemplateSubjects: map[string]struct{}{
+ qemuKey: {},
+ "some-other-key": {},
+ },
+ }
+ cases := []struct {
+ name string
+ scope *BackupInventoryScope
+ record backupRecord
+ want bool
+ }{
+ {
+ // Nil scope -> never a known template.
+ name: "nil_scope_false",
+ scope: nil,
+ record: backupRecord{source: "PVE", vmID: "100"},
+ want: false,
+ },
+ {
+ // Empty template set -> false (guard short-circuit).
+ name: "empty_template_set_false",
+ scope: &BackupInventoryScope{},
+ record: backupRecord{source: "PVE", vmID: "100"},
+ want: false,
+ },
+ {
+ // Non-PVE source -> false (guard).
+ name: "non_pve_source_false",
+ scope: scope,
+ record: backupRecord{source: "PBS", vmID: "100"},
+ want: false,
+ },
+ {
+ // UNCOVERED arm: PVE source but vmID not a number -> false.
+ name: "pve_non_numeric_vmid_false",
+ scope: scope,
+ record: backupRecord{source: "PVE", vmID: "abc"},
+ want: false,
+ },
+ {
+ // UNCOVERED arm: PVE source but vmID <= 0 -> false.
+ name: "pve_zero_vmid_false",
+ scope: scope,
+ record: backupRecord{source: "PVE", vmID: "0"},
+ want: false,
+ },
+ {
+ // UNCOVERED arm: valid vmID but blank instance -> empty key -> false.
+ name: "pve_blank_instance_empty_key_false",
+ scope: scope,
+ record: backupRecord{source: "PVE", vmID: "100", instance: "", node: "node1", subjectType: "qemu"},
+ want: false,
+ },
+ {
+ // Positive lookup: record matches the known qemu template key.
+ name: "known_template_matches_true",
+ scope: scope,
+ record: backupRecord{source: "PVE", vmID: "100", instance: "pve1", node: "node1", subjectType: "qemu"},
+ want: true,
+ },
+ {
+ // Negative lookup: well-formed key not present in the set.
+ name: "unknown_template_false",
+ scope: scope,
+ record: backupRecord{source: "PVE", vmID: "999", instance: "pve1", node: "node1", subjectType: "qemu"},
+ want: false,
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := backupMatchesKnownPVETemplate(tc.scope, tc.record); got != tc.want {
+ t.Fatalf("backupMatchesKnownPVETemplate want %v, got %v", tc.want, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0724pmCanonicalBackupSubjectResourceType raises branch coverage
+// of canonicalBackupSubjectResourceType (backup_snapshot.go:257, baseline
+// 75%). The existing suite covers the lookup-Type-present arm and the qemu/
+// backup-subject switch outcomes, but not the "lxc" case nor the "vmID present
+// -> VM" fall-through. These cases drive every arm with distinct expected
+// ResourceType values.
+func TestBranchcov0724pmCanonicalBackupSubjectResourceType(t *testing.T) {
+ cases := []struct {
+ name string
+ record backupRecord
+ want unifiedresources.ResourceType
+ }{
+ {
+ // lookup.Type present (lxc) wins -> SystemContainer via guest helper.
+ name: "lookup_type_lxc_wins",
+ record: backupRecord{lookup: GuestLookup{Type: "lxc"}, subjectType: "qemu"},
+ want: unifiedresources.ResourceTypeSystemContainer,
+ },
+ {
+ // lookup.Type present (qemu) wins -> VM.
+ name: "lookup_type_qemu_wins",
+ record: backupRecord{lookup: GuestLookup{Type: "qemu"}, subjectType: "lxc"},
+ want: unifiedresources.ResourceTypeVM,
+ },
+ {
+ // UNCOVERED arm: no lookup type, subjectType normalises to lxc.
+ name: "subject_type_lxc",
+ record: backupRecord{subjectType: "ct"},
+ want: unifiedresources.ResourceTypeSystemContainer,
+ },
+ {
+ // subjectType normalises to qemu -> VM.
+ name: "subject_type_qemu",
+ record: backupRecord{subjectType: "vm"},
+ want: unifiedresources.ResourceTypeVM,
+ },
+ {
+ // UNCOVERED arm: unknown subjectType but vmID present -> VM.
+ name: "unknown_subject_with_vmid_vm",
+ record: backupRecord{subjectType: "host", vmID: "100"},
+ want: unifiedresources.ResourceTypeVM,
+ },
+ {
+ // Unknown subjectType and no vmID -> generic backup-subject.
+ name: "unknown_subject_no_vmid_backup_subject",
+ record: backupRecord{subjectType: "storage"},
+ want: unifiedresources.ResourceType("backup-subject"),
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := canonicalBackupSubjectResourceType(tc.record); got != tc.want {
+ t.Fatalf("canonicalBackupSubjectResourceType want %q, got %q", tc.want, got)
+ }
+ })
+ }
+}
diff --git a/internal/alerts/canonical_identity_branchcov0724pm_test.go b/internal/alerts/canonical_identity_branchcov0724pm_test.go
new file mode 100644
index 0000000000..d712b70166
--- /dev/null
+++ b/internal/alerts/canonical_identity_branchcov0724pm_test.go
@@ -0,0 +1,233 @@
+package alerts
+
+import (
+ "testing"
+
+ alertspecs "github.com/rcourtman/pulse-go-rewrite/internal/alerts/specs"
+)
+
+// TestBranchcov0724pmCanonicalPoweredStateSpecID raises branch coverage of
+// canonicalPoweredStateSpecID (canonical_identity.go:41). The existing suite
+// only calls it with a non-empty resourceID (happy path). These cases drive the
+// empty-input early-return arm and re-assert the happy path with a concrete,
+// distinct value.
+func TestBranchcov0724pmCanonicalPoweredStateSpecID(t *testing.T) {
+ cases := []struct {
+ name string
+ resourceID string
+ want string
+ }{
+ {
+ // Empty arm: resourceID == "" short-circuits to "".
+ name: "empty_resource_id_returns_empty",
+ resourceID: "",
+ want: "",
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := canonicalPoweredStateSpecID(tc.resourceID); got != tc.want {
+ t.Fatalf("canonicalPoweredStateSpecID(%q) want %q, got %q", tc.resourceID, tc.want, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0724pmCanonicalDiscreteStateSpecID raises branch coverage of
+// canonicalDiscreteStateSpecID (canonical_identity.go:52). The existing suite
+// only reaches the happy path (both args non-empty). These cases drive both
+// halves of the OR guard -- empty resourceID and empty stateKey -- so each
+// sub-condition is independently exercised, plus the happy path with distinct
+// values.
+func TestBranchcov0724pmCanonicalDiscreteStateSpecID(t *testing.T) {
+ cases := []struct {
+ name string
+ resourceID string
+ stateKey string
+ want string
+ }{
+ {
+ // Empty arm, first half of the OR: resourceID == "" -> "".
+ name: "empty_resource_id_returns_empty",
+ resourceID: "",
+ stateKey: "runtime-state",
+ want: "",
+ },
+ {
+ // Empty arm, second half of the OR: stateKey == "" -> "".
+ name: "empty_state_key_returns_empty",
+ resourceID: "docker:c1",
+ stateKey: "",
+ want: "",
+ },
+ {
+ // Both empty: still "" (does not matter which half fires).
+ name: "both_empty_returns_empty",
+ resourceID: "",
+ stateKey: "",
+ want: "",
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := canonicalDiscreteStateSpecID(tc.resourceID, tc.stateKey); got != tc.want {
+ t.Fatalf("canonicalDiscreteStateSpecID(%q, %q) want %q, got %q", tc.resourceID, tc.stateKey, tc.want, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0724pmCanonicalServiceGapSpecID raises branch coverage of
+// canonicalServiceGapSpecID (canonical_identity.go:63). The existing suite only
+// reaches the happy path. These cases drive the empty-resourceID early-return
+// arm and re-assert the happy path.
+func TestBranchcov0724pmCanonicalServiceGapSpecID(t *testing.T) {
+ cases := []struct {
+ name string
+ resourceID string
+ want string
+ }{
+ {
+ // Empty arm: resourceID == "" short-circuits to "".
+ name: "empty_resource_id_returns_empty",
+ resourceID: "",
+ want: "",
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := canonicalServiceGapSpecID(tc.resourceID); got != tc.want {
+ t.Fatalf("canonicalServiceGapSpecID(%q) want %q, got %q", tc.resourceID, tc.want, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0724pmCanonicalTrackingKeyForSpec raises branch coverage of
+// canonicalTrackingKeyForSpec (canonical_identity.go:389). The existing suite
+// only reaches the happy path (buildCanonicalStateID returns a non-empty key).
+// These cases drive the fallback arm -- when spec.ResourceID or spec.ID is empty
+// the canonical key is "" so the distinct fallback must be returned -- and
+// re-assert the happy path with a concrete expected canonical key.
+func TestBranchcov0724pmCanonicalTrackingKeyForSpec(t *testing.T) {
+ cases := []struct {
+ name string
+ spec alertspecs.ResourceAlertSpec
+ fallback string
+ want string
+ }{
+ {
+ // Fallback arm: empty ResourceID -> buildCanonicalStateID returns "".
+ name: "empty_resource_id_returns_fallback",
+ spec: alertspecs.ResourceAlertSpec{ID: "spec-1"},
+ fallback: "legacy-id-1",
+ want: "legacy-id-1",
+ },
+ {
+ // Fallback arm: empty ID -> buildCanonicalStateID returns "".
+ name: "empty_spec_id_returns_fallback",
+ spec: alertspecs.ResourceAlertSpec{ResourceID: "res-1"},
+ fallback: "legacy-id-2",
+ want: "legacy-id-2",
+ },
+ {
+ // Fallback arm: both empty and fallback itself empty -> "".
+ name: "both_empty_empty_fallback_returns_empty",
+ spec: alertspecs.ResourceAlertSpec{},
+ fallback: "",
+ want: "",
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := canonicalTrackingKeyForSpec(tc.spec, tc.fallback); got != tc.want {
+ t.Fatalf("canonicalTrackingKeyForSpec want %q, got %q", tc.want, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0724pmInferCanonicalKindFromLegacyAlert raises branch coverage of
+// inferCanonicalKindFromLegacyAlert (canonical_identity.go:278). The existing
+// suite already covers the legacy-prefix arms and the type-based arm. The
+// UNCOVERED arms are:
+// 1. alert == nil -> ""
+// 2. Canonical-separator ("::") path where the inferred specID ends with
+// "-powered-state" -> AlertSpecKindPoweredState
+// 3. Same path, specID ends with "-runtime-state" or "-update-state" ->
+// AlertSpecKindDiscreteState
+// 4. Same path, specID ends with "-service-gap" -> AlertSpecKindServiceGap
+// 5. Same path, specID contains "/snapshot:" or ends with "-backup-age" ->
+// AlertSpecKindPostureThreshold
+//
+// When an alert's ID contains "::" the inferred specID is the segment after the
+// first "::" (see inferCanonicalSpecIDFromLegacyAlert), so each case constructs
+// an ID whose post-"::" suffix lands in the target switch arm. Each case uses a
+// distinct resourceID/specID so the expected kind is unambiguous.
+func TestBranchcov0724pmInferCanonicalKindFromLegacyAlert(t *testing.T) {
+ cases := []struct {
+ name string
+ alert *Alert
+ want string
+ }{
+ {
+ // Arm 1: nil guard.
+ name: "nil_alert_returns_empty",
+ alert: nil,
+ want: "",
+ },
+ {
+ // Canonical path -> -powered-state arm.
+ name: "canonical_separator_powered_state",
+ alert: &Alert{ID: "vm-100::vm-100-powered-state"},
+ want: string(alertspecs.AlertSpecKindPoweredState),
+ },
+ {
+ // Canonical path -> -runtime-state arm (DiscreteState).
+ name: "canonical_separator_runtime_state",
+ alert: &Alert{ID: "docker:c1::docker:c1-runtime-state"},
+ want: string(alertspecs.AlertSpecKindDiscreteState),
+ },
+ {
+ // Canonical path -> -update-state arm (also DiscreteState).
+ name: "canonical_separator_update_state",
+ alert: &Alert{ID: "docker:s2::docker:s2-update-state"},
+ want: string(alertspecs.AlertSpecKindDiscreteState),
+ },
+ {
+ // Canonical path -> -service-gap arm (ServiceGap).
+ name: "canonical_separator_service_gap",
+ alert: &Alert{ID: "docker:svc::docker:svc-service-gap"},
+ want: string(alertspecs.AlertSpecKindServiceGap),
+ },
+ {
+ // Canonical path -> contains "/snapshot:" arm (PostureThreshold).
+ name: "canonical_separator_snapshot",
+ alert: &Alert{ID: "pbs-1::pbs/store1/snapshot:nightly"},
+ want: string(alertspecs.AlertSpecKindPostureThreshold),
+ },
+ {
+ // Canonical path -> ends with "-backup-age" arm (PostureThreshold).
+ name: "canonical_separator_backup_age",
+ alert: &Alert{ID: "subj-7::backup-subject-7-backup-age"},
+ want: string(alertspecs.AlertSpecKindPostureThreshold),
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := inferCanonicalKindFromLegacyAlert(tc.alert); got != tc.want {
+ t.Fatalf("inferCanonicalKindFromLegacyAlert want %q, got %q", tc.want, got)
+ }
+ })
+ }
+}
diff --git a/internal/alerts/canonical_metric_branchcov0724pm_test.go b/internal/alerts/canonical_metric_branchcov0724pm_test.go
new file mode 100644
index 0000000000..abc3b5722a
--- /dev/null
+++ b/internal/alerts/canonical_metric_branchcov0724pm_test.go
@@ -0,0 +1,204 @@
+package alerts
+
+import (
+ "testing"
+
+ alertspecs "github.com/rcourtman/pulse-go-rewrite/internal/alerts/specs"
+)
+
+// TestBranchcov0724pmMetricClearThreshold raises branch coverage of
+// metricClearThreshold (canonical_metric.go:36). Its arms, in evaluation
+// order, are:
+// 1. threshold != nil && threshold.Clear > 0 -> return threshold.Clear
+// 2. spec != nil && spec.Recovery != nil -> return *spec.Recovery
+// 3. spec != nil -> return spec.Trigger
+// 4. (both nil / fell through) -> return 0
+//
+// The existing suite only reaches arm 3 through the live metric-evaluation
+// path, so 28.6%. These cases drive every arm plus the hysteresis boundary
+// (Clear == 0 must fall through to the spec) and confirm precedence between
+// the three sources. Each threshold/spec source carries a distinct value so
+// the expected result pins exactly which arm produced it.
+func TestBranchcov0724pmMetricClearThreshold(t *testing.T) {
+ recoveryVal := 41.0
+ cases := []struct {
+ name string
+ spec *alertspecs.MetricThresholdSpec
+ threshold *HysteresisThreshold
+ want float64
+ }{
+ {
+ // Arm 1: positive Clear wins outright, even when a spec with its own
+ // recovery/trigger is present (proves the threshold short-circuits).
+ name: "positive_clear_wins_over_spec_recovery_and_trigger",
+ threshold: &HysteresisThreshold{Trigger: 95, Clear: 12.5},
+ spec: &alertspecs.MetricThresholdSpec{Trigger: 90, Recovery: &recoveryVal},
+ want: 12.5,
+ },
+ {
+ // Boundary of `Clear > 0`: a zero Clear must NOT take arm 1, so the
+ // spec recovery is used instead.
+ name: "zero_clear_falls_through_to_spec_recovery",
+ threshold: &HysteresisThreshold{Trigger: 95, Clear: 0},
+ spec: &alertspecs.MetricThresholdSpec{Trigger: 90, Recovery: &recoveryVal},
+ want: 41.0,
+ },
+ {
+ // Negative Clear also fails `> 0` and falls through to spec recovery.
+ name: "negative_clear_falls_through_to_spec_recovery",
+ threshold: &HysteresisThreshold{Trigger: 95, Clear: -1},
+ spec: &alertspecs.MetricThresholdSpec{Trigger: 90, Recovery: &recoveryVal},
+ want: 41.0,
+ },
+ {
+ // Arm 2 with nil threshold: spec recovery is returned.
+ name: "nil_threshold_uses_spec_recovery",
+ spec: &alertspecs.MetricThresholdSpec{Trigger: 90, Recovery: &recoveryVal},
+ want: 41.0,
+ },
+ {
+ // Arm 3: nil threshold, no recovery -> spec trigger.
+ name: "nil_threshold_no_recovery_uses_trigger",
+ spec: &alertspecs.MetricThresholdSpec{Trigger: 90},
+ want: 90,
+ },
+ {
+ // Arm 3 reached via fall-through: zero Clear, no recovery -> trigger.
+ name: "zero_clear_no_recovery_uses_trigger",
+ threshold: &HysteresisThreshold{Trigger: 95, Clear: 0},
+ spec: &alertspecs.MetricThresholdSpec{Trigger: 88},
+ want: 88,
+ },
+ {
+ // Arm 4: both nil -> 0.
+ name: "both_nil_returns_zero",
+ want: 0,
+ },
+ {
+ // Arm 4 via fall-through: threshold present but Clear <= 0 and no
+ // spec at all -> 0 (proves the final return is reached).
+ name: "zero_clear_nil_spec_returns_zero",
+ threshold: &HysteresisThreshold{Trigger: 95, Clear: 0},
+ spec: nil,
+ want: 0,
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ got := metricClearThreshold(tc.spec, tc.threshold)
+ if got != tc.want {
+ t.Fatalf("metricClearThreshold want %v, got %v", tc.want, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0724pmResourceTypeLabel raises branch coverage of
+// resourceTypeLabel (canonical_metric.go:49). The existing suite covers the
+// common metric types via the live path (~50%); these cases drive every named
+// switch arm plus the empty/whitespace "Resource" arm and -- critically --
+// assert that the default arm returns the ORIGINAL (un-trimmed) input, which
+// is an observable distinction from the trimmed cases.
+func TestBranchcov0724pmResourceTypeLabel(t *testing.T) {
+ cases := []struct {
+ name string
+ in string
+ want string
+ }{
+ {"agent_disk", "agent-disk", "Disk"},
+ {"agent", "agent", "Agent"},
+ {"node", "node", "Node"},
+ {"guest", "guest", "Guest"},
+ {"storage", "storage", "Storage"},
+ {"pbs", "pbs", "PBS"},
+ {"pmg", "pmg", "PMG"},
+ {"empty_is_resource", "", "Resource"},
+ // Whitespace is trimmed before the switch, so whitespace-only collapses
+ // to "" and yields "Resource".
+ {"whitespace_only_is_resource", " ", "Resource"},
+ // Surrounding whitespace is trimmed, then matched.
+ {"padded_agent_matches", " agent ", "Agent"},
+ // Default arm: unknown type returned verbatim, NOT trimmed.
+ {"unknown_returned_as_is", "weird-type", "weird-type"},
+ // The un-trimmed behaviour of the default arm is observable when the
+ // input carries surrounding whitespace that a named case would have
+ // trimmed -- this pins that the default does not re-trim.
+ {"unknown_padded_returned_untrimmed", " weird-type ", " weird-type "},
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := resourceTypeLabel(tc.in); got != tc.want {
+ t.Fatalf("resourceTypeLabel(%q) want %q, got %q", tc.in, tc.want, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0724pmAlertspecsMetricTriggered raises branch coverage of
+// alertspecsMetricTriggered (canonical_metric.go:355). The existing suite only
+// exercises the "above" direction via live evaluation (~50%). These cases
+// drive: nil spec, the "above" boundary (>=), the "below" direction and its
+// boundary (<=), and the default/invalid-direction arm.
+func TestBranchcov0724pmAlertspecsMetricTriggered(t *testing.T) {
+ cases := []struct {
+ name string
+ spec *alertspecs.MetricThresholdSpec
+ observed float64
+ want bool
+ }{
+ {"nil_spec_is_false", nil, 999, false},
+ {
+ // Above: strictly over trigger -> true.
+ "above_over_trigger",
+ &alertspecs.MetricThresholdSpec{Metric: "cpu", Direction: alertspecs.ThresholdDirectionAbove, Trigger: 90},
+ 91, true,
+ },
+ {
+ // Boundary of `observed >= Trigger`: equality triggers.
+ "above_equal_trigger_triggers",
+ &alertspecs.MetricThresholdSpec{Metric: "cpu", Direction: alertspecs.ThresholdDirectionAbove, Trigger: 90},
+ 90, true,
+ },
+ {
+ "above_under_trigger_does_not_trigger",
+ &alertspecs.MetricThresholdSpec{Metric: "cpu", Direction: alertspecs.ThresholdDirectionAbove, Trigger: 90},
+ 89.9, false,
+ },
+ {
+ // Below: strictly under trigger -> true.
+ "below_under_trigger",
+ &alertspecs.MetricThresholdSpec{Metric: "cpu", Direction: alertspecs.ThresholdDirectionBelow, Trigger: 10},
+ 9, true,
+ },
+ {
+ // Boundary of `observed <= Trigger`: equality triggers.
+ "below_equal_trigger_triggers",
+ &alertspecs.MetricThresholdSpec{Metric: "cpu", Direction: alertspecs.ThresholdDirectionBelow, Trigger: 10},
+ 10, true,
+ },
+ {
+ "below_over_trigger_does_not_trigger",
+ &alertspecs.MetricThresholdSpec{Metric: "cpu", Direction: alertspecs.ThresholdDirectionBelow, Trigger: 10},
+ 10.1, false,
+ },
+ {
+ // Default arm: an unrecognised direction never triggers.
+ "invalid_direction_is_false",
+ &alertspecs.MetricThresholdSpec{Metric: "cpu", Direction: "sideways", Trigger: 1},
+ 5, false,
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := alertspecsMetricTriggered(tc.spec, tc.observed); got != tc.want {
+ t.Fatalf("alertspecsMetricTriggered want %v, got %v", tc.want, got)
+ }
+ })
+ }
+}
diff --git a/internal/models/deepcopy_branchcov0724pm_test.go b/internal/models/deepcopy_branchcov0724pm_test.go
new file mode 100644
index 0000000000..f447d21501
--- /dev/null
+++ b/internal/models/deepcopy_branchcov0724pm_test.go
@@ -0,0 +1,660 @@
+package models
+
+import (
+ "reflect"
+ "testing"
+ "time"
+)
+
+// bc0724pmT is a stable timestamp reused across these branch-coverage tests;
+// it is deliberately distinct from w0716dcT so the independence assertions
+// (which compare clone values against an immutable reference) stay legible.
+var bc0724pmT = time.Date(2025, 7, 24, 13, 45, 0, 0, time.UTC)
+
+// This file exercises the previously-uncovered ARMS of the deep-copy helpers
+// in deepcopy.go / converters.go and the cephClusterSourceRank ranking
+// function in ceph_cluster_identity.go. For every clone helper it covers:
+// - the nil-input guard (returns nil),
+// - the empty-collection path (collapsed/normalized as the source dictates),
+// - the fully-populated path,
+// - INDEPENDENCE: mutating every nested slice, map and pointer field of the
+// returned CLONE must leave the original input completely untouched (a
+// shared backing array/map would alias and is a real clone-correctness bug).
+//
+// cephClusterSourceRank is a plain ranking switch; the provably-unreachable
+// default arm is documented inline rather than faked.
+
+// ---------------------------------------------------------------------------
+// deepcopy.go: cloneHostUnraidStorage (was 75.0%)
+// ---------------------------------------------------------------------------
+
+func TestBranchcov0724pmCloneHostUnraidStorage(t *testing.T) {
+ t.Run("nil returns nil", func(t *testing.T) {
+ if got := cloneHostUnraidStorage(nil); got != nil {
+ t.Fatalf("cloneHostUnraidStorage(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("empty disks normalized to non-nil empty slice", func(t *testing.T) {
+ src := &HostUnraidStorage{ArrayStarted: true, ArrayState: "Started", Disks: nil}
+ got := cloneHostUnraidStorage(src)
+ if got == nil {
+ t.Fatal("non-nil input returned nil clone")
+ }
+ if !got.ArrayStarted || got.ArrayState != "Started" {
+ t.Fatalf("scalar fields not preserved: %#v", got)
+ }
+ // The len==0 branch skips the copy; NormalizeCollections must still
+ // materialise a non-nil empty slice so the clone never carries a nil.
+ if got.Disks == nil {
+ t.Fatal("Disks must normalize to a non-nil empty slice, got nil")
+ }
+ if len(got.Disks) != 0 {
+ t.Fatalf("len(Disks) = %d, want 0", len(got.Disks))
+ }
+ })
+
+ t.Run("populated disks are deep-copied and isolated", func(t *testing.T) {
+ src := &HostUnraidStorage{
+ ArrayStarted: true,
+ SyncProgress: 42.5,
+ Disks: []HostUnraidDisk{
+ {Name: "parity", Device: "/dev/sda", Status: "DISK_OK"},
+ {Name: "disk1", Device: "/dev/sdb", Status: "DISK_OK"},
+ },
+ }
+ clone := cloneHostUnraidStorage(src)
+ if clone == nil {
+ t.Fatal("non-nil input returned nil clone")
+ }
+ if len(clone.Disks) != 2 || clone.Disks[0].Name != "parity" || clone.Disks[1].Device != "/dev/sdb" {
+ t.Fatalf("disks not preserved: %#v", clone.Disks)
+ }
+ if clone.SyncProgress != 42.5 {
+ t.Fatalf("SyncProgress = %v, want 42.5", clone.SyncProgress)
+ }
+
+ // Mutate the clone's nested Disks slice; the original must be untouched.
+ clone.Disks[0].Name = "MUTATED"
+ clone.Disks[0].Status = "MUTATED"
+ if src.Disks[0].Name != "parity" || src.Disks[0].Status != "DISK_OK" {
+ t.Errorf("Disks slice aliases source backing array: src[0]=%#v", src.Disks[0])
+ }
+ })
+}
+
+// ---------------------------------------------------------------------------
+// deepcopy.go: cloneHostCephHealth (was 62.5%)
+// ---------------------------------------------------------------------------
+
+func TestBranchcov0724pmCloneHostCephHealth(t *testing.T) {
+ t.Run("empty checks collapses to nil then re-normalized", func(t *testing.T) {
+ src := HostCephHealth{Status: "HEALTH_OK"}
+ got := cloneHostCephHealth(src)
+ if got.Status != "HEALTH_OK" {
+ t.Fatalf("Status = %q, want HEALTH_OK", got.Status)
+ }
+ // The len==0 branch sets Checks=nil; NormalizeCollections must give back
+ // a non-nil empty map so downstream code never sees a nil map.
+ if got.Checks == nil {
+ t.Fatal("Checks must normalize to non-nil empty map, got nil")
+ }
+ if len(got.Checks) != 0 {
+ t.Fatalf("len(Checks) = %d, want 0", len(got.Checks))
+ }
+ if got.Summary == nil {
+ t.Fatal("Summary must normalize to non-nil empty slice, got nil")
+ }
+ })
+
+ t.Run("populated checks and summary are deep-copied and isolated", func(t *testing.T) {
+ src := HostCephHealth{
+ Status: "HEALTH_WARN",
+ Checks: map[string]HostCephCheck{
+ "OSD_DOWN": {Severity: "warning", Message: "1 osd down", Detail: []string{"osd.3 is down", "host node2"}},
+ },
+ Summary: []HostCephHealthSummary{
+ {Severity: "warning", Message: "1 osds down"},
+ },
+ }
+ clone := cloneHostCephHealth(src)
+ if clone.Status != "HEALTH_WARN" {
+ t.Fatalf("Status = %q, want HEALTH_WARN", clone.Status)
+ }
+ if len(clone.Checks) != 1 {
+ t.Fatalf("len(Checks) = %d, want 1", len(clone.Checks))
+ }
+ gotCheck := clone.Checks["OSD_DOWN"]
+ if gotCheck.Severity != "warning" || gotCheck.Message != "1 osd down" {
+ t.Fatalf("check scalar fields not preserved: %#v", gotCheck)
+ }
+ if len(gotCheck.Detail) != 2 || gotCheck.Detail[0] != "osd.3 is down" {
+ t.Fatalf("check Detail not deep-copied: %#v", gotCheck.Detail)
+ }
+
+ // Mutate the CLONE's nested check (Detail slice + scalar) and add a key;
+ // the source Checks map and its Detail slice must stay untouched.
+ mut := clone.Checks["OSD_DOWN"]
+ mut.Detail[0] = "MUTATED"
+ mut.Severity = "MUTATED"
+ clone.Checks["OSD_DOWN"] = mut
+ clone.Checks["leak"] = HostCephCheck{Severity: "x"}
+ if src.Checks["OSD_DOWN"].Detail[0] != "osd.3 is down" {
+ t.Errorf("Checks Detail slice aliases source: %q", src.Checks["OSD_DOWN"].Detail[0])
+ }
+ if src.Checks["OSD_DOWN"].Severity != "warning" {
+ t.Errorf("Checks severity not isolated: %q", src.Checks["OSD_DOWN"].Severity)
+ }
+ if _, leak := src.Checks["leak"]; leak {
+ t.Error("adding a key to clone Checks leaked into source map")
+ }
+
+ // Mutate the CLONE's Summary slice; the source Summary must stay untouched.
+ if len(clone.Summary) != 1 || clone.Summary[0].Message != "1 osds down" {
+ t.Fatalf("Summary not deep-copied: %#v", clone.Summary)
+ }
+ clone.Summary[0].Message = "MUTATED"
+ clone.Summary[0].Severity = "MUTATED"
+ if src.Summary[0].Message != "1 osds down" || src.Summary[0].Severity != "warning" {
+ t.Errorf("Summary slice aliases source: %#v", src.Summary[0])
+ }
+ })
+}
+
+// ---------------------------------------------------------------------------
+// deepcopy.go: cloneHostCephCluster (was 80.0%)
+// ---------------------------------------------------------------------------
+
+func TestBranchcov0724pmCloneHostCephCluster(t *testing.T) {
+ t.Run("nil returns nil", func(t *testing.T) {
+ if got := cloneHostCephCluster(nil); got != nil {
+ t.Fatalf("cloneHostCephCluster(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("empty services normalized to non-nil empty slice", func(t *testing.T) {
+ src := &HostCephCluster{FSID: "fsid-1", Services: nil}
+ got := cloneHostCephCluster(src)
+ if got == nil {
+ t.Fatal("non-nil input returned nil clone")
+ }
+ if got.FSID != "fsid-1" {
+ t.Fatalf("FSID = %q, want fsid-1", got.FSID)
+ }
+ // The len==0 branch sets Services=nil; NormalizeCollections re-materialises
+ // a non-nil empty slice.
+ if got.Services == nil {
+ t.Fatal("Services must normalize to non-nil empty slice, got nil")
+ }
+ if len(got.Services) != 0 {
+ t.Fatalf("len(Services) = %d, want 0", len(got.Services))
+ }
+ })
+
+ t.Run("populated monitors pools services health are deep-copied and isolated", func(t *testing.T) {
+ src := &HostCephCluster{
+ FSID: "fsid-1",
+ Health: HostCephHealth{
+ Status: "HEALTH_OK",
+ Checks: map[string]HostCephCheck{
+ "POOL_NEAR_FULL": {Severity: "warning", Detail: []string{"pool rbd near full"}},
+ },
+ },
+ MonMap: HostCephMonitorMap{
+ Epoch: 3,
+ NumMons: 1,
+ Monitors: []HostCephMonitor{
+ {Name: "mon-a", Rank: 0, Addr: "10.0.0.1:6789", Status: "ok"},
+ },
+ },
+ Pools: []HostCephPool{{ID: 1, Name: "rbd", PercentUsed: 85.0}},
+ Services: []HostCephService{
+ {Type: "mon", Running: 1, Total: 1, Daemons: []string{"mon.a", "mon.b"}},
+ },
+ }
+ clone := cloneHostCephCluster(src)
+ if clone == nil {
+ t.Fatal("non-nil input returned nil clone")
+ }
+ if clone.FSID != "fsid-1" || len(clone.Pools) != 1 || clone.Pools[0].Name != "rbd" {
+ t.Fatalf("scalar/pool fields not preserved: %#v", clone)
+ }
+ if len(clone.MonMap.Monitors) != 1 || clone.MonMap.Monitors[0].Name != "mon-a" {
+ t.Fatalf("monitors not preserved: %#v", clone.MonMap.Monitors)
+ }
+ if len(clone.Services) != 1 || len(clone.Services[0].Daemons) != 2 {
+ t.Fatalf("services not preserved: %#v", clone.Services)
+ }
+
+ // Mutate every nested collection of the CLONE; the source must be untouched.
+ clone.MonMap.Monitors[0].Name = "MUTATED"
+ clone.MonMap.Monitors[0].Status = "MUTATED"
+ clone.Pools[0].Name = "MUTATED"
+ clone.Services[0].Daemons[0] = "MUTATED"
+ mutCheck := clone.Health.Checks["POOL_NEAR_FULL"]
+ mutCheck.Detail[0] = "MUTATED"
+ clone.Health.Checks["POOL_NEAR_FULL"] = mutCheck
+ clone.Health.Checks["leak"] = HostCephCheck{Severity: "x"}
+
+ if src.MonMap.Monitors[0].Name != "mon-a" || src.MonMap.Monitors[0].Status != "ok" {
+ t.Errorf("MonMap.Monitors aliases source: %#v", src.MonMap.Monitors[0])
+ }
+ if src.Pools[0].Name != "rbd" {
+ t.Errorf("Pools slice aliases source: %q", src.Pools[0].Name)
+ }
+ if src.Services[0].Daemons[0] != "mon.a" {
+ t.Errorf("Services Daemons slice aliases source: %q", src.Services[0].Daemons[0])
+ }
+ if src.Health.Checks["POOL_NEAR_FULL"].Detail[0] != "pool rbd near full" {
+ t.Errorf("Health Checks Detail aliases source: %q", src.Health.Checks["POOL_NEAR_FULL"].Detail[0])
+ }
+ if _, leak := src.Health.Checks["leak"]; leak {
+ t.Error("adding a key to clone Health Checks leaked into source map")
+ }
+ })
+}
+
+// ---------------------------------------------------------------------------
+// deepcopy.go: cloneDockerPodmanContainer (was 50.0%)
+// ---------------------------------------------------------------------------
+
+func TestBranchcov0724pmCloneDockerPodmanContainer(t *testing.T) {
+ t.Run("nil returns nil", func(t *testing.T) {
+ if got := cloneDockerPodmanContainer(nil); got != nil {
+ t.Fatalf("cloneDockerPodmanContainer(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("populated returns distinct pointer with preserved values", func(t *testing.T) {
+ src := &DockerPodmanContainer{
+ PodName: "web-pod",
+ PodID: "pod-123",
+ Infra: true,
+ ComposeProject: "app",
+ }
+ clone := cloneDockerPodmanContainer(src)
+ if clone == nil {
+ t.Fatal("non-nil input returned nil clone")
+ }
+ if clone == src {
+ t.Fatal("clone aliases the source pointer instead of allocating a new struct")
+ }
+ if clone.PodName != "web-pod" || clone.PodID != "pod-123" || !clone.Infra || clone.ComposeProject != "app" {
+ t.Fatalf("fields not preserved: %#v", clone)
+ }
+ // Mutate clone scalar fields; a value copy must not propagate back to src.
+ clone.PodName = "MUTATED"
+ clone.Infra = false
+ if src.PodName != "web-pod" || !src.Infra {
+ t.Errorf("source struct mutated by clone write: %#v", src)
+ }
+ })
+}
+
+// ---------------------------------------------------------------------------
+// deepcopy.go: cloneDockerContainerUpdateStatus (was 50.0%)
+// ---------------------------------------------------------------------------
+
+func TestBranchcov0724pmCloneDockerContainerUpdateStatus(t *testing.T) {
+ t.Run("nil returns nil", func(t *testing.T) {
+ if got := cloneDockerContainerUpdateStatus(nil); got != nil {
+ t.Fatalf("cloneDockerContainerUpdateStatus(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("populated returns distinct pointer with preserved values", func(t *testing.T) {
+ src := &DockerContainerUpdateStatus{
+ UpdateAvailable: true,
+ CurrentDigest: "sha256:aaa",
+ LatestDigest: "sha256:bbb",
+ LastChecked: bc0724pmT,
+ Error: "rate limited",
+ }
+ clone := cloneDockerContainerUpdateStatus(src)
+ if clone == nil {
+ t.Fatal("non-nil input returned nil clone")
+ }
+ if clone == src {
+ t.Fatal("clone aliases the source pointer instead of allocating a new struct")
+ }
+ if !clone.UpdateAvailable || clone.CurrentDigest != "sha256:aaa" ||
+ clone.LatestDigest != "sha256:bbb" || clone.Error != "rate limited" ||
+ !clone.LastChecked.Equal(bc0724pmT) {
+ t.Fatalf("fields not preserved: %#v", clone)
+ }
+ // Mutate clone scalar fields; a value copy must not propagate back to src.
+ clone.UpdateAvailable = false
+ clone.Error = "MUTATED"
+ if !src.UpdateAvailable || src.Error != "rate limited" {
+ t.Errorf("source struct mutated by clone write: %#v", src)
+ }
+ })
+}
+
+// ---------------------------------------------------------------------------
+// deepcopy.go: cloneDockerStorageUsage (was 50.0%)
+// ---------------------------------------------------------------------------
+
+func TestBranchcov0724pmCloneDockerStorageUsage(t *testing.T) {
+ t.Run("nil returns nil", func(t *testing.T) {
+ if got := cloneDockerStorageUsage(nil); got != nil {
+ t.Fatalf("cloneDockerStorageUsage(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("populated returns distinct pointer with preserved values", func(t *testing.T) {
+ src := &DockerStorageUsage{
+ Images: DockerStorageUsageBucket{TotalCount: 5, TotalSizeBytes: 1024},
+ Containers: DockerStorageUsageBucket{TotalCount: 10, ReclaimableBytes: 512},
+ Volumes: DockerStorageUsageBucket{TotalCount: 3, ActiveCount: 2},
+ BuildCache: DockerStorageUsageBucket{TotalCount: 1, ReclaimableBytes: 256},
+ }
+ clone := cloneDockerStorageUsage(src)
+ if clone == nil {
+ t.Fatal("non-nil input returned nil clone")
+ }
+ if clone == src {
+ t.Fatal("clone aliases the source pointer instead of allocating a new struct")
+ }
+ if clone.Images.TotalCount != 5 || clone.Containers.ReclaimableBytes != 512 ||
+ clone.Volumes.ActiveCount != 2 || clone.BuildCache.TotalSizeBytes != 0 {
+ t.Fatalf("fields not preserved: %#v", clone)
+ }
+ // Mutate clone nested value fields; a value copy must not propagate to src.
+ clone.Images.TotalCount = 999
+ clone.Containers.ReclaimableBytes = 999
+ if src.Images.TotalCount != 5 || src.Containers.ReclaimableBytes != 512 {
+ t.Errorf("source struct mutated by clone write: %#v", src)
+ }
+ })
+}
+
+// ---------------------------------------------------------------------------
+// deepcopy.go: cloneDockerServiceUpdate (was 40.0%)
+// ---------------------------------------------------------------------------
+
+func TestBranchcov0724pmCloneDockerServiceUpdate(t *testing.T) {
+ t.Run("nil returns nil", func(t *testing.T) {
+ if got := cloneDockerServiceUpdate(nil); got != nil {
+ t.Fatalf("cloneDockerServiceUpdate(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("populated with nil CompletedAt preserved", func(t *testing.T) {
+ src := &DockerServiceUpdate{State: "completed", Message: "done"}
+ clone := cloneDockerServiceUpdate(src)
+ if clone == nil {
+ t.Fatal("non-nil input returned nil clone")
+ }
+ if clone.CompletedAt != nil {
+ t.Fatalf("CompletedAt = %#v, want nil when source has none", clone.CompletedAt)
+ }
+ if clone.State != "completed" || clone.Message != "done" {
+ t.Fatalf("scalar fields not preserved: %#v", clone)
+ }
+ })
+
+ t.Run("populated CompletedAt pointer deep-copied and isolated", func(t *testing.T) {
+ completed := bc0724pmT
+ src := &DockerServiceUpdate{State: "completed", CompletedAt: &completed}
+ clone := cloneDockerServiceUpdate(src)
+ if clone == nil {
+ t.Fatal("non-nil input returned nil clone")
+ }
+ if clone.CompletedAt == nil {
+ t.Fatal("CompletedAt dropped during clone")
+ }
+ if clone.CompletedAt == src.CompletedAt {
+ t.Fatal("CompletedAt aliases the source pointer instead of allocating a new *time.Time")
+ }
+ if !clone.CompletedAt.Equal(bc0724pmT) {
+ t.Fatalf("CompletedAt = %v, want %v", clone.CompletedAt, bc0724pmT)
+ }
+ // Mutate the pointed-to time through the CLONE; the source must be untouched.
+ *clone.CompletedAt = time.Date(1999, 1, 1, 0, 0, 0, 0, time.UTC)
+ if !src.CompletedAt.Equal(bc0724pmT) {
+ t.Errorf("CompletedAt pointer not isolated: src = %v", src.CompletedAt)
+ }
+ })
+}
+
+// ---------------------------------------------------------------------------
+// deepcopy.go: cloneDockerSwarmInfo (was 50.0%)
+// ---------------------------------------------------------------------------
+
+func TestBranchcov0724pmCloneDockerSwarmInfo(t *testing.T) {
+ t.Run("nil returns nil", func(t *testing.T) {
+ if got := cloneDockerSwarmInfo(nil); got != nil {
+ t.Fatalf("cloneDockerSwarmInfo(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("populated returns distinct pointer with preserved values", func(t *testing.T) {
+ src := &DockerSwarmInfo{
+ NodeID: "node-1",
+ NodeRole: "manager",
+ LocalState: "active",
+ ControlAvailable: true,
+ ClusterID: "cluster-1",
+ ClusterName: "prod",
+ Scope: "swarm",
+ Error: "",
+ }
+ clone := cloneDockerSwarmInfo(src)
+ if clone == nil {
+ t.Fatal("non-nil input returned nil clone")
+ }
+ if clone == src {
+ t.Fatal("clone aliases the source pointer instead of allocating a new struct")
+ }
+ if clone.NodeID != "node-1" || clone.NodeRole != "manager" || !clone.ControlAvailable ||
+ clone.ClusterName != "prod" {
+ t.Fatalf("fields not preserved: %#v", clone)
+ }
+ // Mutate clone scalar fields; a value copy must not propagate to src.
+ clone.NodeRole = "MUTATED"
+ clone.ControlAvailable = false
+ if src.NodeRole != "manager" || !src.ControlAvailable {
+ t.Errorf("source struct mutated by clone write: %#v", src)
+ }
+ })
+}
+
+// ---------------------------------------------------------------------------
+// deepcopy.go: cloneDockerHostSecurity (was 40.0%)
+// ---------------------------------------------------------------------------
+
+func TestBranchcov0724pmCloneDockerHostSecurity(t *testing.T) {
+ t.Run("nil returns nil", func(t *testing.T) {
+ if got := cloneDockerHostSecurity(nil); got != nil {
+ t.Fatalf("cloneDockerHostSecurity(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("populated with empty plugins preserved", func(t *testing.T) {
+ src := &DockerHostSecurity{MutatingCommandsBlocked: true, MutatingCommandsBlockedReason: "rootful"}
+ got := cloneDockerHostSecurity(src)
+ if got == nil {
+ t.Fatal("non-nil input returned nil clone")
+ }
+ if got.AuthorizationPlugins != nil {
+ t.Fatalf("AuthorizationPlugins = %#v, want nil for empty source", got.AuthorizationPlugins)
+ }
+ if !got.MutatingCommandsBlocked || got.MutatingCommandsBlockedReason != "rootful" {
+ t.Fatalf("scalar fields not preserved: %#v", got)
+ }
+ })
+
+ t.Run("populated plugins slice deep-copied and isolated", func(t *testing.T) {
+ src := &DockerHostSecurity{
+ AuthorizationPlugins: []string{"opa", "opa-authz"},
+ MutatingCommandsBlocked: true,
+ }
+ clone := cloneDockerHostSecurity(src)
+ if clone == nil {
+ t.Fatal("non-nil input returned nil clone")
+ }
+ if clone == src {
+ t.Fatal("clone aliases the source pointer instead of allocating a new struct")
+ }
+ if len(clone.AuthorizationPlugins) != 2 || clone.AuthorizationPlugins[0] != "opa" {
+ t.Fatalf("AuthorizationPlugins not preserved: %#v", clone.AuthorizationPlugins)
+ }
+ // Mutate the CLONE's plugins slice; the source slice must be untouched.
+ clone.AuthorizationPlugins[0] = "MUTATED"
+ if src.AuthorizationPlugins[0] != "opa" {
+ t.Errorf("AuthorizationPlugins slice aliases source: %q", src.AuthorizationPlugins[0])
+ }
+ })
+}
+
+// ---------------------------------------------------------------------------
+// deepcopy.go: cloneKubernetesNamespaces (was 25.0%)
+// ---------------------------------------------------------------------------
+
+func TestBranchcov0724pmCloneKubernetesNamespaces(t *testing.T) {
+ t.Run("nil returns nil", func(t *testing.T) {
+ if got := cloneKubernetesNamespaces(nil); got != nil {
+ t.Fatalf("cloneKubernetesNamespaces(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("empty returns nil", func(t *testing.T) {
+ if got := cloneKubernetesNamespaces([]KubernetesNamespace{}); got != nil {
+ t.Fatalf("cloneKubernetesNamespaces(empty) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("populated labels are deep-copied and isolated", func(t *testing.T) {
+ src := []KubernetesNamespace{
+ {
+ UID: "ns-1",
+ Name: "default",
+ Phase: "Active",
+ Labels: map[string]string{
+ "kubernetes.io/metadata.name": "default",
+ },
+ },
+ {
+ UID: "ns-2",
+ Name: "kube-system",
+ Phase: "Active",
+ Labels: map[string]string{"app": "coredns"},
+ },
+ }
+ clone := cloneKubernetesNamespaces(src)
+ if !reflect.DeepEqual(src, clone) {
+ t.Fatalf("value mismatch: src=%#v clone=%#v", src, clone)
+ }
+
+ // Mutate the CLONE's nested Labels maps; the source maps must be untouched.
+ clone[0].Labels["kubernetes.io/metadata.name"] = "MUTATED"
+ clone[0].Labels["leak"] = "x"
+ clone[1].Labels["app"] = "MUTATED"
+ if src[0].Labels["kubernetes.io/metadata.name"] != "default" {
+ t.Errorf("Labels map aliases source: %q", src[0].Labels["kubernetes.io/metadata.name"])
+ }
+ if _, leak := src[0].Labels["leak"]; leak {
+ t.Error("adding a key to clone Labels leaked into source map")
+ }
+ if src[1].Labels["app"] != "coredns" {
+ t.Errorf("Labels map aliases source: %q", src[1].Labels["app"])
+ }
+ })
+
+ t.Run("nil labels normalized to non-nil empty map", func(t *testing.T) {
+ src := []KubernetesNamespace{{UID: "ns-3", Name: "blank"}}
+ clone := cloneKubernetesNamespaces(src)
+ if clone == nil || len(clone) != 1 {
+ t.Fatalf("clone = %#v, want one element", clone)
+ }
+ // cloneStringMap(nil) returns nil; NormalizeCollections must materialise a
+ // non-nil empty map so consumers never observe a nil Labels.
+ if clone[0].Labels == nil {
+ t.Fatal("Labels must normalize to non-nil empty map, got nil")
+ }
+ if len(clone[0].Labels) != 0 {
+ t.Fatalf("len(Labels) = %d, want 0", len(clone[0].Labels))
+ }
+ })
+}
+
+// ---------------------------------------------------------------------------
+// converters.go: cloneDiskIOForFrontend (was 50.0%)
+// ---------------------------------------------------------------------------
+
+func TestBranchcov0724pmCloneDiskIOForFrontend(t *testing.T) {
+ t.Run("nil returns nil", func(t *testing.T) {
+ if got := cloneDiskIOForFrontend(nil); got != nil {
+ t.Fatalf("cloneDiskIOForFrontend(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("populated returns distinct pointer with preserved values", func(t *testing.T) {
+ src := &DiskIO{
+ Device: "/dev/sda",
+ ReadBytes: 1024,
+ WriteBytes: 2048,
+ ReadOps: 10,
+ WriteOps: 20,
+ ReadTime: 100,
+ WriteTime: 200,
+ IOTime: 500,
+ }
+ clone := cloneDiskIOForFrontend(src)
+ if clone == nil {
+ t.Fatal("non-nil input returned nil clone")
+ }
+ if clone == src {
+ t.Fatal("clone aliases the source pointer instead of allocating a new struct")
+ }
+ if clone.Device != "/dev/sda" || clone.ReadBytes != 1024 || clone.WriteOps != 20 ||
+ clone.ReadTime != 100 || clone.IOTime != 500 {
+ t.Fatalf("fields not preserved: %#v", clone)
+ }
+ // Mutate clone scalar fields; a value copy must not propagate to src.
+ clone.ReadBytes = 999999
+ clone.IOTime = 999999
+ if src.ReadBytes != 1024 || src.IOTime != 500 {
+ t.Errorf("source struct mutated by clone write: %#v", src)
+ }
+ })
+}
+
+// ---------------------------------------------------------------------------
+// ceph_cluster_identity.go: cephClusterSourceRank (was 75.0%)
+// ---------------------------------------------------------------------------
+
+func TestBranchcov0724pmCephClusterSourceRank(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ cluster CephCluster
+ wantRank int
+ }{
+ {"proxmox-api canonical source ranks 2", CephCluster{Source: CephClusterSourceProxmoxAPI}, 2},
+ {"proxmox alias source ranks 2", CephCluster{Source: "pve"}, 2},
+ {"api alias source ranks 2", CephCluster{Source: "api"}, 2},
+ {"host-agent canonical source ranks 1", CephCluster{Source: CephClusterSourceHostAgent}, 1},
+ {"agent alias source ranks 1", CephCluster{Source: "agent"}, 1},
+ {"host alias source ranks 1", CephCluster{Source: "host"}, 1},
+ {"agent: instance prefix ranks 1", CephCluster{Instance: "agent:node1"}, 1},
+ // An "unknown" source does NOT rank 0: normalizeCephClusterSource's final
+ // fallback coerces anything unrecognized to proxmox-api, so it ranks 2.
+ {"unknown source coerces to proxmox-api rank 2", CephCluster{Source: "who-knows"}, 2},
+ {"empty source and instance coerces to proxmox-api rank 2", CephCluster{}, 2},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := cephClusterSourceRank(tc.cluster); got != tc.wantRank {
+ t.Fatalf("cephClusterSourceRank(cluster{Source:%q,Instance:%q}) = %d, want %d",
+ tc.cluster.Source, tc.cluster.Instance, got, tc.wantRank)
+ }
+ })
+ }
+
+ // The `default: return 0` arm of cephClusterSourceRank is PROVABLY
+ // UNREACHABLE: it switches on normalizeCephClusterSource(...), which only
+ // ever returns CephClusterSourceProxmoxAPI or CephClusterSourceHostAgent
+ // (its only two return values). No input can produce any other value, so
+ // the default case is dead code and cannot be covered without faking it.
+ // See the report for details.
+}
diff --git a/internal/servicediscovery/commands_branchcov0724pm_test.go b/internal/servicediscovery/commands_branchcov0724pm_test.go
new file mode 100644
index 0000000000..7d501d9ac4
--- /dev/null
+++ b/internal/servicediscovery/commands_branchcov0724pm_test.go
@@ -0,0 +1,207 @@
+package servicediscovery
+
+import (
+ "strings"
+ "testing"
+)
+
+// TestBranchcov0724pmValidateResourceID covers the empty-ID arm (commands.go:16-18)
+// and the too-long arm (commands.go:19-21) that the existing suite never reaches,
+// plus boundary and rejection-reason assertions.
+func TestBranchcov0724pmValidateResourceID(t *testing.T) {
+ cases := []struct {
+ name string
+ id string
+ wantErr string // substring expected in the error message; "" means no error
+ }{
+ {name: "empty-rejected", id: "", wantErr: "cannot be empty"},
+ {name: "too-long-257-rejected", id: strings.Repeat("a", 257), wantErr: "too long"},
+ {name: "max-length-256-accepted", id: strings.Repeat("a", 256), wantErr: ""},
+ {name: "simple-alphanumeric", id: "abc123", wantErr: ""},
+ {name: "all-allowed-chars", id: "a-b_c.d:e", wantErr: ""},
+ {name: "single-char", id: "1", wantErr: ""},
+ {name: "starts-with-period", id: ".bad", wantErr: "invalid characters"},
+ {name: "starts-with-colon", id: ":bad", wantErr: "invalid characters"},
+ {name: "starts-with-underscore", id: "_bad", wantErr: "invalid characters"},
+ {name: "contains-space", id: "a b", wantErr: "invalid characters"},
+ {name: "contains-dollar", id: "a$b", wantErr: "invalid characters"},
+ {name: "contains-semicolon", id: "a;b", wantErr: "invalid characters"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ err := ValidateResourceID(tc.id)
+ if tc.wantErr == "" {
+ if err != nil {
+ t.Fatalf("ValidateResourceID(%q) returned unexpected error: %v", tc.id, err)
+ }
+ } else {
+ if err == nil {
+ t.Fatalf("ValidateResourceID(%q) returned nil, want error containing %q", tc.id, tc.wantErr)
+ }
+ if !strings.Contains(err.Error(), tc.wantErr) {
+ t.Fatalf("ValidateResourceID(%q) error = %q, want substring %q", tc.id, err.Error(), tc.wantErr)
+ }
+ }
+ })
+ }
+}
+
+// TestBranchcov0724pmBuildLXCCommand covers the error arm (commands.go:344-347)
+// that the existing suite never reaches, and asserts the exact happy-path string.
+func TestBranchcov0724pmBuildLXCCommand(t *testing.T) {
+ t.Run("valid-exact-string", func(t *testing.T) {
+ got := BuildLXCCommand("101", "echo hi")
+ want := "pct exec 101 -- sh -c 'echo hi'"
+ if got != want {
+ t.Fatalf("BuildLXCCommand =\n got: %q\nwant: %q", got, want)
+ }
+ })
+
+ t.Run("invalid-vmid-returns-error-command", func(t *testing.T) {
+ got := BuildLXCCommand("", "echo hi")
+ want := "sh -c 'echo \"Discovery error: invalid container ID\" >&2; exit 1'"
+ if got != want {
+ t.Fatalf("BuildLXCCommand(invalid) =\n got: %q\nwant: %q", got, want)
+ }
+ })
+
+ t.Run("option-like-vmid-returns-error-command", func(t *testing.T) {
+ got := BuildLXCCommand("--malicious", "echo hi")
+ want := "sh -c 'echo \"Discovery error: invalid container ID\" >&2; exit 1'"
+ if got != want {
+ t.Fatalf("BuildLXCCommand(option-like) =\n got: %q\nwant: %q", got, want)
+ }
+ })
+}
+
+// TestBranchcov0724pmBuildNestedDockerCommand covers the invalid-vmid arm
+// (commands.go:377-379) and the invalid-container-name arm (commands.go:382-384)
+// that the existing suite never reaches, plus the leading-slash trim.
+func TestBranchcov0724pmBuildNestedDockerCommand(t *testing.T) {
+ t.Run("lxc-nested-exact", func(t *testing.T) {
+ got := BuildNestedDockerCommand("201", true, "web", "echo hi")
+ // dockerCmd = docker exec 'web' sh -c 'echo hi'
+ // That string is shell-quoted inside the pct exec wrapper.
+ want := "pct exec 201 -- sh -c 'docker exec '\"'\"'web'\"'\"' sh -c '\"'\"'echo hi'\"'\"''"
+ if got != want {
+ t.Fatalf("BuildNestedDockerCommand(lxc) =\n got: %s\nwant: %s", got, want)
+ }
+ })
+
+ t.Run("vm-nested-exact", func(t *testing.T) {
+ got := BuildNestedDockerCommand("301", false, "web", "echo hi")
+ want := "qm guest exec 301 -- sh -c 'docker exec '\"'\"'web'\"'\"' sh -c '\"'\"'echo hi'\"'\"''"
+ if got != want {
+ t.Fatalf("BuildNestedDockerCommand(vm) =\n got: %s\nwant: %s", got, want)
+ }
+ })
+
+ t.Run("leading-slash-trimmed-from-container-name", func(t *testing.T) {
+ // Docker API returns names with leading slash; it must be trimmed
+ // before validation so "/web" and "web" produce the same command.
+ withSlash := BuildNestedDockerCommand("201", true, "/web", "echo hi")
+ noSlash := BuildNestedDockerCommand("201", true, "web", "echo hi")
+ if withSlash != noSlash {
+ t.Fatalf("leading slash not trimmed:\n withSlash: %s\n noSlash: %s", withSlash, noSlash)
+ }
+ })
+
+ t.Run("invalid-vmid-error", func(t *testing.T) {
+ got := BuildNestedDockerCommand("", true, "web", "echo hi")
+ want := "sh -c 'echo \"Discovery error: invalid VM/LXC ID\" >&2; exit 1'"
+ if got != want {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+ })
+
+ t.Run("invalid-container-name-error", func(t *testing.T) {
+ got := BuildNestedDockerCommand("201", true, "-bad", "echo hi")
+ want := "sh -c 'echo \"Discovery error: invalid container name\" >&2; exit 1'"
+ if got != want {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+ })
+}
+
+// TestBranchcov0724pmBuildK8sCommand covers the invalid-pod-name arm
+// (commands.go:398-400) and the invalid-container-name arm (commands.go:402-404)
+// that the existing suite never reaches, and asserts exact command strings.
+func TestBranchcov0724pmBuildK8sCommand(t *testing.T) {
+ t.Run("with-container-exact", func(t *testing.T) {
+ got := BuildK8sCommand("default", "pod1", "app", "echo hi")
+ want := "kubectl exec -n 'default' 'pod1' -c 'app' -- sh -c 'echo hi'"
+ if got != want {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+ })
+
+ t.Run("without-container-exact", func(t *testing.T) {
+ got := BuildK8sCommand("default", "pod1", "", "echo hi")
+ want := "kubectl exec -n 'default' 'pod1' -- sh -c 'echo hi'"
+ if got != want {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+ })
+
+ t.Run("invalid-pod-name-error", func(t *testing.T) {
+ got := BuildK8sCommand("default", "", "app", "echo hi")
+ want := "sh -c 'echo \"Discovery error: invalid pod name\" >&2; exit 1'"
+ if got != want {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+ })
+
+ t.Run("invalid-container-name-error", func(t *testing.T) {
+ got := BuildK8sCommand("default", "pod1", "-bad", "echo hi")
+ want := "sh -c 'echo \"Discovery error: invalid container name\" >&2; exit 1'"
+ if got != want {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+ })
+}
+
+// TestBranchcov0724pmFormatScopeHint covers the empty-summary arm
+// (formatters.go:275-277) and the multi-discovery "+N more" arm
+// (formatters.go:278-280) that the existing suite never reaches.
+func TestBranchcov0724pmFormatScopeHint(t *testing.T) {
+ t.Run("multiple-discoveries-adds-more-count", func(t *testing.T) {
+ d1 := &ResourceDiscovery{ServiceName: "App1", ServiceType: "app"}
+ d2 := &ResourceDiscovery{ServiceName: "App2", ServiceType: "app"}
+ hint := FormatScopeHint([]*ResourceDiscovery{d1, d2})
+ if !strings.Contains(hint, "Discovery:") {
+ t.Fatalf("expected 'Discovery:' prefix, got %q", hint)
+ }
+ if !strings.Contains(hint, "(+1 more)") {
+ t.Fatalf("expected '(+1 more)' for 2 discoveries, got %q", hint)
+ }
+ })
+
+ t.Run("three-discoveries-shows-2-more", func(t *testing.T) {
+ d1 := &ResourceDiscovery{ServiceName: "A"}
+ d2 := &ResourceDiscovery{ServiceName: "B"}
+ d3 := &ResourceDiscovery{ServiceName: "C"}
+ hint := FormatScopeHint([]*ResourceDiscovery{d1, d2, d3})
+ if !strings.Contains(hint, "(+2 more)") {
+ t.Fatalf("expected '(+2 more)' for 3 discoveries, got %q", hint)
+ }
+ })
+
+ t.Run("empty-identity-returns-empty", func(t *testing.T) {
+ // A discovery with no identity fields produces an empty summary,
+ // which FormatScopeHint must propagate as "".
+ hint := FormatScopeHint([]*ResourceDiscovery{{}})
+ if hint != "" {
+ t.Fatalf("expected empty hint for identity-less discovery, got %q", hint)
+ }
+ })
+
+ t.Run("nil-primary-in-slice-returns-empty", func(t *testing.T) {
+ // A nil primary entry also yields an empty summary from
+ // formatScopeDiscoverySummary.
+ hint := FormatScopeHint([]*ResourceDiscovery{nil})
+ if hint != "" {
+ t.Fatalf("expected empty hint for nil primary discovery, got %q", hint)
+ }
+ })
+}
diff --git a/internal/servicediscovery/fingerprint_branchcov0724pm_test.go b/internal/servicediscovery/fingerprint_branchcov0724pm_test.go
new file mode 100644
index 0000000000..0d21983799
--- /dev/null
+++ b/internal/servicediscovery/fingerprint_branchcov0724pm_test.go
@@ -0,0 +1,431 @@
+package servicediscovery
+
+import (
+ "testing"
+)
+
+// TestBranchcov0724pmGenerateDockerFingerprint covers the loop bodies for
+// Ports, Mounts, and Labels (fingerprint.go:26-42) that the existing suite
+// never reaches, plus stability and sensitivity assertions.
+func TestBranchcov0724pmGenerateDockerFingerprint(t *testing.T) {
+ // Fully-populated container — exercises the Ports, Mounts, and Labels
+ // range bodies (the uncovered arms at 75.0%).
+ full := &DockerContainer{
+ Name: "web",
+ Image: "nginx:1.25",
+ Ports: []DockerPort{{PrivatePort: 8080, Protocol: "tcp"}, {PrivatePort: 443, Protocol: "tcp"}},
+ Mounts: []DockerMount{{Source: "/host/z", Destination: "/z"}, {Source: "/host/a", Destination: "/a"}},
+ Labels: map[string]string{"zoo": "1", "alpha": "2"},
+ }
+
+ t.Run("populated-extracts-and-sorts", func(t *testing.T) {
+ fp := GenerateDockerFingerprint("host1", full)
+ if fp.ResourceID != "web" {
+ t.Fatalf("ResourceID = %q, want %q", fp.ResourceID, "web")
+ }
+ if fp.TargetID != "host1" {
+ t.Fatalf("TargetID = %q, want %q", fp.TargetID, "host1")
+ }
+ if fp.ImageName != "nginx:1.25" {
+ t.Fatalf("ImageName = %q, want %q", fp.ImageName, "nginx:1.25")
+ }
+ if fp.SchemaVersion != FingerprintSchemaVersion {
+ t.Fatalf("SchemaVersion = %d, want %d", fp.SchemaVersion, FingerprintSchemaVersion)
+ }
+ // Ports formatted then sorted: input [8080, 443] -> ["8080/tcp","443/tcp"] -> sorted ["443/tcp","8080/tcp"]
+ wantPorts := []string{"443/tcp", "8080/tcp"}
+ if len(fp.Ports) != len(wantPorts) {
+ t.Fatalf("Ports = %v, want %v", fp.Ports, wantPorts)
+ }
+ for i, w := range wantPorts {
+ if fp.Ports[i] != w {
+ t.Fatalf("Ports[%d] = %q, want %q (full: %v)", i, fp.Ports[i], w, fp.Ports)
+ }
+ }
+ // Mount destinations sorted: input ["/z","/a"] -> sorted ["/a","/z"]
+ wantMounts := []string{"/a", "/z"}
+ if len(fp.MountPaths) != len(wantMounts) {
+ t.Fatalf("MountPaths = %v, want %v", fp.MountPaths, wantMounts)
+ }
+ for i, w := range wantMounts {
+ if fp.MountPaths[i] != w {
+ t.Fatalf("MountPaths[%d] = %q, want %q", i, fp.MountPaths[i], w)
+ }
+ }
+ // Label keys sorted: map keys ["zoo","alpha"] -> sorted ["alpha","zoo"]
+ wantEnvKeys := []string{"alpha", "zoo"}
+ if len(fp.EnvKeys) != len(wantEnvKeys) {
+ t.Fatalf("EnvKeys = %v, want %v", fp.EnvKeys, wantEnvKeys)
+ }
+ for i, w := range wantEnvKeys {
+ if fp.EnvKeys[i] != w {
+ t.Fatalf("EnvKeys[%d] = %q, want %q (full: %v)", i, fp.EnvKeys[i], w, fp.EnvKeys)
+ }
+ }
+ if len(fp.Hash) != 16 {
+ t.Fatalf("Hash length = %d, want 16 (truncated SHA256)", len(fp.Hash))
+ }
+ })
+
+ t.Run("empty-optional-fields", func(t *testing.T) {
+ bare := &DockerContainer{Name: "bare", Image: "alpine:latest"}
+ fp := GenerateDockerFingerprint("node", bare)
+ if len(fp.Ports) != 0 {
+ t.Fatalf("Ports = %v, want empty", fp.Ports)
+ }
+ if len(fp.MountPaths) != 0 {
+ t.Fatalf("MountPaths = %v, want empty", fp.MountPaths)
+ }
+ if len(fp.EnvKeys) != 0 {
+ t.Fatalf("EnvKeys = %v, want empty", fp.EnvKeys)
+ }
+ if fp.Hash == "" {
+ t.Fatalf("Hash must be non-empty even with no optional fields")
+ }
+ })
+
+ t.Run("stability-same-input-same-hash", func(t *testing.T) {
+ fp1 := GenerateDockerFingerprint("h", full)
+ fp2 := GenerateDockerFingerprint("h", full)
+ if fp1.Hash != fp2.Hash {
+ t.Fatalf("same input must produce same hash: %q vs %q", fp1.Hash, fp2.Hash)
+ }
+ })
+
+ t.Run("sensitivity-image-change", func(t *testing.T) {
+ base := GenerateDockerFingerprint("host1", full)
+ modified := *full
+ modified.Image = "nginx:1.26"
+ changed := GenerateDockerFingerprint("host1", &modified)
+ if base.Hash == changed.Hash {
+ t.Fatalf("changing Image must change hash (both = %q)", base.Hash)
+ }
+ })
+
+ t.Run("sensitivity-port-change", func(t *testing.T) {
+ base := GenerateDockerFingerprint("host1", full)
+ modified := *full
+ modified.Ports = []DockerPort{{PrivatePort: 9090, Protocol: "tcp"}, {PrivatePort: 443, Protocol: "tcp"}}
+ changed := GenerateDockerFingerprint("host1", &modified)
+ if base.Hash == changed.Hash {
+ t.Fatalf("changing Ports must change hash (both = %q)", base.Hash)
+ }
+ })
+}
+
+// TestBranchcov0724pmHasSchemaChanged covers the nil-other arm
+// (fingerprint.go:76-78) that the existing suite never reaches, plus both
+// verdicts.
+func TestBranchcov0724pmHasSchemaChanged(t *testing.T) {
+ fp := &ContainerFingerprint{SchemaVersion: FingerprintSchemaVersion}
+
+ t.Run("nil-other-returns-false", func(t *testing.T) {
+ if fp.HasSchemaChanged(nil) {
+ t.Fatalf("HasSchemaChanged(nil) must return false")
+ }
+ })
+
+ t.Run("same-schema-returns-false", func(t *testing.T) {
+ other := &ContainerFingerprint{SchemaVersion: FingerprintSchemaVersion}
+ if fp.HasSchemaChanged(other) {
+ t.Fatalf("HasSchemaChanged with same schema must return false")
+ }
+ })
+
+ t.Run("different-schema-returns-true", func(t *testing.T) {
+ other := &ContainerFingerprint{SchemaVersion: FingerprintSchemaVersion + 1}
+ if !fp.HasSchemaChanged(other) {
+ t.Fatalf("HasSchemaChanged with different schema must return true")
+ }
+ })
+}
+
+// TestBranchcov0724pmGenerateLXCFingerprint covers the IsOCI, Template, and
+// Tags arms (fingerprint.go:114-131) that the existing suite never reaches,
+// plus stability, sensitivity, and the intentional IP-address exclusion.
+func TestBranchcov0724pmGenerateLXCFingerprint(t *testing.T) {
+ base := &Container{
+ VMID: 101,
+ Name: "lxc1",
+ OSTemplate: "debian-12-standard",
+ OSName: "debian",
+ CPUs: 2,
+ MaxMemory: 4096,
+ MaxDisk: 8,
+ }
+
+ t.Run("identity-fields-populated", func(t *testing.T) {
+ fp := GenerateLXCFingerprint("node1", base)
+ if fp.ResourceID != "101" {
+ t.Fatalf("ResourceID = %q, want %q", fp.ResourceID, "101")
+ }
+ if fp.TargetID != "node1" {
+ t.Fatalf("TargetID = %q, want %q", fp.TargetID, "node1")
+ }
+ if fp.ImageName != "debian-12-standard" {
+ t.Fatalf("ImageName = %q, want %q", fp.ImageName, "debian-12-standard")
+ }
+ if fp.SchemaVersion != FingerprintSchemaVersion {
+ t.Fatalf("SchemaVersion = %d, want %d", fp.SchemaVersion, FingerprintSchemaVersion)
+ }
+ })
+
+ t.Run("stability-same-input-same-hash", func(t *testing.T) {
+ fp1 := GenerateLXCFingerprint("node1", base)
+ fp2 := GenerateLXCFingerprint("node1", base)
+ if fp1.Hash != fp2.Hash {
+ t.Fatalf("same input must produce same hash: %q vs %q", fp1.Hash, fp2.Hash)
+ }
+ })
+
+ t.Run("oci-flag-changes-hash", func(t *testing.T) {
+ baseFP := GenerateLXCFingerprint("node1", base)
+ oci := *base
+ oci.IsOCI = true
+ ociFP := GenerateLXCFingerprint("node1", &oci)
+ if baseFP.Hash == ociFP.Hash {
+ t.Fatalf("setting IsOCI must change hash (both = %q)", baseFP.Hash)
+ }
+ })
+
+ t.Run("template-flag-changes-hash", func(t *testing.T) {
+ baseFP := GenerateLXCFingerprint("node1", base)
+ tmpl := *base
+ tmpl.Template = true
+ tmplFP := GenerateLXCFingerprint("node1", &tmpl)
+ if baseFP.Hash == tmplFP.Hash {
+ t.Fatalf("setting Template must change hash (both = %q)", baseFP.Hash)
+ }
+ })
+
+ t.Run("tags-change-hash-and-order-independent", func(t *testing.T) {
+ baseFP := GenerateLXCFingerprint("node1", base)
+ tagged := *base
+ tagged.Tags = []string{"web", "api"}
+ taggedFP := GenerateLXCFingerprint("node1", &tagged)
+ if baseFP.Hash == taggedFP.Hash {
+ t.Fatalf("adding Tags must change hash (both = %q)", baseFP.Hash)
+ }
+ reordered := *base
+ reordered.Tags = []string{"api", "web"}
+ reorderedFP := GenerateLXCFingerprint("node1", &reordered)
+ if taggedFP.Hash != reorderedFP.Hash {
+ t.Fatalf("different tag order must produce same hash: %q vs %q", taggedFP.Hash, reorderedFP.Hash)
+ }
+ })
+
+ t.Run("ip-addresses-excluded-from-hash", func(t *testing.T) {
+ baseFP := GenerateLXCFingerprint("node1", base)
+ withIPs := *base
+ withIPs.IPAddresses = []string{"10.0.0.5", "192.168.1.10"}
+ ipFP := GenerateLXCFingerprint("node1", &withIPs)
+ if baseFP.Hash != ipFP.Hash {
+ t.Fatalf("IP addresses must be excluded from hash: base=%q withIPs=%q", baseFP.Hash, ipFP.Hash)
+ }
+ })
+
+ t.Run("empty-input-does-not-panic", func(t *testing.T) {
+ fp := GenerateLXCFingerprint("node", &Container{})
+ if fp.Hash == "" {
+ t.Fatalf("Hash must be non-empty for zero-value Container")
+ }
+ if fp.ResourceID != "0" {
+ t.Fatalf("ResourceID = %q, want %q for VMID=0", fp.ResourceID, "0")
+ }
+ })
+
+ t.Run("vmid-change-changes-hash", func(t *testing.T) {
+ baseFP := GenerateLXCFingerprint("node1", base)
+ modified := *base
+ modified.VMID = 102
+ modifiedFP := GenerateLXCFingerprint("node1", &modified)
+ if baseFP.Hash == modifiedFP.Hash {
+ t.Fatalf("changing VMID must change hash (both = %q)", baseFP.Hash)
+ }
+ })
+}
+
+// TestBranchcov0724pmGenerateVMFingerprint covers the Template and Tags arms
+// (fingerprint.go:167-179) that the existing suite never reaches, plus
+// stability, sensitivity, and the intentional IP-address exclusion.
+func TestBranchcov0724pmGenerateVMFingerprint(t *testing.T) {
+ base := &VM{
+ VMID: 201,
+ Name: "vm1",
+ OSName: "ubuntu",
+ OSVersion: "22.04",
+ CPUs: 4,
+ MaxMemory: 8192,
+ MaxDisk: 32,
+ }
+
+ t.Run("identity-fields-populated", func(t *testing.T) {
+ fp := GenerateVMFingerprint("node1", base)
+ if fp.ResourceID != "201" {
+ t.Fatalf("ResourceID = %q, want %q", fp.ResourceID, "201")
+ }
+ if fp.TargetID != "node1" {
+ t.Fatalf("TargetID = %q, want %q", fp.TargetID, "node1")
+ }
+ if fp.ImageName != "ubuntu" {
+ t.Fatalf("ImageName = %q, want %q (OSName)", fp.ImageName, "ubuntu")
+ }
+ })
+
+ t.Run("stability-same-input-same-hash", func(t *testing.T) {
+ fp1 := GenerateVMFingerprint("node1", base)
+ fp2 := GenerateVMFingerprint("node1", base)
+ if fp1.Hash != fp2.Hash {
+ t.Fatalf("same input must produce same hash: %q vs %q", fp1.Hash, fp2.Hash)
+ }
+ })
+
+ t.Run("template-flag-changes-hash", func(t *testing.T) {
+ baseFP := GenerateVMFingerprint("node1", base)
+ tmpl := *base
+ tmpl.Template = true
+ tmplFP := GenerateVMFingerprint("node1", &tmpl)
+ if baseFP.Hash == tmplFP.Hash {
+ t.Fatalf("setting Template must change hash (both = %q)", baseFP.Hash)
+ }
+ })
+
+ t.Run("tags-change-hash-and-order-independent", func(t *testing.T) {
+ baseFP := GenerateVMFingerprint("node1", base)
+ tagged := *base
+ tagged.Tags = []string{"prod", "db"}
+ taggedFP := GenerateVMFingerprint("node1", &tagged)
+ if baseFP.Hash == taggedFP.Hash {
+ t.Fatalf("adding Tags must change hash (both = %q)", baseFP.Hash)
+ }
+ reordered := *base
+ reordered.Tags = []string{"db", "prod"}
+ reorderedFP := GenerateVMFingerprint("node1", &reordered)
+ if taggedFP.Hash != reorderedFP.Hash {
+ t.Fatalf("different tag order must produce same hash: %q vs %q", taggedFP.Hash, reorderedFP.Hash)
+ }
+ })
+
+ t.Run("ip-addresses-excluded-from-hash", func(t *testing.T) {
+ baseFP := GenerateVMFingerprint("node1", base)
+ withIPs := *base
+ withIPs.IPAddresses = []string{"10.0.0.5"}
+ ipFP := GenerateVMFingerprint("node1", &withIPs)
+ if baseFP.Hash != ipFP.Hash {
+ t.Fatalf("IP addresses must be excluded from hash: base=%q withIPs=%q", baseFP.Hash, ipFP.Hash)
+ }
+ })
+
+ t.Run("empty-input-does-not-panic", func(t *testing.T) {
+ fp := GenerateVMFingerprint("node", &VM{})
+ if fp.Hash == "" {
+ t.Fatalf("Hash must be non-empty for zero-value VM")
+ }
+ if fp.ResourceID != "0" {
+ t.Fatalf("ResourceID = %q, want %q for VMID=0", fp.ResourceID, "0")
+ }
+ })
+
+ t.Run("osversion-change-changes-hash", func(t *testing.T) {
+ baseFP := GenerateVMFingerprint("node1", base)
+ modified := *base
+ modified.OSVersion = "24.04"
+ modifiedFP := GenerateVMFingerprint("node1", &modified)
+ if baseFP.Hash == modifiedFP.Hash {
+ t.Fatalf("changing OSVersion must change hash (both = %q)", baseFP.Hash)
+ }
+ })
+}
+
+// TestBranchcov0724pmGenerateHostFingerprint covers the Tags arm
+// (fingerprint.go:217-222) that the existing suite never reaches, plus
+// stability, sensitivity, and the intentional Status exclusion.
+func TestBranchcov0724pmGenerateHostFingerprint(t *testing.T) {
+ base := &Host{
+ ID: "agent-1",
+ Hostname: "server1",
+ Platform: "linux",
+ OSName: "Ubuntu",
+ OSVersion: "22.04",
+ KernelVersion: "6.1.0",
+ Architecture: "amd64",
+ CPUCount: 8,
+ }
+
+ t.Run("identity-fields-populated", func(t *testing.T) {
+ fp := GenerateHostFingerprint(base)
+ if fp.ResourceID != "agent-1" {
+ t.Fatalf("ResourceID = %q, want %q", fp.ResourceID, "agent-1")
+ }
+ if fp.TargetID != "agent-1" {
+ t.Fatalf("TargetID = %q, want %q (same as ID for hosts)", fp.TargetID, "agent-1")
+ }
+ if fp.ImageName != "Ubuntu" {
+ t.Fatalf("ImageName = %q, want %q (OSName)", fp.ImageName, "Ubuntu")
+ }
+ })
+
+ t.Run("stability-same-input-same-hash", func(t *testing.T) {
+ fp1 := GenerateHostFingerprint(base)
+ fp2 := GenerateHostFingerprint(base)
+ if fp1.Hash != fp2.Hash {
+ t.Fatalf("same input must produce same hash: %q vs %q", fp1.Hash, fp2.Hash)
+ }
+ })
+
+ t.Run("tags-change-hash-and-order-independent", func(t *testing.T) {
+ baseFP := GenerateHostFingerprint(base)
+ tagged := *base
+ tagged.Tags = []string{"rack-a", "prod"}
+ taggedFP := GenerateHostFingerprint(&tagged)
+ if baseFP.Hash == taggedFP.Hash {
+ t.Fatalf("adding Tags must change hash (both = %q)", baseFP.Hash)
+ }
+ reordered := *base
+ reordered.Tags = []string{"prod", "rack-a"}
+ reorderedFP := GenerateHostFingerprint(&reordered)
+ if taggedFP.Hash != reorderedFP.Hash {
+ t.Fatalf("different tag order must produce same hash: %q vs %q", taggedFP.Hash, reorderedFP.Hash)
+ }
+ })
+
+ t.Run("status-excluded-from-hash", func(t *testing.T) {
+ baseFP := GenerateHostFingerprint(base)
+ modified := *base
+ modified.Status = "offline"
+ modifiedFP := GenerateHostFingerprint(&modified)
+ if baseFP.Hash != modifiedFP.Hash {
+ t.Fatalf("Status must be excluded from hash: base=%q modified=%q", baseFP.Hash, modifiedFP.Hash)
+ }
+ })
+
+ t.Run("empty-input-does-not-panic", func(t *testing.T) {
+ fp := GenerateHostFingerprint(&Host{})
+ if fp.Hash == "" {
+ t.Fatalf("Hash must be non-empty for zero-value Host")
+ }
+ if fp.ResourceID != "" {
+ t.Fatalf("ResourceID = %q, want empty for zero-value Host", fp.ResourceID)
+ }
+ })
+
+ t.Run("hostname-change-changes-hash", func(t *testing.T) {
+ baseFP := GenerateHostFingerprint(base)
+ modified := *base
+ modified.Hostname = "server2"
+ modifiedFP := GenerateHostFingerprint(&modified)
+ if baseFP.Hash == modifiedFP.Hash {
+ t.Fatalf("changing Hostname must change hash (both = %q)", baseFP.Hash)
+ }
+ })
+
+ t.Run("cpucount-change-changes-hash", func(t *testing.T) {
+ baseFP := GenerateHostFingerprint(base)
+ modified := *base
+ modified.CPUCount = 16
+ modifiedFP := GenerateHostFingerprint(&modified)
+ if baseFP.Hash == modifiedFP.Hash {
+ t.Fatalf("changing CPUCount must change hash (both = %q)", baseFP.Hash)
+ }
+ })
+}
diff --git a/internal/storagehealth/topology_branchcov0724pm_test.go b/internal/storagehealth/topology_branchcov0724pm_test.go
new file mode 100644
index 0000000000..d2f293af76
--- /dev/null
+++ b/internal/storagehealth/topology_branchcov0724pm_test.go
@@ -0,0 +1,93 @@
+package storagehealth
+
+import (
+ "testing"
+)
+
+// TestBranchcov0724pmZfsScanActive covers the default return-false arm
+// (topology.go:241-242) that the existing suite never reaches — all current
+// indirect callers pass "SCANNING", hitting only the return-true arm.
+// Also verifies case- and whitespace-insensitivity for every canonical
+// active state.
+func TestBranchcov0724pmZfsScanActive(t *testing.T) {
+ activeCases := []struct {
+ name string
+ state string
+ }{
+ {name: "scanning", state: "SCANNING"},
+ {name: "running", state: "RUNNING"},
+ {name: "in-progress", state: "IN_PROGRESS"},
+ {name: "inprogress-no-underscore", state: "INPROGRESS"},
+ {name: "lowercase-scanning", state: "scanning"},
+ {name: "mixedcase-Running", state: "Running"},
+ {name: "whitespace-padded", state: " SCANNING "},
+ }
+ for _, tc := range activeCases {
+ t.Run("active-"+tc.name, func(t *testing.T) {
+ if !zfsScanActive(tc.state) {
+ t.Fatalf("zfsScanActive(%q) = false, want true", tc.state)
+ }
+ })
+ }
+
+ inactiveCases := []struct {
+ name string
+ state string
+ }{
+ {name: "finished", state: "FINISHED"},
+ {name: "done", state: "DONE"},
+ {name: "empty", state: ""},
+ {name: "canceled", state: "CANCELED"},
+ {name: "paused", state: "PAUSED"},
+ {name: "whitespace-only", state: " "},
+ {name: "lowercase-finished", state: "finished"},
+ }
+ for _, tc := range inactiveCases {
+ t.Run("inactive-"+tc.name, func(t *testing.T) {
+ if zfsScanActive(tc.state) {
+ t.Fatalf("zfsScanActive(%q) = true, want false", tc.state)
+ }
+ })
+ }
+}
+
+// TestBranchcov0724pmFirstNonEmpty covers the all-empty return arm
+// (topology.go:252) that the existing suite never reaches, plus the
+// trim-and-skip behaviour and the no-argument edge case.
+func TestBranchcov0724pmFirstNonEmpty(t *testing.T) {
+ t.Run("returns-first-non-empty", func(t *testing.T) {
+ if got := firstNonEmpty("", "hello", "world"); got != "hello" {
+ t.Fatalf("firstNonEmpty = %q, want %q", got, "hello")
+ }
+ })
+
+ t.Run("returns-trimmed-value", func(t *testing.T) {
+ if got := firstNonEmpty(" padded "); got != "padded" {
+ t.Fatalf("firstNonEmpty = %q, want %q", got, "padded")
+ }
+ })
+
+ t.Run("skips-whitespace-only-values", func(t *testing.T) {
+ if got := firstNonEmpty(" ", "\t", "\n", "found"); got != "found" {
+ t.Fatalf("firstNonEmpty = %q, want %q", got, "found")
+ }
+ })
+
+ t.Run("all-empty-returns-empty-string", func(t *testing.T) {
+ if got := firstNonEmpty("", " ", "\t"); got != "" {
+ t.Fatalf("firstNonEmpty = %q, want empty string", got)
+ }
+ })
+
+ t.Run("no-args-returns-empty-string", func(t *testing.T) {
+ if got := firstNonEmpty(); got != "" {
+ t.Fatalf("firstNonEmpty() = %q, want empty string", got)
+ }
+ })
+
+ t.Run("single-empty-arg-returns-empty-string", func(t *testing.T) {
+ if got := firstNonEmpty(""); got != "" {
+ t.Fatalf("firstNonEmpty(\"\") = %q, want empty string", got)
+ }
+ })
+}
diff --git a/pkg/securityutil/httpurl_branchcov0724pm_test.go b/pkg/securityutil/httpurl_branchcov0724pm_test.go
new file mode 100644
index 0000000000..e6ffc25744
--- /dev/null
+++ b/pkg/securityutil/httpurl_branchcov0724pm_test.go
@@ -0,0 +1,198 @@
+package securityutil
+
+import (
+ "net"
+ "testing"
+)
+
+// This file raises branch coverage for the SSRF guard helpers in httpurl.go:
+// joinURLPath, IsLocalNetworkHost, isLocalNetworkIP, and
+// isCarrierGradeNATIPv4. Every case targets an arm the existing suite reaches
+// only indirectly (or not at all): empty inputs, every network class the
+// classifier must recognise, and the CGNAT range boundaries. No DNS, daemon,
+// or network is exercised.
+
+func TestBranchcov0724pmJoinURLPath(t *testing.T) {
+ tests := []struct {
+ name string
+ basePath string
+ relPath string
+ want string
+ }{
+ // Branch: relative trims to empty (no append) AND joined is empty
+ // (path.Join("") == "") -> default arm, no leading slash -> "/" prepended.
+ {name: "empty base empty path", basePath: "", relPath: "", want: "/"},
+ {name: "empty base slash only path", basePath: "", relPath: "/", want: "/"},
+
+ // Branch: switch case "/" -> return "".
+ {name: "root base slash only path", basePath: "/", relPath: "/", want: ""},
+ {name: "root base empty path", basePath: "/", relPath: "", want: ""},
+ // Parent references collapse the join to "/".
+ {name: "parent ref collapse to root", basePath: "/api", relPath: "/..", want: ""},
+
+ // Branch: switch case "." -> return "" (basePath that Clean()s to ".").
+ {name: "dot base empty path", basePath: ".", relPath: "", want: ""},
+ {name: "dot base slash only path", basePath: ".", relPath: "/", want: ""},
+
+ // Branch: default arm, joined already has leading slash (HasPrefix true).
+ {name: "base keeps nonempty path", basePath: "/api", relPath: "/users", want: "/api/users"},
+ {name: "trailing slash base normalised", basePath: "/api/", relPath: "/v1", want: "/api/v1"},
+ // relative trims to empty so the existing base path is returned verbatim.
+ {name: "nonempty base slash only path", basePath: "/api", relPath: "/", want: "/api"},
+
+ // Branch: default arm, joined has NO leading slash (HasPrefix false).
+ {name: "empty base with content path", basePath: "", relPath: "/users", want: "/users"},
+ {name: "relative base no slash", basePath: "api", relPath: "/users", want: "/api/users"},
+
+ // Branch: an encoded segment is joined verbatim (no decoding here).
+ {name: "encoded segment preserved", basePath: "/api", relPath: "/us%20ers", want: "/api/us%20ers"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := joinURLPath(tt.basePath, tt.relPath)
+ if got != tt.want {
+ t.Fatalf("joinURLPath(%q, %q) = %q, want %q", tt.basePath, tt.relPath, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0724pmIsLocalNetworkHost(t *testing.T) {
+ tests := []struct {
+ name string
+ host string
+ want bool
+ }{
+ // Branch: normalised to empty -> return false.
+ {name: "empty string", host: "", want: false},
+ {name: "whitespace only", host: " ", want: false},
+ {name: "brackets only", host: "[]", want: false},
+
+ // Branch: IsLoopbackHost true -> return true.
+ {name: "localhost", host: "localhost", want: true},
+ {name: "localhost upper", host: "LOCALHOST", want: true},
+ {name: "localhost subdomain", host: "foo.localhost", want: true},
+ {name: "ipv4 loopback literal", host: "127.0.0.1", want: true},
+ {name: "ipv6 loopback literal", host: "::1", want: true},
+ {name: "ipv6 loopback bracketed", host: "[::1]", want: true},
+ // Trailing dot is stripped before classification.
+ {name: "localhost trailing dot", host: "localhost.", want: true},
+
+ // Branch: IP literal -> isLocalNetworkIP true (private / link-local).
+ {name: "ipv4 private 10/8", host: "10.0.0.1", want: true},
+ {name: "ipv4 private 172.16/12", host: "172.16.5.4", want: true},
+ {name: "ipv4 private 192.168/16", host: "192.168.1.1", want: true},
+ {name: "ipv4 link local", host: "169.254.1.1", want: true},
+ {name: "ipv6 link local", host: "fe80::1", want: true},
+ {name: "ipv6 unique local", host: "fc00::1", want: true},
+ {name: "ipv4 cgnat first address", host: "100.64.0.0", want: true},
+ {name: "ipv4 cgnat last address", host: "100.127.255.255", want: true},
+
+ // Branch: single-label name (no dot) -> return true.
+ {name: "single label name", host: "myhost", want: true},
+ {name: "single label upper", host: "MYHOST", want: true},
+
+ // Branch: operator-local suffix match -> return true.
+ {name: "dot-local suffix", host: "nas.local", want: true},
+ {name: "dot-lan suffix", host: "router.lan", want: true},
+ {name: "dot-home suffix", host: "server.home", want: true},
+ {name: "dot-home-arpa suffix", host: "server.home.arpa", want: true},
+ {name: "dot-internal suffix", host: "host.internal", want: true},
+
+ // Branch: fall-through public hostname -> return false.
+ {name: "public hostname", host: "example.com", want: false},
+ {name: "multi-label public hostname", host: "api.example.com", want: false},
+ {name: "public ipv4 literal", host: "203.0.113.1", want: false},
+ {name: "public ipv6 literal", host: "2001:db8::1", want: false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := IsLocalNetworkHost(tt.host)
+ if got != tt.want {
+ t.Fatalf("IsLocalNetworkHost(%q) = %v, want %v", tt.host, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0724pmIsLocalNetworkIP(t *testing.T) {
+ tests := []struct {
+ name string
+ ip net.IP
+ want bool
+ }{
+ // Branch: nil guard -> false.
+ {name: "nil ip", ip: nil, want: false},
+
+ // Branch: loopback.
+ {name: "ipv4 loopback", ip: net.ParseIP("127.0.0.1"), want: true},
+ {name: "ipv6 loopback", ip: net.ParseIP("::1"), want: true},
+
+ // Branch: private (RFC1918 + ULA).
+ {name: "ipv4 private 10", ip: net.ParseIP("10.1.2.3"), want: true},
+ {name: "ipv4 private 172.16", ip: net.ParseIP("172.16.0.1"), want: true},
+ {name: "ipv4 private 192.168", ip: net.ParseIP("192.168.50.50"), want: true},
+ {name: "ipv6 unique local", ip: net.ParseIP("fd00::1"), want: true},
+
+ // Branch: link-local unicast.
+ {name: "ipv4 link local", ip: net.ParseIP("169.254.3.4"), want: true},
+ {name: "ipv6 link local", ip: net.ParseIP("fe80::abcd"), want: true},
+
+ // Branch: CGNAT 100.64.0.0/10.
+ {name: "cgnat first octet boundary", ip: net.ParseIP("100.64.0.1"), want: true},
+ {name: "cgnat last octet boundary", ip: net.ParseIP("100.127.255.255"), want: true},
+
+ // Branch: all classifiers false (public).
+ {name: "public ipv4", ip: net.ParseIP("203.0.113.10"), want: false},
+ {name: "public ipv6", ip: net.ParseIP("2001:db8::1"), want: false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := isLocalNetworkIP(tt.ip)
+ if got != tt.want {
+ t.Fatalf("isLocalNetworkIP(%v) = %v, want %v", tt.ip, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0724pmIsCarrierGradeNATIPv4(t *testing.T) {
+ tests := []struct {
+ name string
+ ip net.IP
+ want bool
+ }{
+ // Branch: To4() == nil (IPv6 or nil) -> false.
+ {name: "nil ip", ip: nil, want: false},
+ {name: "ipv6 loopback not v4", ip: net.ParseIP("::1"), want: false},
+ {name: "ipv6 public not v4", ip: net.ParseIP("2001:db8::1"), want: false},
+
+ // Branch: inside 100.64.0.0/10 -> true, both boundaries.
+ {name: "first address of range", ip: net.ParseIP("100.64.0.0"), want: true},
+ {name: "first host of range", ip: net.ParseIP("100.64.0.1"), want: true},
+ {name: "last address of range", ip: net.ParseIP("100.127.255.255"), want: true},
+
+ // Branch: just outside the range -> false.
+ {name: "just below range second octet", ip: net.ParseIP("100.63.255.255"), want: false},
+ {name: "just above range second octet", ip: net.ParseIP("100.128.0.0"), want: false},
+
+ // Branch: wrong first octet -> false.
+ {name: "first octet 99", ip: net.ParseIP("99.64.0.1"), want: false},
+ {name: "first octet 101", ip: net.ParseIP("101.64.0.1"), want: false},
+
+ // Branch: ordinary public address -> false.
+ {name: "public ipv4", ip: net.ParseIP("203.0.113.1"), want: false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := isCarrierGradeNATIPv4(tt.ip)
+ if got != tt.want {
+ t.Fatalf("isCarrierGradeNATIPv4(%v) = %v, want %v", tt.ip, got, tt.want)
+ }
+ })
+ }
+}
diff --git a/pkg/securityutil/outbound_branchcov0724pm_test.go b/pkg/securityutil/outbound_branchcov0724pm_test.go
new file mode 100644
index 0000000000..deb732553a
--- /dev/null
+++ b/pkg/securityutil/outbound_branchcov0724pm_test.go
@@ -0,0 +1,354 @@
+package securityutil
+
+import (
+ "context"
+ "crypto/tls"
+ "errors"
+ "net"
+ "net/http"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+)
+
+// This file raises branch coverage for the outbound SSRF helpers in
+// outbound_http.go: resolveOutboundIPAddrs, resolvePermittedOutboundIPs, and
+// cloneRestrictedTransport. No real DNS, daemon, or network is used: every
+// hostname target is an IP literal (short-circuited before resolution) or is
+// routed through an injected ResolveIPAddrs stub / the swapped
+// resolveOutboundFetchIPs package variable. The package's tests do not use
+// t.Parallel(), so temporarily swapping package-level variables and restoring
+// them via t.Cleanup is safe.
+
+func TestBranchcov0724pmResolveOutboundIPAddrs(t *testing.T) {
+ t.Run("custom resolver invoked and args forwarded", func(t *testing.T) {
+ ctx := context.Background()
+ want := []net.IPAddr{{IP: net.ParseIP("203.0.113.9")}}
+ var gotCtx context.Context
+ var gotHost string
+ got, err := resolveOutboundIPAddrs(ctx, "anything.test", RestrictedOutboundHTTPOptions{
+ ResolveIPAddrs: func(c context.Context, h string) ([]net.IPAddr, error) {
+ gotCtx, gotHost = c, h
+ return want, nil
+ },
+ })
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if gotCtx != ctx {
+ t.Fatalf("ctx not forwarded, got %v want %v", gotCtx, ctx)
+ }
+ if gotHost != "anything.test" {
+ t.Fatalf("host = %q, want anything.test", gotHost)
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+ })
+
+ t.Run("default resolver used when nil and args forwarded", func(t *testing.T) {
+ orig := resolveOutboundFetchIPs
+ var gotCtx context.Context
+ var gotHost string
+ resolveOutboundFetchIPs = func(c context.Context, h string) ([]net.IPAddr, error) {
+ gotCtx, gotHost = c, h
+ return []net.IPAddr{{IP: net.ParseIP("198.51.100.7")}}, nil
+ }
+ t.Cleanup(func() { resolveOutboundFetchIPs = orig })
+
+ ctx := context.Background()
+ got, err := resolveOutboundIPAddrs(ctx, "swap.example", RestrictedOutboundHTTPOptions{})
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if gotCtx != ctx {
+ t.Fatalf("ctx not forwarded to swapped default resolver, got %v want %v", gotCtx, ctx)
+ }
+ if gotHost != "swap.example" {
+ t.Fatalf("host = %q, want swap.example", gotHost)
+ }
+ if len(got) != 1 || !got[0].IP.Equal(net.ParseIP("198.51.100.7")) {
+ t.Fatalf("got %v, want [198.51.100.7]", got)
+ }
+ })
+
+ t.Run("default resolver error propagated", func(t *testing.T) {
+ orig := resolveOutboundFetchIPs
+ resolveOutboundFetchIPs = func(context.Context, string) ([]net.IPAddr, error) {
+ return nil, errors.New("no such host")
+ }
+ t.Cleanup(func() { resolveOutboundFetchIPs = orig })
+
+ _, err := resolveOutboundIPAddrs(context.Background(), "missing.example", RestrictedOutboundHTTPOptions{})
+ if err == nil || !strings.Contains(err.Error(), "no such host") {
+ t.Fatalf("err = %v, want error containing no such host", err)
+ }
+ })
+}
+
+func TestBranchcov0724pmResolvePermittedOutboundIPs(t *testing.T) {
+ strict := RestrictedOutboundHTTPOptions{} // no loopback/private
+ permit := RestrictedOutboundHTTPOptions{AllowPrivateIPs: true, AllowLoopback: true}
+
+ // Arms reached without any DNS: empty host, metadata hosts, and IP literals.
+ tests := []struct {
+ name string
+ host string
+ opts RestrictedOutboundHTTPOptions
+ wantErr string
+ wantIPs []string
+ }{
+ {name: "empty host rejected", host: " ", opts: permit, wantErr: "URL hostname is required"},
+ {name: "metadata google internal rejected", host: "metadata.google.internal", opts: permit, wantErr: "metadata service host is not allowed"},
+ {name: "metadata goog rejected", host: "metadata.goog", opts: permit, wantErr: "metadata service host is not allowed"},
+ {name: "metadata host case insensitive", host: "Metadata.Goog", opts: permit, wantErr: "metadata service host is not allowed"},
+ {name: "ip literal public permitted", host: "203.0.113.5", opts: strict, wantIPs: []string{"203.0.113.5"}},
+ {name: "ip literal loopback blocked when disallowed", host: "127.0.0.1", opts: strict, wantErr: "loopback addresses are not allowed"},
+ {name: "ip literal private blocked when disallowed", host: "10.0.0.1", opts: strict, wantErr: "private addresses are not allowed"},
+ {name: "ip literal private permitted", host: "10.0.0.1", opts: permit, wantIPs: []string{"10.0.0.1"}},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := resolvePermittedOutboundIPs(context.Background(), tt.host, tt.opts)
+ if tt.wantErr != "" {
+ if err == nil {
+ t.Fatalf("resolvePermittedOutboundIPs(%q) = %v, want error containing %q", tt.host, got, tt.wantErr)
+ }
+ if !strings.Contains(err.Error(), tt.wantErr) {
+ t.Fatalf("resolvePermittedOutboundIPs(%q) err = %q, want substring %q", tt.host, err.Error(), tt.wantErr)
+ }
+ if got != nil {
+ t.Fatalf("resolvePermittedOutboundIPs(%q) returned non-nil %v with error", tt.host, got)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("resolvePermittedOutboundIPs(%q) unexpected error: %v", tt.host, err)
+ }
+ if len(got) != len(tt.wantIPs) {
+ t.Fatalf("got %d IPs %v, want %d %v", len(got), got, len(tt.wantIPs), tt.wantIPs)
+ }
+ for i, want := range tt.wantIPs {
+ if !got[i].Equal(net.ParseIP(want)) {
+ t.Fatalf("got[%d] = %v, want %s", i, got[i], want)
+ }
+ }
+ })
+ }
+
+ // DNS-dependent arms, driven entirely through an injected resolver so no
+ // real network resolution is required.
+ t.Run("resolve error wrapped", func(t *testing.T) {
+ opts := permit
+ opts.ResolveIPAddrs = func(context.Context, string) ([]net.IPAddr, error) {
+ return nil, errors.New("lookup timeout")
+ }
+ _, err := resolvePermittedOutboundIPs(context.Background(), "host.example", opts)
+ if err == nil || !strings.Contains(err.Error(), "failed to resolve hostname host.example") {
+ t.Fatalf("err = %v, want failed to resolve hostname", err)
+ }
+ if !strings.Contains(err.Error(), "lookup timeout") {
+ t.Fatalf("err = %v, want wrapped lookup timeout", err)
+ }
+ })
+
+ t.Run("empty resolution rejected", func(t *testing.T) {
+ opts := permit
+ opts.ResolveIPAddrs = func(context.Context, string) ([]net.IPAddr, error) {
+ return nil, nil
+ }
+ _, err := resolvePermittedOutboundIPs(context.Background(), "host.example", opts)
+ if err == nil || !strings.Contains(err.Error(), "host.example did not resolve") {
+ t.Fatalf("err = %v, want did not resolve", err)
+ }
+ })
+
+ t.Run("mixed blocked and permitted returns permitted only", func(t *testing.T) {
+ opts := strict // loopback blocked, public allowed
+ opts.ResolveIPAddrs = func(context.Context, string) ([]net.IPAddr, error) {
+ return []net.IPAddr{
+ {IP: net.ParseIP("127.0.0.1")}, // blocked (loopback)
+ {IP: net.ParseIP("203.0.113.5")}, // permitted (public)
+ {IP: net.ParseIP("192.168.1.1")}, // blocked (private)
+ }, nil
+ }
+ got, err := resolvePermittedOutboundIPs(context.Background(), "host.example", opts)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if len(got) != 1 || !got[0].Equal(net.ParseIP("203.0.113.5")) {
+ t.Fatalf("got %v, want only [203.0.113.5] (blocked ones filtered)", got)
+ }
+ })
+
+ t.Run("only blocked addresses rejected", func(t *testing.T) {
+ opts := strict
+ opts.ResolveIPAddrs = func(context.Context, string) ([]net.IPAddr, error) {
+ return []net.IPAddr{
+ {IP: net.ParseIP("127.0.0.1")}, // blocked
+ {IP: net.ParseIP("192.168.1.1")}, // blocked
+ }, nil
+ }
+ _, err := resolvePermittedOutboundIPs(context.Background(), "host.example", opts)
+ if err == nil || !strings.Contains(err.Error(), "resolves only to blocked addresses") {
+ t.Fatalf("err = %v, want resolves only to blocked addresses", err)
+ }
+ })
+
+ t.Run("all permitted returned in order", func(t *testing.T) {
+ opts := strict
+ opts.ResolveIPAddrs = func(context.Context, string) ([]net.IPAddr, error) {
+ return []net.IPAddr{
+ {IP: net.ParseIP("203.0.113.5")},
+ {IP: net.ParseIP("198.51.100.7")},
+ }, nil
+ }
+ got, err := resolvePermittedOutboundIPs(context.Background(), "host.example", opts)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if len(got) != 2 || !got[0].Equal(net.ParseIP("203.0.113.5")) || !got[1].Equal(net.ParseIP("198.51.100.7")) {
+ t.Fatalf("got %v, want both public addresses in order", got)
+ }
+ })
+
+ t.Run("nil ctx falls back to background without panic", func(t *testing.T) {
+ var seenCtx context.Context
+ opts := permit
+ opts.ResolveIPAddrs = func(c context.Context, _ string) ([]net.IPAddr, error) {
+ seenCtx = c
+ return []net.IPAddr{{IP: net.ParseIP("10.0.0.5")}}, nil
+ }
+ got, err := resolvePermittedOutboundIPs(nil, "host.example", opts)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ // context.WithTimeout panics on a nil parent, so the fact that the
+ // resolver was invoked at all proves the nil-ctx -> Background fallback
+ // arm ran.
+ if seenCtx == nil {
+ t.Fatal("resolver never invoked; nil ctx fallback arm did not run")
+ }
+ if len(got) != 1 || !got[0].Equal(net.ParseIP("10.0.0.5")) {
+ t.Fatalf("got %v, want [10.0.0.5]", got)
+ }
+ })
+}
+
+func TestBranchcov0724pmCloneRestrictedTransport(t *testing.T) {
+ t.Run("default transport cloned with tls12 floor and existing config re-cloned", func(t *testing.T) {
+ opts := RestrictedOutboundHTTPOptions{}
+ clone := cloneRestrictedTransport(opts)
+ if clone == nil {
+ t.Fatal("clone is nil")
+ }
+ if clone.TLSClientConfig == nil {
+ t.Fatal("TLSClientConfig nil, want cloned config from DefaultTransport")
+ }
+ // Default transport clone already sets a non-nil TLSClientConfig, so the
+ // "clone existing" arm should have run and MinVersion floored to TLS 1.2.
+ if clone.TLSClientConfig.MinVersion != tls.VersionTLS12 {
+ t.Fatalf("MinVersion = %d, want %d", clone.TLSClientConfig.MinVersion, tls.VersionTLS12)
+ }
+ })
+
+ t.Run("opts tls config cloned onto clone", func(t *testing.T) {
+ provided := &tls.Config{MinVersion: tls.VersionTLS12, ServerName: "provided.test"}
+ clone := cloneRestrictedTransport(RestrictedOutboundHTTPOptions{TLSConfig: provided})
+ if clone.TLSClientConfig == provided {
+ t.Fatal("clone uses the same *tls.Config pointer as opts; expected a clone")
+ }
+ if clone.TLSClientConfig.ServerName != "provided.test" {
+ t.Fatalf("ServerName = %q, want provided.test", clone.TLSClientConfig.ServerName)
+ }
+ if clone.TLSClientConfig.MinVersion != tls.VersionTLS12 {
+ t.Fatalf("MinVersion = %d, want %d", clone.TLSClientConfig.MinVersion, tls.VersionTLS12)
+ }
+ })
+
+ t.Run("response header timeout applied when positive", func(t *testing.T) {
+ clone := cloneRestrictedTransport(RestrictedOutboundHTTPOptions{ResponseHeaderTimeout: 7 * time.Second})
+ if clone.ResponseHeaderTimeout != 7*time.Second {
+ t.Fatalf("ResponseHeaderTimeout = %v, want 7s", clone.ResponseHeaderTimeout)
+ }
+ })
+
+ t.Run("response header timeout left untouched when zero", func(t *testing.T) {
+ clone := cloneRestrictedTransport(RestrictedOutboundHTTPOptions{})
+ if clone.ResponseHeaderTimeout != 0 {
+ t.Fatalf("ResponseHeaderTimeout = %v, want 0 (not overridden)", clone.ResponseHeaderTimeout)
+ }
+ })
+
+ t.Run("fallback transport and fresh tls config when default not http transport", func(t *testing.T) {
+ // Swapping http.DefaultTransport lets the "else" arm run, which creates a
+ // bare *http.Transport with a nil TLSClientConfig, in turn hitting the
+ // switch default arm that allocates a fresh &tls.Config{}.
+ orig := http.DefaultTransport
+ http.DefaultTransport = roundTripperStub{}
+ t.Cleanup(func() { http.DefaultTransport = orig })
+
+ clone := cloneRestrictedTransport(RestrictedOutboundHTTPOptions{})
+ if clone == nil {
+ t.Fatal("clone is nil")
+ }
+ // The fallback transport is constructed with Proxy: http.ProxyFromEnvironment.
+ if clone.Proxy == nil {
+ t.Fatal("fallback transport Proxy nil, want ProxyFromEnvironment")
+ }
+ if clone.TLSClientConfig == nil {
+ t.Fatal("TLSClientConfig nil, want freshly allocated config")
+ }
+ if clone.TLSClientConfig.MinVersion != tls.VersionTLS12 {
+ t.Fatalf("MinVersion = %d, want %d", clone.TLSClientConfig.MinVersion, tls.VersionTLS12)
+ }
+ })
+
+ t.Run("clone tls config is independent from opts source", func(t *testing.T) {
+ provided := &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: false}
+ clone := cloneRestrictedTransport(RestrictedOutboundHTTPOptions{TLSConfig: provided})
+
+ // Mutate the clone's nested config and assert the source is unchanged.
+ clone.TLSClientConfig.InsecureSkipVerify = true
+ clone.TLSClientConfig.MinVersion = tls.VersionTLS10
+ if provided.InsecureSkipVerify {
+ t.Fatal("mutating clone leaked into opts.TLSConfig (InsecureSkipVerify)")
+ }
+ if provided.MinVersion != tls.VersionTLS12 {
+ t.Fatalf("opts.TLSConfig.MinVersion mutated to %d, want %d", provided.MinVersion, tls.VersionTLS12)
+ }
+ })
+
+ t.Run("clone is independent from default transport", func(t *testing.T) {
+ defaultBefore := http.DefaultTransport.(*http.Transport).Clone()
+ clone := cloneRestrictedTransport(RestrictedOutboundHTTPOptions{ResponseHeaderTimeout: 9 * time.Second})
+
+ // Mutate the clone's independent fields/config and assert the shared
+ // default transport is untouched.
+ clone.ResponseHeaderTimeout = 0
+ clone.MaxIdleConns = 9999
+ if clone.TLSClientConfig != nil {
+ clone.TLSClientConfig.InsecureSkipVerify = true
+ }
+ defaultAfter := http.DefaultTransport.(*http.Transport).Clone()
+ if defaultAfter.ResponseHeaderTimeout != defaultBefore.ResponseHeaderTimeout {
+ t.Fatalf("DefaultTransport.ResponseHeaderTimeout changed: before %v after %v", defaultBefore.ResponseHeaderTimeout, defaultAfter.ResponseHeaderTimeout)
+ }
+ if defaultAfter.MaxIdleConns != defaultBefore.MaxIdleConns {
+ t.Fatalf("DefaultTransport.MaxIdleConns changed: before %v after %v", defaultBefore.MaxIdleConns, defaultAfter.MaxIdleConns)
+ }
+ if defaultAfter.TLSClientConfig != nil && defaultAfter.TLSClientConfig.InsecureSkipVerify {
+ t.Fatal("DefaultTransport TLSClientConfig.InsecureSkipVerify leaked to true")
+ }
+ })
+}
+
+// roundTripperStub is a non-*http.Transport used to drive the fallback arm of
+// cloneRestrictedTransport when swapped in as http.DefaultTransport.
+type roundTripperStub struct{}
+
+func (roundTripperStub) RoundTrip(*http.Request) (*http.Response, error) {
+ return nil, errors.New("roundTripperStub: not implemented")
+}