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.

test: Add comprehensive tests for update detection system

rcourtman056f503516cf
diff --git a/internal/alerts/update_alerts_test.go b/internal/alerts/update_alerts_test.go
new file mode 100644
index 0000000000..b641218c76
--- /dev/null
+++ b/internal/alerts/update_alerts_test.go
@@ -0,0 +1,441 @@
+package alerts
+
+import (
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+// Helper to find an alert by ID in the active alerts list
+func findAlertByID(alerts []Alert, idPrefix string) *Alert {
+ for _, a := range alerts {
+ if a.ID == idPrefix || (len(a.ID) > len(idPrefix) && a.ID[:len(idPrefix)] == idPrefix[:min(len(idPrefix), len(a.ID))]) {
+ return &a
+ }
+ }
+ return nil
+}
+
+// Helper to check if an alert exists with the given ID prefix
+func hasAlertWithPrefix(alerts []Alert, prefix string) bool {
+ for _, a := range alerts {
+ if len(a.ID) >= len(prefix) && a.ID[:len(prefix)] == prefix {
+ return true
+ }
+ }
+ return false
+}
+
+func min(a, b int) int {
+ if a < b {
+ return a
+ }
+ return b
+}
+
+func TestCheckDockerContainerImageUpdate(t *testing.T) {
+ // Create a manager for testing
+ m := NewManager()
+
+ // Set the default delay hours - NewManager doesn't set this,
+ // it's normally set during config loading
+ m.mu.Lock()
+ m.config.DockerDefaults.UpdateAlertDelayHours = 24 // Default: alert after 24 hours
+ m.mu.Unlock()
+
+ hostID := "docker-host-1"
+ containerID := "container-abc123"
+ resourceID := "docker:" + hostID + "/" + containerID
+ containerName := "test-container"
+ instanceName := "docker-instance"
+ nodeName := "docker-node"
+
+ host := models.DockerHost{ID: hostID, DisplayName: "Test Host"}
+
+ t.Run("no update status - no alert", func(t *testing.T) {
+ container := models.DockerContainer{
+ ID: containerID,
+ Name: containerName,
+ Image: "nginx:latest",
+ UpdateStatus: nil,
+ }
+
+ m.checkDockerContainerImageUpdate(host, container, resourceID, containerName, instanceName, nodeName)
+
+ alerts := m.GetActiveAlerts()
+ if hasAlertWithPrefix(alerts, "docker-container-update-"+resourceID) {
+ t.Error("Expected no alert when UpdateStatus is nil")
+ }
+ })
+
+ t.Run("update not available - no alert", func(t *testing.T) {
+ container := models.DockerContainer{
+ ID: containerID,
+ Name: containerName,
+ Image: "nginx:latest",
+ UpdateStatus: &models.DockerContainerUpdateStatus{
+ UpdateAvailable: false,
+ CurrentDigest: "sha256:current",
+ LatestDigest: "sha256:current",
+ LastChecked: time.Now(),
+ },
+ }
+
+ m.checkDockerContainerImageUpdate(host, container, resourceID, containerName, instanceName, nodeName)
+
+ alerts := m.GetActiveAlerts()
+ if hasAlertWithPrefix(alerts, "docker-container-update-"+resourceID) {
+ t.Error("Expected no alert when update is not available")
+ }
+ })
+
+ t.Run("update detection error - no alert", func(t *testing.T) {
+ container := models.DockerContainer{
+ ID: containerID,
+ Name: containerName,
+ Image: "nginx:latest",
+ UpdateStatus: &models.DockerContainerUpdateStatus{
+ UpdateAvailable: false,
+ Error: "rate limited",
+ LastChecked: time.Now(),
+ },
+ }
+
+ m.checkDockerContainerImageUpdate(host, container, resourceID, containerName, instanceName, nodeName)
+
+ alerts := m.GetActiveAlerts()
+ if hasAlertWithPrefix(alerts, "docker-container-update-"+resourceID) {
+ t.Error("Expected no alert when there's an error in update detection")
+ }
+ })
+
+ t.Run("update available but not yet past threshold - no alert", func(t *testing.T) {
+ container := models.DockerContainer{
+ ID: containerID,
+ Name: containerName,
+ Image: "nginx:latest",
+ UpdateStatus: &models.DockerContainerUpdateStatus{
+ UpdateAvailable: true,
+ CurrentDigest: "sha256:olddigest",
+ LatestDigest: "sha256:newdigest",
+ LastChecked: time.Now(),
+ },
+ }
+
+ // First call - should record firstSeen but not alert yet
+ m.checkDockerContainerImageUpdate(host, container, resourceID, containerName, instanceName, nodeName)
+
+ alerts := m.GetActiveAlerts()
+ if hasAlertWithPrefix(alerts, "docker-container-update-"+resourceID) {
+ t.Error("Expected no alert when update just detected (threshold not reached)")
+ }
+
+ // Verify tracking is set
+ m.mu.RLock()
+ _, tracked := m.dockerUpdateFirstSeen[resourceID]
+ m.mu.RUnlock()
+ if !tracked {
+ t.Error("Expected update to be tracked in dockerUpdateFirstSeen")
+ }
+ })
+
+ t.Run("update available and past threshold - creates alert", func(t *testing.T) {
+ // Use a fresh resource ID for this test to avoid interference
+ testResourceID := "docker:" + hostID + "/container-threshold-test"
+
+ // Set up tracking as if we detected the update 25 hours ago
+ m.mu.Lock()
+ m.dockerUpdateFirstSeen[testResourceID] = time.Now().Add(-25 * time.Hour)
+ m.mu.Unlock()
+
+ container := models.DockerContainer{
+ ID: "container-threshold-test",
+ Name: "threshold-test-container",
+ Image: "nginx:latest",
+ UpdateStatus: &models.DockerContainerUpdateStatus{
+ UpdateAvailable: true,
+ CurrentDigest: "sha256:olddigest",
+ LatestDigest: "sha256:newdigest",
+ LastChecked: time.Now(),
+ },
+ }
+
+ m.checkDockerContainerImageUpdate(host, container, testResourceID, "threshold-test-container", instanceName, nodeName)
+
+ alerts := m.GetActiveAlerts()
+ found := false
+ for _, a := range alerts {
+ if a.Type == "docker-container-update" {
+ found = true
+ if a.Level != AlertLevelWarning {
+ t.Errorf("Expected level %q, got %q", AlertLevelWarning, a.Level)
+ }
+ break
+ }
+ }
+ if !found {
+ t.Error("Expected alert to be created after threshold")
+ }
+ })
+
+ t.Run("alert cleared when update applied", func(t *testing.T) {
+ // Use a fresh resource ID
+ testResourceID := "docker:" + hostID + "/container-clear-test"
+
+ // Set up an existing alert by triggering past threshold
+ m.mu.Lock()
+ m.dockerUpdateFirstSeen[testResourceID] = time.Now().Add(-25 * time.Hour)
+ m.mu.Unlock()
+
+ container := models.DockerContainer{
+ ID: "container-clear-test",
+ Name: "clear-test-container",
+ Image: "nginx:latest",
+ UpdateStatus: &models.DockerContainerUpdateStatus{
+ UpdateAvailable: true,
+ CurrentDigest: "sha256:olddigest",
+ LatestDigest: "sha256:newdigest",
+ LastChecked: time.Now(),
+ },
+ }
+
+ // First trigger the alert
+ m.checkDockerContainerImageUpdate(host, container, testResourceID, "clear-test-container", instanceName, nodeName)
+
+ // Now simulate container being updated
+ container.UpdateStatus = &models.DockerContainerUpdateStatus{
+ UpdateAvailable: false,
+ CurrentDigest: "sha256:newdigest",
+ LatestDigest: "sha256:newdigest",
+ LastChecked: time.Now(),
+ }
+
+ m.checkDockerContainerImageUpdate(host, container, testResourceID, "clear-test-container", instanceName, nodeName)
+
+ // Verify tracking is removed
+ m.mu.RLock()
+ _, tracked := m.dockerUpdateFirstSeen[testResourceID]
+ m.mu.RUnlock()
+ if tracked {
+ t.Error("Expected tracking to be removed when update is applied")
+ }
+ })
+
+ t.Run("disabled by negative delay hours", func(t *testing.T) {
+ // Create manager with disabled update alerts
+ m2 := NewManager()
+ m2.mu.Lock()
+ m2.config.DockerDefaults.UpdateAlertDelayHours = -1 // Disable
+ m2.mu.Unlock()
+
+ testResourceID := "docker:" + hostID + "/container-disabled-test"
+
+ container := models.DockerContainer{
+ ID: "container-disabled-test",
+ Name: "disabled-test-container",
+ Image: "nginx:latest",
+ UpdateStatus: &models.DockerContainerUpdateStatus{
+ UpdateAvailable: true,
+ CurrentDigest: "sha256:olddigest",
+ LatestDigest: "sha256:newdigest",
+ LastChecked: time.Now(),
+ },
+ }
+
+ m2.checkDockerContainerImageUpdate(host, container, testResourceID, "disabled-test-container", instanceName, nodeName)
+
+ alerts := m2.GetActiveAlerts()
+ for _, a := range alerts {
+ if a.Type == "docker-container-update" {
+ t.Error("Expected no alert when delay hours is negative (disabled)")
+ break
+ }
+ }
+ })
+}
+
+func TestUpdateAlertProLicenseGating(t *testing.T) {
+ hostID := "docker-host-1"
+ containerName := "test-container"
+ instanceName := "docker-instance"
+ nodeName := "docker-node"
+ host := models.DockerHost{ID: hostID, DisplayName: "Test Host"}
+
+ t.Run("no license checker - alerts work", func(t *testing.T) {
+ m := NewManager()
+ m.mu.Lock()
+ m.config.DockerDefaults.UpdateAlertDelayHours = 24
+ m.mu.Unlock()
+
+ testResourceID := "docker:" + hostID + "/container-license-test-1"
+
+ // Set up tracking as if we detected the update 25 hours ago
+ m.mu.Lock()
+ m.dockerUpdateFirstSeen[testResourceID] = time.Now().Add(-25 * time.Hour)
+ m.mu.Unlock()
+
+ container := models.DockerContainer{
+ ID: "container-license-test-1",
+ Name: containerName,
+ Image: "nginx:latest",
+ UpdateStatus: &models.DockerContainerUpdateStatus{
+ UpdateAvailable: true,
+ CurrentDigest: "sha256:olddigest",
+ LatestDigest: "sha256:newdigest",
+ LastChecked: time.Now(),
+ },
+ }
+
+ m.checkDockerContainerImageUpdate(host, container, testResourceID, containerName, instanceName, nodeName)
+
+ alerts := m.GetActiveAlerts()
+ found := false
+ for _, a := range alerts {
+ if a.Type == "docker-container-update" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Error("Expected alert when no license checker is set")
+ }
+ })
+
+ t.Run("pro license grants feature - alerts work", func(t *testing.T) {
+ m := NewManager()
+ m.mu.Lock()
+ m.config.DockerDefaults.UpdateAlertDelayHours = 24
+ m.mu.Unlock()
+ m.SetLicenseChecker(func(feature string) bool {
+ return feature == "update_alerts" // Grant the feature
+ })
+
+ testResourceID := "docker:" + hostID + "/container-license-test-2"
+
+ // Set up tracking as if we detected the update 25 hours ago
+ m.mu.Lock()
+ m.dockerUpdateFirstSeen[testResourceID] = time.Now().Add(-25 * time.Hour)
+ m.mu.Unlock()
+
+ container := models.DockerContainer{
+ ID: "container-license-test-2",
+ Name: containerName,
+ Image: "nginx:latest",
+ UpdateStatus: &models.DockerContainerUpdateStatus{
+ UpdateAvailable: true,
+ CurrentDigest: "sha256:olddigest",
+ LatestDigest: "sha256:newdigest",
+ LastChecked: time.Now(),
+ },
+ }
+
+ m.checkDockerContainerImageUpdate(host, container, testResourceID, containerName, instanceName, nodeName)
+
+ alerts := m.GetActiveAlerts()
+ found := false
+ for _, a := range alerts {
+ if a.Type == "docker-container-update" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Error("Expected alert when Pro license grants update_alerts feature")
+ }
+ })
+
+ t.Run("free license - no alerts", func(t *testing.T) {
+ m := NewManager()
+ m.mu.Lock()
+ m.config.DockerDefaults.UpdateAlertDelayHours = 24
+ m.mu.Unlock()
+ m.SetLicenseChecker(func(feature string) bool {
+ return false // Free tier - no features
+ })
+
+ testResourceID := "docker:" + hostID + "/container-license-test-3"
+
+ // Set up tracking as if we detected the update 25 hours ago
+ m.mu.Lock()
+ m.dockerUpdateFirstSeen[testResourceID] = time.Now().Add(-25 * time.Hour)
+ m.mu.Unlock()
+
+ container := models.DockerContainer{
+ ID: "container-license-test-3",
+ Name: containerName,
+ Image: "nginx:latest",
+ UpdateStatus: &models.DockerContainerUpdateStatus{
+ UpdateAvailable: true,
+ CurrentDigest: "sha256:olddigest",
+ LatestDigest: "sha256:newdigest",
+ LastChecked: time.Now(),
+ },
+ }
+
+ m.checkDockerContainerImageUpdate(host, container, testResourceID, containerName, instanceName, nodeName)
+
+ alerts := m.GetActiveAlerts()
+ for _, a := range alerts {
+ if a.Type == "docker-container-update" {
+ t.Error("Expected no alert when license doesn't grant update_alerts feature")
+ break
+ }
+ }
+
+ // Verify tracking is also cleared
+ m.mu.RLock()
+ _, tracked := m.dockerUpdateFirstSeen[testResourceID]
+ m.mu.RUnlock()
+ if tracked {
+ t.Error("Expected tracking to be cleared when license doesn't grant feature")
+ }
+ })
+}
+
+func TestDockerUpdateTrackingCleanup(t *testing.T) {
+ m := NewManager()
+
+ hostID := "docker-host-1"
+ prefix := "docker:" + hostID + "/"
+
+ // Add some tracking entries
+ m.mu.Lock()
+ m.dockerUpdateFirstSeen[prefix+"container-1"] = time.Now()
+ m.dockerUpdateFirstSeen[prefix+"container-2"] = time.Now()
+ m.dockerUpdateFirstSeen[prefix+"container-3"] = time.Now()
+ m.dockerUpdateFirstSeen["docker:other-host/container-x"] = time.Now()
+ m.mu.Unlock()
+
+ // Create host and seen map with only container-1 and container-2
+ host := models.DockerHost{ID: hostID}
+ seen := map[string]struct{}{
+ prefix + "container-1": {},
+ prefix + "container-2": {},
+ // container-3 is removed
+ }
+
+ // Run cleanup
+ m.cleanupDockerContainerAlerts(host, seen)
+
+ // Verify container-3 tracking is removed
+ m.mu.RLock()
+ _, hasC1 := m.dockerUpdateFirstSeen[prefix+"container-1"]
+ _, hasC2 := m.dockerUpdateFirstSeen[prefix+"container-2"]
+ _, hasC3 := m.dockerUpdateFirstSeen[prefix+"container-3"]
+ _, hasOther := m.dockerUpdateFirstSeen["docker:other-host/container-x"]
+ m.mu.RUnlock()
+
+ if !hasC1 {
+ t.Error("Expected container-1 tracking to remain")
+ }
+ if !hasC2 {
+ t.Error("Expected container-2 tracking to remain")
+ }
+ if hasC3 {
+ t.Error("Expected container-3 tracking to be removed")
+ }
+ if !hasOther {
+ t.Error("Expected other host tracking to remain")
+ }
+}
diff --git a/internal/api/update_detection_test.go b/internal/api/update_detection_test.go
new file mode 100644
index 0000000000..7f56fc0d1b
--- /dev/null
+++ b/internal/api/update_detection_test.go
@@ -0,0 +1,277 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
+)
+
+
+func TestHandleGetInfraUpdates(t *testing.T) {
+ // We can't easily create a real Monitor, so we'll test the core logic
+ t.Run("collectDockerUpdates filters correctly", func(t *testing.T) {
+ handler := &UpdateDetectionHandlers{}
+ // Can't test directly without a monitor, but we can verify the behavior
+ // through the HTTP handlers
+
+ // For now, verify the response structure when no updates
+ req := httptest.NewRequest(http.MethodGet, "/api/infra-updates", nil)
+ rr := httptest.NewRecorder()
+
+ handler.HandleGetInfraUpdates(rr, req)
+
+ if rr.Code != http.StatusOK {
+ t.Errorf("Expected status 200, got %d", rr.Code)
+ }
+
+ var response map[string]interface{}
+ if err := json.NewDecoder(rr.Body).Decode(&response); err != nil {
+ t.Fatalf("Failed to decode response: %v", err)
+ }
+
+ // Verify structure
+ if _, ok := response["updates"]; !ok {
+ t.Error("Expected 'updates' field in response")
+ }
+ if _, ok := response["total"]; !ok {
+ t.Error("Expected 'total' field in response")
+ }
+ })
+
+ t.Run("method not allowed for POST", func(t *testing.T) {
+ handler := &UpdateDetectionHandlers{}
+ req := httptest.NewRequest(http.MethodPost, "/api/infra-updates", nil)
+ rr := httptest.NewRecorder()
+
+ handler.HandleGetInfraUpdates(rr, req)
+
+ if rr.Code != http.StatusMethodNotAllowed {
+ t.Errorf("Expected status 405, got %d", rr.Code)
+ }
+ })
+}
+
+func TestHandleGetInfraUpdatesSummary(t *testing.T) {
+ handler := &UpdateDetectionHandlers{}
+
+ t.Run("returns empty summary without monitor", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/api/infra-updates/summary", nil)
+ rr := httptest.NewRecorder()
+
+ handler.HandleGetInfraUpdatesSummary(rr, req)
+
+ if rr.Code != http.StatusOK {
+ t.Errorf("Expected status 200, got %d", rr.Code)
+ }
+
+ var response map[string]interface{}
+ if err := json.NewDecoder(rr.Body).Decode(&response); err != nil {
+ t.Fatalf("Failed to decode response: %v", err)
+ }
+
+ if response["totalUpdates"].(float64) != 0 {
+ t.Error("Expected totalUpdates to be 0")
+ }
+ })
+
+ t.Run("method not allowed for POST", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodPost, "/api/infra-updates/summary", nil)
+ rr := httptest.NewRecorder()
+
+ handler.HandleGetInfraUpdatesSummary(rr, req)
+
+ if rr.Code != http.StatusMethodNotAllowed {
+ t.Errorf("Expected status 405, got %d", rr.Code)
+ }
+ })
+}
+
+func TestHandleGetInfraUpdatesForHost(t *testing.T) {
+ handler := &UpdateDetectionHandlers{}
+
+ t.Run("returns empty for non-existent host", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/api/infra-updates/host/nonexistent", nil)
+ rr := httptest.NewRecorder()
+
+ handler.HandleGetInfraUpdatesForHost(rr, req, "nonexistent")
+
+ if rr.Code != http.StatusOK {
+ t.Errorf("Expected status 200, got %d", rr.Code)
+ }
+
+ var response map[string]interface{}
+ if err := json.NewDecoder(rr.Body).Decode(&response); err != nil {
+ t.Fatalf("Failed to decode response: %v", err)
+ }
+
+ if response["hostId"] != "nonexistent" {
+ t.Error("Expected hostId in response")
+ }
+ if response["total"].(float64) != 0 {
+ t.Error("Expected total to be 0")
+ }
+ })
+
+ t.Run("method not allowed for POST", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodPost, "/api/infra-updates/host/test", nil)
+ rr := httptest.NewRecorder()
+
+ handler.HandleGetInfraUpdatesForHost(rr, req, "test")
+
+ if rr.Code != http.StatusMethodNotAllowed {
+ t.Errorf("Expected status 405, got %d", rr.Code)
+ }
+ })
+}
+
+func TestHandleGetInfraUpdateForResource(t *testing.T) {
+ handler := &UpdateDetectionHandlers{}
+
+ t.Run("returns 404 for non-existent resource", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/api/infra-updates/resource-123", nil)
+ rr := httptest.NewRecorder()
+
+ handler.HandleGetInfraUpdateForResource(rr, req, "resource-123")
+
+ if rr.Code != http.StatusNotFound {
+ t.Errorf("Expected status 404, got %d", rr.Code)
+ }
+ })
+
+ t.Run("method not allowed for POST", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodPost, "/api/infra-updates/resource-123", nil)
+ rr := httptest.NewRecorder()
+
+ handler.HandleGetInfraUpdateForResource(rr, req, "resource-123")
+
+ if rr.Code != http.StatusMethodNotAllowed {
+ t.Errorf("Expected status 405, got %d", rr.Code)
+ }
+ })
+}
+
+func TestHandleTriggerInfraUpdateCheck(t *testing.T) {
+ handler := &UpdateDetectionHandlers{}
+
+ t.Run("returns 503 without monitor", func(t *testing.T) {
+ body := strings.NewReader(`{"hostId":"test-host"}`)
+ req := httptest.NewRequest(http.MethodPost, "/api/infra-updates/check", body)
+ req.Header.Set("Content-Type", "application/json")
+ rr := httptest.NewRecorder()
+
+ handler.HandleTriggerInfraUpdateCheck(rr, req)
+
+ if rr.Code != http.StatusServiceUnavailable {
+ t.Errorf("Expected status 503, got %d", rr.Code)
+ }
+ })
+
+ t.Run("method not allowed for GET", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/api/infra-updates/check", nil)
+ rr := httptest.NewRecorder()
+
+ handler.HandleTriggerInfraUpdateCheck(rr, req)
+
+ if rr.Code != http.StatusMethodNotAllowed {
+ t.Errorf("Expected status 405, got %d", rr.Code)
+ }
+ })
+}
+
+func TestContainerUpdateInfo_JSONSerialization(t *testing.T) {
+ info := ContainerUpdateInfo{
+ HostID: "host-1",
+ HostName: "Test Host",
+ ContainerID: "container-abc",
+ ContainerName: "nginx",
+ Image: "nginx:latest",
+ CurrentDigest: "sha256:current",
+ LatestDigest: "sha256:latest",
+ UpdateAvailable: true,
+ LastChecked: time.Now().Unix(),
+ ResourceType: "docker",
+ }
+
+ data, err := json.Marshal(info)
+ if err != nil {
+ t.Fatalf("Failed to marshal ContainerUpdateInfo: %v", err)
+ }
+
+ var decoded ContainerUpdateInfo
+ if err := json.Unmarshal(data, &decoded); err != nil {
+ t.Fatalf("Failed to unmarshal ContainerUpdateInfo: %v", err)
+ }
+
+ if decoded.HostID != info.HostID {
+ t.Errorf("Expected HostID %q, got %q", info.HostID, decoded.HostID)
+ }
+ if decoded.UpdateAvailable != info.UpdateAvailable {
+ t.Errorf("Expected UpdateAvailable %v, got %v", info.UpdateAvailable, decoded.UpdateAvailable)
+ }
+ if decoded.ResourceType != "docker" {
+ t.Errorf("Expected ResourceType 'docker', got %q", decoded.ResourceType)
+ }
+}
+
+// Integration test with real monitor (requires more setup)
+func TestUpdateDetectionHandlersWithMonitor(t *testing.T) {
+ // Skip in short mode - this requires more infrastructure
+ if testing.Short() {
+ t.Skip("Skipping integration test in short mode")
+ }
+
+ // This would require setting up a real Monitor instance
+ // For now, we test the handler methods in isolation above
+ t.Log("Full integration test requires Monitor setup - see manual testing instructions")
+}
+
+// Verify handler doesn't panic with nil monitor
+func TestHandlerNilMonitorSafety(t *testing.T) {
+ handler := &UpdateDetectionHandlers{monitor: nil}
+
+ tests := []struct {
+ name string
+ handler func(w http.ResponseWriter, r *http.Request)
+ method string
+ path string
+ }{
+ {
+ name: "GetInfraUpdates",
+ handler: func(w http.ResponseWriter, r *http.Request) {
+ handler.HandleGetInfraUpdates(w, r)
+ },
+ method: http.MethodGet,
+ path: "/api/infra-updates",
+ },
+ {
+ name: "GetInfraUpdatesSummary",
+ handler: func(w http.ResponseWriter, r *http.Request) {
+ handler.HandleGetInfraUpdatesSummary(w, r)
+ },
+ method: http.MethodGet,
+ path: "/api/infra-updates/summary",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ req := httptest.NewRequest(tt.method, tt.path, nil)
+ rr := httptest.NewRecorder()
+
+ // Should not panic
+ tt.handler(rr, req)
+
+ if rr.Code != http.StatusOK {
+ t.Errorf("Expected OK status, got %d", rr.Code)
+ }
+ })
+ }
+}
+
+// Placeholder for monitor interface - actual implementation is in monitoring package
+var _ = (*monitoring.Monitor)(nil) // Ensure we reference the package
diff --git a/internal/dockeragent/registry_http_test.go b/internal/dockeragent/registry_http_test.go
new file mode 100644
index 0000000000..7b6734364e
--- /dev/null
+++ b/internal/dockeragent/registry_http_test.go
@@ -0,0 +1,331 @@
+package dockeragent
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/rs/zerolog"
+)
+
+func TestRegistryChecker_CheckImageUpdate_Behavior(t *testing.T) {
+ logger := zerolog.Nop()
+ checker := NewRegistryChecker(logger)
+
+ t.Run("disabled checker returns nil", func(t *testing.T) {
+ checker.SetEnabled(false)
+ result := checker.CheckImageUpdate(context.Background(), "nginx:latest", "sha256:current")
+ if result != nil {
+ t.Error("Expected nil result when checker is disabled")
+ }
+ checker.SetEnabled(true)
+ })
+
+ t.Run("digest-pinned image skipped", func(t *testing.T) {
+ result := checker.CheckImageUpdate(context.Background(), "nginx@sha256:abc123", "sha256:abc123")
+ if result == nil {
+ t.Fatal("Expected result for digest-pinned image")
+ }
+ if result.UpdateAvailable {
+ t.Error("Expected no update available for digest-pinned image")
+ }
+ if result.Error != "digest-pinned image" {
+ t.Errorf("Expected error 'digest-pinned image', got %q", result.Error)
+ }
+ })
+
+ t.Run("empty image name", func(t *testing.T) {
+ result := checker.CheckImageUpdate(context.Background(), "", "sha256:current")
+ if result == nil {
+ t.Fatal("Expected result for empty image")
+ }
+ // Should have an error since we can't parse empty image
+ })
+}
+
+func TestRegistryChecker_Caching(t *testing.T) {
+ logger := zerolog.Nop()
+ checker := NewRegistryChecker(logger)
+
+ // Test caching behavior
+ cacheKey := "test-key"
+
+ t.Run("cache miss returns nil", func(t *testing.T) {
+ entry := checker.getCached(cacheKey)
+ if entry != nil {
+ t.Error("Expected nil for cache miss")
+ }
+ })
+
+ t.Run("cache hit for digest", func(t *testing.T) {
+ checker.cacheDigest(cacheKey, "sha256:testdigest")
+ entry := checker.getCached(cacheKey)
+ if entry == nil {
+ t.Fatal("Expected cache hit")
+ }
+ if entry.latestDigest != "sha256:testdigest" {
+ t.Errorf("Expected digest 'sha256:testdigest', got %q", entry.latestDigest)
+ }
+ })
+
+ t.Run("cache hit for error", func(t *testing.T) {
+ errorKey := "error-key"
+ checker.cacheError(errorKey, "test error")
+ entry := checker.getCached(errorKey)
+ if entry == nil {
+ t.Fatal("Expected cache hit for error")
+ }
+ if entry.err != "test error" {
+ t.Errorf("Expected error 'test error', got %q", entry.err)
+ }
+ })
+
+ t.Run("cleanup removes expired entries", func(t *testing.T) {
+ // Add an expired entry manually
+ checker.cache.mu.Lock()
+ checker.cache.entries["expired-key"] = cacheEntry{
+ latestDigest: "sha256:old",
+ expiresAt: time.Now().Add(-1 * time.Hour), // Already expired
+ }
+ checker.cache.mu.Unlock()
+
+ checker.CleanupCache()
+
+ entry := checker.getCached("expired-key")
+ if entry != nil {
+ t.Error("Expected expired entry to be removed")
+ }
+ })
+}
+
+func TestRegistryChecker_ShouldCheck(t *testing.T) {
+ logger := zerolog.Nop()
+ checker := NewRegistryChecker(logger)
+
+ t.Run("should check when never checked", func(t *testing.T) {
+ if !checker.ShouldCheck() {
+ t.Error("Expected ShouldCheck to return true when never checked")
+ }
+ })
+
+ t.Run("should not check immediately after mark", func(t *testing.T) {
+ checker.MarkChecked()
+ if checker.ShouldCheck() {
+ t.Error("Expected ShouldCheck to return false immediately after MarkChecked")
+ }
+ })
+
+ t.Run("should not check when disabled", func(t *testing.T) {
+ checker.SetEnabled(false)
+ if checker.ShouldCheck() {
+ t.Error("Expected ShouldCheck to return false when disabled")
+ }
+ checker.SetEnabled(true)
+ })
+}
+
+func TestParseImageReference_EdgeCases(t *testing.T) {
+ tests := []struct {
+ name string
+ image string
+ wantReg string
+ wantRepo string
+ wantTag string
+ }{
+ {
+ name: "quay.io image",
+ image: "quay.io/prometheus/prometheus:v2.45.0",
+ wantReg: "quay.io",
+ wantRepo: "prometheus/prometheus",
+ wantTag: "v2.45.0",
+ },
+ {
+ name: "ecr image",
+ image: "123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:prod",
+ wantReg: "123456789.dkr.ecr.us-east-1.amazonaws.com",
+ wantRepo: "myapp",
+ wantTag: "prod",
+ },
+ {
+ name: "gcr.io image",
+ image: "gcr.io/google-containers/pause:3.2",
+ wantReg: "gcr.io",
+ wantRepo: "google-containers/pause",
+ wantTag: "3.2",
+ },
+ {
+ name: "multi-level path",
+ image: "registry.example.com/org/team/project/app:v1",
+ wantReg: "registry.example.com",
+ wantRepo: "org/team/project/app",
+ wantTag: "v1",
+ },
+ {
+ name: "image with sha256 in name (not pinned)",
+ image: "myimage-sha256:latest",
+ wantReg: "registry-1.docker.io",
+ wantRepo: "library/myimage-sha256",
+ wantTag: "latest",
+ },
+ {
+ name: "mcr.io image",
+ image: "mcr.microsoft.com/dotnet/sdk:7.0",
+ wantReg: "mcr.microsoft.com",
+ wantRepo: "dotnet/sdk",
+ wantTag: "7.0",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotReg, gotRepo, gotTag := parseImageReference(tt.image)
+ if gotReg != tt.wantReg {
+ t.Errorf("registry = %q, want %q", gotReg, tt.wantReg)
+ }
+ if gotRepo != tt.wantRepo {
+ t.Errorf("repository = %q, want %q", gotRepo, tt.wantRepo)
+ }
+ if gotTag != tt.wantTag {
+ t.Errorf("tag = %q, want %q", gotTag, tt.wantTag)
+ }
+ })
+ }
+}
+
+// TestRegistryChecker_FetchDigest documents the fetchDigest behavior
+// Note: This function requires HTTPS, so we can't easily mock it with httptest
+// The function is tested via integration tests with real registries
+func TestRegistryChecker_FetchDigest_Documentation(t *testing.T) {
+ // fetchDigest:
+ // - Always uses HTTPS
+ // - Sets Accept headers for manifest types (OCI, Docker V2, V1)
+ // - Uses Docker-Content-Digest header if available
+ // - Falls back to Etag header if Docker-Content-Digest is missing
+ // - Returns error for 4xx/5xx status codes
+ // - Caches errors for rate limiting scenarios
+
+ t.Run("documents expected behavior", func(t *testing.T) {
+ logger := zerolog.Nop()
+ checker := NewRegistryChecker(logger)
+
+ // Attempting to fetch from an invalid registry should fail
+ ctx := context.Background()
+ _, err := checker.fetchDigest(ctx, "invalid.registry.test", "library/nginx", "latest")
+ if err == nil {
+ t.Error("Expected error when fetching from invalid registry")
+ }
+ })
+
+ t.Run("context cancellation", func(t *testing.T) {
+ logger := zerolog.Nop()
+ checker := NewRegistryChecker(logger)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel() // Cancel before fetching
+
+ _, err := checker.fetchDigest(ctx, "registry-1.docker.io", "library/nginx", "latest")
+ if err == nil {
+ t.Error("Expected error when context is cancelled")
+ }
+ })
+}
+
+// TestRegistryChecker_AuthToken_Documentation documents the auth token behavior
+// Note: We can't easily test this with a mock server since the auth URL is hardcoded
+// The auth flow is tested via integration tests with real registries
+func TestRegistryChecker_AuthToken_Documentation(t *testing.T) {
+ t.Run("auth token documentation", func(t *testing.T) {
+ // Auth token flow for Docker Hub:
+ // 1. Request manifest without token
+ // 2. Receive 401 with Www-Authenticate header
+ // 3. Request token from auth.docker.io
+ // 4. Retry manifest request with Bearer token
+
+ // For GHCR:
+ // 1. Request token from ghcr.io/token
+ // 2. Use token for manifest request
+
+ // This behavior is tested via integration tests
+ t.Log("Auth token flow is verified via integration tests with real registries")
+ })
+}
+
+func TestImageUpdateResult_Fields(t *testing.T) {
+ result := ImageUpdateResult{
+ Image: "nginx:latest",
+ CurrentDigest: "sha256:current",
+ LatestDigest: "sha256:latest",
+ UpdateAvailable: true,
+ CheckedAt: time.Now(),
+ Error: "",
+ }
+
+ if !result.UpdateAvailable {
+ t.Error("Expected UpdateAvailable to be true")
+ }
+
+ if result.Image != "nginx:latest" {
+ t.Errorf("Expected image 'nginx:latest', got %q", result.Image)
+ }
+}
+
+func BenchmarkParseImageReference(b *testing.B) {
+ images := []string{
+ "nginx",
+ "nginx:latest",
+ "myrepo/myapp:v1",
+ "ghcr.io/owner/repo:tag",
+ "registry.example.com:5000/app:v2",
+ "nginx@sha256:abc123def456",
+ }
+
+ for i := 0; i < b.N; i++ {
+ for _, img := range images {
+ parseImageReference(img)
+ }
+ }
+}
+
+func BenchmarkDigestsDiffer(b *testing.B) {
+ checker := &RegistryChecker{}
+ current := "sha256:a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
+ latest := "sha256:f6e5d4c3b2a1987654321098765432109876543210987654321098765432fedc"
+
+ for i := 0; i < b.N; i++ {
+ checker.digestsDiffer(current, latest)
+ }
+}
+
+// TestConcurrentCacheAccess verifies thread-safety of the cache
+func TestConcurrentCacheAccess(t *testing.T) {
+ logger := zerolog.Nop()
+ checker := NewRegistryChecker(logger)
+
+ // Spawn multiple goroutines accessing the cache
+ done := make(chan bool)
+ for i := 0; i < 10; i++ {
+ go func(id int) {
+ for j := 0; j < 100; j++ {
+ key := fmt.Sprintf("key-%d-%d", id, j)
+ checker.cacheDigest(key, fmt.Sprintf("digest-%d", j))
+ checker.getCached(key)
+ }
+ done <- true
+ }(i)
+ }
+
+ // Also run cleanup concurrently
+ go func() {
+ for i := 0; i < 50; i++ {
+ checker.CleanupCache()
+ time.Sleep(time.Millisecond)
+ }
+ done <- true
+ }()
+
+ // Wait for all goroutines
+ for i := 0; i < 11; i++ {
+ <-done
+ }
+}