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.

Add Go branch-coverage tests for models config securityutil and aicontracts helpers

rcourtmandf4e02ef8971
diff --git a/internal/config/config_ai_effective_branchcov0716_test.go b/internal/config/config_ai_effective_branchcov0716_test.go
new file mode 100644
index 0000000000..cbcceb06fd
--- /dev/null
+++ b/internal/config/config_ai_effective_branchcov0716_test.go
@@ -0,0 +1,386 @@
+package config
+
+import (
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/stretchr/testify/assert"
+)
+
+// These branch-coverage tests target the effective-evaluation accessors on
+// AIConfig: GetEffectiveControlLevel, GetEffectivePatrolAutonomy(WithPolicy),
+// IsPatrolFullModeActive, and SetPatrolEventTriggersEnabled. They exercise the
+// nil-receiver guards, the entitlement downgrade, every EvaluatePatrolAutopilot
+// outcome reachable through the config wrapper, and the nil-receiver no-op of
+// the setter. They reuse the same in-package evidence helpers as the sibling
+// patrol-autopilot persistence tests.
+
+// TestBranchCovGetEffectiveControlLevel covers both the nil-receiver guard of
+// GetEffectiveControlLevel and every branch of the entitlement evaluation it
+// delegates to: the read_only default (empty, unknown, and legacy levels), the
+// untouched controlled/read_only levels, and the autonomous downgrade that
+// fires only when the autonomous entitlement is missing.
+func TestBranchCovGetEffectiveControlLevel(t *testing.T) {
+ tests := []struct {
+ name string
+ config *AIConfig
+ autonomousAllowed bool
+ want string
+ }{
+ {
+ name: "nil receiver fails closed to read_only",
+ config: nil,
+ autonomousAllowed: true,
+ want: ControlLevelReadOnly,
+ },
+ {
+ name: "nil receiver fails closed regardless of entitlement",
+ config: nil,
+ autonomousAllowed: false,
+ want: ControlLevelReadOnly,
+ },
+ {
+ name: "empty control level normalizes to read_only",
+ config: &AIConfig{ControlLevel: ""},
+ autonomousAllowed: true,
+ want: ControlLevelReadOnly,
+ },
+ {
+ name: "explicit read_only is preserved with entitlement",
+ config: &AIConfig{ControlLevel: ControlLevelReadOnly},
+ autonomousAllowed: true,
+ want: ControlLevelReadOnly,
+ },
+ {
+ name: "explicit read_only preserved without entitlement",
+ config: &AIConfig{ControlLevel: ControlLevelReadOnly},
+ autonomousAllowed: false,
+ want: ControlLevelReadOnly,
+ },
+ {
+ name: "controlled is preserved with entitlement",
+ config: &AIConfig{ControlLevel: ControlLevelControlled},
+ autonomousAllowed: true,
+ want: ControlLevelControlled,
+ },
+ {
+ name: "controlled is preserved even without autonomous entitlement",
+ config: &AIConfig{ControlLevel: ControlLevelControlled},
+ autonomousAllowed: false,
+ want: ControlLevelControlled,
+ },
+ {
+ name: "autonomous preserved when entitlement allows it",
+ config: &AIConfig{ControlLevel: ControlLevelAutonomous},
+ autonomousAllowed: true,
+ want: ControlLevelAutonomous,
+ },
+ {
+ name: "autonomous downgraded to controlled when entitlement missing",
+ config: &AIConfig{ControlLevel: ControlLevelAutonomous},
+ autonomousAllowed: false,
+ want: ControlLevelControlled,
+ },
+ {
+ name: "unknown level fails closed to read_only with entitlement",
+ config: &AIConfig{ControlLevel: "nonsense"},
+ autonomousAllowed: true,
+ want: ControlLevelReadOnly,
+ },
+ {
+ name: "unknown level fails closed to read_only without entitlement",
+ config: &AIConfig{ControlLevel: "nonsense"},
+ autonomousAllowed: false,
+ want: ControlLevelReadOnly,
+ },
+ {
+ name: "legacy suggest level fails closed to read_only",
+ config: &AIConfig{ControlLevel: "suggest"},
+ autonomousAllowed: true,
+ want: ControlLevelReadOnly,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := tt.config.GetEffectiveControlLevel(tt.autonomousAllowed)
+ assert.Equal(t, tt.want, got)
+ })
+ }
+}
+
+// TestBranchCovGetEffectivePatrolAutonomy covers every reachable branch of
+// GetEffectivePatrolAutonomyWithPolicy (which GetEffectivePatrolAutonomy
+// delegates to): the nil-receiver contract fallback, the not-requested arm for
+// each non-full requested mode, and the full-mode evaluation paths
+// (acknowledgement required, legacy boolean ignored, invalid activation digest,
+// wrong-org activation, and a genuinely active full-mode activation). It also
+// confirms the time-based GetEffectivePatrolAutonomy wrapper agrees with the
+// explicit-policy variant.
+func TestBranchCovGetEffectivePatrolAutonomy(t *testing.T) {
+ now := time.Date(2026, 7, 16, 12, 0, 0, 0, time.UTC)
+ policy := unifiedresources.CurrentPatrolAutopilotServerPolicy(now)
+ actor := configPatrolAutopilotActor("admin", "session:org-a", "org-a")
+ acknowledgement, activation := configPatrolAutopilotEvidence(t, "ack-effective-branchcov", actor, policy)
+
+ // An activation with a blank digest trips the activation-digest-invalid
+ // arm before any acknowledgement lookup occurs.
+ invalidDigestActivation := activation
+ invalidDigestActivation.Digest = ""
+
+ tests := []struct {
+ name string
+ config *AIConfig
+ orgID string
+ wantLevel string
+ wantCode string
+ wantActive bool
+ }{
+ {
+ name: "nil receiver returns monitor with acknowledgement-required status",
+ config: nil,
+ orgID: "org-a",
+ wantLevel: PatrolAutonomyMonitor,
+ wantCode: unifiedresources.PatrolAutopilotStatusAcknowledgementRequired,
+ wantActive: false,
+ },
+ {
+ name: "monitor requested mode is returned unchanged as not-requested",
+ config: &AIConfig{
+ PatrolAutonomyLevel: PatrolAutonomyMonitor,
+ },
+ orgID: "org-a",
+ wantLevel: PatrolAutonomyMonitor,
+ wantCode: unifiedresources.PatrolAutopilotStatusNotRequested,
+ wantActive: false,
+ },
+ {
+ name: "approval requested mode is returned unchanged as not-requested",
+ config: &AIConfig{
+ PatrolAutonomyLevel: PatrolAutonomyApproval,
+ },
+ orgID: "org-a",
+ wantLevel: PatrolAutonomyApproval,
+ wantCode: unifiedresources.PatrolAutopilotStatusNotRequested,
+ wantActive: false,
+ },
+ {
+ name: "assisted requested mode is returned unchanged as not-requested",
+ config: &AIConfig{
+ PatrolAutonomyLevel: PatrolAutonomyAssisted,
+ },
+ orgID: "org-a",
+ wantLevel: PatrolAutonomyAssisted,
+ wantCode: unifiedresources.PatrolAutopilotStatusNotRequested,
+ wantActive: false,
+ },
+ {
+ name: "full mode without activation requires acknowledgement and falls back to approval",
+ config: &AIConfig{
+ PatrolAutonomyLevel: PatrolAutonomyFull,
+ },
+ orgID: "org-a",
+ wantLevel: PatrolAutonomyApproval,
+ wantCode: unifiedresources.PatrolAutopilotStatusAcknowledgementRequired,
+ wantActive: false,
+ },
+ {
+ name: "full mode with legacy boolean unlocked but no activation reports legacy-ignored",
+ config: &AIConfig{
+ PatrolAutonomyLevel: PatrolAutonomyFull,
+ PatrolFullModeUnlocked: true,
+ },
+ orgID: "org-a",
+ wantLevel: PatrolAutonomyApproval,
+ wantCode: unifiedresources.PatrolAutopilotStatusLegacyBooleanIgnored,
+ wantActive: false,
+ },
+ {
+ name: "full mode with invalid activation digest falls back to approval",
+ config: &AIConfig{
+ PatrolAutonomyLevel: PatrolAutonomyFull,
+ PatrolAutopilotActivation: &invalidDigestActivation,
+ },
+ orgID: "org-a",
+ wantLevel: PatrolAutonomyApproval,
+ wantCode: unifiedresources.PatrolAutopilotStatusActivationDigestInvalid,
+ wantActive: false,
+ },
+ {
+ name: "full mode with activation bound to a different org is rejected as wrong-org",
+ config: &AIConfig{
+ PatrolAutonomyLevel: PatrolAutonomyFull,
+ PatrolAutopilotAcknowledgements: []unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement},
+ PatrolAutopilotActivation: &activation,
+ },
+ orgID: "org-b",
+ wantLevel: PatrolAutonomyApproval,
+ wantCode: unifiedresources.PatrolAutopilotStatusWrongOrg,
+ wantActive: false,
+ },
+ {
+ name: "full mode with matching activation and acknowledgement is active",
+ config: &AIConfig{
+ PatrolAutonomyLevel: PatrolAutonomyFull,
+ PatrolAutopilotAcknowledgements: []unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement},
+ PatrolAutopilotActivation: &activation,
+ },
+ orgID: "org-a",
+ wantLevel: PatrolAutonomyFull,
+ wantCode: unifiedresources.PatrolAutopilotStatusActive,
+ wantActive: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ level, status := tt.config.GetEffectivePatrolAutonomyWithPolicy(tt.orgID, policy)
+ assert.Equal(t, tt.wantLevel, level)
+ assert.Equal(t, tt.wantCode, status.Code, "status code mismatch")
+ assert.Equal(t, tt.wantActive, status.Active, "active flag mismatch")
+ assert.Equal(t, policy.CurrentVersion, status.CurrentVersion, "status carries the server policy version")
+ })
+ }
+
+ // The nil-receiver path is also reachable through the time-based wrapper and
+ // must surface the server-owned contract scope/limits rather than an empty
+ // status, so callers can render the acknowledgement surface.
+ t.Run("nil receiver contract status carries current accepted scope and limits", func(t *testing.T) {
+ var cfg *AIConfig
+ level, status := cfg.GetEffectivePatrolAutonomyWithPolicy("org-a", policy)
+ assert.Equal(t, PatrolAutonomyMonitor, level)
+ assert.Equal(t, unifiedresources.PatrolAutopilotStatusAcknowledgementRequired, status.Code)
+ assert.False(t, status.Active)
+ expectedContract, ok := unifiedresources.PatrolAutopilotContractForVersion(policy.CurrentVersion)
+ assert.True(t, ok, "current contract must be registered")
+ assert.Equal(t, expectedContract.AcceptedScope, status.AcceptedScope)
+ assert.Equal(t, expectedContract.AcceptedLimits, status.AcceptedLimits)
+ })
+
+ // GetEffectivePatrolAutonomy (the convenience wrapper) must agree with the
+ // explicit-policy variant for the same wall-clock time, exercising the
+ // CurrentPatrolAutopilotServerPolicy delegation.
+ t.Run("time-based wrapper agrees with explicit policy for monitor mode", func(t *testing.T) {
+ cfg := &AIConfig{PatrolAutonomyLevel: PatrolAutonomyMonitor}
+ wrapperLevel, wrapperStatus := cfg.GetEffectivePatrolAutonomy("org-a", now)
+ policyLevel, policyStatus := cfg.GetEffectivePatrolAutonomyWithPolicy("org-a", policy)
+ assert.Equal(t, policyLevel, wrapperLevel)
+ assert.Equal(t, PatrolAutonomyMonitor, wrapperLevel)
+ assert.Equal(t, policyStatus.Code, wrapperStatus.Code)
+ assert.Equal(t, unifiedresources.PatrolAutopilotStatusNotRequested, wrapperStatus.Code)
+ })
+}
+
+// TestBranchCovIsPatrolFullModeActive covers the conjunction in
+// IsPatrolFullModeActive (level == full AND status.Active): the nil-receiver
+// path (which never dereferences the receiver thanks to the underlying nil
+// guard), a non-full requested mode, a full request without activation, and a
+// genuinely active full-mode activation.
+func TestBranchCovIsPatrolFullModeActive(t *testing.T) {
+ now := time.Date(2026, 7, 16, 12, 0, 0, 0, time.UTC)
+ policy := unifiedresources.CurrentPatrolAutopilotServerPolicy(now)
+ actor := configPatrolAutopilotActor("admin", "session:org-a", "org-a")
+ acknowledgement, activation := configPatrolAutopilotEvidence(t, "ack-isfull-branchcov", actor, policy)
+
+ t.Run("nil receiver returns false without panic", func(t *testing.T) {
+ var cfg *AIConfig
+ assert.False(t, cfg.IsPatrolFullModeActive("org-a", now))
+ })
+
+ t.Run("monitor mode is not full", func(t *testing.T) {
+ cfg := &AIConfig{PatrolAutonomyLevel: PatrolAutonomyMonitor}
+ assert.False(t, cfg.IsPatrolFullModeActive("org-a", now))
+ })
+
+ t.Run("full mode without activation is not active", func(t *testing.T) {
+ cfg := &AIConfig{PatrolAutonomyLevel: PatrolAutonomyFull}
+ assert.False(t, cfg.IsPatrolFullModeActive("org-a", now))
+ })
+
+ t.Run("full mode with matching activation is active", func(t *testing.T) {
+ cfg := &AIConfig{
+ PatrolAutonomyLevel: PatrolAutonomyFull,
+ PatrolAutopilotAcknowledgements: []unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement},
+ PatrolAutopilotActivation: &activation,
+ }
+ assert.True(t, cfg.IsPatrolFullModeActive("org-a", now))
+ })
+
+ t.Run("full mode with activation bound to a different org is not active", func(t *testing.T) {
+ cfg := &AIConfig{
+ PatrolAutonomyLevel: PatrolAutonomyFull,
+ PatrolAutopilotAcknowledgements: []unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement},
+ PatrolAutopilotActivation: &activation,
+ }
+ assert.False(t, cfg.IsPatrolFullModeActive("org-b", now))
+ })
+}
+
+// TestBranchCovSetPatrolEventTriggersEnabled covers the nil-receiver no-op and
+// both values of the enabled argument, including the case where the granular
+// flags start divergent and are collapsed to a single setting. It also confirms
+// the setter writes all three persisted fields (both canonical split flags and
+// the legacy aggregate) and that GetPatrolEventTriggerSettings reflects them.
+func TestBranchCovSetPatrolEventTriggersEnabled(t *testing.T) {
+ t.Run("nil receiver is a no-op without panic", func(t *testing.T) {
+ var cfg *AIConfig
+ // SetPatrolEventTriggersEnabled is nil-safe and must early-return
+ // without mutating the receiver. The receiver stays nil afterwards; we
+ // do NOT call the non-nil-safe IsPatrolEventTriggersEnabled getter here
+ // (it dereferences c.Enabled and is therefore not symmetric with the
+ // setter's nil guard).
+ assert.NotPanics(t, func() { cfg.SetPatrolEventTriggersEnabled(true) })
+ assert.Nil(t, cfg)
+ })
+
+ t.Run("enabling sets all three persisted trigger flags from an empty config", func(t *testing.T) {
+ cfg := &AIConfig{}
+ cfg.SetPatrolEventTriggersEnabled(true)
+ assert.True(t, cfg.PatrolAlertTriggersEnabled)
+ assert.True(t, cfg.PatrolAnomalyTriggersEnabled)
+ assert.True(t, cfg.PatrolEventTriggersEnabled)
+ settings := cfg.GetPatrolEventTriggerSettings()
+ assert.True(t, settings.AlertTriggersEnabled)
+ assert.True(t, settings.AnomalyTriggersEnabled)
+ })
+
+ t.Run("disabling clears all three persisted trigger flags after being enabled", func(t *testing.T) {
+ cfg := &AIConfig{
+ PatrolAlertTriggersEnabled: true,
+ PatrolAnomalyTriggersEnabled: true,
+ PatrolEventTriggersEnabled: true,
+ }
+ cfg.SetPatrolEventTriggersEnabled(false)
+ assert.False(t, cfg.PatrolAlertTriggersEnabled)
+ assert.False(t, cfg.PatrolAnomalyTriggersEnabled)
+ assert.False(t, cfg.PatrolEventTriggersEnabled)
+ settings := cfg.GetPatrolEventTriggerSettings()
+ assert.False(t, settings.AlertTriggersEnabled)
+ assert.False(t, settings.AnomalyTriggersEnabled)
+ })
+
+ t.Run("enable collapses divergent granular flags to both true", func(t *testing.T) {
+ cfg := &AIConfig{
+ PatrolAlertTriggersEnabled: true,
+ PatrolAnomalyTriggersEnabled: false,
+ PatrolEventTriggersEnabled: true,
+ }
+ cfg.SetPatrolEventTriggersEnabled(true)
+ assert.True(t, cfg.PatrolAlertTriggersEnabled)
+ assert.True(t, cfg.PatrolAnomalyTriggersEnabled)
+ assert.True(t, cfg.PatrolEventTriggersEnabled)
+ })
+
+ t.Run("disable collapses divergent granular flags to both false", func(t *testing.T) {
+ cfg := &AIConfig{
+ PatrolAlertTriggersEnabled: true,
+ PatrolAnomalyTriggersEnabled: false,
+ PatrolEventTriggersEnabled: true,
+ }
+ cfg.SetPatrolEventTriggersEnabled(false)
+ assert.False(t, cfg.PatrolAlertTriggersEnabled)
+ assert.False(t, cfg.PatrolAnomalyTriggersEnabled)
+ assert.False(t, cfg.PatrolEventTriggersEnabled)
+ })
+}
diff --git a/internal/config/config_entitlement_billing_branchcov0716_test.go b/internal/config/config_entitlement_billing_branchcov0716_test.go
new file mode 100644
index 0000000000..ddf5f97f0f
--- /dev/null
+++ b/internal/config/config_entitlement_billing_branchcov0716_test.go
@@ -0,0 +1,193 @@
+package config
+
+import (
+ "testing"
+
+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
+ "github.com/stretchr/testify/assert"
+)
+
+// This file adds branch coverage for the entitlement-billing helpers in
+// entitlement_billing_state.go: NormalizeEntitlementBillingOrgID and
+// billingStateHasEntitlementAuthority. Test functions use the BranchCov prefix
+// so they can be selected with `-run BranchCov`.
+
+// TestBranchCovNormalizeEntitlementBillingOrgID covers both branches of
+// NormalizeEntitlementBillingOrgID: the empty-after-trim arm that returns the
+// "default" sentinel, and the non-empty arm that returns the trimmed value
+// verbatim. It also exercises whitespace-only input (mixing spaces, tabs and
+// newlines), the literal "default" id, and the fact that internal whitespace is
+// preserved (only leading/trailing whitespace is trimmed).
+func TestBranchCovNormalizeEntitlementBillingOrgID(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ want string
+ }{
+ // --- Empty-after-trim branch: returns entitlementBillingDefaultOrgID. ---
+ {
+ name: "empty string falls back to default",
+ raw: "",
+ want: "default",
+ },
+ {
+ name: "single space falls back to default",
+ raw: " ",
+ want: "default",
+ },
+ {
+ name: "mixed whitespace only falls back to default",
+ raw: " \t\n\r\t ",
+ want: "default",
+ },
+
+ // --- Non-empty branch: returns the trimmed value verbatim. ---
+ {
+ name: "plain id returned as-is",
+ raw: "org-123",
+ want: "org-123",
+ },
+ {
+ name: "leading and trailing whitespace trimmed",
+ raw: " org-123\t\n",
+ want: "org-123",
+ },
+ {
+ name: "internal whitespace is preserved only outer trimmed",
+ raw: " org 456 ",
+ want: "org 456",
+ },
+ {
+ name: "literal default id returned as default",
+ raw: "default",
+ want: "default",
+ },
+ {
+ name: "literal default id with surrounding whitespace trimmed to default",
+ raw: " default ",
+ want: "default",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ assert.Equal(t, tc.want, NormalizeEntitlementBillingOrgID(tc.raw))
+ })
+ }
+}
+
+// TestBranchCovBillingStateHasEntitlementAuthority covers every branch of
+// billingStateHasEntitlementAuthority:
+// - the nil-state early return (false)
+// - each of the three OR operands independently granting authority when set
+// (SubscriptionState, EntitlementJWT, EntitlementRefreshToken)
+// - each operand being whitespace-only so its TrimSpace collapses to "" and
+// it does NOT grant authority
+// - a fully empty/zero BillingState (all three operands empty) returning false
+// - a fully populated BillingState returning true
+//
+// Because billingStateHasEntitlementAuthority is an unexported helper in this
+// package, the test lives in-package (`package config`) and invokes it
+// directly rather than driving it through LoadEffectiveEntitlementBillingState.
+func TestBranchCovBillingStateHasEntitlementAuthority(t *testing.T) {
+ tests := []struct {
+ name string
+ state *pkglicensing.BillingState
+ want bool
+ }{
+ // --- nil guard branch. ---
+ {
+ name: "nil state returns false",
+ state: nil,
+ want: false,
+ },
+
+ // --- Empty / zero BillingState: all three operands empty. ---
+ {
+ name: "empty billing state returns false",
+ state: &pkglicensing.BillingState{},
+ want: false,
+ },
+
+ // --- Each operand alone grants authority (non-whitespace value). ---
+ {
+ name: "subscription state alone grants authority",
+ state: &pkglicensing.BillingState{
+ SubscriptionState: pkglicensing.SubStateActive,
+ },
+ want: true,
+ },
+ {
+ name: "subscription state trial grants authority",
+ state: &pkglicensing.BillingState{
+ SubscriptionState: pkglicensing.SubStateTrial,
+ },
+ want: true,
+ },
+ {
+ name: "entitlement jwt alone grants authority",
+ state: &pkglicensing.BillingState{
+ EntitlementJWT: "eyJhbGciOiJIUzI1NiJ9.payload.sig",
+ },
+ want: true,
+ },
+ {
+ name: "entitlement refresh token alone grants authority",
+ state: &pkglicensing.BillingState{
+ EntitlementRefreshToken: "refresh-token-abc",
+ },
+ want: true,
+ },
+
+ // --- Each operand whitespace-only does NOT grant authority. ---
+ {
+ name: "whitespace only subscription state does not grant authority",
+ state: &pkglicensing.BillingState{
+ SubscriptionState: pkglicensing.SubscriptionState(" "),
+ },
+ want: false,
+ },
+ {
+ name: "whitespace only entitlement jwt does not grant authority",
+ state: &pkglicensing.BillingState{
+ EntitlementJWT: "\t\n ",
+ },
+ want: false,
+ },
+ {
+ name: "whitespace only refresh token does not grant authority",
+ state: &pkglicensing.BillingState{
+ EntitlementRefreshToken: " \r\n\t ",
+ },
+ want: false,
+ },
+
+ // --- All three operands whitespace-only exercises every OR arm false. ---
+ {
+ name: "all three whitespace only returns false",
+ state: &pkglicensing.BillingState{
+ SubscriptionState: pkglicensing.SubscriptionState(" "),
+ EntitlementJWT: " ",
+ EntitlementRefreshToken: " ",
+ },
+ want: false,
+ },
+
+ // --- All three populated returns true. ---
+ {
+ name: "all three populated returns true",
+ state: &pkglicensing.BillingState{
+ SubscriptionState: pkglicensing.SubStateGrace,
+ EntitlementJWT: "jwt",
+ EntitlementRefreshToken: "refresh",
+ },
+ want: true,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ assert.Equal(t, tc.want, billingStateHasEntitlementAuthority(tc.state))
+ })
+ }
+}
diff --git a/internal/config/config_report_schedules_branchcov0716_test.go b/internal/config/config_report_schedules_branchcov0716_test.go
new file mode 100644
index 0000000000..8955e49966
--- /dev/null
+++ b/internal/config/config_report_schedules_branchcov0716_test.go
@@ -0,0 +1,278 @@
+package config
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// This file adds branch coverage for the report-schedule helpers in
+// report_schedules.go: EmptyReportScheduleStore, NormalizeReportScheduleStore,
+// NormalizeReportSchedule, normalizeReportScheduleStringSlice, and
+// parseReportScheduleStoreJSON. Test functions use the BranchCov prefix so
+// they can be selected with `-run BranchCov`.
+
+// TestBranchCovEmptyReportScheduleStore verifies that EmptyReportScheduleStore
+// returns a store whose Schedules slice is allocated (non-nil) and empty. The
+// nil-vs-empty distinction is observable: json.Marshal renders a nil slice as
+// `null` and an empty slice as `[]`.
+func TestBranchCovEmptyReportScheduleStore(t *testing.T) {
+ store := EmptyReportScheduleStore()
+ require.NotNil(t, store.Schedules, "Schedules must be non-nil so it serializes as [] not null")
+ assert.Len(t, store.Schedules, 0)
+
+ encoded, err := json.Marshal(store)
+ require.NoError(t, err)
+ assert.Contains(t, string(encoded), `"schedules":[]`)
+ assert.NotContains(t, string(encoded), `"schedules":null`)
+}
+
+// TestBranchCovNormalizeReportScheduleStore covers both arms of the
+// nil-Schedules guard (true and false) and exercises the per-element
+// normalization loop with zero and multiple entries.
+func TestBranchCovNormalizeReportScheduleStore(t *testing.T) {
+ t.Run("nil schedules is replaced with a non-nil empty slice", func(t *testing.T) {
+ got := NormalizeReportScheduleStore(ReportScheduleStore{Schedules: nil})
+ require.NotNil(t, got.Schedules)
+ assert.Len(t, got.Schedules, 0)
+ })
+
+ t.Run("empty non-nil schedules stays empty and non-nil", func(t *testing.T) {
+ got := NormalizeReportScheduleStore(ReportScheduleStore{Schedules: []ReportSchedule{}})
+ require.NotNil(t, got.Schedules)
+ assert.Len(t, got.Schedules, 0)
+ })
+
+ t.Run("each schedule is normalized in place (loop runs for every index)", func(t *testing.T) {
+ in := ReportScheduleStore{Schedules: []ReportSchedule{
+ {ID: " A ", Name: " First "},
+ {ID: "\tB\t", Name: "Second "},
+ }}
+ got := NormalizeReportScheduleStore(in)
+ require.Len(t, got.Schedules, 2)
+ assert.Equal(t, "A", got.Schedules[0].ID)
+ assert.Equal(t, "First", got.Schedules[0].Name)
+ assert.Equal(t, "B", got.Schedules[1].ID)
+ assert.Equal(t, "Second", got.Schedules[1].Name)
+ // The shared backing array is mutated, so the caller's slice reflects
+ // the normalized values too.
+ assert.Equal(t, "A", in.Schedules[0].ID)
+ assert.Equal(t, "B", in.Schedules[1].ID)
+ })
+}
+
+// TestBranchCovNormalizeReportSchedule exercises every branch and
+// transformation of NormalizeReportSchedule: whitespace trimming, the
+// lowercased-vs-trim-only distinction between fields, both arms of the
+// RetentionCount<=0 guard (including the boundary at 1), both arms of the nil
+// Resources guard, and the per-resource normalization loop.
+func TestBranchCovNormalizeReportSchedule(t *testing.T) {
+ t.Run("strings are trimmed and only the designated fields are lowercased", func(t *testing.T) {
+ in := ReportSchedule{
+ ID: " Rep-1 ",
+ Name: " Monthly Report ",
+ Cadence: ReportScheduleCadence{
+ Type: " MONTHLY ",
+ DayOfMonth: 1,
+ Weekday: " MON ",
+ Time: " 08:00 ",
+ Timezone: " America/New_York ",
+ },
+ Window: " last_month ",
+ Format: " PDF ",
+ Delivery: ReportScheduleDelivery{Method: " EMAIL "},
+ LastRunStatus: " OK ",
+ LastError: " boom ",
+ LastOccurrenceKey: " key-1 ",
+ RetentionCount: 5,
+ }
+ got := NormalizeReportSchedule(in)
+
+ // Trimmed-only fields preserve original case.
+ assert.Equal(t, "Rep-1", got.ID)
+ assert.Equal(t, "Monthly Report", got.Name)
+ assert.Equal(t, "08:00", got.Cadence.Time)
+ assert.Equal(t, "America/New_York", got.Cadence.Timezone)
+ assert.Equal(t, "last_month", got.Window)
+ assert.Equal(t, "boom", got.LastError)
+ assert.Equal(t, "key-1", got.LastOccurrenceKey)
+
+ // Trimmed + lowercased fields.
+ assert.Equal(t, "monthly", got.Cadence.Type)
+ assert.Equal(t, "mon", got.Cadence.Weekday)
+ assert.Equal(t, "pdf", got.Format)
+ assert.Equal(t, "email", got.Delivery.Method)
+ assert.Equal(t, "ok", got.LastRunStatus)
+
+ // RetentionCount > 0 and integer fields like DayOfMonth are untouched.
+ assert.Equal(t, 5, got.RetentionCount)
+ assert.Equal(t, 1, got.Cadence.DayOfMonth)
+ })
+
+ t.Run("retention count guard: zero, negative, and boundary values", func(t *testing.T) {
+ tests := []struct {
+ name string
+ in int
+ want int
+ }{
+ {"zero resets to default", 0, DefaultReportScheduleRetentionCount},
+ {"negative resets to default", -7, DefaultReportScheduleRetentionCount},
+ {"one is preserved (boundary)", 1, 1},
+ {"large positive preserved", 999, 999},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := NormalizeReportSchedule(ReportSchedule{RetentionCount: tc.in})
+ assert.Equal(t, tc.want, got.RetentionCount)
+ })
+ }
+ })
+
+ t.Run("nil scope resources is replaced with empty slice", func(t *testing.T) {
+ got := NormalizeReportSchedule(ReportSchedule{}) // Scope.Resources is nil
+ require.NotNil(t, got.Scope.Resources)
+ assert.Len(t, got.Scope.Resources, 0)
+ })
+
+ t.Run("each scope resource is normalized (loop runs for every index)", func(t *testing.T) {
+ in := ReportSchedule{Scope: ReportScheduleScope{Resources: []ReportScheduleResource{
+ {ResourceType: " HOST ", ResourceID: " h-1 ", Name: " Host One "},
+ {ResourceType: "VM", ResourceID: "v-2", Name: " VM Two "},
+ }}}
+ got := NormalizeReportSchedule(in)
+ require.Len(t, got.Scope.Resources, 2)
+ assert.Equal(t, "host", got.Scope.Resources[0].ResourceType) // lowercased
+ assert.Equal(t, "h-1", got.Scope.Resources[0].ResourceID)
+ assert.Equal(t, "Host One", got.Scope.Resources[0].Name)
+ assert.Equal(t, "vm", got.Scope.Resources[1].ResourceType)
+ assert.Equal(t, "v-2", got.Scope.Resources[1].ResourceID)
+ assert.Equal(t, "VM Two", got.Scope.Resources[1].Name)
+ })
+
+ t.Run("tags and delivery recipients are normalized via the slice helper", func(t *testing.T) {
+ in := ReportSchedule{
+ Scope: ReportScheduleScope{Tags: []string{" prod ", "Prod", " ", "staging"}},
+ Delivery: ReportScheduleDelivery{To: []string{"[email protected]", " [email protected] ", ""}},
+ }
+ got := NormalizeReportSchedule(in)
+ assert.Equal(t, []string{"prod", "staging"}, got.Scope.Tags)
+ assert.Equal(t, []string{"[email protected]"}, got.Delivery.To)
+ })
+}
+
+// TestBranchCovNormalizeReportScheduleStringSlice covers every branch of
+// normalizeReportScheduleStringSlice: the nil-input short-circuit, the
+// empty/whitespace skip arm, the case-insensitive duplicate skip arm, the
+// add-to-output arm, and first-occurrence ordering.
+func TestBranchCovNormalizeReportScheduleStringSlice(t *testing.T) {
+ tests := []struct {
+ name string
+ in []string
+ want []string
+ }{
+ {"nil input returns empty slice", nil, []string{}},
+ {"empty input returns empty slice", []string{}, []string{}},
+ {"all whitespace values filtered out", []string{" ", "\t", "\n", " "}, []string{}},
+ {"whitespace values trimmed before empty check", []string{" a ", " ", "b"}, []string{"a", "b"}},
+ {"case-insensitive duplicates keep first occurrence casing", []string{"Prod", "PROD", "prod", "Staging", "staging"}, []string{"Prod", "Staging"}},
+ {"first occurrence ordering preserved", []string{"z", "a", "Z", "A", "m"}, []string{"z", "a", "m"}},
+ {"mixed empty whitespace and valid deduped", []string{"", " ", "x", "X", "y", ""}, []string{"x", "y"}},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := normalizeReportScheduleStringSlice(tc.in)
+ require.NotNil(t, got, "result must be non-nil")
+ assert.Equal(t, tc.want, got)
+ })
+ }
+}
+
+// TestBranchCovParseReportScheduleStoreJSON covers every branch of
+// parseReportScheduleStoreJSON: the empty/whitespace short-circuit, the
+// object-form success path (store.Schedules != nil), the object-form-but-nil-
+// schedules fallthrough, the bare-array-form success path, and the both-forms-
+// fail error path.
+func TestBranchCovParseReportScheduleStoreJSON(t *testing.T) {
+ t.Run("nil data returns empty store no error", func(t *testing.T) {
+ got, err := parseReportScheduleStoreJSON(nil)
+ require.NoError(t, err)
+ require.NotNil(t, got.Schedules)
+ assert.Len(t, got.Schedules, 0)
+ })
+
+ t.Run("empty byte slice returns empty store no error", func(t *testing.T) {
+ got, err := parseReportScheduleStoreJSON([]byte{})
+ require.NoError(t, err)
+ require.NotNil(t, got.Schedules)
+ assert.Len(t, got.Schedules, 0)
+ })
+
+ t.Run("whitespace only data returns empty store no error", func(t *testing.T) {
+ got, err := parseReportScheduleStoreJSON([]byte(" \n\t "))
+ require.NoError(t, err)
+ require.NotNil(t, got.Schedules)
+ assert.Len(t, got.Schedules, 0)
+ })
+
+ t.Run("object form with non-nil schedules is normalized", func(t *testing.T) {
+ data := []byte(`{"schedules":[{"id":" r1 ","name":" Report 1 ","format":" PDF "}]}`)
+ got, err := parseReportScheduleStoreJSON(data)
+ require.NoError(t, err)
+ require.Len(t, got.Schedules, 1)
+ assert.Equal(t, "r1", got.Schedules[0].ID)
+ assert.Equal(t, "Report 1", got.Schedules[0].Name)
+ assert.Equal(t, "pdf", got.Schedules[0].Format) // lowercased by normalize
+ // Default retention applied via normalize (retention_count was absent -> 0).
+ assert.Equal(t, DefaultReportScheduleRetentionCount, got.Schedules[0].RetentionCount)
+ })
+
+ t.Run("object form with empty schedules array returns empty store", func(t *testing.T) {
+ got, err := parseReportScheduleStoreJSON([]byte(`{"schedules":[]}`))
+ require.NoError(t, err)
+ require.NotNil(t, got.Schedules)
+ assert.Len(t, got.Schedules, 0)
+ })
+
+ t.Run("bare array form is parsed when object form fails", func(t *testing.T) {
+ data := []byte(`[{"id":" a ","name":"A"}]`)
+ got, err := parseReportScheduleStoreJSON(data)
+ require.NoError(t, err)
+ require.Len(t, got.Schedules, 1)
+ assert.Equal(t, "a", got.Schedules[0].ID)
+ assert.Equal(t, "A", got.Schedules[0].Name)
+ })
+
+ t.Run("empty bare array returns empty store", func(t *testing.T) {
+ got, err := parseReportScheduleStoreJSON([]byte(`[]`))
+ require.NoError(t, err)
+ require.NotNil(t, got.Schedules)
+ assert.Len(t, got.Schedules, 0)
+ })
+
+ t.Run("invalid JSON returns an error and zero store", func(t *testing.T) {
+ got, err := parseReportScheduleStoreJSON([]byte(`{not json`))
+ require.Error(t, err)
+ // On the error path the function returns a zero ReportScheduleStore.
+ assert.Nil(t, got.Schedules)
+ })
+
+ t.Run("object form with null schedules falls through and errors", func(t *testing.T) {
+ // `{"schedules":null}` unmarshals cleanly but leaves store.Schedules
+ // nil, so the parser falls through to the bare-array branch which
+ // cannot interpret an object as an array and returns an error.
+ got, err := parseReportScheduleStoreJSON([]byte(`{"schedules":null}`))
+ require.Error(t, err)
+ assert.Nil(t, got.Schedules)
+ })
+
+ t.Run("empty object without schedules field falls through and errors", func(t *testing.T) {
+ // `{}` parses as an empty struct (no error) but store.Schedules is
+ // nil, so it falls through; the object cannot be reinterpreted as a
+ // bare array, yielding an error.
+ got, err := parseReportScheduleStoreJSON([]byte(`{}`))
+ require.Error(t, err)
+ assert.Nil(t, got.Schedules)
+ })
+}
diff --git a/internal/models/models_collections_branchcov0716_test.go b/internal/models/models_collections_branchcov0716_test.go
new file mode 100644
index 0000000000..d754ca10e0
--- /dev/null
+++ b/internal/models/models_collections_branchcov0716_test.go
@@ -0,0 +1,381 @@
+package models
+
+import "testing"
+
+// TestBranchCovCephPoolStorage exercises the two branches of the free function
+// CephPoolStorage: the early "no pools -> nil" return and the pool-projection
+// loop. The projection itself delegates to StorageFromCephPool, so the
+// cluster-health-driven status/active flags are asserted end-to-end through
+// CephPoolStorage's returned slice (covering the HEALTH_ERR path that the
+// existing StorageFromCephPool happy-path test does not reach).
+func TestBranchCovCephPoolStorage(t *testing.T) {
+ tests := []struct {
+ name string
+ cluster CephCluster
+ wantNil bool
+ wantLen int
+ wantStatus string // asserted on every projected entry when wantNil is false
+ wantActive bool
+ }{
+ {
+ name: "nil pools returns nil",
+ cluster: CephCluster{Instance: "pve1", Health: "HEALTH_OK", Pools: nil},
+ wantNil: true,
+ },
+ {
+ name: "empty (non-nil) pools slice returns nil",
+ cluster: CephCluster{Instance: "pve1", Health: "HEALTH_OK", Pools: []CephPool{}},
+ wantNil: true,
+ },
+ {
+ name: "healthy cluster projects available active storage",
+ cluster: CephCluster{
+ Instance: "pve1",
+ Health: "HEALTH_OK",
+ Pools: []CephPool{{ID: 1, Name: "data"}},
+ },
+ wantLen: 1,
+ wantStatus: "available",
+ wantActive: true,
+ },
+ {
+ name: "health_err cluster projects unavailable inactive storage",
+ cluster: CephCluster{
+ Instance: "pve1",
+ Health: "HEALTH_ERR",
+ Pools: []CephPool{{ID: 2, Name: "ssd"}},
+ },
+ wantLen: 1,
+ wantStatus: "unavailable",
+ wantActive: false,
+ },
+ {
+ name: "multiple pools projected in order",
+ cluster: CephCluster{
+ Instance: "pve1",
+ Health: "HEALTH_WARN",
+ Pools: []CephPool{
+ {ID: 1, Name: "data"},
+ {ID: 2, Name: "ssd"},
+ },
+ },
+ wantLen: 2,
+ wantStatus: "available",
+ wantActive: true,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := CephPoolStorage(tc.cluster)
+ if tc.wantNil {
+ if got != nil {
+ t.Fatalf("CephPoolStorage = %#v, want nil for empty/nil pools", got)
+ }
+ return
+ }
+ if got == nil {
+ t.Fatal("CephPoolStorage = nil, want non-nil slice")
+ }
+ if len(got) != tc.wantLen {
+ t.Fatalf("len = %d, want %d", len(got), tc.wantLen)
+ }
+ for i, st := range got {
+ if st.Type != "ceph" {
+ t.Errorf("entry %d Type = %q, want ceph", i, st.Type)
+ }
+ if !st.Shared || !st.Enabled {
+ t.Errorf("entry %d flags Shared=%v Enabled=%v, want both true", i, st.Shared, st.Enabled)
+ }
+ if st.Status != tc.wantStatus {
+ t.Errorf("entry %d Status = %q, want %q", i, st.Status, tc.wantStatus)
+ }
+ if st.Active != tc.wantActive {
+ t.Errorf("entry %d Active = %v, want %v", i, st.Active, tc.wantActive)
+ }
+ if st.Name != tc.cluster.Pools[i].Name {
+ t.Errorf("entry %d Name = %q, want %q (pool order not preserved)", i, st.Name, tc.cluster.Pools[i].Name)
+ }
+ }
+ })
+ }
+}
+
+// TestBranchCovCephPoolStorage_NamesFromEmptyPoolID covers the boundary where a
+// CephPool has an empty name: StorageFromCephPool falls back to "pool-<id>".
+// This is reached through CephPoolStorage and is not covered elsewhere.
+func TestBranchCovCephPoolStorage_NamesFromEmptyPoolID(t *testing.T) {
+ got := CephPoolStorage(CephCluster{
+ Instance: "pve1",
+ Health: "HEALTH_OK",
+ Pools: []CephPool{{ID: 9, Name: ""}},
+ })
+ if len(got) != 1 {
+ t.Fatalf("len = %d, want 1", len(got))
+ }
+ if got[0].Name != "pool-9" {
+ t.Errorf("empty-named pool projected Name = %q, want pool-9", got[0].Name)
+ }
+ if got[0].Pool != "pool-9" {
+ t.Errorf("empty-named pool projected Pool = %q, want pool-9", got[0].Pool)
+ }
+}
+
+// TestBranchCovMergeTagColors covers every branch of State.MergeTagColors:
+// the empty/nil early return (no lock, no map init, no LastUpdate bump), the
+// nil-map initialization arm, the reuse-existing-map arm, and the per-entry
+// tag/color normalization (TrimSpace + ToLower on keys, TrimSpace on values).
+func TestBranchCovMergeTagColors(t *testing.T) {
+ // Read state fields directly: MergeTagColors has already returned, the test
+ // is single-goroutine, and reading the raw fields verifies the *true*
+ // internal state (nil vs initialized map) rather than the post-processed
+ // snapshot, which NormalizeCollections() turns into a non-nil empty map.
+ t.Run("nil colors is a no-op and leaves map nil and LastUpdate untouched", func(t *testing.T) {
+ state := &State{}
+ before := state.LastUpdate
+ state.MergeTagColors(nil)
+
+ if state.PVETagColors != nil {
+ t.Fatalf("nil colors should leave PVETagColors nil, got %#v", state.PVETagColors)
+ }
+ if state.LastUpdate != before {
+ t.Fatal("nil colors must not touch LastUpdate")
+ }
+ })
+
+ t.Run("empty colors is a no-op and leaves LastUpdate untouched", func(t *testing.T) {
+ state := &State{}
+ before := state.LastUpdate
+ state.MergeTagColors(map[string]string{})
+
+ if state.PVETagColors != nil {
+ t.Fatalf("empty colors should leave PVETagColors nil, got %#v", state.PVETagColors)
+ }
+ if state.LastUpdate != before {
+ t.Fatal("empty colors must not touch LastUpdate")
+ }
+ })
+
+ t.Run("nil destination map is initialized and entries normalized", func(t *testing.T) {
+ state := &State{}
+ state.MergeTagColors(map[string]string{
+ " Production ": " #ff0000 ",
+ "\tBACKUP\t": "#00ff00",
+ })
+
+ if state.PVETagColors == nil {
+ t.Fatal("nil destination map should be initialized by a non-empty merge")
+ }
+ if got := state.PVETagColors["production"]; got != "#ff0000" {
+ t.Errorf("production color = %q, want #ff0000 (tag trimmed+lowercased, color trimmed)", got)
+ }
+ if got := state.PVETagColors["backup"]; got != "#00ff00" {
+ t.Errorf("backup color = %q, want #00ff00", got)
+ }
+ if _, ok := state.PVETagColors[" Production "]; ok {
+ t.Error("un-normalized tag key should not be present")
+ }
+ })
+
+ t.Run("existing destination map is reused and merged", func(t *testing.T) {
+ state := NewState() // PVETagColors starts as a non-nil empty map
+ state.MergeTagColors(map[string]string{"existing": "#111111"})
+ state.MergeTagColors(map[string]string{"added": "#222222"})
+
+ if got := state.PVETagColors["existing"]; got != "#111111" {
+ t.Errorf("existing color = %q, want #111111 (prior merge must survive)", got)
+ }
+ if got := state.PVETagColors["added"]; got != "#222222" {
+ t.Errorf("added color = %q, want #222222", got)
+ }
+ if len(state.PVETagColors) != 2 {
+ t.Errorf("merged color count = %d, want 2", len(state.PVETagColors))
+ }
+ })
+
+ t.Run("non-empty merge bumps LastUpdate", func(t *testing.T) {
+ state := &State{}
+ before := state.LastUpdate
+ state.MergeTagColors(map[string]string{"x": "#000000"})
+
+ if state.LastUpdate == before {
+ t.Fatal("LastUpdate should advance after a non-empty merge")
+ }
+ })
+}
+
+// TestBranchCovStorageNormalizeCollections covers both arms of each conditional
+// in Storage.NormalizeCollections: the nil-collection initialization arms
+// (Nodes, NodeIDs) and both sides of the ZFSPool branch (nil pointer stays nil;
+// non-nil pointer is recursively normalized, including its own nil Devices).
+func TestBranchCovStorageNormalizeCollections(t *testing.T) {
+ t.Run("nil slices initialized and nil zfs left untouched", func(t *testing.T) {
+ s := Storage{} // Nodes, NodeIDs, ZFSPool all nil
+ out := s.NormalizeCollections()
+
+ if out.Nodes == nil {
+ t.Error("Nodes should be initialized to non-nil empty slice")
+ }
+ if len(out.Nodes) != 0 {
+ t.Errorf("Nodes len = %d, want 0", len(out.Nodes))
+ }
+ if out.NodeIDs == nil {
+ t.Error("NodeIDs should be initialized to non-nil empty slice")
+ }
+ if out.ZFSPool != nil {
+ t.Errorf("ZFSPool = %#v, want nil (must not synthesize a pointer)", out.ZFSPool)
+ }
+ })
+
+ t.Run("non-nil slices preserved and zfs recursively normalized", func(t *testing.T) {
+ s := Storage{
+ Nodes: []string{"n1"},
+ NodeIDs: []string{"id1"},
+ ZFSPool: &ZFSPool{Name: "tank"}, // Devices nil -> must be normalized
+ }
+ out := s.NormalizeCollections()
+
+ if len(out.Nodes) != 1 || out.Nodes[0] != "n1" {
+ t.Errorf("Nodes = %#v, want [n1] (already-set slice must be preserved)", out.Nodes)
+ }
+ if len(out.NodeIDs) != 1 || out.NodeIDs[0] != "id1" {
+ t.Errorf("NodeIDs = %#v, want [id1]", out.NodeIDs)
+ }
+ if out.ZFSPool == nil {
+ t.Fatal("ZFSPool should remain non-nil")
+ }
+ if out.ZFSPool.Devices == nil {
+ t.Error("nested ZFSPool.Devices should be initialized to non-nil empty slice")
+ }
+ if len(out.ZFSPool.Devices) != 0 {
+ t.Errorf("ZFSPool.Devices len = %d, want 0", len(out.ZFSPool.Devices))
+ }
+ })
+}
+
+// TestBranchCovCephClusterNormalizeCollections covers the nil-initialization
+// arms for InstanceAliases/Pools/Services and the else path where pre-set
+// slices pass through unchanged.
+func TestBranchCovCephClusterNormalizeCollections(t *testing.T) {
+ t.Run("nil collections initialized", func(t *testing.T) {
+ c := CephCluster{}
+ out := c.NormalizeCollections()
+
+ if out.InstanceAliases == nil || out.Pools == nil || out.Services == nil {
+ t.Fatalf("nil collections should be initialized: %#v", out)
+ }
+ if len(out.InstanceAliases) != 0 || len(out.Pools) != 0 || len(out.Services) != 0 {
+ t.Errorf("initialized collections should be empty: %#v", out)
+ }
+ })
+
+ t.Run("existing collections preserved", func(t *testing.T) {
+ c := CephCluster{
+ InstanceAliases: []string{"a"},
+ Pools: []CephPool{{ID: 1, Name: "data"}},
+ Services: []CephServiceStatus{{Type: "mon", Running: 1, Total: 1}},
+ }
+ out := c.NormalizeCollections()
+
+ if len(out.InstanceAliases) != 1 || out.InstanceAliases[0] != "a" {
+ t.Errorf("InstanceAliases = %#v, want [a]", out.InstanceAliases)
+ }
+ if len(out.Pools) != 1 || out.Pools[0].Name != "data" {
+ t.Errorf("Pools = %#v, want unchanged", out.Pools)
+ }
+ if len(out.Services) != 1 || out.Services[0].Type != "mon" {
+ t.Errorf("Services = %#v, want unchanged", out.Services)
+ }
+ })
+}
+
+// TestBranchCovPBSInstanceNormalizeCollections covers the nil-initialization
+// arms of all seven PBS slice fields and the Datastores normalization loop body
+// (a datastore with nil Namespaces is recursed into and normalized), plus the
+// else path where pre-populated job slices pass through unchanged.
+func TestBranchCovPBSInstanceNormalizeCollections(t *testing.T) {
+ t.Run("nil collections initialized and datastore recursion runs", func(t *testing.T) {
+ inst := PBSInstance{
+ Datastores: []PBSDatastore{{Name: "store1"}}, // Namespaces nil
+ }
+ out := inst.NormalizeCollections()
+
+ if out.Datastores == nil || len(out.Datastores) != 1 {
+ t.Fatalf("Datastores = %#v, want single entry preserved", out.Datastores)
+ }
+ if out.Datastores[0].Namespaces == nil {
+ t.Error("nested Datastore.Namespaces should be initialized by the loop body")
+ }
+ for field, got := range map[string][]struct{}{
+ "BackupJobs": toIfaces(out.BackupJobs),
+ "SyncJobs": toIfaces(out.SyncJobs),
+ "VerifyJobs": toIfaces(out.VerifyJobs),
+ "PruneJobs": toIfaces(out.PruneJobs),
+ "GarbageJobs": toIfaces(out.GarbageJobs),
+ "JobHealthEvidence": toIfaces(out.JobHealthEvidence),
+ } {
+ if got == nil {
+ t.Errorf("%s should be initialized to non-nil empty slice", field)
+ }
+ }
+ })
+
+ t.Run("all nil fields become empty slices", func(t *testing.T) {
+ out := PBSInstance{}.NormalizeCollections()
+ checks := map[string][]struct{}{
+ "Datastores": toIfaces(out.Datastores),
+ "BackupJobs": toIfaces(out.BackupJobs),
+ "SyncJobs": toIfaces(out.SyncJobs),
+ "VerifyJobs": toIfaces(out.VerifyJobs),
+ "PruneJobs": toIfaces(out.PruneJobs),
+ "GarbageJobs": toIfaces(out.GarbageJobs),
+ "JobHealthEvidence": toIfaces(out.JobHealthEvidence),
+ }
+ for field, got := range checks {
+ if got == nil {
+ t.Errorf("%s should be initialized to non-nil empty slice", field)
+ }
+ if len(got) != 0 {
+ t.Errorf("%s len = %d, want 0", field, len(got))
+ }
+ }
+ })
+
+ t.Run("existing job slices preserved unchanged", func(t *testing.T) {
+ inst := PBSInstance{
+ BackupJobs: []PBSBackupJob{{ID: "j1"}},
+ SyncJobs: []PBSSyncJob{{ID: "s1"}},
+ VerifyJobs: []PBSVerifyJob{{ID: "v1"}},
+ PruneJobs: []PBSPruneJob{{ID: "p1"}},
+ GarbageJobs: []PBSGarbageJob{{ID: "g1"}},
+ }
+ out := inst.NormalizeCollections()
+
+ if len(out.BackupJobs) != 1 || out.BackupJobs[0].ID != "j1" {
+ t.Errorf("BackupJobs = %#v, want [j1]", out.BackupJobs)
+ }
+ if len(out.SyncJobs) != 1 || out.SyncJobs[0].ID != "s1" {
+ t.Errorf("SyncJobs = %#v, want [s1]", out.SyncJobs)
+ }
+ if len(out.VerifyJobs) != 1 || out.VerifyJobs[0].ID != "v1" {
+ t.Errorf("VerifyJobs = %#v, want [v1]", out.VerifyJobs)
+ }
+ if len(out.PruneJobs) != 1 || out.PruneJobs[0].ID != "p1" {
+ t.Errorf("PruneJobs = %#v, want [p1]", out.PruneJobs)
+ }
+ if len(out.GarbageJobs) != 1 || out.GarbageJobs[0].ID != "g1" {
+ t.Errorf("GarbageJobs = %#v, want [g1]", out.GarbageJobs)
+ }
+ })
+}
+
+// toIfaces is a tiny local helper that lets the table-driven collection checks
+// uniformly assert non-nil/length without reflecting over each distinct slice
+// type. It preserves nil-ness (a nil input yields a nil result).
+func toIfaces[T any](s []T) []struct{} {
+ if s == nil {
+ return nil
+ }
+ out := make([]struct{}, len(s))
+ return out
+}
diff --git a/internal/models/models_deepcopy_branchcov0716_test.go b/internal/models/models_deepcopy_branchcov0716_test.go
new file mode 100644
index 0000000000..3b09fd38bf
--- /dev/null
+++ b/internal/models/models_deepcopy_branchcov0716_test.go
@@ -0,0 +1,437 @@
+package models
+
+import (
+ "reflect"
+ "testing"
+ "time"
+)
+
+// bcIntPtr returns a pointer to v; used to build metric values that exercise
+// the reflect.Pointer arm of cloneDynamicValue. It is prefixed to avoid any
+// future collision with other test helpers in this package.
+func bcIntPtr(v int) *int { return &v }
+
+// TestBranchCovCloneMetricValues covers every branch of cloneMetricValues:
+// - the len==0 fast path (exercised by BOTH a nil map and an allocated-but-empty
+// map, which are distinct boundaries that both collapse to nil),
+// - the iteration body that delegates each value to cloneDynamicValue.
+//
+// Independence is verified for nested reference values (maps, slices, pointers)
+// so the test exercises the deep-copy behavior rather than being a vacuous echo
+// of the input.
+func TestBranchCovCloneMetricValues(t *testing.T) {
+ t.Run("nil map returns nil", func(t *testing.T) {
+ if got := cloneMetricValues(nil); got != nil {
+ t.Fatalf("cloneMetricValues(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("empty non-nil map also returns nil", func(t *testing.T) {
+ // Distinct boundary from nil: an allocated-but-empty map still has
+ // len==0 and must collapse to nil via the same fast path.
+ if got := cloneMetricValues(map[string]interface{}{}); got != nil {
+ t.Fatalf("cloneMetricValues(empty) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("non-empty map is deep-copied and isolated", func(t *testing.T) {
+ src := map[string]interface{}{
+ "scalar": 42,
+ "nested": map[string]int{"x": 1},
+ "slice": []int{1, 2, 3},
+ "ptr": bcIntPtr(7),
+ "nilValue": nil,
+ }
+ got := cloneMetricValues(src)
+ if got == nil {
+ t.Fatal("non-empty input must return a non-nil map")
+ }
+ if len(got) != len(src) {
+ t.Fatalf("len = %d, want %d", len(got), len(src))
+ }
+
+ // Scalar values are preserved through the default arm of cloneDynamicValue.
+ if got["scalar"] != 42 {
+ t.Errorf("scalar = %v, want 42", got["scalar"])
+ }
+ // A nil-valued entry survives cloning (cloneDynamicValue(nil) -> nil,
+ // but the key must remain present in the destination map).
+ if _, ok := got["nilValue"]; !ok {
+ t.Error("nil-valued key was dropped during clone")
+ }
+
+ // Nested map independence: mutating the cloned inner map must not leak.
+ nestedGot := got["nested"].(map[string]int)
+ nestedGot["x"] = 999
+ if src["nested"].(map[string]int)["x"] != 1 {
+ t.Error("mutating cloned nested map affected source")
+ }
+
+ // Slice independence.
+ sliceGot := got["slice"].([]int)
+ sliceGot[0] = 999
+ if src["slice"].([]int)[0] != 1 {
+ t.Error("mutating cloned nested slice affected source")
+ }
+
+ // Pointer independence.
+ *got["ptr"].(*int) = 999
+ if *src["ptr"].(*int) != 7 {
+ t.Error("mutating cloned nested pointer affected source")
+ }
+
+ // Top-level map independence: adding a key to the clone must not leak.
+ got["new"] = "added"
+ if _, ok := src["new"]; ok {
+ t.Error("mutating cloned top-level map affected source")
+ }
+ })
+}
+
+// TestBranchCovCloneDynamicValue covers every arm and sub-branch of
+// cloneDynamicValue:
+// - the top-level `value == nil` guard (untyped nil interface),
+// - reflect.Map arm: typed-nil map (returns original) AND a populated map
+// (deep-copied with independence),
+// - reflect.Slice arm: typed-nil slice (returns original) AND a populated
+// slice (deep-copied with independence, including a nil element),
+// - reflect.Pointer arm: typed-nil pointer (returns original) AND a populated
+// pointer (deep-copied with independence),
+// - the default arm for primitive/scalar values.
+//
+// The typed-nil cases are distinct from the untyped-nil guard because a typed
+// nil wrapped in an interface is itself non-nil; only the inner IsNil() check
+// catches it.
+func TestBranchCovCloneDynamicValue(t *testing.T) {
+ // Branch: untyped nil interface -> nil.
+ if got := cloneDynamicValue(nil); got != nil {
+ t.Fatalf("cloneDynamicValue(nil) = %#v, want nil", got)
+ }
+
+ // --- Default arm: scalars are returned as-is. ---
+ for _, tc := range []struct {
+ name string
+ value interface{}
+ }{
+ {"int", 42},
+ {"string", "hello"},
+ {"bool", true},
+ {"float64", 3.5},
+ } {
+ t.Run("default/"+tc.name, func(t *testing.T) {
+ got := cloneDynamicValue(tc.value)
+ if got != tc.value {
+ t.Fatalf("cloneDynamicValue(%v) = %#v, want %#v", tc.value, got, tc.value)
+ }
+ })
+ }
+
+ // --- Map arm. ---
+ t.Run("map/typed-nil map returns original", func(t *testing.T) {
+ var nilMap map[string]int // typed nil, non-nil interface
+ got := cloneDynamicValue(nilMap)
+ rv := reflect.ValueOf(got)
+ if rv.Kind() != reflect.Map {
+ t.Fatalf("kind = %v, want Map", rv.Kind())
+ }
+ if !rv.IsNil() {
+ t.Fatal("typed-nil map must be returned as a nil map, not deep-copied")
+ }
+ })
+
+ t.Run("map/populated map is deep-copied and isolated", func(t *testing.T) {
+ src := map[string]interface{}{
+ "k": map[string]int{"x": 1},
+ }
+ got := cloneDynamicValue(src)
+ gotMap, ok := got.(map[string]interface{})
+ if !ok {
+ t.Fatalf("result type = %T, want map[string]interface{}", got)
+ }
+ inner := gotMap["k"].(map[string]int)
+ inner["x"] = 999
+ if src["k"].(map[string]int)["x"] != 1 {
+ t.Error("mutating cloned nested map value affected source map")
+ }
+ // Mutating the top-level cloned map must not affect the source.
+ gotMap["extra"] = 1
+ if _, leak := src["extra"]; leak {
+ t.Error("mutating cloned top-level map affected source map")
+ }
+ })
+
+ t.Run("map/element-type conversion via valueForType", func(t *testing.T) {
+ // A map whose element type is a concrete numeric type exercises the
+ // valueForType call site inside the Map arm: the cloned dynamic value
+ // (an int) is assignable to the element type (int) and is set directly.
+ src := map[string]int{"a": 1, "b": 2}
+ got := cloneDynamicValue(src)
+ gotMap, ok := got.(map[string]int)
+ if !ok {
+ t.Fatalf("result type = %T, want map[string]int", got)
+ }
+ if len(gotMap) != 2 || gotMap["a"] != 1 || gotMap["b"] != 2 {
+ t.Errorf("cloned map = %#v, want {a:1,b:2}", gotMap)
+ }
+ gotMap["a"] = 99
+ if src["a"] != 1 {
+ t.Error("mutating cloned int-typed map affected source")
+ }
+ })
+
+ // --- Slice arm. ---
+ t.Run("slice/typed-nil slice returns original", func(t *testing.T) {
+ var nilSlice []int // typed nil, non-nil interface
+ got := cloneDynamicValue(nilSlice)
+ rv := reflect.ValueOf(got)
+ if rv.Kind() != reflect.Slice {
+ t.Fatalf("kind = %v, want Slice", rv.Kind())
+ }
+ if !rv.IsNil() {
+ t.Fatal("typed-nil slice must be returned as a nil slice, not deep-copied")
+ }
+ })
+
+ t.Run("slice/populated slice is deep-copied and isolated", func(t *testing.T) {
+ src := []interface{}{
+ map[string]int{"x": 1},
+ []int{2, 3},
+ nil, // nil element exercises cloneDynamicValue(nil) within recursion
+ 4,
+ }
+ got := cloneDynamicValue(src)
+ gotSlice, ok := got.([]interface{})
+ if !ok {
+ t.Fatalf("result type = %T, want []interface{}", got)
+ }
+ if len(gotSlice) != len(src) {
+ t.Fatalf("len = %d, want %d", len(gotSlice), len(src))
+ }
+
+ // Element 0: nested map independence.
+ gotSlice[0].(map[string]int)["x"] = 999
+ if src[0].(map[string]int)["x"] != 1 {
+ t.Error("mutating cloned nested map inside slice affected source")
+ }
+ // Element 1: nested slice independence.
+ gotSlice[1].([]int)[0] = 999
+ if src[1].([]int)[0] != 2 {
+ t.Error("mutating cloned nested slice inside slice affected source")
+ }
+ // Element 2: nil element preserved.
+ if gotSlice[2] != nil {
+ t.Errorf("nil element = %#v, want nil", gotSlice[2])
+ }
+ // Element 3: scalar element preserved.
+ if gotSlice[3] != 4 {
+ t.Errorf("scalar element = %v, want 4", gotSlice[3])
+ }
+ })
+
+ t.Run("slice/concrete element type", func(t *testing.T) {
+ // A []int exercises valueForType's AssignableTo path inside the Slice
+ // arm (element type int, cloned dynamic value is int).
+ src := []int{10, 20, 30}
+ got := cloneDynamicValue(src)
+ gotSlice, ok := got.([]int)
+ if !ok {
+ t.Fatalf("result type = %T, want []int", got)
+ }
+ gotSlice[0] = 999
+ if src[0] != 10 {
+ t.Error("mutating cloned []int affected source")
+ }
+ })
+
+ // --- Pointer arm. ---
+ t.Run("pointer/typed-nil pointer returns original", func(t *testing.T) {
+ var nilPtr *int // typed nil, non-nil interface
+ got := cloneDynamicValue(nilPtr)
+ rv := reflect.ValueOf(got)
+ if rv.Kind() != reflect.Ptr {
+ t.Fatalf("kind = %v, want Ptr", rv.Kind())
+ }
+ if !rv.IsNil() {
+ t.Fatal("typed-nil pointer must be returned as a nil pointer, not deep-copied")
+ }
+ })
+
+ t.Run("pointer/populated pointer is deep-copied and isolated", func(t *testing.T) {
+ v := 5
+ src := &v
+ got := cloneDynamicValue(src)
+ gotPtr, ok := got.(*int)
+ if !ok {
+ t.Fatalf("result type = %T, want *int", got)
+ }
+ if gotPtr == src {
+ t.Fatal("cloned pointer aliases the source pointer; expected a distinct allocation")
+ }
+ if *gotPtr != 5 {
+ t.Errorf("cloned pointed-to value = %d, want 5", *gotPtr)
+ }
+ *gotPtr = 999
+ if *src != 5 {
+ t.Error("mutating cloned pointer's target affected source pointer")
+ }
+ })
+}
+
+// TestBranchCovValueForType covers every branch of valueForType in isolation:
+// - value == nil -> reflect.Zero(targetType) (for both a value type and a
+// pointer type, whose zero is a nil pointer),
+// - AssignableTo -> the value returned unchanged,
+// - ConvertibleTo-but-not-AssignableTo -> result.Convert(targetType),
+// - neither assignable nor convertible -> reflect.Zero(targetType) fallback.
+func TestBranchCovValueForType(t *testing.T) {
+ intType := reflect.TypeOf(int(0))
+ float64Type := reflect.TypeOf(float64(0))
+ ptrIntType := reflect.TypeOf((*int)(nil))
+
+ for _, tc := range []struct {
+ name string
+ targetType reflect.Type
+ value interface{}
+ validate func(t *testing.T, rv reflect.Value)
+ }{
+ {
+ name: "nil value yields zero int",
+ targetType: intType,
+ value: nil,
+ validate: func(t *testing.T, rv reflect.Value) {
+ if rv.Kind() != reflect.Int || rv.Int() != 0 {
+ t.Fatalf("got %v (kind %v), want zero int", rv, rv.Kind())
+ }
+ },
+ },
+ {
+ name: "nil value yields nil pointer of target type",
+ targetType: ptrIntType,
+ value: nil,
+ validate: func(t *testing.T, rv reflect.Value) {
+ if rv.Kind() != reflect.Ptr || !rv.IsNil() {
+ t.Fatalf("got %v (kind %v), want nil *int", rv, rv.Kind())
+ }
+ },
+ },
+ {
+ name: "assignable: int value to int target",
+ targetType: intType,
+ value: 7,
+ validate: func(t *testing.T, rv reflect.Value) {
+ if rv.Kind() != reflect.Int || rv.Int() != 7 {
+ t.Fatalf("got %v, want int 7", rv)
+ }
+ },
+ },
+ {
+ name: "convertible: int value to float64 target via Convert",
+ targetType: float64Type,
+ value: 3, // int not assignable to float64, but convertible
+ validate: func(t *testing.T, rv reflect.Value) {
+ if rv.Kind() != reflect.Float64 || rv.Float() != 3.0 {
+ t.Fatalf("got %v, want float64 3.0", rv)
+ }
+ },
+ },
+ {
+ name: "neither assignable nor convertible: string to int yields zero",
+ targetType: intType,
+ value: "hello", // string not assignable nor convertible to int
+ validate: func(t *testing.T, rv reflect.Value) {
+ if rv.Kind() != reflect.Int || rv.Int() != 0 {
+ t.Fatalf("got %v, want zero int fallback", rv)
+ }
+ },
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tc.validate(t, valueForType(tc.targetType, tc.value))
+ })
+ }
+}
+
+// TestBranchCovCloneMetric covers cloneMetric end to end:
+// - the nil/empty Values path, which must surface NormalizeCollections'
+// guarantee that a cloned Metric never has a nil Values map,
+// - deep-copy independence of nested reference values within Values,
+// - preservation of the scalar (non-collection) fields Timestamp/Type/ID.
+func TestBranchCovCloneMetric(t *testing.T) {
+ ts := time.Date(2024, 1, 2, 3, 4, 5, 0, time.UTC)
+
+ t.Run("nil Values normalized to non-nil empty map", func(t *testing.T) {
+ src := Metric{Timestamp: ts, Type: "cpu", ID: "m1", Values: nil}
+ got := cloneMetric(src)
+ if got.Values == nil {
+ t.Fatal("cloneMetric must normalize nil Values to a non-nil map")
+ }
+ if len(got.Values) != 0 {
+ t.Fatalf("len(Values) = %d, want 0", len(got.Values))
+ }
+ })
+
+ t.Run("empty Values map normalized to non-nil empty map", func(t *testing.T) {
+ // cloneMetricValues collapses the empty map to nil; NormalizeCollections
+ // must then re-materialize an empty (non-nil) map.
+ src := Metric{Timestamp: ts, Type: "cpu", ID: "m1", Values: map[string]interface{}{}}
+ got := cloneMetric(src)
+ if got.Values == nil {
+ t.Fatal("cloneMetric must normalize empty Values to a non-nil map")
+ }
+ if len(got.Values) != 0 {
+ t.Fatalf("len(Values) = %d, want 0", len(got.Values))
+ }
+ })
+
+ t.Run("scalar fields preserved", func(t *testing.T) {
+ src := Metric{Timestamp: ts, Type: "mem", ID: "m2", Values: map[string]interface{}{"u": 1.0}}
+ got := cloneMetric(src)
+ if !got.Timestamp.Equal(ts) {
+ t.Errorf("Timestamp = %v, want %v", got.Timestamp, ts)
+ }
+ if got.Type != "mem" {
+ t.Errorf("Type = %q, want %q", got.Type, "mem")
+ }
+ if got.ID != "m2" {
+ t.Errorf("ID = %q, want %q", got.ID, "m2")
+ }
+ })
+
+ t.Run("nested values are deep-copied and isolated", func(t *testing.T) {
+ src := Metric{
+ Timestamp: ts,
+ Type: "disk",
+ ID: "m3",
+ Values: map[string]interface{}{
+ "nested": map[string]int{"x": 1},
+ "slice": []int{1, 2},
+ "ptr": bcIntPtr(7),
+ },
+ }
+ got := cloneMetric(src)
+
+ // Nested map independence.
+ got.Values["nested"].(map[string]int)["x"] = 999
+ if src.Values["nested"].(map[string]int)["x"] != 1 {
+ t.Error("mutating cloned Metric nested map affected source Metric")
+ }
+
+ // Nested slice independence.
+ got.Values["slice"].([]int)[0] = 999
+ if src.Values["slice"].([]int)[0] != 1 {
+ t.Error("mutating cloned Metric nested slice affected source Metric")
+ }
+
+ // Nested pointer independence.
+ *got.Values["ptr"].(*int) = 999
+ if *src.Values["ptr"].(*int) != 7 {
+ t.Error("mutating cloned Metric nested pointer affected source Metric")
+ }
+
+ // Top-level Values map independence.
+ got.Values["added"] = true
+ if _, leak := src.Values["added"]; leak {
+ t.Error("mutating cloned Metric Values map affected source Metric")
+ }
+ })
+}
diff --git a/internal/models/models_removed_hosts_branchcov0716_test.go b/internal/models/models_removed_hosts_branchcov0716_test.go
new file mode 100644
index 0000000000..722311f31a
--- /dev/null
+++ b/internal/models/models_removed_hosts_branchcov0716_test.go
@@ -0,0 +1,352 @@
+package models
+
+import (
+ "testing"
+ "time"
+)
+
+// TestBranchCovAddRemovedHostAgent exercises both arms of the replace-vs-append
+// decision and the descending RemovedAt sort performed by AddRemovedHostAgent:
+// - append branch (replaced == false): empty slice and no-match among entries
+// - replace branch (replaced == true, break): existing ID is overwritten in place
+// - sort.Slice comparator: entries end up newest-first by RemovedAt
+// - replace does not grow the slice
+func TestBranchCovAddRemovedHostAgent(t *testing.T) {
+ t.Run("append branch on empty slice", func(t *testing.T) {
+ state := NewState()
+ now := time.Now()
+ entry := RemovedHostAgent{ID: "a-1", Hostname: "h1", RemovedAt: now}
+
+ state.AddRemovedHostAgent(entry)
+
+ got := state.GetRemovedHostAgents()
+ if len(got) != 1 {
+ t.Fatalf("len = %d, want 1", len(got))
+ }
+ if got[0].ID != "a-1" || got[0].Hostname != "h1" {
+ t.Fatalf("stored entry = %+v, want ID a-1 / Hostname h1", got[0])
+ }
+ if !got[0].RemovedAt.Equal(now) {
+ t.Fatalf("RemovedAt = %v, want %v", got[0].RemovedAt, now)
+ }
+ if state.LastUpdate.IsZero() {
+ t.Fatalf("AddRemovedHostAgent did not set LastUpdate")
+ }
+ })
+
+ t.Run("append branch when no existing ID matches", func(t *testing.T) {
+ state := NewState()
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "a-1", RemovedAt: t0})
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "a-2", RemovedAt: t0.Add(time.Hour)})
+
+ // Third add with an ID that matches neither existing entry must take
+ // the append branch; the loop runs but never sets replaced=true.
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "a-3", RemovedAt: t0.Add(2 * time.Hour)})
+
+ got := state.GetRemovedHostAgents()
+ if len(got) != 3 {
+ t.Fatalf("len = %d, want 3", len(got))
+ }
+ })
+
+ t.Run("replace branch overwrites existing ID in place", func(t *testing.T) {
+ state := NewState()
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "a-1", Hostname: "old", RemovedAt: t0})
+
+ // Same ID -> replace branch: slice must not grow, fields updated.
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "a-1", Hostname: "new", RemovedAt: t0.Add(time.Hour)})
+
+ got := state.GetRemovedHostAgents()
+ if len(got) != 1 {
+ t.Fatalf("replace grew slice: len = %d, want 1", len(got))
+ }
+ if got[0].Hostname != "new" {
+ t.Fatalf("entry not replaced: Hostname = %q, want %q", got[0].Hostname, "new")
+ }
+ if !got[0].RemovedAt.Equal(t0.Add(time.Hour)) {
+ t.Fatalf("RemovedAt not replaced: got %v", got[0].RemovedAt)
+ }
+ })
+
+ t.Run("sort keeps entries newest-first by RemovedAt", func(t *testing.T) {
+ state := NewState()
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+
+ // Insert in ascending (oldest first) order; sort must reverse to descending.
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "old", RemovedAt: t0})
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "mid", RemovedAt: t0.Add(time.Hour)})
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "new", RemovedAt: t0.Add(2 * time.Hour)})
+
+ got := state.GetRemovedHostAgents()
+ if len(got) != 3 {
+ t.Fatalf("len = %d, want 3", len(got))
+ }
+ wantOrder := []string{"new", "mid", "old"}
+ for i, w := range wantOrder {
+ if got[i].ID != w {
+ t.Fatalf("pos %d ID = %q, want %q (order=%v)", i, got[i].ID, w, ids(got))
+ }
+ }
+ })
+
+ t.Run("replace re-sorts using the new RemovedAt", func(t *testing.T) {
+ state := NewState()
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "a", RemovedAt: t0})
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "b", RemovedAt: t0.Add(time.Hour)})
+
+ // Replace "a" with a newer timestamp than "b"; after re-sort it must lead.
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "a", RemovedAt: t0.Add(2 * time.Hour)})
+
+ got := state.GetRemovedHostAgents()
+ if len(got) != 2 {
+ t.Fatalf("len = %d, want 2", len(got))
+ }
+ if got[0].ID != "a" || got[1].ID != "b" {
+ t.Fatalf("post-replace order = %v, want [a b]", ids(got))
+ }
+ })
+}
+
+// TestBranchCovRemoveRemovedHostAgent covers:
+// - match branch: existing ID removed, slice shrinks, LastUpdate refreshed
+// - no-match branch: unknown ID on non-empty list is a no-op (LastUpdate untouched)
+// - empty list: no iteration, no panic
+// - first-match-only: break removes exactly one matching entry
+func TestBranchCovRemoveRemovedHostAgent(t *testing.T) {
+ t.Run("match branch removes entry and refreshes LastUpdate", func(t *testing.T) {
+ state := NewState()
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "a-1", RemovedAt: t0})
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "a-2", RemovedAt: t0.Add(time.Hour)})
+
+ before := state.LastUpdate
+ // Ensure time advances so a new LastUpdate would be distinguishable.
+ time.Sleep(2 * time.Millisecond)
+ state.RemoveRemovedHostAgent("a-1")
+
+ got := state.GetRemovedHostAgents()
+ if len(got) != 1 {
+ t.Fatalf("len = %d, want 1", len(got))
+ }
+ if got[0].ID != "a-2" {
+ t.Fatalf("remaining ID = %q, want %q", got[0].ID, "a-2")
+ }
+ if !state.LastUpdate.After(before) {
+ t.Fatalf("LastUpdate not refreshed on remove: before=%v after=%v", before, state.LastUpdate)
+ }
+ })
+
+ t.Run("no-match branch is a no-op on non-empty list", func(t *testing.T) {
+ state := NewState()
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "a-1", RemovedAt: t0})
+
+ before := state.LastUpdate
+ state.RemoveRemovedHostAgent("does-not-exist")
+
+ got := state.GetRemovedHostAgents()
+ if len(got) != 1 {
+ t.Fatalf("no-match remove changed length: len = %d, want 1", len(got))
+ }
+ if got[0].ID != "a-1" {
+ t.Fatalf("entry changed unexpectedly: ID = %q", got[0].ID)
+ }
+ if state.LastUpdate != before {
+ t.Fatalf("no-match remove touched LastUpdate: before=%v after=%v", before, state.LastUpdate)
+ }
+ })
+
+ t.Run("empty list does not panic and leaves nothing to remove", func(t *testing.T) {
+ state := NewState()
+
+ // Must not panic on a zero-length loop.
+ state.RemoveRemovedHostAgent("anything")
+
+ got := state.GetRemovedHostAgents()
+ if len(got) != 0 {
+ t.Fatalf("len = %d, want 0", len(got))
+ }
+ })
+
+ t.Run("removing down to empty across successive calls", func(t *testing.T) {
+ state := NewState()
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "a-1", RemovedAt: t0})
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "a-2", RemovedAt: t0.Add(time.Hour)})
+
+ state.RemoveRemovedHostAgent("a-1")
+ state.RemoveRemovedHostAgent("a-2")
+
+ got := state.GetRemovedHostAgents()
+ if len(got) != 0 {
+ t.Fatalf("len = %d, want 0 after removing all", len(got))
+ }
+ })
+}
+
+// TestBranchCovGetRemovedHostAgents covers:
+// - empty state returns a usable (non-nil) empty slice
+// - non-empty state returns a content- and length-equal copy
+// - the returned slice is a defensive copy: mutating it must not affect state
+func TestBranchCovGetRemovedHostAgents(t *testing.T) {
+ t.Run("empty state returns non-nil empty slice", func(t *testing.T) {
+ state := NewState()
+
+ got := state.GetRemovedHostAgents()
+ if got == nil {
+ t.Fatalf("got == nil, want non-nil empty slice (make([]T, 0))")
+ }
+ if len(got) != 0 {
+ t.Fatalf("len = %d, want 0", len(got))
+ }
+ })
+
+ t.Run("returns content- and order-equal copy", func(t *testing.T) {
+ state := NewState()
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "old", RemovedAt: t0})
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "new", RemovedAt: t0.Add(time.Hour)})
+
+ got := state.GetRemovedHostAgents()
+ if len(got) != 2 {
+ t.Fatalf("len = %d, want 2", len(got))
+ }
+ wantOrder := []string{"new", "old"}
+ for i, w := range wantOrder {
+ if got[i].ID != w {
+ t.Fatalf("pos %d ID = %q, want %q", i, got[i].ID, w)
+ }
+ }
+ })
+
+ t.Run("returned slice is isolated from internal state", func(t *testing.T) {
+ state := NewState()
+ t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+ state.AddRemovedHostAgent(RemovedHostAgent{ID: "a-1", Hostname: "h1", RemovedAt: t0})
+
+ first := state.GetRemovedHostAgents()
+ // Mutate the caller-owned copy in every way available.
+ first[0].ID = "mutated"
+ first[0].Hostname = "mutated"
+ first[0].RemovedAt = t0.Add(999 * time.Hour)
+ first[0].MachineID = "mutated-mid"
+
+ again := state.GetRemovedHostAgents()
+ if len(again) != 1 {
+ t.Fatalf("len = %d, want 1", len(again))
+ }
+ if again[0].ID != "a-1" || again[0].Hostname != "h1" || again[0].MachineID != "" {
+ t.Fatalf("internal state mutated via returned slice: %+v", again[0])
+ }
+ if !again[0].RemovedAt.Equal(t0) {
+ t.Fatalf("internal RemovedAt mutated via returned slice: %v", again[0].RemovedAt)
+ }
+ })
+}
+
+// TestBranchCovUpdatePollStats covers the unconditional assignment path of
+// UpdatePollStats, which has no validation branch, plus the accumulation vs.
+// overwrite semantics of its fields and the fact that it deliberately does
+// NOT refresh LastUpdate (unlike Add/Remove).
+func TestBranchCovUpdatePollStats(t *testing.T) {
+ t.Run("writes all four fields from zero baseline", func(t *testing.T) {
+ state := NewState()
+
+ state.UpdatePollStats(12.5, int64(3600), 3)
+
+ if got := state.Stats.PollingCycles; got != 1 {
+ t.Fatalf("PollingCycles = %d, want 1 (first cycle)", got)
+ }
+ if got := state.Performance.LastPollDuration; got != 12.5 {
+ t.Fatalf("LastPollDuration = %v, want 12.5", got)
+ }
+ if got := state.Stats.Uptime; got != int64(3600) {
+ t.Fatalf("Uptime = %d, want 3600", got)
+ }
+ if got := state.Stats.WebSocketClients; got != 3 {
+ t.Fatalf("WebSocketClients = %d, want 3", got)
+ }
+ })
+
+ t.Run("zero values are stored as-is (no guard branch)", func(t *testing.T) {
+ state := NewState()
+
+ state.UpdatePollStats(0, int64(0), 0)
+
+ if state.Performance.LastPollDuration != 0 {
+ t.Fatalf("LastPollDuration = %v, want 0", state.Performance.LastPollDuration)
+ }
+ if state.Stats.Uptime != 0 {
+ t.Fatalf("Uptime = %d, want 0", state.Stats.Uptime)
+ }
+ if state.Stats.WebSocketClients != 0 {
+ t.Fatalf("WebSocketClients = %d, want 0", state.Stats.WebSocketClients)
+ }
+ if state.Stats.PollingCycles != 1 {
+ t.Fatalf("PollingCycles = %d, want 1", state.Stats.PollingCycles)
+ }
+ })
+
+ t.Run("negative values are stored as-is (no validation branch)", func(t *testing.T) {
+ state := NewState()
+
+ // There is no guard against nonsensical inputs; the function assigns them.
+ state.UpdatePollStats(-7.25, int64(-100), -2)
+
+ if state.Performance.LastPollDuration != -7.25 {
+ t.Fatalf("LastPollDuration = %v, want -7.25", state.Performance.LastPollDuration)
+ }
+ if state.Stats.Uptime != -100 {
+ t.Fatalf("Uptime = %d, want -100", state.Stats.Uptime)
+ }
+ if state.Stats.WebSocketClients != -2 {
+ t.Fatalf("WebSocketClients = %d, want -2", state.Stats.WebSocketClients)
+ }
+ })
+
+ t.Run("PollingCycles accumulates while other fields overwrite", func(t *testing.T) {
+ state := NewState()
+
+ state.UpdatePollStats(1.0, int64(10), 1)
+ state.UpdatePollStats(2.0, int64(20), 2)
+ state.UpdatePollStats(3.0, int64(30), 3)
+
+ if state.Stats.PollingCycles != 3 {
+ t.Fatalf("PollingCycles = %d, want 3 (accumulates)", state.Stats.PollingCycles)
+ }
+ // These three are overwritten each call, not accumulated.
+ if state.Performance.LastPollDuration != 3.0 {
+ t.Fatalf("LastPollDuration = %v, want 3.0 (last value)", state.Performance.LastPollDuration)
+ }
+ if state.Stats.Uptime != int64(30) {
+ t.Fatalf("Uptime = %d, want 30 (last value)", state.Stats.Uptime)
+ }
+ if state.Stats.WebSocketClients != 3 {
+ t.Fatalf("WebSocketClients = %d, want 3 (last value)", state.Stats.WebSocketClients)
+ }
+ })
+
+ t.Run("does not refresh LastUpdate", func(t *testing.T) {
+ state := NewState()
+ before := state.LastUpdate
+
+ state.UpdatePollStats(5.0, int64(5), 5)
+
+ if state.LastUpdate != before {
+ t.Fatalf("UpdatePollStats modified LastUpdate: before=%v after=%v", before, state.LastUpdate)
+ }
+ })
+}
+
+// ids is a small helper that flattens a slice of RemovedHostAgent to its IDs,
+// used only to produce readable failure messages.
+func ids(entries []RemovedHostAgent) []string {
+ out := make([]string, len(entries))
+ for i, e := range entries {
+ out[i] = e.ID
+ }
+ return out
+}
diff --git a/pkg/aicontracts/aicontracts_safety_branchcov0716_test.go b/pkg/aicontracts/aicontracts_safety_branchcov0716_test.go
new file mode 100644
index 0000000000..db31a3069d
--- /dev/null
+++ b/pkg/aicontracts/aicontracts_safety_branchcov0716_test.go
@@ -0,0 +1,284 @@
+package aicontracts
+
+import "testing"
+
+// TestBranchCovIsDestructiveCommand exercises IsDestructiveCommand directly.
+// IsDestructiveCommand delegates to IsBlockedCommand, whose branches are:
+// the empty-input early return, the per-pattern substring match (hit), and
+// the fall-through no-match return. It also depends on normalizeCommandForCheck
+// (quote/escape stripping + whitespace collapsing) and case folding, all of
+// which are covered here with inputs the sibling ClassifyAutomationRisk test
+// never reaches directly.
+func TestBranchCovIsDestructiveCommand(t *testing.T) {
+ tests := []struct {
+ name string
+ command string
+ want bool
+ }{
+ {
+ name: "empty input short circuits to false",
+ command: "",
+ want: false,
+ },
+ {
+ name: "direct blocked pattern match returns true",
+ command: "rm -rf /tmp/pulse-data",
+ want: true,
+ },
+ {
+ name: "benign command falls through all patterns to false",
+ command: "uptime",
+ want: false,
+ },
+ {
+ name: "uppercase blocked pattern still matches case insensitively",
+ command: "RM -RF /x",
+ want: true,
+ },
+ {
+ name: "single quoted command word is normalized before matching",
+ command: "'rm' -rf /x",
+ want: true,
+ },
+ {
+ name: "double quoted token is normalized before matching",
+ command: `"shutdown" now`,
+ want: true,
+ },
+ {
+ name: "backslash escaped command is normalized before matching",
+ command: `\rm -rf /x`,
+ want: true,
+ },
+ {
+ name: "backtick wrapped command is normalized before matching",
+ command: "`mkfs`",
+ want: true,
+ },
+ {
+ name: "tab between flag tokens collapses to single space then matches",
+ command: "rm\t-rf /x",
+ want: true,
+ },
+ {
+ name: "runs of spaces collapse to single space then match",
+ command: "rm -rf /x",
+ want: true,
+ },
+ {
+ name: "sql drop table matches case insensitively inside quoted arg",
+ command: "psql -c 'drop table users'",
+ want: true,
+ },
+ {
+ name: "substring overmatch flags benign word containing blocked token",
+ command: "echo information",
+ want: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := IsDestructiveCommand(tt.command); got != tt.want {
+ t.Fatalf("IsDestructiveCommand(%q) = %v, want %v", tt.command, got, tt.want)
+ }
+ })
+ }
+}
+
+// TestBranchCovIsReadOnlyPart exercises isReadOnlyPart directly. Its branches
+// are the per-pattern prefix match (hit) and the fall-through no-match return.
+// It folds case and trims leading/trailing whitespace before matching.
+func TestBranchCovIsReadOnlyPart(t *testing.T) {
+ tests := []struct {
+ name string
+ cmd string
+ want bool
+ }{
+ {
+ name: "empty input matches no pattern",
+ cmd: "",
+ want: false,
+ },
+ {
+ name: "whitespace only trims to empty and matches nothing",
+ cmd: " ",
+ want: false,
+ },
+ {
+ name: "prefixed pattern with trailing space variant matches",
+ cmd: "ls -la",
+ want: true,
+ },
+ {
+ name: "bare single token pattern matches",
+ cmd: "ls",
+ want: true,
+ },
+ {
+ name: "case insensitive prefix match",
+ cmd: "LS -LA",
+ want: true,
+ },
+ {
+ name: "leading whitespace is trimmed before prefix match",
+ cmd: " cat /etc/hosts",
+ want: true,
+ },
+ {
+ name: "bare env token pattern matches",
+ cmd: "env",
+ want: true,
+ },
+ {
+ name: "non read only command falls through to false",
+ cmd: "rm -rf /tmp",
+ want: false,
+ },
+ {
+ name: "command sharing no read only prefix is false",
+ cmd: "vim /etc/hosts",
+ want: false,
+ },
+ {
+ name: "single char w pattern overmatches commands starting with w",
+ cmd: "wget -O- http://example/payload",
+ want: true,
+ },
+ {
+ name: "env pattern overmatches command prefixed with env",
+ cmd: "environment-frobber --delete-everything",
+ want: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := isReadOnlyPart(tt.cmd); got != tt.want {
+ t.Fatalf("isReadOnlyPart(%q) = %v, want %v", tt.cmd, got, tt.want)
+ }
+ })
+ }
+}
+
+// TestBranchCovIsSafePipeCommand exercises isSafePipeCommand directly. Its
+// branches are: per-pattern prefix match (hit, return true), the special case
+// where a matched command is sed and contains -i (return false), and the
+// fall-through no-match return. Case folding and whitespace trimming precede
+// matching.
+func TestBranchCovIsSafePipeCommand(t *testing.T) {
+ tests := []struct {
+ name string
+ cmd string
+ want bool
+ }{
+ {
+ name: "empty input matches no pattern",
+ cmd: "",
+ want: false,
+ },
+ {
+ name: "whitespace only trims to empty and matches nothing",
+ cmd: " ",
+ want: false,
+ },
+ {
+ name: "grep prefix matches",
+ cmd: "grep foo",
+ want: true,
+ },
+ {
+ name: "fgrep with i flag is not treated like sed in place",
+ cmd: "fgrep -i foo",
+ want: true,
+ },
+ {
+ name: "sed without in place flag is safe",
+ cmd: "sed 's/a/b/'",
+ want: true,
+ },
+ {
+ name: "sed bare token with no flag is safe",
+ cmd: "sed",
+ want: true,
+ },
+ {
+ name: "sed with short in place flag is rejected",
+ cmd: "sed -i.bak file",
+ want: false,
+ },
+ {
+ name: "sed with long in place flag rejected via i substring",
+ cmd: "sed --in-place file",
+ want: false,
+ },
+ {
+ name: "uppercase sed with in place flag still rejected after fold",
+ cmd: "SED -I file",
+ want: false,
+ },
+ {
+ name: "sort with flags matches",
+ cmd: "sort -u",
+ want: true,
+ },
+ {
+ name: "wc token matches",
+ cmd: "wc -l",
+ want: true,
+ },
+ {
+ name: "tee to dev null multi word pattern matches",
+ cmd: "tee /dev/null",
+ want: true,
+ },
+ {
+ name: "tee to real file is not in safe pattern set",
+ cmd: "tee /tmp/log",
+ want: false,
+ },
+ {
+ name: "xargs echo multi word pattern matches",
+ cmd: "xargs echo",
+ want: true,
+ },
+ {
+ name: "xargs with destructive payload is not the safe variant",
+ cmd: "xargs rm",
+ want: false,
+ },
+ {
+ name: "read only command not in pipe safe set is rejected",
+ cmd: "cat foo",
+ want: false,
+ },
+ {
+ name: "non pipe safe command falls through to false",
+ cmd: "curl http://example",
+ want: false,
+ },
+ {
+ name: "case insensitive prefix match",
+ cmd: "GREP foo",
+ want: true,
+ },
+ {
+ name: "leading whitespace trimmed before prefix match",
+ cmd: " head -5",
+ want: true,
+ },
+ {
+ name: "awk in place edit is classified safe despite being destructive",
+ cmd: "awk -i inplace file",
+ want: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := isSafePipeCommand(tt.cmd); got != tt.want {
+ t.Fatalf("isSafePipeCommand(%q) = %v, want %v", tt.cmd, got, tt.want)
+ }
+ })
+ }
+}
diff --git a/pkg/securityutil/securityutil_websocket_origin_branchcov0716_test.go b/pkg/securityutil/securityutil_websocket_origin_branchcov0716_test.go
new file mode 100644
index 0000000000..59a73052bf
--- /dev/null
+++ b/pkg/securityutil/securityutil_websocket_origin_branchcov0716_test.go
@@ -0,0 +1,209 @@
+package securityutil
+
+import (
+ "strings"
+ "testing"
+)
+
+// These tests target the websocket-origin helpers in websocket_origin.go:
+// NormalizeWebSocketOriginHost, SameHostWebSocketOrigin,
+// HTTPOriginForWebSocketBaseURL, and HTTPOriginForWebSocketBaseURLWithOptions.
+// They exercise both sides of each conditional, the switch arms, error paths,
+// and boundary/empty inputs against the package's real exported functions.
+
+func TestBranchCovNormalizeWebSocketOriginHost(t *testing.T) {
+ tests := []struct {
+ name string
+ host string
+ want string
+ }{
+ // Branch: empty after TrimSpace -> return "".
+ {name: "empty string", host: "", want: ""},
+ {name: "whitespace only", host: " ", want: ""},
+ {name: "tab newline only", host: "\t\n", want: ""},
+
+ // Branch: SplitHostPort error (no port) -> return lowercased+trimmed host.
+ {name: "plain host lowercased", host: "Example.COM", want: "example.com"},
+ {name: "plain host trimmed and lowercased", host: " Host.Example.COM ", want: "host.example.com"},
+
+ // Branch: port == "80" -> strip, return host only.
+ {name: "port 80 stripped", host: "example.com:80", want: "example.com"},
+ {name: "uppercase host port 80 stripped", host: "API.Example.COM:80", want: "api.example.com"},
+
+ // Branch: port == "443" -> strip, return host only.
+ {name: "port 443 stripped", host: "example.com:443", want: "example.com"},
+
+ // Branch: other port -> JoinHostPort(host, port).
+ {name: "nonstandard port kept", host: "example.com:8080", want: "example.com:8080"},
+ {name: "uppercase host nonstandard port", host: "API.Host:9000", want: "api.host:9000"},
+
+ // Boundary: "080" is not "80", so the port is preserved verbatim.
+ {name: "non canonical port string kept", host: "example.com:080", want: "example.com:080"},
+
+ // IPv6: JoinHostPort re-wraps in brackets.
+ {name: "ipv6 nonstandard port joined", host: "[::1]:8080", want: "[::1]:8080"},
+ {name: "ipv6 bracketed without port kept", host: "[::1]", want: "[::1]"},
+
+ // IPv6 with standard port: SplitHostPort returns the bare host without
+ // brackets, so the returned value loses its IPv6 bracketing. This is the
+ // actual current behavior (see report for the same-origin impact).
+ {name: "ipv6 port 80 loses brackets", host: "[::1]:80", want: "::1"},
+ {name: "ipv6 port 443 loses brackets", host: "[fe80::1]:443", want: "fe80::1"},
+
+ // Boundary: empty host with a port. SplitHostPort(":8080") succeeds with
+ // an empty host, so JoinHostPort reproduces ":8080"; ":80" strips to "".
+ {name: "empty host with nonstandard port", host: ":8080", want: ":8080"},
+ {name: "empty host with port 80 collapses to empty", host: ":80", want: ""},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := NormalizeWebSocketOriginHost(tt.host)
+ if got != tt.want {
+ t.Fatalf("NormalizeWebSocketOriginHost(%q) = %q, want %q", tt.host, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestBranchCovSameHostWebSocketOrigin(t *testing.T) {
+ tests := []struct {
+ name string
+ origin string
+ requestHost string
+ want bool
+ }{
+ // Branch: url.Parse error -> false. "%zz" is an invalid escape that
+ // url.Parse rejects (same input used elsewhere for parse-error coverage).
+ {name: "parse error invalid escape", origin: "http://host/%zz", requestHost: "host", want: false},
+
+ // Branch: parsed.Host == "" -> false.
+ {name: "empty origin", origin: "", requestHost: "example.com", want: false},
+ {name: "whitespace only origin", origin: " ", requestHost: "example.com", want: false},
+ {name: "scheme but empty host", origin: "http://", requestHost: "example.com", want: false},
+
+ // Branch: scheme not http/https -> false. Note ws/wss origins are rejected.
+ {name: "ftp scheme rejected", origin: "ftp://example.com", requestHost: "example.com", want: false},
+ {name: "ws scheme rejected", origin: "ws://localhost", requestHost: "localhost", want: false},
+ {name: "wss scheme rejected", origin: "wss://localhost", requestHost: "localhost", want: false},
+ {name: "file scheme rejected", origin: "file:///etc/passwd", requestHost: "localhost", want: false},
+
+ // Branch: http/https scheme, equal normalized hosts -> true.
+ {name: "https same host", origin: "https://example.com", requestHost: "example.com", want: true},
+ {name: "http same host", origin: "http://example.com", requestHost: "example.com", want: true},
+ {name: "scheme differs but host equal", origin: "https://example.com", requestHost: "example.com", want: true},
+ {name: "origin trimmed before parse", origin: " https://example.com ", requestHost: "example.com", want: true},
+ {name: "uppercase origin host matches", origin: "https://API.Example.COM", requestHost: "api.example.com", want: true},
+
+ // Integration: standard ports normalize away on both sides -> match.
+ {name: "origin port 80 equals bare host", origin: "http://example.com:80", requestHost: "example.com", want: true},
+ {name: "both standard port 443 match", origin: "https://example.com:443", requestHost: "example.com:443", want: true},
+
+ // Branch: normalized hosts differ -> false.
+ {name: "nonstandard port mismatch", origin: "http://example.com:8080", requestHost: "example.com", want: false},
+ {name: "host mismatch", origin: "https://example.com", requestHost: "evil.com", want: false},
+ {name: "both same nonstandard port match", origin: "http://example.com:9000", requestHost: "example.com:9000", want: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := SameHostWebSocketOrigin(tt.origin, tt.requestHost)
+ if got != tt.want {
+ t.Fatalf("SameHostWebSocketOrigin(%q, %q) = %v, want %v", tt.origin, tt.requestHost, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestBranchCovHTTPOriginForWebSocketBaseURL(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ wantErr string
+ want string
+ }{
+ // Delegating entrypoint: wss -> https.
+ {name: "wss to https", raw: "wss://example.com", want: "https://example.com"},
+ // ws over loopback -> http.
+ {name: "ws loopback to http", raw: "ws://localhost:8080", want: "http://localhost:8080"},
+ // https is upgraded to wss by the normalizer, then mapped to https.
+ {name: "https round trips to https", raw: "https://example.com", want: "https://example.com"},
+ // Error path delegated from the zero-option validator.
+ {name: "empty required", raw: " ", wantErr: "Pulse URL is required"},
+ {name: "non loopback http rejected", raw: "http://example.com", wantErr: "must use https/wss unless host is loopback"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := HTTPOriginForWebSocketBaseURL(tt.raw)
+ if tt.wantErr != "" {
+ if err == nil {
+ t.Fatalf("HTTPOriginForWebSocketBaseURL(%q) = %q, want error containing %q", tt.raw, got, tt.wantErr)
+ }
+ if !strings.Contains(err.Error(), tt.wantErr) {
+ t.Fatalf("HTTPOriginForWebSocketBaseURL(%q) err = %q, want substring %q", tt.raw, err.Error(), tt.wantErr)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("HTTPOriginForWebSocketBaseURL(%q) unexpected error: %v", tt.raw, err)
+ }
+ if got != tt.want {
+ t.Fatalf("HTTPOriginForWebSocketBaseURL(%q) = %q, want %q", tt.raw, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestBranchCovHTTPOriginForWebSocketBaseURLWithOptions(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ opts PulseURLValidationOptions
+ wantErr string
+ want string
+ }{
+ // switch arm "ws" -> "http".
+ {name: "ws maps to http", raw: "ws://localhost:8080", opts: PulseURLValidationOptions{}, want: "http://localhost:8080"},
+ // switch arm "wss" -> "https".
+ {name: "wss maps to https", raw: "wss://example.com", opts: PulseURLValidationOptions{}, want: "https://example.com"},
+ // https is normalized to wss upstream, then mapped back to https.
+ {name: "https normalized to wss then https", raw: "https://api.example.com", opts: PulseURLValidationOptions{}, want: "https://api.example.com"},
+
+ // The normalizer preserves a non-root path; this function must clear
+ // Path/RawPath/RawQuery/Fragment so only the bare origin remains.
+ {name: "path stripped to origin", raw: "wss://example.com/a/b", opts: PulseURLValidationOptions{}, want: "https://example.com"},
+ {name: "loopback ws path stripped to origin", raw: "ws://127.0.0.1/agent/feed", opts: PulseURLValidationOptions{}, want: "http://127.0.0.1"},
+
+ // opts flow through to the validator: AllowLocalNetworkHTTP permits
+ // plaintext to a private IPv4, which then maps ws -> http.
+ {name: "opts allow local network plaintext", raw: "http://192.168.1.5:9000", opts: PulseURLValidationOptions{AllowLocalNetworkHTTP: true}, want: "http://192.168.1.5:9000"},
+
+ // Error path: upstream normalization failure is returned as-is.
+ {name: "empty required", raw: "", opts: PulseURLValidationOptions{}, wantErr: "Pulse URL is required"},
+ {name: "missing scheme websocket message", raw: "example.com", opts: PulseURLValidationOptions{}, wantErr: "must include scheme"},
+ {name: "non loopback http without opts rejected", raw: "http://example.com", opts: PulseURLValidationOptions{}, wantErr: "must use https/wss unless host is loopback"},
+ {name: "unsupported scheme rejected upstream", raw: "ftp://host", opts: PulseURLValidationOptions{}, wantErr: "unsupported scheme"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := HTTPOriginForWebSocketBaseURLWithOptions(tt.raw, tt.opts)
+ if tt.wantErr != "" {
+ if err == nil {
+ t.Fatalf("HTTPOriginForWebSocketBaseURLWithOptions(%q) = %q, want error containing %q", tt.raw, got, tt.wantErr)
+ }
+ if !strings.Contains(err.Error(), tt.wantErr) {
+ t.Fatalf("HTTPOriginForWebSocketBaseURLWithOptions(%q) err = %q, want substring %q", tt.raw, err.Error(), tt.wantErr)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("HTTPOriginForWebSocketBaseURLWithOptions(%q) unexpected error: %v", tt.raw, err)
+ }
+ if got != tt.want {
+ t.Fatalf("HTTPOriginForWebSocketBaseURLWithOptions(%q) = %q, want %q", tt.raw, got, tt.want)
+ }
+ })
+ }
+}