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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
test: expand api handler coverage
rcourtman02946d45ece2
diff --git a/internal/api/ai_handlers_more_test.go b/internal/api/ai_handlers_more_test.gonew file mode 100644index 0000000000..049a7b0d8b--- /dev/null+++ b/internal/api/ai_handlers_more_test.go@@ -0,0 +1,220 @@+package api++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/memory"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/resources"+ "github.com/rcourtman/pulse-go-rewrite/internal/servicediscovery"+)++type stubMetadataProvider struct{}++func (stubMetadataProvider) SetGuestURL(string, string) error { return nil }+func (stubMetadataProvider) SetDockerURL(string, string) error { return nil }+func (stubMetadataProvider) SetHostURL(string, string) error { return nil }++type stubThresholdProvider struct{}++func (stubThresholdProvider) GetNodeCPUThreshold() float64 { return 80 }+func (stubThresholdProvider) GetNodeMemoryThreshold() float64 { return 85 }+func (stubThresholdProvider) GetGuestMemoryThreshold() float64 {+ return 90+}+func (stubThresholdProvider) GetGuestDiskThreshold() float64 { return 95 }+func (stubThresholdProvider) GetStorageThreshold() float64 { return 92 }++type stubMetricsHistoryProvider struct{}++func (stubMetricsHistoryProvider) GetNodeMetrics(string, string, time.Duration) []ai.MetricPoint {+ return nil+}+func (stubMetricsHistoryProvider) GetGuestMetrics(string, string, time.Duration) []ai.MetricPoint {+ return nil+}+func (stubMetricsHistoryProvider) GetAllGuestMetrics(string, time.Duration) map[string][]ai.MetricPoint {+ return nil+}+func (stubMetricsHistoryProvider) GetAllStorageMetrics(string, time.Duration) map[string][]ai.MetricPoint {+ return nil+}++type stubResourceProvider struct{}++func (stubResourceProvider) GetAll() []resources.Resource { return nil }+func (stubResourceProvider) GetInfrastructure() []resources.Resource { return nil }+func (stubResourceProvider) GetWorkloads() []resources.Resource { return nil }+func (stubResourceProvider) GetByType(resources.ResourceType) []resources.Resource {+ return nil+}+func (stubResourceProvider) GetStats() resources.StoreStats {+ return resources.StoreStats{}+}+func (stubResourceProvider) GetTopByCPU(int, []resources.ResourceType) []resources.Resource {+ return nil+}+func (stubResourceProvider) GetTopByMemory(int, []resources.ResourceType) []resources.Resource {+ return nil+}+func (stubResourceProvider) GetTopByDisk(int, []resources.ResourceType) []resources.Resource {+ return nil+}+func (stubResourceProvider) GetRelated(string) map[string][]resources.Resource {+ return map[string][]resources.Resource{}+}+func (stubResourceProvider) GetResourceSummary() resources.ResourceSummary {+ return resources.ResourceSummary{}+}+func (stubResourceProvider) FindContainerHost(string) string { return "" }++func TestAISettingsHandler_setSSECORSHeaders(t *testing.T) {+ handler := newTestAISettingsHandler(&config.Config{AllowedOrigins: "*"}, nil, nil)++ req := httptest.NewRequest(http.MethodGet, "/api/ai/stream", nil)+ req.Header.Set("Origin", "https://example.com")+ rec := httptest.NewRecorder()+ handler.setSSECORSHeaders(rec, req)++ if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "https://example.com" {+ t.Fatalf("expected allow origin, got %q", got)+ }+ if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "true" {+ t.Fatalf("expected credentials header, got %q", got)+ }+ if rec.Header().Get("Access-Control-Allow-Methods") == "" {+ t.Fatalf("expected allow methods header")+ }+ if rec.Header().Get("Access-Control-Allow-Headers") == "" {+ t.Fatalf("expected allow headers header")+ }+ if got := rec.Header().Get("Vary"); got != "Origin" {+ t.Fatalf("expected Vary=Origin, got %q", got)+ }++ handler = newTestAISettingsHandler(&config.Config{AllowedOrigins: "https://allowed.com"}, nil, nil)+ req = httptest.NewRequest(http.MethodGet, "/api/ai/stream", nil)+ req.Header.Set("Origin", "https://nope.com")+ rec = httptest.NewRecorder()+ handler.setSSECORSHeaders(rec, req)+ if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "" {+ t.Fatalf("expected no allow origin for mismatched origin, got %q", got)+ }+ if rec.Header().Get("Access-Control-Allow-Methods") == "" {+ t.Fatalf("expected allow methods header for mismatched origin")+ }+ if got := rec.Header().Get("Vary"); got != "Origin" {+ t.Fatalf("expected Vary=Origin for mismatched origin, got %q", got)+ }++ handler = newTestAISettingsHandler(&config.Config{AllowedOrigins: "*"}, nil, nil)+ req = httptest.NewRequest(http.MethodGet, "/api/ai/stream", nil)+ rec = httptest.NewRecorder()+ handler.setSSECORSHeaders(rec, req)+ if len(rec.Header()) != 0 {+ t.Fatalf("expected no headers when origin is missing, got %v", rec.Header())+ }+}++func TestAISettingsHandler_GetAIService_MultiTenantProviders(t *testing.T) {+ tmp := t.TempDir()+ mtp := config.NewMultiTenantPersistence(tmp)+ handler := NewAISettingsHandler(mtp, nil, nil)++ handler.SetStateProvider(&stubStateProvider{})+ handler.SetResourceProvider(stubResourceProvider{})+ handler.SetMetadataProvider(stubMetadataProvider{})+ handler.SetPatrolThresholdProvider(stubThresholdProvider{})+ handler.SetMetricsHistoryProvider(stubMetricsHistoryProvider{})+ handler.SetBaselineStore(ai.NewBaselineStore(ai.DefaultBaselineConfig()))+ handler.SetChangeDetector(ai.NewChangeDetector(ai.ChangeDetectorConfig{}))+ handler.SetRemediationLog(ai.NewRemediationLog(ai.RemediationLogConfig{MaxRecords: 1}))+ handler.SetIncidentStore(memory.NewIncidentStore(memory.IncidentStoreConfig{DataDir: t.TempDir()}))+ handler.SetPatternDetector(ai.NewPatternDetector(ai.DefaultPatternConfig()))+ handler.SetCorrelationDetector(ai.NewCorrelationDetector(ai.DefaultCorrelationConfig()))++ discoveryStore, err := servicediscovery.NewStore(t.TempDir())+ if err != nil {+ t.Fatalf("NewStore: %v", err)+ }+ handler.SetDiscoveryStore(discoveryStore)++ ctx := context.WithValue(context.Background(), OrgIDContextKey, "tenant-1")+ svc := handler.GetAIService(ctx)+ if svc == nil {+ t.Fatalf("expected tenant service to be created")+ }+ if svc2 := handler.GetAIService(ctx); svc2 != svc {+ t.Fatalf("expected cached tenant service")+ }+}++func TestAISettingsHandler_DiscoveryStoreAccessors(t *testing.T) {+ handler := newTestAISettingsHandler(&config.Config{DataPath: t.TempDir()}, config.NewConfigPersistence(t.TempDir()), nil)++ store, err := servicediscovery.NewStore(t.TempDir())+ if err != nil {+ t.Fatalf("NewStore: %v", err)+ }+ handler.SetDiscoveryStore(store)++ if got := handler.GetDiscoveryStore(); got != store {+ t.Fatalf("expected discovery store to match")+ }+}++func TestAutonomyLevelProviderAdapter(t *testing.T) {+ adapter := &autonomyLevelProviderAdapter{}+ if got := adapter.GetCurrentAutonomyLevel(); got != config.PatrolAutonomyMonitor {+ t.Fatalf("expected default autonomy %q, got %q", config.PatrolAutonomyMonitor, got)+ }+ if adapter.IsFullModeUnlocked() {+ t.Fatalf("expected full mode locked by default")+ }++ tmp := t.TempDir()+ persistence := config.NewConfigPersistence(tmp)+ aiCfg := config.NewDefaultAIConfig()+ aiCfg.PatrolAutonomyLevel = config.PatrolAutonomyAssisted+ aiCfg.PatrolFullModeUnlocked = true+ if err := persistence.SaveAIConfig(*aiCfg); err != nil {+ t.Fatalf("SaveAIConfig: %v", err)+ }++ svc := ai.NewService(persistence, nil)+ if err := svc.LoadConfig(); err != nil {+ t.Fatalf("LoadConfig: %v", err)+ }+ adapter = &autonomyLevelProviderAdapter{svc: svc}++ if got := adapter.GetCurrentAutonomyLevel(); got != config.PatrolAutonomyAssisted {+ t.Fatalf("expected autonomy %q, got %q", config.PatrolAutonomyAssisted, got)+ }+ if !adapter.IsFullModeUnlocked() {+ t.Fatalf("expected full mode unlocked")+ }+}++func TestLicenseCheckerForOrchestrator(t *testing.T) {+ tmp := t.TempDir()+ persistence := config.NewConfigPersistence(tmp)+ svc := ai.NewService(persistence, nil)+ if err := svc.LoadConfig(); err != nil {+ t.Fatalf("LoadConfig: %v", err)+ }++ checker := &licenseCheckerForOrchestrator{svc: svc}+ if !checker.HasFeature("pro") {+ t.Fatalf("expected default license to allow feature")+ }++ svc.SetLicenseChecker(stubLicenseChecker{allow: false})+ if checker.HasFeature("pro") {+ t.Fatalf("expected license checker to deny feature")+ }+}diff --git a/internal/api/ai_intelligence_handlers_more2_test.go b/internal/api/ai_intelligence_handlers_more2_test.gonew file mode 100644index 0000000000..888eb050ef--- /dev/null+++ b/internal/api/ai_intelligence_handlers_more2_test.go@@ -0,0 +1,760 @@+package api++import (+ "bytes"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/forecast"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/learning"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/proxmox"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/remediation"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/unified"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++type stubForecastProvider struct {+ points []forecast.MetricDataPoint+ err error+}++func (s stubForecastProvider) GetMetricHistory(_ string, _ string, _, _ time.Time) ([]forecast.MetricDataPoint, error) {+ if s.err != nil {+ return nil, s.err+ }+ return s.points, nil+}++type stubForecastStateProvider struct {+ state forecast.StateSnapshot+}++func (s stubForecastStateProvider) GetState() forecast.StateSnapshot {+ return s.state+}++func makeForecastPoints(count int, start time.Time, startValue, step float64) []forecast.MetricDataPoint {+ points := make([]forecast.MetricDataPoint, 0, count)+ for i := 0; i < count; i++ {+ points = append(points, forecast.MetricDataPoint{+ Timestamp: start.Add(time.Duration(i) * time.Hour),+ Value: startValue + float64(i)*step,+ })+ }+ return points+}++func addBaseline(t *testing.T, store *ai.BaselineStore, resourceID, resourceType, metric string, value float64) {+ t.Helper()+ points := []ai.BaselineMetricPoint{{Value: value, Timestamp: time.Now()}}+ if err := store.Learn(resourceID, resourceType, metric, points); err != nil {+ t.Fatalf("baseline Learn error: %v", err)+ }+}++func TestHandleGetAnomalies_NoStateProvider(t *testing.T) {+ svc := newEnabledAIService(t)+ store := ai.NewBaselineStore(ai.BaselineConfig{MinSamples: 1})+ svc.SetBaselineStore(store)++ handler := &AISettingsHandler{legacyAIService: svc}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/intelligence/anomalies", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetAnomalies(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+ var payload map[string]interface{}+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if payload["message"] != "State provider not available" {+ t.Fatalf("unexpected message: %#v", payload["message"])+ }+}++func TestHandleGetAnomalies_MixedResources(t *testing.T) {+ svc := newEnabledAIService(t)+ store := ai.NewBaselineStore(ai.BaselineConfig{MinSamples: 1})+ addBaseline(t, store, "vm-1", "vm", "cpu", 10)+ addBaseline(t, store, "vm-1", "vm", "memory", 10)+ addBaseline(t, store, "vm-1", "vm", "disk", 10)+ addBaseline(t, store, "ct-1", "container", "cpu", 10)+ addBaseline(t, store, "ct-1", "container", "memory", 10)+ addBaseline(t, store, "ct-1", "container", "disk", 10)+ addBaseline(t, store, "node-1", "node", "cpu", 10)+ addBaseline(t, store, "node-1", "node", "memory", 10)+ svc.SetBaselineStore(store)++ state := models.StateSnapshot{+ VMs: []models.VM{+ {ID: "vm-1", Name: "vm-one", Status: "running", CPU: 0.9, Memory: models.Memory{Usage: 85}, Disk: models.Disk{Usage: 90}},+ {ID: "vm-template", Template: true, Status: "running", CPU: 0.9, Memory: models.Memory{Usage: 90}},+ {ID: "vm-stopped", Status: "stopped", CPU: 0.9, Memory: models.Memory{Usage: 90}},+ },+ Containers: []models.Container{+ {ID: "ct-1", Name: "ct-one", Status: "running", CPU: 0.9, Memory: models.Memory{Usage: 85}, Disk: models.Disk{Usage: 90}},+ {ID: "ct-template", Template: true, Status: "running", CPU: 0.9, Memory: models.Memory{Usage: 90}},+ {ID: "ct-stopped", Status: "stopped", CPU: 0.9, Memory: models.Memory{Usage: 90}},+ },+ Nodes: []models.Node{+ {ID: "node-1", Name: "node-one", CPU: 0.9, Memory: models.Memory{Usage: 85}},+ },+ }+ svc.SetStateProvider(snapshotStateProvider{state: state})++ handler := &AISettingsHandler{legacyAIService: svc}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/intelligence/anomalies", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetAnomalies(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }++ var payload map[string]interface{}+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }++ anomalies, ok := payload["anomalies"].([]interface{})+ if !ok || len(anomalies) == 0 {+ t.Fatalf("expected anomalies, got %#v", payload["anomalies"])+ }++ types := map[string]bool{}+ for _, item := range anomalies {+ row, _ := item.(map[string]interface{})+ if rtype, ok := row["resource_type"].(string); ok {+ types[rtype] = true+ }+ }+ if !types["vm"] || !types["container"] || !types["node"] {+ t.Fatalf("expected vm, container, node anomalies, got %#v", types)+ }+}++func TestHandleGetLearningStatus_WaitingAndActive(t *testing.T) {+ t.Run("waiting", func(t *testing.T) {+ svc := newEnabledAIService(t)+ store := ai.NewBaselineStore(ai.BaselineConfig{MinSamples: 1})+ svc.SetBaselineStore(store)++ handler := &AISettingsHandler{legacyAIService: svc}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/intelligence/learning", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetLearningStatus(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+ var payload map[string]interface{}+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if payload["status"] != "waiting" {+ t.Fatalf("expected status waiting, got %#v", payload["status"])+ }+ })++ t.Run("active", func(t *testing.T) {+ svc := newEnabledAIService(t)+ store := ai.NewBaselineStore(ai.BaselineConfig{MinSamples: 1})+ for i := 0; i < 5; i++ {+ id := fmt.Sprintf("res-%d", i)+ addBaseline(t, store, id, "vm", "cpu", 10)+ }+ svc.SetBaselineStore(store)++ handler := &AISettingsHandler{legacyAIService: svc}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/intelligence/learning", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetLearningStatus(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+ var payload map[string]interface{}+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if payload["status"] != "active" {+ t.Fatalf("expected status active, got %#v", payload["status"])+ }+ })+}++func TestHandleGetLearningPreferences_Stats(t *testing.T) {+ store := learning.NewLearningStore(learning.LearningStoreConfig{})+ store.RecordFeedback(learning.FeedbackRecord{+ FindingID: "finding-1",+ ResourceID: "res-1",+ Category: "performance",+ Severity: "warning",+ Action: learning.ActionAcknowledge,+ })++ handler := &AISettingsHandler{}+ handler.SetLearningStore(store)++ req := httptest.NewRequest(http.MethodGet, "/api/ai/learning/preferences", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetLearningPreferences(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+ var payload map[string]interface{}+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if _, ok := payload["statistics"]; !ok {+ t.Fatalf("expected statistics in response")+ }+}++func TestHandleGetUnifiedFindings_Statuses(t *testing.T) {+ store := unified.NewUnifiedStore(unified.DefaultAlertToFindingConfig())+ now := time.Now()+ resolvedAt := now.Add(-2 * time.Hour)+ snoozedUntil := now.Add(2 * time.Hour)++ store.AddFromAI(&unified.UnifiedFinding{+ ID: "finding-active",+ Source: unified.SourceAIPatrol,+ Severity: unified.SeverityWarning,+ Category: unified.CategoryPerformance,+ ResourceID: "res-1",+ ResourceName: "res-1",+ ResourceType: "vm",+ Title: "Active",+ Description: "active",+ DetectedAt: now,+ LastSeenAt: now,+ })+ store.AddFromAI(&unified.UnifiedFinding{+ ID: "finding-resolved",+ Source: unified.SourceThreshold,+ Severity: unified.SeverityCritical,+ Category: unified.CategoryCapacity,+ ResourceID: "res-1",+ ResourceName: "res-1",+ ResourceType: "vm",+ Title: "Resolved",+ Description: "resolved",+ ResolvedAt: &resolvedAt,+ DetectedAt: now,+ LastSeenAt: now,+ })+ store.AddFromAI(&unified.UnifiedFinding{+ ID: "finding-snoozed",+ Source: unified.SourceAIPatrol,+ Severity: unified.SeverityWarning,+ Category: unified.CategoryPerformance,+ ResourceID: "res-1",+ ResourceName: "res-1",+ ResourceType: "vm",+ Title: "Snoozed",+ Description: "snoozed",+ SnoozedUntil: &snoozedUntil,+ DetectedAt: now,+ LastSeenAt: now,+ })+ store.AddFromAI(&unified.UnifiedFinding{+ ID: "finding-dismissed",+ Source: unified.SourceAIPatrol,+ Severity: unified.SeverityInfo,+ Category: unified.CategoryGeneral,+ ResourceID: "res-1",+ ResourceName: "res-1",+ ResourceType: "vm",+ Title: "Dismissed",+ Description: "dismissed",+ DismissedReason: "noise",+ Suppressed: true,+ DetectedAt: now,+ LastSeenAt: now,+ })++ handler := &AISettingsHandler{}+ handler.SetUnifiedStore(store)++ req := httptest.NewRequest(http.MethodGet, "/api/ai/unified/findings?resource_id=res-1&include_resolved=true", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetUnifiedFindings(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+ var payload map[string]interface{}+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if payload["count"] != float64(4) {+ t.Fatalf("expected count 4, got %#v", payload["count"])+ }+ if payload["active_count"] != float64(1) {+ t.Fatalf("expected active_count 1, got %#v", payload["active_count"])+ }+}++func TestHandleGetForecast_MissingParams(t *testing.T) {+ handler := &AISettingsHandler{forecastService: forecast.NewService(forecast.DefaultForecastConfig())}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/forecast?metric=cpu", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetForecast(rec, req)++ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+}++func TestHandleGetForecast_Success(t *testing.T) {+ points := makeForecastPoints(60, time.Now().Add(-60*time.Hour), 50, 0.1)+ svc := forecast.NewService(forecast.DefaultForecastConfig())+ svc.SetDataProvider(stubForecastProvider{points: points})++ handler := &AISettingsHandler{forecastService: svc}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/forecast?resource_id=vm-1&resource_name=vm-one&metric=cpu&horizon_hours=2&threshold=60", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetForecast(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+ var payload map[string]interface{}+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ forecastVal, ok := payload["forecast"].(map[string]interface{})+ if !ok {+ t.Fatalf("expected forecast object")+ }+ if forecastVal["resource_id"] != "vm-1" {+ t.Fatalf("unexpected resource_id: %#v", forecastVal["resource_id"])+ }+ if forecastVal["metric"] != "cpu" {+ t.Fatalf("unexpected metric: %#v", forecastVal["metric"])+ }+}++func TestHandleGetForecastOverview_Success(t *testing.T) {+ points := makeForecastPoints(60, time.Now().Add(-60*time.Hour), 50, 0.1)+ svc := forecast.NewService(forecast.DefaultForecastConfig())+ svc.SetDataProvider(stubForecastProvider{points: points})+ svc.SetStateProvider(stubForecastStateProvider{state: forecast.StateSnapshot{+ VMs: []forecast.VMInfo{{ID: "vm-1", Name: "vm-one"}},+ Containers: []forecast.ContainerInfo{{ID: "ct-1", Name: "ct-one"}},+ Nodes: []forecast.NodeInfo{{ID: "node-1", Name: "node-one"}},+ }})++ handler := &AISettingsHandler{forecastService: svc}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/forecasts/overview?metric=cpu&horizon_hours=24&threshold=60", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetForecastOverview(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+ var payload map[string]interface{}+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if payload["metric"] != "cpu" {+ t.Fatalf("unexpected metric: %#v", payload["metric"])+ }+ if payload["threshold"] != float64(60) {+ t.Fatalf("unexpected threshold: %#v", payload["threshold"])+ }+ forecasts, ok := payload["forecasts"].([]interface{})+ if !ok || len(forecasts) == 0 {+ t.Fatalf("expected forecasts, got %#v", payload["forecasts"])+ }+}++func TestHandleGetProxmoxEvents_ResourceFilter(t *testing.T) {+ correlator := proxmox.NewEventCorrelator(proxmox.EventCorrelatorConfig{})+ correlator.RecordEvent(proxmox.ProxmoxEvent{+ ID: "evt-1",+ Type: proxmox.EventVMStart,+ ResourceID: "vm-1",+ })++ handler := &AISettingsHandler{proxmoxCorrelator: correlator}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/proxmox/events?resource_id=vm-1&limit=1", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetProxmoxEvents(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+ var payload map[string]interface{}+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ events, ok := payload["events"].([]interface{})+ if !ok || len(events) != 1 {+ t.Fatalf("expected 1 event, got %#v", payload["events"])+ }+}++func TestHandleGetProxmoxCorrelations_ResourceFilter(t *testing.T) {+ correlator := proxmox.NewEventCorrelator(proxmox.EventCorrelatorConfig{})+ corr := proxmox.EventCorrelation{+ ID: "corr-1",+ Event: proxmox.ProxmoxEvent{+ ID: "evt-1",+ Type: proxmox.EventVMStart,+ ResourceID: "vm-1",+ },+ ImpactedResources: []string{"vm-1"},+ CreatedAt: time.Now(),+ }+ setUnexportedField(t, correlator, "correlations", []proxmox.EventCorrelation{corr})++ handler := &AISettingsHandler{proxmoxCorrelator: correlator}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/proxmox/correlations?resource_id=vm-1", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetProxmoxCorrelations(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+ var payload map[string]interface{}+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ correlations, ok := payload["correlations"].([]interface{})+ if !ok || len(correlations) != 1 {+ t.Fatalf("expected 1 correlation, got %#v", payload["correlations"])+ }+}++func TestHandleExecuteRemediationPlan_Errors(t *testing.T) {+ t.Run("no_engine", func(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/remediation/plans/plan-1/execute", nil)+ rec := httptest.NewRecorder()+ handler.HandleExecuteRemediationPlan(rec, req)+ if rec.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected status %d, got %d", http.StatusServiceUnavailable, rec.Code)+ }+ })++ t.Run("invalid_body", func(t *testing.T) {+ handler := &AISettingsHandler{remediationEngine: remediation.NewEngine(remediation.EngineConfig{})}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/remediation/plans/plan-1/execute", bytes.NewBufferString("bad-json"))+ rec := httptest.NewRecorder()+ handler.HandleExecuteRemediationPlan(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ })++ t.Run("missing_ids", func(t *testing.T) {+ handler := &AISettingsHandler{remediationEngine: remediation.NewEngine(remediation.EngineConfig{})}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/remediation/plans/plan-1/execute", bytes.NewBufferString("{}"))+ rec := httptest.NewRecorder()+ handler.HandleExecuteRemediationPlan(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ })++ t.Run("execution_error", func(t *testing.T) {+ engine := remediation.NewEngine(remediation.EngineConfig{})+ plan := &remediation.RemediationPlan{+ ID: "plan-no-exec",+ FindingID: "finding-1",+ ResourceID: "res-1",+ Title: "Restart",+ Description: "Restart service",+ Steps: []remediation.RemediationStep{+ {+ Order: 0,+ Description: "Restart",+ Command: "echo ok",+ Target: "host-1",+ },+ },+ }+ if err := engine.CreatePlan(plan); err != nil {+ t.Fatalf("CreatePlan: %v", err)+ }+ handler := &AISettingsHandler{remediationEngine: engine}+ body := bytes.NewBufferString(`{"plan_id":"plan-no-exec"}`)+ req := httptest.NewRequest(http.MethodPost, "/api/ai/remediation/plans/plan-no-exec/execute", body)+ rec := httptest.NewRecorder()+ handler.HandleExecuteRemediationPlan(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ })+}++func TestHandleRollbackRemediationPlan_Errors(t *testing.T) {+ t.Run("no_engine", func(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/remediation/plans/plan-1/rollback", nil)+ rec := httptest.NewRecorder()+ handler.HandleRollbackRemediationPlan(rec, req)+ if rec.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected status %d, got %d", http.StatusServiceUnavailable, rec.Code)+ }+ })++ t.Run("invalid_body", func(t *testing.T) {+ handler := &AISettingsHandler{remediationEngine: remediation.NewEngine(remediation.EngineConfig{})}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/remediation/plans/plan-1/rollback", bytes.NewBufferString("bad-json"))+ rec := httptest.NewRecorder()+ handler.HandleRollbackRemediationPlan(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ })++ t.Run("missing_execution_id", func(t *testing.T) {+ handler := &AISettingsHandler{remediationEngine: remediation.NewEngine(remediation.EngineConfig{})}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/remediation/plans/plan-1/rollback", bytes.NewBufferString("{}"))+ rec := httptest.NewRecorder()+ handler.HandleRollbackRemediationPlan(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ })+}++func TestHandleGetIncidentData_Errors(t *testing.T) {+ t.Run("invalid_path", func(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/incident/abc", nil)+ rec := httptest.NewRecorder()+ handler.HandleGetIncidentData(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ })++ t.Run("missing_resource", func(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/incidents/", nil)+ rec := httptest.NewRecorder()+ handler.HandleGetIncidentData(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ })++ t.Run("no_service", func(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/incidents/res-1", nil)+ rec := httptest.NewRecorder()+ handler.HandleGetIncidentData(rec, req)+ if rec.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected status %d, got %d", http.StatusServiceUnavailable, rec.Code)+ }+ })+}++func TestHandleGetRecentIncidents_NoService(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/incidents", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetRecentIncidents(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+ var payload map[string]interface{}+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if payload["message"] != "Pulse Patrol service not available" {+ t.Fatalf("unexpected message: %#v", payload["message"])+ }+}++func TestHandleGetCircuitBreakerStatus_MethodNotAllowed(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/circuit/status", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetCircuitBreakerStatus(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHandleGetForecastOverview_NoStateProvider(t *testing.T) {+ points := makeForecastPoints(40, time.Now().Add(-40*time.Hour), 20, 1)+ svc := forecast.NewService(forecast.DefaultForecastConfig())+ svc.SetDataProvider(stubForecastProvider{points: points})++ handler := &AISettingsHandler{forecastService: svc}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/forecasts/overview?metric=cpu", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetForecastOverview(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+ var payload map[string]interface{}+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if payload["error"] == nil {+ t.Fatalf("expected error in response")+ }+}++func TestHandleGetForecast_MethodNotAllowed(t *testing.T) {+ handler := &AISettingsHandler{forecastService: forecast.NewService(forecast.DefaultForecastConfig())}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/forecast", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetForecast(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHandleGetIncidentData_MethodNotAllowed(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/incidents/res-1", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetIncidentData(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHandleGetRecentIncidents_MethodNotAllowed(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/incidents", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetRecentIncidents(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHandleGetAnomalies_MethodNotAllowed(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/intelligence/anomalies", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetAnomalies(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHandleGetForecastOverview_MethodNotAllowed(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/forecasts/overview", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetForecastOverview(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHandleGetLearningPreferences_MethodNotAllowed(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/learning/preferences", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetLearningPreferences(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHandleGetUnifiedFindings_MethodNotAllowed(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/unified/findings", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetUnifiedFindings(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHandleGetProxmoxEvents_MethodNotAllowed(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/proxmox/events", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetProxmoxEvents(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHandleGetProxmoxCorrelations_MethodNotAllowed(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodPost, "/api/ai/proxmox/correlations", nil)+ rec := httptest.NewRecorder()++ handler.HandleGetProxmoxCorrelations(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHandleExecuteRemediationPlan_MethodNotAllowed(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/remediation/plans/plan-1/execute", nil)+ rec := httptest.NewRecorder()++ handler.HandleExecuteRemediationPlan(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHandleRollbackRemediationPlan_MethodNotAllowed(t *testing.T) {+ handler := &AISettingsHandler{}+ req := httptest.NewRequest(http.MethodGet, "/api/ai/remediation/plans/plan-1/rollback", nil)+ rec := httptest.NewRecorder()++ handler.HandleRollbackRemediationPlan(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}diff --git a/internal/api/host_agents_more_test.go b/internal/api/host_agents_more_test.gonew file mode 100644index 0000000000..877c0ca0af--- /dev/null+++ b/internal/api/host_agents_more_test.go@@ -0,0 +1,471 @@+package api++import (+ "bytes"+ "crypto/ed25519"+ "crypto/rand"+ "encoding/base64"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "sync"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"+)++func resetConfigSigningStateForTests() {+ configSigningState = struct {+ once sync.Once+ key ed25519.PrivateKey+ err error+ }{}+}++func generateSigningKey(t *testing.T) string {+ t.Helper()++ _, priv, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatalf("GenerateKey: %v", err)+ }+ return base64.StdEncoding.EncodeToString(priv)+}++func decodeErrorCode(t *testing.T, rec *httptest.ResponseRecorder) string {+ t.Helper()++ var resp struct {+ Code string `json:"code"`+ }+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {+ t.Fatalf("decode error response: %v", err)+ }+ return resp.Code+}++func TestHostAgentHandlers_HandleReportMethodNotAllowed(t *testing.T) {+ handler := newHostAgentHandlerForTests(t)++ req := httptest.NewRequest(http.MethodGet, "/api/agents/host/report", nil)+ rec := httptest.NewRecorder()++ handler.HandleReport(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHostAgentHandlers_HandleReportInvalidJSON(t *testing.T) {+ handler := newHostAgentHandlerForTests(t)++ req := httptest.NewRequest(http.MethodPost, "/api/agents/host/report", bytes.NewBufferString("{"))+ rec := httptest.NewRecorder()++ handler.HandleReport(rec, req)++ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "invalid_json" {+ t.Fatalf("expected error code %q, got %q", "invalid_json", code)+ }+}++func TestHostAgentHandlers_HandleReportInvalidReport(t *testing.T) {+ handler := newHostAgentHandlerForTests(t)++ report := agentshost.Report{+ Agent: agentshost.AgentInfo{ID: "agent-err"},+ Host: agentshost.HostInfo{Hostname: ""},+ }+ body, _ := json.Marshal(report)++ req := httptest.NewRequest(http.MethodPost, "/api/agents/host/report", bytes.NewReader(body))+ rec := httptest.NewRecorder()++ handler.HandleReport(rec, req)++ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "invalid_report" {+ t.Fatalf("expected error code %q, got %q", "invalid_report", code)+ }+}++func TestHostAgentHandlers_HandleReportIncludesConfigOverride(t *testing.T) {+ handler, monitor := newHostAgentHandlers(t, nil)++ hostID := "machine-override"+ enabled := true+ if err := monitor.UpdateHostAgentConfig(hostID, &enabled); err != nil {+ t.Fatalf("UpdateHostAgentConfig: %v", err)+ }++ report := agentshost.Report{+ Agent: agentshost.AgentInfo{ID: "agent-override"},+ Host: agentshost.HostInfo{+ ID: hostID,+ Hostname: "host-override.local",+ Platform: "linux",+ },+ }+ body, _ := json.Marshal(report)++ req := httptest.NewRequest(http.MethodPost, "/api/agents/host/report", bytes.NewReader(body))+ rec := httptest.NewRecorder()++ handler.HandleReport(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())+ }++ var resp map[string]any+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp["hostId"] != hostID {+ t.Fatalf("expected hostId %q, got %#v", hostID, resp["hostId"])+ }+ cfg, ok := resp["config"].(map[string]any)+ if !ok {+ t.Fatalf("expected config override in response")+ }+ if val, ok := cfg["commandsEnabled"].(bool); !ok || !val {+ t.Fatalf("expected commandsEnabled=true, got %#v", cfg["commandsEnabled"])+ }+}++func TestHostAgentHandlers_HandleDeleteHostErrors(t *testing.T) {+ handler := newHostAgentHandlerForTests(t)++ req := httptest.NewRequest(http.MethodGet, "/api/agents/host/host-1", nil)+ rec := httptest.NewRecorder()+ handler.HandleDeleteHost(rec, req)+ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }++ req = httptest.NewRequest(http.MethodDelete, "/api/agents/host/", nil)+ rec = httptest.NewRecorder()+ handler.HandleDeleteHost(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "missing_host_id" {+ t.Fatalf("expected error code %q, got %q", "missing_host_id", code)+ }+}++func TestHostAgentHandlers_HandleConfigErrors(t *testing.T) {+ handler := newHostAgentHandlerForTests(t, models.Host{+ ID: "host-1",+ TokenID: "token-1",+ })++ req := httptest.NewRequest(http.MethodPost, "/api/agents/host/host-1/config", nil)+ rec := httptest.NewRecorder()+ handler.HandleConfig(rec, req)+ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }++ req = httptest.NewRequest(http.MethodGet, "/api/agents/host//config", nil)+ rec = httptest.NewRecorder()+ handler.HandleConfig(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "missing_host_id" {+ t.Fatalf("expected error code %q, got %q", "missing_host_id", code)+ }++ req = httptest.NewRequest(http.MethodGet, "/api/agents/host/host-1/config", nil)+ attachAPITokenRecord(req, &config.APITokenRecord{+ ID: "token-2",+ Scopes: []string{config.ScopeHostConfigRead},+ })+ rec = httptest.NewRecorder()+ handler.HandleConfig(rec, req)+ if rec.Code != http.StatusNotFound {+ t.Fatalf("expected status %d, got %d", http.StatusNotFound, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "host_not_found" {+ t.Fatalf("expected error code %q, got %q", "host_not_found", code)+ }+}++func TestHostAgentHandlers_HandleConfigPatchErrors(t *testing.T) {+ handler := newHostAgentHandlerForTests(t)++ req := httptest.NewRequest(http.MethodPatch, "/api/agents/host/host-1/config", bytes.NewBufferString("{"))+ rec := httptest.NewRecorder()+ handler.HandleConfig(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "invalid_json" {+ t.Fatalf("expected error code %q, got %q", "invalid_json", code)+ }++ req = httptest.NewRequest(http.MethodPatch, "/api/agents/host/host-1/config", bytes.NewBufferString(`{"commandsEnabled":true}`))+ rec = httptest.NewRecorder()+ handler.HandleConfig(rec, req)+ if rec.Code != http.StatusInternalServerError {+ t.Fatalf("expected status %d, got %d", http.StatusInternalServerError, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "update_failed" {+ t.Fatalf("expected error code %q, got %q", "update_failed", code)+ }+}++func TestHostAgentHandlers_EnsureHostTokenMatchScopes(t *testing.T) {+ handler := newHostAgentHandlerForTests(t)++ req := httptest.NewRequest(http.MethodGet, "/api/agents/host/host-1/config", nil)+ attachAPITokenRecord(req, &config.APITokenRecord{+ ID: "token-1",+ Scopes: []string{config.ScopeWildcard},+ })+ rec := httptest.NewRecorder()+ if ok := handler.ensureHostTokenMatch(rec, req, "missing"); !ok {+ t.Fatalf("expected wildcard scope to allow access")+ }+ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }++ req = httptest.NewRequest(http.MethodGet, "/api/agents/host/host-1/config", nil)+ attachAPITokenRecord(req, &config.APITokenRecord{+ ID: "token-1",+ Scopes: []string{config.ScopeHostConfigRead},+ })+ rec = httptest.NewRecorder()+ if ok := handler.ensureHostTokenMatch(rec, req, "missing"); ok {+ t.Fatalf("expected missing host to fail")+ }+ if rec.Code != http.StatusNotFound {+ t.Fatalf("expected status %d, got %d", http.StatusNotFound, rec.Code)+ }+}++func TestHostAgentHandlers_HandleConfigSigningRequiredMissingKey(t *testing.T) {+ handler := newHostAgentHandlerForTests(t, models.Host{ID: "host-1"})++ t.Setenv("PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED", "true")+ t.Setenv("PULSE_AGENT_CONFIG_SIGNING_KEY", "")+ resetConfigSigningStateForTests()+ t.Cleanup(resetConfigSigningStateForTests)++ req := httptest.NewRequest(http.MethodGet, "/api/agents/host/host-1/config", nil)+ rec := httptest.NewRecorder()+ handler.HandleConfig(rec, req)+ if rec.Code != http.StatusInternalServerError {+ t.Fatalf("expected status %d, got %d", http.StatusInternalServerError, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "config_signing_failed" {+ t.Fatalf("expected error code %q, got %q", "config_signing_failed", code)+ }+}++func TestHostAgentHandlers_HandleConfigSigningSuccess(t *testing.T) {+ handler := newHostAgentHandlerForTests(t, models.Host{ID: "host-1"})++ t.Setenv("PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED", "true")+ t.Setenv("PULSE_AGENT_CONFIG_SIGNING_KEY", generateSigningKey(t))+ resetConfigSigningStateForTests()+ t.Cleanup(resetConfigSigningStateForTests)++ req := httptest.NewRequest(http.MethodGet, "/api/agents/host/host-1/config", nil)+ rec := httptest.NewRecorder()+ handler.HandleConfig(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }++ var resp struct {+ Success bool `json:"success"`+ HostID string `json:"hostId"`+ Config monitoring.HostAgentConfig `json:"config"`+ }+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.HostID != "host-1" {+ t.Fatalf("expected hostId %q, got %q", "host-1", resp.HostID)+ }+ if resp.Config.Signature == "" {+ t.Fatalf("expected config signature to be set")+ }+ if resp.Config.IssuedAt == nil || resp.Config.ExpiresAt == nil {+ t.Fatalf("expected issuedAt/expiresAt to be set")+ }+ if !resp.Config.ExpiresAt.After(*resp.Config.IssuedAt) {+ t.Fatalf("expected expiresAt after issuedAt")+ }+}++func TestHostAgentHandlers_HandleConfigInvalidKeyAllowed(t *testing.T) {+ handler := newHostAgentHandlerForTests(t, models.Host{ID: "host-1"})++ t.Setenv("PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED", "false")+ t.Setenv("PULSE_AGENT_CONFIG_SIGNING_KEY", "not-base64")+ resetConfigSigningStateForTests()+ t.Cleanup(resetConfigSigningStateForTests)++ req := httptest.NewRequest(http.MethodGet, "/api/agents/host/host-1/config", nil)+ rec := httptest.NewRecorder()+ handler.HandleConfig(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }++ var resp struct {+ Config monitoring.HostAgentConfig `json:"config"`+ }+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.Config.Signature != "" {+ t.Fatalf("expected no signature when signing key is invalid")+ }+ if resp.Config.IssuedAt != nil || resp.Config.ExpiresAt != nil {+ t.Fatalf("expected no issuedAt/expiresAt when signing key is invalid")+ }+}++func TestHostAgentHandlers_HandleUninstallErrors(t *testing.T) {+ handler := newHostAgentHandlerForTests(t)++ req := httptest.NewRequest(http.MethodGet, "/api/agents/host/uninstall", nil)+ rec := httptest.NewRecorder()+ handler.HandleUninstall(rec, req)+ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }++ req = httptest.NewRequest(http.MethodPost, "/api/agents/host/uninstall", bytes.NewBufferString("{"))+ rec = httptest.NewRecorder()+ handler.HandleUninstall(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "invalid_json" {+ t.Fatalf("expected error code %q, got %q", "invalid_json", code)+ }++ req = httptest.NewRequest(http.MethodPost, "/api/agents/host/uninstall", bytes.NewBufferString(`{"hostId":""}`))+ rec = httptest.NewRecorder()+ handler.HandleUninstall(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "missing_host_id" {+ t.Fatalf("expected error code %q, got %q", "missing_host_id", code)+ }+}++func TestHostAgentHandlers_HandleUninstallMissingHostStillSucceeds(t *testing.T) {+ handler, _ := newHostAgentHandlers(t, nil)++ req := httptest.NewRequest(http.MethodPost, "/api/agents/host/uninstall", bytes.NewBufferString(`{"hostId":"missing"}`))+ rec := httptest.NewRecorder()+ handler.HandleUninstall(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+}++func TestHostAgentHandlers_HandleLinkUnlinkErrors(t *testing.T) {+ handler := newHostAgentHandlerForTests(t)++ req := httptest.NewRequest(http.MethodGet, "/api/agents/host/link", nil)+ rec := httptest.NewRecorder()+ handler.HandleLink(rec, req)+ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }++ req = httptest.NewRequest(http.MethodPost, "/api/agents/host/link", bytes.NewBufferString("{"))+ rec = httptest.NewRecorder()+ handler.HandleLink(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "invalid_json" {+ t.Fatalf("expected error code %q, got %q", "invalid_json", code)+ }++ req = httptest.NewRequest(http.MethodPost, "/api/agents/host/link", bytes.NewBufferString(`{"hostId":"","nodeId":"node-1"}`))+ rec = httptest.NewRecorder()+ handler.HandleLink(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "missing_host_id" {+ t.Fatalf("expected error code %q, got %q", "missing_host_id", code)+ }++ req = httptest.NewRequest(http.MethodPost, "/api/agents/host/link", bytes.NewBufferString(`{"hostId":"host-1","nodeId":""}`))+ rec = httptest.NewRecorder()+ handler.HandleLink(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "missing_node_id" {+ t.Fatalf("expected error code %q, got %q", "missing_node_id", code)+ }++ req = httptest.NewRequest(http.MethodPost, "/api/agents/host/link", bytes.NewBufferString(`{"hostId":"host-1","nodeId":"node-1"}`))+ rec = httptest.NewRecorder()+ handler.HandleLink(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "link_failed" {+ t.Fatalf("expected error code %q, got %q", "link_failed", code)+ }++ req = httptest.NewRequest(http.MethodGet, "/api/agents/host/unlink", nil)+ rec = httptest.NewRecorder()+ handler.HandleUnlink(rec, req)+ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }++ req = httptest.NewRequest(http.MethodPost, "/api/agents/host/unlink", bytes.NewBufferString("{"))+ rec = httptest.NewRecorder()+ handler.HandleUnlink(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "invalid_json" {+ t.Fatalf("expected error code %q, got %q", "invalid_json", code)+ }++ req = httptest.NewRequest(http.MethodPost, "/api/agents/host/unlink", bytes.NewBufferString(`{"hostId":""}`))+ rec = httptest.NewRecorder()+ handler.HandleUnlink(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "missing_host_id" {+ t.Fatalf("expected error code %q, got %q", "missing_host_id", code)+ }++ req = httptest.NewRequest(http.MethodPost, "/api/agents/host/unlink", bytes.NewBufferString(`{"hostId":"missing"}`))+ rec = httptest.NewRecorder()+ handler.HandleUnlink(rec, req)+ if rec.Code != http.StatusNotFound {+ t.Fatalf("expected status %d, got %d", http.StatusNotFound, rec.Code)+ }+ if code := decodeErrorCode(t, rec); code != "unlink_failed" {+ t.Fatalf("expected error code %q, got %q", "unlink_failed", code)+ }+}diff --git a/internal/api/rbac_handlers_more_test.go b/internal/api/rbac_handlers_more_test.gonew file mode 100644index 0000000000..dbdcfc029f--- /dev/null+++ b/internal/api/rbac_handlers_more_test.go@@ -0,0 +1,277 @@+package api++import (+ "bytes"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++type errorRBACManager struct {+ mockRBACManager+ saveErr error+ deleteErr error+ updateErr error+ perms []auth.Permission+ rolesByID map[string]auth.Role+ assignByID map[string]auth.UserRoleAssignment+}++func (m *errorRBACManager) GetRole(id string) (auth.Role, bool) {+ if m.rolesByID != nil {+ role, ok := m.rolesByID[id]+ return role, ok+ }+ return m.mockRBACManager.GetRole(id)+}++func (m *errorRBACManager) SaveRole(role auth.Role) error {+ if m.saveErr != nil {+ return m.saveErr+ }+ return m.mockRBACManager.SaveRole(role)+}++func (m *errorRBACManager) DeleteRole(id string) error {+ if m.deleteErr != nil {+ return m.deleteErr+ }+ return m.mockRBACManager.DeleteRole(id)+}++func (m *errorRBACManager) UpdateUserRoles(username string, roleIDs []string) error {+ if m.updateErr != nil {+ return m.updateErr+ }+ return m.mockRBACManager.UpdateUserRoles(username, roleIDs)+}++func (m *errorRBACManager) GetUserAssignment(username string) (auth.UserRoleAssignment, bool) {+ if m.assignByID != nil {+ assignment, ok := m.assignByID[username]+ return assignment, ok+ }+ return m.mockRBACManager.GetUserAssignment(username)+}++func (m *errorRBACManager) GetUserPermissions(username string) []auth.Permission {+ if m.perms != nil {+ return m.perms+ }+ return nil+}++func TestRBACHandlers_HandleRoles_MoreBranches(t *testing.T) {+ orig := auth.GetManager()+ t.Cleanup(func() { auth.SetManager(orig) })++ cfg := &config.Config{}+ handler := NewRBACHandlers(cfg)++ t.Run("MethodNotAllowed", func(t *testing.T) {+ auth.SetManager(&mockRBACManager{})+ req := httptest.NewRequest(http.MethodPatch, "/api/admin/roles", nil)+ rr := httptest.NewRecorder()+ handler.HandleRoles(rr, req)+ if rr.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rr.Code)+ }+ })++ t.Run("GetRoleNotFound", func(t *testing.T) {+ auth.SetManager(&mockRBACManager{})+ req := httptest.NewRequest(http.MethodGet, "/api/admin/roles/missing", nil)+ rr := httptest.NewRecorder()+ handler.HandleRoles(rr, req)+ if rr.Code != http.StatusNotFound {+ t.Fatalf("expected status %d, got %d", http.StatusNotFound, rr.Code)+ }+ })++ t.Run("InvalidRoleIDInBody", func(t *testing.T) {+ auth.SetManager(&mockRBACManager{})+ role := auth.Role{ID: "bad role", Name: "Bad"}+ body, _ := json.Marshal(role)+ req := httptest.NewRequest(http.MethodPost, "/api/admin/roles", bytes.NewReader(body))+ rr := httptest.NewRecorder()+ handler.HandleRoles(rr, req)+ if rr.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rr.Code)+ }++ req = httptest.NewRequest(http.MethodPut, "/api/admin/roles", bytes.NewReader(body))+ rr = httptest.NewRecorder()+ handler.HandleRoles(rr, req)+ if rr.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rr.Code)+ }+ })++ t.Run("SaveRoleErrorOnCreate", func(t *testing.T) {+ auth.SetManager(&errorRBACManager{saveErr: errors.New("boom")})+ role := auth.Role{ID: "viewer", Name: "Viewer"}+ body, _ := json.Marshal(role)+ req := httptest.NewRequest(http.MethodPost, "/api/admin/roles", bytes.NewReader(body))+ rr := httptest.NewRecorder()+ handler.HandleRoles(rr, req)+ if rr.Code != http.StatusInternalServerError {+ t.Fatalf("expected status %d, got %d", http.StatusInternalServerError, rr.Code)+ }+ })++ t.Run("SaveRoleErrorOnUpdate", func(t *testing.T) {+ auth.SetManager(&errorRBACManager{saveErr: errors.New("boom")})+ role := auth.Role{ID: "admin", Name: "Admin"}+ body, _ := json.Marshal(role)+ req := httptest.NewRequest(http.MethodPut, "/api/admin/roles/admin", bytes.NewReader(body))+ rr := httptest.NewRecorder()+ handler.HandleRoles(rr, req)+ if rr.Code != http.StatusInternalServerError {+ t.Fatalf("expected status %d, got %d", http.StatusInternalServerError, rr.Code)+ }+ })++ t.Run("DeleteRoleError", func(t *testing.T) {+ auth.SetManager(&errorRBACManager{deleteErr: errors.New("boom")})+ req := httptest.NewRequest(http.MethodDelete, "/api/admin/roles/admin", nil)+ rr := httptest.NewRecorder()+ handler.HandleRoles(rr, req)+ if rr.Code != http.StatusInternalServerError {+ t.Fatalf("expected status %d, got %d", http.StatusInternalServerError, rr.Code)+ }+ })+}++func TestRBACHandlers_HandleGetUsers_MoreBranches(t *testing.T) {+ orig := auth.GetManager()+ t.Cleanup(func() { auth.SetManager(orig) })++ cfg := &config.Config{}+ handler := NewRBACHandlers(cfg)++ auth.SetManager(&mockRBACManager{})+ req := httptest.NewRequest(http.MethodPost, "/api/admin/users", nil)+ rr := httptest.NewRecorder()+ handler.HandleGetUsers(rr, req)+ if rr.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rr.Code)+ }++ auth.SetManager(nil)+ req = httptest.NewRequest(http.MethodGet, "/api/admin/users", nil)+ rr = httptest.NewRecorder()+ handler.HandleGetUsers(rr, req)+ if rr.Code != http.StatusNotImplemented {+ t.Fatalf("expected status %d, got %d", http.StatusNotImplemented, rr.Code)+ }+}++func TestRBACHandlers_HandleUserRoleActions_MoreBranches(t *testing.T) {+ orig := auth.GetManager()+ t.Cleanup(func() { auth.SetManager(orig) })++ cfg := &config.Config{}+ handler := NewRBACHandlers(cfg)++ auth.SetManager(nil)+ req := httptest.NewRequest(http.MethodGet, "/api/admin/users/alice/roles", nil)+ rr := httptest.NewRecorder()+ handler.HandleUserRoleActions(rr, req)+ if rr.Code != http.StatusNotImplemented {+ t.Fatalf("expected status %d, got %d", http.StatusNotImplemented, rr.Code)+ }++ auth.SetManager(&errorRBACManager{assignByID: map[string]auth.UserRoleAssignment{}})+ req = httptest.NewRequest(http.MethodGet, "/api/admin/users/alice/roles", nil)+ rr = httptest.NewRecorder()+ handler.HandleUserRoleActions(rr, req)+ if rr.Code != http.StatusNotFound {+ t.Fatalf("expected status %d, got %d", http.StatusNotFound, rr.Code)+ }++ auth.SetManager(&errorRBACManager{updateErr: errors.New("boom")})+ body, _ := json.Marshal(map[string]any{"roleIds": []string{"admin"}})+ req = httptest.NewRequest(http.MethodPut, "/api/admin/users/alice/roles", bytes.NewReader(body))+ rr = httptest.NewRecorder()+ handler.HandleUserRoleActions(rr, req)+ if rr.Code != http.StatusInternalServerError {+ t.Fatalf("expected status %d, got %d", http.StatusInternalServerError, rr.Code)+ }++ auth.SetManager(&mockRBACManager{})+ req = httptest.NewRequest(http.MethodDelete, "/api/admin/users/alice/roles", nil)+ rr = httptest.NewRecorder()+ handler.HandleUserRoleActions(rr, req)+ if rr.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rr.Code)+ }+}++func TestRBACHandlers_ChangelogAndEffectiveBranches(t *testing.T) {+ orig := auth.GetManager()+ t.Cleanup(func() { auth.SetManager(orig) })++ cfg := &config.Config{}+ handler := NewRBACHandlers(cfg)++ auth.SetManager(&mockExtendedRBACManager{})+ req := httptest.NewRequest(http.MethodPost, "/api/admin/rbac/changelog", nil)+ rr := httptest.NewRecorder()+ handler.HandleRBACChangelog(rr, req)+ if rr.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rr.Code)+ }++ em := &mockExtendedRBACManager{}+ auth.SetManager(em)+ req = httptest.NewRequest(http.MethodGet, "/api/admin/rbac/changelog?entity_type=role&entity_id=custom", nil)+ rr = httptest.NewRecorder()+ handler.HandleRBACChangelog(rr, req)+ if rr.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rr.Code)+ }++ req = httptest.NewRequest(http.MethodGet, "/api/admin/roles/invalid$id/effective", nil)+ rr = httptest.NewRecorder()+ handler.HandleRoleEffective(rr, req)+ if rr.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rr.Code)+ }++ em = &mockExtendedRBACManager{role: auth.Role{ID: "existing"}}+ auth.SetManager(em)+ req = httptest.NewRequest(http.MethodGet, "/api/admin/roles/missing/effective", nil)+ rr = httptest.NewRecorder()+ handler.HandleRoleEffective(rr, req)+ if rr.Code != http.StatusNotFound {+ t.Fatalf("expected status %d, got %d", http.StatusNotFound, rr.Code)+ }++ req = httptest.NewRequest(http.MethodPost, "/api/admin/users/alice/effective-permissions", nil)+ rr = httptest.NewRecorder()+ handler.HandleUserEffectivePermissions(rr, req)+ if rr.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rr.Code)+ }++ auth.SetManager(&errorRBACManager{})+ req = httptest.NewRequest(http.MethodGet, "/api/admin/users/invalid$user/effective-permissions", nil)+ rr = httptest.NewRecorder()+ handler.HandleUserEffectivePermissions(rr, req)+ if rr.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rr.Code)+ }++ auth.SetManager(&errorRBACManager{perms: nil})+ req = httptest.NewRequest(http.MethodGet, "/api/admin/users/alice/effective-permissions", nil)+ rr = httptest.NewRecorder()+ handler.HandleUserEffectivePermissions(rr, req)+ if rr.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rr.Code)+ }+}diff --git a/internal/api/resource_handlers_more_test.go b/internal/api/resource_handlers_more_test.gonew file mode 100644index 0000000000..ddbdee5d27--- /dev/null+++ b/internal/api/resource_handlers_more_test.go@@ -0,0 +1,332 @@+package api++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/resources"+)++type stubResourceStateProvider struct {+ snapshot models.StateSnapshot+}++func (s stubResourceStateProvider) GetState() models.StateSnapshot {+ return s.snapshot+}++type stubTenantStateProvider struct {+ snapshot models.StateSnapshot+}++func (s stubTenantStateProvider) GetStateForTenant(_ string) models.StateSnapshot {+ return s.snapshot+}++func decodeResourcesResponse(t *testing.T, rec *httptest.ResponseRecorder) ResourcesResponse {+ t.Helper()+ var resp ResourcesResponse+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ return resp+}++func TestResourceHandlers_GetStoreStats(t *testing.T) {+ handlers := NewResourceHandlers()+ handlers.Store().Upsert(resources.Resource{ID: "vm-1", Type: resources.ResourceTypeVM})+ handlers.getStoreForTenant("tenant-a").Upsert(resources.Resource{ID: "node-1", Type: resources.ResourceTypeNode})++ stats := handlers.GetStoreStats()+ if stats["default"].TotalResources != 1 {+ t.Fatalf("expected default total 1, got %d", stats["default"].TotalResources)+ }+ if stats["tenant-a"].TotalResources != 1 {+ t.Fatalf("expected tenant total 1, got %d", stats["tenant-a"].TotalResources)+ }+}++func TestHandleGetResources_FiltersAndModes(t *testing.T) {+ handlers := NewResourceHandlers()+ handlers.Store().Upsert(resources.Resource{+ ID: "vm-1",+ Type: resources.ResourceTypeVM,+ Status: resources.StatusRunning,+ PlatformType: resources.PlatformProxmoxPVE,+ ParentID: "node-1",+ Alerts: []resources.ResourceAlert{{ID: "alert-1"}},+ })+ handlers.Store().Upsert(resources.Resource{+ ID: "node-1",+ Type: resources.ResourceTypeNode,+ Status: resources.StatusOnline,+ PlatformType: resources.PlatformProxmoxPVE,+ })+ handlers.Store().Upsert(resources.Resource{+ ID: "ct-1",+ Type: resources.ResourceTypeContainer,+ Status: resources.StatusStopped,+ PlatformType: resources.PlatformProxmoxPVE,+ })+ handlers.Store().Upsert(resources.Resource{+ ID: "dh-1",+ Type: resources.ResourceTypeDockerHost,+ Status: resources.StatusOnline,+ PlatformType: resources.PlatformDocker,+ })++ req := httptest.NewRequest(http.MethodGet, "/api/resources", nil)+ rec := httptest.NewRecorder()+ handlers.HandleGetResources(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+ resp := decodeResourcesResponse(t, rec)+ if resp.Count != 4 {+ t.Fatalf("expected count 4, got %d", resp.Count)+ }++ req = httptest.NewRequest(http.MethodGet, "/api/resources?type=vm,container", nil)+ rec = httptest.NewRecorder()+ handlers.HandleGetResources(rec, req)+ resp = decodeResourcesResponse(t, rec)+ if resp.Count != 2 {+ t.Fatalf("expected type count 2, got %d", resp.Count)+ }++ req = httptest.NewRequest(http.MethodGet, "/api/resources?platform=docker", nil)+ rec = httptest.NewRecorder()+ handlers.HandleGetResources(rec, req)+ resp = decodeResourcesResponse(t, rec)+ if resp.Count != 1 || resp.Resources[0].ID != "dh-1" {+ t.Fatalf("expected docker host, got %#v", resp.Resources)+ }++ req = httptest.NewRequest(http.MethodGet, "/api/resources?status=running", nil)+ rec = httptest.NewRecorder()+ handlers.HandleGetResources(rec, req)+ resp = decodeResourcesResponse(t, rec)+ if resp.Count != 1 || resp.Resources[0].ID != "vm-1" {+ t.Fatalf("expected running vm, got %#v", resp.Resources)+ }++ req = httptest.NewRequest(http.MethodGet, "/api/resources?parent=node-1", nil)+ rec = httptest.NewRecorder()+ handlers.HandleGetResources(rec, req)+ resp = decodeResourcesResponse(t, rec)+ if resp.Count != 1 || resp.Resources[0].ID != "vm-1" {+ t.Fatalf("expected parent filter vm, got %#v", resp.Resources)+ }++ req = httptest.NewRequest(http.MethodGet, "/api/resources?alerts=true", nil)+ rec = httptest.NewRecorder()+ handlers.HandleGetResources(rec, req)+ resp = decodeResourcesResponse(t, rec)+ if resp.Count != 1 || resp.Resources[0].ID != "vm-1" {+ t.Fatalf("expected alerts filter vm, got %#v", resp.Resources)+ }++ req = httptest.NewRequest(http.MethodGet, "/api/resources?infrastructure=true", nil)+ rec = httptest.NewRecorder()+ handlers.HandleGetResources(rec, req)+ resp = decodeResourcesResponse(t, rec)+ if resp.Count != 2 {+ t.Fatalf("expected infrastructure count 2, got %d", resp.Count)+ }++ req = httptest.NewRequest(http.MethodGet, "/api/resources?workloads=true", nil)+ rec = httptest.NewRecorder()+ handlers.HandleGetResources(rec, req)+ resp = decodeResourcesResponse(t, rec)+ if resp.Count != 2 {+ t.Fatalf("expected workloads count 2, got %d", resp.Count)+ }+}++func TestHandleGetResources_MethodNotAllowed(t *testing.T) {+ handlers := NewResourceHandlers()+ req := httptest.NewRequest(http.MethodPost, "/api/resources", nil)+ rec := httptest.NewRecorder()++ handlers.HandleGetResources(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHandleGetResource_MethodNotAllowedAndMissingID(t *testing.T) {+ handlers := NewResourceHandlers()++ req := httptest.NewRequest(http.MethodPost, "/api/resources/vm-1", nil)+ rec := httptest.NewRecorder()+ handlers.HandleGetResource(rec, req)+ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }++ req = httptest.NewRequest(http.MethodGet, "/api/resources/", nil)+ rec = httptest.NewRecorder()+ handlers.HandleGetResource(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)+ }+}++func TestHandleGetResourceStats_MethodNotAllowed(t *testing.T) {+ handlers := NewResourceHandlers()+ req := httptest.NewRequest(http.MethodPost, "/api/resources/stats", nil)+ rec := httptest.NewRecorder()++ handlers.HandleGetResourceStats(rec, req)++ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)+ }+}++func TestHandleGetResources_StateProviderAndTenantProvider(t *testing.T) {+ handlers := NewResourceHandlers()++ snapshot := models.StateSnapshot{+ Nodes: []models.Node{{ID: "node-1", Name: "node-1"}},+ }+ handlers.SetStateProvider(stubResourceStateProvider{snapshot: snapshot})++ req := httptest.NewRequest(http.MethodGet, "/api/resources", nil)+ rec := httptest.NewRecorder()+ handlers.HandleGetResources(rec, req)+ resp := decodeResourcesResponse(t, rec)+ if resp.Count != 1 {+ t.Fatalf("expected count 1 from state provider, got %d", resp.Count)+ }++ tenantSnapshot := models.StateSnapshot{+ Nodes: []models.Node{{ID: "node-tenant", Name: "node-tenant"}},+ }+ handlers.SetTenantStateProvider(stubTenantStateProvider{snapshot: tenantSnapshot})+ req = httptest.NewRequest(http.MethodGet, "/api/resources", nil)+ ctx := context.WithValue(req.Context(), OrgIDContextKey, "tenant-1")+ req = req.WithContext(ctx)+ rec = httptest.NewRecorder()+ handlers.HandleGetResources(rec, req)+ resp = decodeResourcesResponse(t, rec)+ if resp.Count != 1 || resp.Resources[0].ID != "node-tenant" {+ t.Fatalf("expected tenant resource, got %#v", resp.Resources)+ }+}++func TestPopulateFromSnapshotForTenant(t *testing.T) {+ handlers := NewResourceHandlers()++ now := time.Now()+ snapshot := models.StateSnapshot{+ Nodes: []models.Node{{+ ID: "node-1",+ Name: "node-1",+ CPU: 0.2,+ Memory: models.Memory{Total: 100, Used: 50, Free: 50, Usage: 50},+ Disk: models.Disk{Total: 100, Used: 10, Free: 90, Usage: 10},+ }},+ VMs: []models.VM{{+ ID: "vm-1",+ Name: "vm-1",+ Status: "running",+ Memory: models.Memory{Total: 100, Used: 10, Free: 90, Usage: 10},+ Disk: models.Disk{Total: 100, Used: 10, Free: 90, Usage: 10},+ }},+ Containers: []models.Container{{+ ID: "ct-1",+ Name: "ct-1",+ Status: "running",+ Memory: models.Memory{Total: 100, Used: 10, Free: 90, Usage: 10},+ Disk: models.Disk{Total: 100, Used: 10, Free: 90, Usage: 10},+ }},+ Hosts: []models.Host{{+ ID: "host-1",+ Hostname: "host-1",+ Status: "online",+ Memory: models.Memory{Total: 100, Used: 20, Free: 80, Usage: 20},+ }},+ DockerHosts: []models.DockerHost{{+ ID: "dh-1",+ Hostname: "dh-1",+ Status: "online",+ CPUUsage: 5,+ Memory: models.Memory{Total: 100, Used: 20, Free: 80, Usage: 20},+ TotalMemoryBytes: 100,+ LastSeen: now,+ IntervalSeconds: 60,+ Containers: []models.DockerContainer{{+ ID: "dc-1",+ Name: "dc-1",+ State: "running",+ Status: "running",+ CPUPercent: 1,+ MemoryLimit: 100,+ MemoryUsage: 20,+ MemoryPercent: 20,+ UptimeSeconds: 10,+ CreatedAt: now,+ }},+ }},+ PBSInstances: []models.PBSInstance{{+ ID: "pbs-1",+ Name: "pbs-1",+ Host: "pbs-host",+ Status: "online",+ CPU: 2,+ Memory: 10,+ MemoryUsed: 10,+ MemoryTotal: 100,+ Uptime: 10,+ ConnectionHealth: "ok",+ LastSeen: now,+ }},+ Storage: []models.Storage{{+ ID: "storage-1",+ Name: "storage-1",+ Instance: "inst-1",+ Node: "node-1",+ Status: "online",+ Total: 100,+ Used: 50,+ Free: 50,+ Usage: 50,+ Content: "images",+ Enabled: true,+ Active: true,+ }},+ }++ handlers.PopulateFromSnapshotForTenant("tenant-1", snapshot)++ store := handlers.getStoreForTenant("tenant-1")+ stats := store.GetStats()+ if stats.TotalResources != 8 {+ t.Fatalf("expected 8 resources, got %d", stats.TotalResources)+ }+}++func TestParsePlatformTypesAndStatuses(t *testing.T) {+ platforms := parsePlatformTypes(" docker , proxmox-pve , ")+ if len(platforms) != 2 {+ t.Fatalf("expected 2 platforms, got %d", len(platforms))+ }+ if platforms[0] != resources.PlatformDocker || platforms[1] != resources.PlatformProxmoxPVE {+ t.Fatalf("unexpected platforms: %#v", platforms)+ }++ statuses := parseStatuses("running, stopped ,")+ if len(statuses) != 2 {+ t.Fatalf("expected 2 statuses, got %d", len(statuses))+ }+ if statuses[0] != resources.StatusRunning || statuses[1] != resources.StatusStopped {+ t.Fatalf("unexpected statuses: %#v", statuses)+ }+}