package server import ( "path/filepath" "testing" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" ) func TestAnalyticsAPI(t *testing.T) { st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour}) l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")}) st.SetEventLog(l) now := time.Now() for i := 0; i < 5; i++ { st.Ingest(core.Event{Time: now.Add(-time.Hour - time.Duration(i)*time.Minute), IP: "20.0.0.1", Cat: core.Scanner, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/.env", Status: 404, UA: "zgrab/0.x"}) } st.Ingest(core.Event{Time: now.Add(-time.Hour), IP: "20.0.0.2", Cat: core.Scanner, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/x", Status: 404}) st.Ingest(core.Event{Time: now.Add(-30 * time.Minute), IP: "20.0.0.1", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"}) h := New(Options{Token: userTok, Version: "t", Store: st}) auth := map[string]string{"Authorization": "Bearer " + userTok} e := getJSON(t, h, "/api/v1/evolution", auth) if e["total"].(float64) != 6 || len(e["days"].([]any)) < 30 || len(e["hour_dow"].([]any)) != 7 { t.Fatalf("evolution: %v", e) } for _, k := range []string{"new_families", "gone_families", "delta_pct"} { if _, ok := e[k]; !ok { t.Errorf("evolution misses %s", k) } } c := getJSON(t, h, "/api/v1/concentration?dim=ip&range=24h", auth) items := c["items"].([]any) if c["total"].(float64) != 6 || len(items) != 2 || items[0].(map[string]any)["key"] != "20.0.0.1" { t.Fatalf("concentration: %v", c) } v := getJSON(t, h, "/api/v1/survival?range=24h", auth) if v["km"] == nil || v["by_family"] == nil || v["recidivists"] == nil || v["banned"].(float64) != 1 { t.Fatalf("survival: %v", v) } for path, want := range map[string]int{ "/api/v1/concentration?dim=nope": 400, "/api/v1/survival?range=bogus": 400, "/api/v1/evolution?host=nowhere": 404, "/api/v1/concentration?dim=path&host": 200, } { if w := do(h, "GET", path, cloneHdr(auth), nil); w.Code != want { t.Errorf("%s: %d want %d", path, w.Code, want) } } if w := do(h, "GET", "/api/v1/survival", nil, nil); w.Code != 401 && w.Code != 302 && w.Code != 403 { t.Errorf("anonymous: %d", w.Code) } }