package server import ( "encoding/json" "net/http" "testing" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" ) func TestServicesAndErrorsAPI(t *testing.T) { st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour}) now := time.Now() mk := func(status, origin int, path, ref string, cat core.Category) core.Event { return core.Event{Time: now.Add(-30 * time.Minute), IP: "20.0.0.9", Cat: cat, Source: "traefik", Domain: "a.example", Method: "GET", Path: path, Referer: ref, UA: "Mozilla/5.0 x", Status: status, OriginStatus: origin, DurationNS: 30e6, OriginNS: 28e6, Router: "r-app@docker", Service: "r-app@docker", Proto: "HTTP/2.0", Scheme: "https", TLSVer: "1.3", TLSCiph: "TLS_AES_128_GCM_SHA256", E: core.Enrich{Device: "desktop"}} } for i := 0; i < 8; i++ { st.ObserveService(mk(200, 200, "/", "", core.OK)) } st.ObserveService(mk(500, 500, "/api/a", "", core.OK)) st.ObserveService(mk(404, 404, "/gone", "https://a.example/", core.NotFound)) st.ObserveService(mk(404, 404, "/.env", "", core.Scanner)) h := New(Options{Token: userTok, Version: "t", Store: st}) auth := map[string]string{"Authorization": "Bearer " + userTok} e := getJSON(t, h, "/api/v1/errors?range=24h", auth) cl := e["classes"].(map[string]any) if cl["app"].(float64) != 1 || cl["attack"].(float64) != 1 || cl["client"].(float64) != 1 || e["errors"].(float64) != 3 { t.Fatalf("errors: %v", e) } if len(e["broken"].([]any)) != 1 || len(e["top_routes"].([]any)) != 3 { t.Fatalf("lists: %v", e) } s := getJSONList(t, h, "/api/v1/services?range=24h", auth) if len(s) != 1 || s[0].(map[string]any)["svc"] != "r-app" { t.Fatalf("services: %v", s) } d := getJSON(t, h, "/api/v1/services/r-app?range=24h", auth) if d["histograms"] == nil || d["timeline"] == nil { t.Fatalf("service: %v", d) } if w := do(h, "GET", "/api/v1/services/nope?range=24h", cloneHdr(auth), nil); w.Code != 404 { t.Fatalf("404 expected, got %d", w.Code) } p := getJSON(t, h, "/api/v1/protocols?range=24h", auth) if p["protocols"].(map[string]any)["http2"] == nil || p["scheme"].(map[string]any)["https"].(float64) != 11 { t.Fatalf("protocols: %v", p) } } func getJSONList(t *testing.T, h http.Handler, path string, hd map[string]string) []any { w := do(h, "GET", path, cloneHdr(hd), nil) if w.Code != 200 { t.Fatalf("%s: %d %s", path, w.Code, w.Body) } var m []any if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil { t.Fatal(err) } return m }