package serviceapi import ( "context" "encoding/json" "errors" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/itworx/pulse/internal/auth" "github.com/itworx/pulse/internal/probe" "github.com/itworx/pulse/internal/service" ) type staticProvider struct { snapshot service.Snapshot err error } func (p staticProvider) Snapshot(context.Context) (service.Snapshot, error) { return p.snapshot, p.err } func authenticatedRequest(method, path string) *http.Request { request := httptest.NewRequest(method, path, nil) return request.WithContext(auth.WithPrincipal(request.Context(), auth.Principal{Subject: "viewer", Role: auth.RoleViewer})) } func apiSnapshot() service.Snapshot { now := time.Date(2026, 8, 2, 12, 0, 0, 0, time.UTC) latency := 12 return service.Snapshot{ContractVersion: service.ContractVersion, ObservedAt: now, Services: []service.ServiceStatus{ {ID: "service-2", Name: "Second", State: service.StateUp, History: []probe.Result{{ProbeID: "probe-2", ObservedAt: now, State: service.StateUp, ResponseTimeMS: &latency}}}, {ID: "service-1", Name: "First", State: service.StateDown, History: []probe.Result{{ProbeID: "probe-1", ObservedAt: now, State: service.StateDown}}}, }, Total: 2} } func TestServiceHandlerRequiresViewerAndBoundsListAndHistory(t *testing.T) { handler := Handler{Provider: staticProvider{snapshot: apiSnapshot()}, MaxPageSize: 1, MaxHistory: 1} unauthorized := httptest.NewRecorder() handler.ServeHTTP(unauthorized, httptest.NewRequest(http.MethodGet, "/api/v1/services", nil)) if unauthorized.Code != http.StatusUnauthorized { t.Fatalf("unauthorized status=%d", unauthorized.Code) } listResponse := httptest.NewRecorder() handler.ServeHTTP(listResponse, authenticatedRequest(http.MethodGet, "/api/v1/services?limit=1")) if listResponse.Code != http.StatusOK { t.Fatalf("list status=%d body=%s", listResponse.Code, listResponse.Body.String()) } var snapshot service.Snapshot if err := json.Unmarshal(listResponse.Body.Bytes(), &snapshot); err != nil { t.Fatal(err) } if len(snapshot.Services) != 1 || snapshot.Services[0].ID != "service-1" || snapshot.Total != 2 || len(snapshot.Services[0].History) != 1 { t.Fatalf("bounded/deterministic list=%+v", snapshot) } historyResponse := httptest.NewRecorder() handler.ServeHTTP(historyResponse, authenticatedRequest(http.MethodGet, "/api/v1/services/service-2/history?limit=1")) if historyResponse.Code != http.StatusOK || !strings.Contains(historyResponse.Body.String(), `"serviceId":"service-2"`) { t.Fatalf("history response status=%d body=%s", historyResponse.Code, historyResponse.Body.String()) } } func TestServiceHandlerDetailErrorsAndCancellation(t *testing.T) { handler := Handler{Provider: staticProvider{snapshot: apiSnapshot()}, MaxPageSize: 2, MaxHistory: 2} detail := httptest.NewRecorder() handler.ServeHTTP(detail, authenticatedRequest(http.MethodGet, "/api/v1/services/service-1")) if detail.Code != http.StatusOK || !strings.Contains(detail.Body.String(), `"state":"down"`) { t.Fatalf("detail status=%d body=%s", detail.Code, detail.Body.String()) } invalidLimit := httptest.NewRecorder() handler.ServeHTTP(invalidLimit, authenticatedRequest(http.MethodGet, "/api/v1/services?limit=3")) if invalidLimit.Code != http.StatusBadRequest { t.Fatalf("invalid limit status=%d", invalidLimit.Code) } missing := httptest.NewRecorder() handler.ServeHTTP(missing, authenticatedRequest(http.MethodGet, "/api/v1/services/missing")) if missing.Code != http.StatusNotFound { t.Fatalf("missing status=%d", missing.Code) } failed := Handler{Provider: staticProvider{err: errors.New("backend unavailable")}} failedResponse := httptest.NewRecorder() failed.ServeHTTP(failedResponse, authenticatedRequest(http.MethodGet, "/api/v1/services")) if failedResponse.Code != http.StatusServiceUnavailable { t.Fatalf("provider failure status=%d", failedResponse.Code) } } type staticDependencyProvider struct { items []service.Dependency err error } func (p staticDependencyProvider) List(context.Context, string, int) ([]service.Dependency, error) { return p.items, p.err } func TestServiceHandlerDependenciesAuthBoundsAndDeterminism(t *testing.T) { provider := staticDependencyProvider{items: []service.Dependency{{ID: "dep-2", ServiceID: "service-1", DependsOnServiceID: "service-3", RelationType: service.RelationDependsOn, Confidence: .8}, {ID: "dep-1", ServiceID: "service-1", DependsOnServiceID: "service-2", RelationType: service.RelationDependsOn, Confidence: .9}}} handler := Handler{Provider: staticProvider{snapshot: apiSnapshot()}, Dependencies: provider} unauthorized := httptest.NewRecorder() handler.ServeHTTP(unauthorized, httptest.NewRequest(http.MethodGet, "/api/v1/services/service-1/dependencies", nil)) if unauthorized.Code != http.StatusUnauthorized { t.Fatalf("unauthorized dependency status=%d", unauthorized.Code) } response := httptest.NewRecorder() handler.ServeHTTP(response, authenticatedRequest(http.MethodGet, "/api/v1/services/service-1/dependencies?limit=1")) if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"serviceId":"service-1"`) { t.Fatalf("dependency status=%d body=%s", response.Code, response.Body.String()) } if strings.Index(response.Body.String(), "service-2") > strings.Index(response.Body.String(), "service-3") { t.Fatalf("dependencies were not deterministic: %s", response.Body.String()) } invalid := httptest.NewRecorder() handler.ServeHTTP(invalid, authenticatedRequest(http.MethodGet, "/api/v1/services/service-1/dependencies?limit=101")) if invalid.Code != http.StatusBadRequest { t.Fatalf("invalid dependency limit status=%d", invalid.Code) } failed := Handler{Dependencies: staticDependencyProvider{err: errors.New("dependency backend unavailable")}} failure := httptest.NewRecorder() failed.ServeHTTP(failure, authenticatedRequest(http.MethodGet, "/api/v1/services/service-1/dependencies")) if failure.Code != http.StatusServiceUnavailable { t.Fatalf("dependency failure status=%d", failure.Code) } } func TestServiceHandlerTopologyIsAuthenticatedBoundedAndExplicit(t *testing.T) { provider := staticDependencyProvider{items: []service.Dependency{{ID: "edge-2", ServiceID: "service-2", DependsOnServiceID: "service-1", RelationType: service.RelationDependsOn, Confidence: .7}, {ID: "edge-1", ServiceID: "service-1", DependsOnServiceID: "missing", RelationType: service.RelationBacks, Confidence: .4}}} handler := Handler{Provider: staticProvider{snapshot: apiSnapshot()}, Dependencies: provider} unauthorized := httptest.NewRecorder() handler.ServeHTTP(unauthorized, httptest.NewRequest(http.MethodGet, "/api/v1/topology", nil)) if unauthorized.Code != http.StatusUnauthorized { t.Fatalf("unauthorized topology status=%d", unauthorized.Code) } response := httptest.NewRecorder() handler.ServeHTTP(response, authenticatedRequest(http.MethodGet, "/api/v1/topology?limit=2")) if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"truncated"`) || !strings.Contains(response.Body.String(), `"inferred":true`) { t.Fatalf("topology status=%d body=%s", response.Code, response.Body.String()) } invalid := httptest.NewRecorder() handler.ServeHTTP(invalid, authenticatedRequest(http.MethodGet, "/api/v1/topology?limit=101")) if invalid.Code != http.StatusBadRequest { t.Fatalf("invalid topology limit status=%d", invalid.Code) } }