package store import ( "bytes" "encoding/json" "os" "path/filepath" "testing" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" ) func visit(ip, dom, path, ref string, status int, ago time.Duration) core.Event { return core.Event{Time: t0.Add(-ago), IP: ip, Cat: core.OK, Source: "traefik", Domain: dom, Method: "GET", Path: path, UA: "Mozilla/5.0 test", Status: status, DurationNS: 40e6, Bytes: 1000, Referer: ref, E: core.Enrich{CC: "BR", City: "Recife", Browser: "Firefox", OS: "Linux", Device: "desktop"}} } func TestTrafficAggregatesAndPrivacy(t *testing.T) { s := newStore("oracle", 100) for i := 0; i < 5; i++ { s.Traffic(visit("200.100.50.25", "a.example", "/blog", "https://www.google.com/search?q=x", 200, time.Duration(i)*time.Minute)) } s.Traffic(visit("200.100.50.26", "a.example", "/", "https://a.example/blog", 200, time.Minute)) s.Traffic(visit("200.100.50.26", "a.example", "/style.css", "", 200, time.Minute)) s.Traffic(visit("200.100.50.27", "b.example", "/s.css", "", 200, time.Minute)) s.Traffic(visit("200.100.50.27", "b.example", "/x", "", 404, time.Minute)) bot := visit("66.249.66.1", "a.example", "/", "", 200, time.Minute) bot.E = core.Enrich{Bot: true, BotName: "Googlebot", Device: "bot"} s.Traffic(bot) all := s.TrafficSummary("24h", "all") if all.Requests != 10 || all.Pages != 6 || all.Visitors != 2 || all.Bots != 1 { t.Fatalf("all: %+v", all) } if all.Status[0] != 9 || all.Status[2] != 1 || all.Bytes != 10000 { t.Fatalf("status/bytes %+v %d", all.Status, all.Bytes) } if all.P50 < 25 || all.P50 > 50 || all.P95 < 25 || all.P95 > 50 { t.Fatalf("latency p50=%v p95=%v", all.P50, all.P95) } if len(all.Domains) != 2 || all.Domains[0].Key != "a.example" { t.Fatalf("domains %+v", all.Domains) } if len(all.Referrers) != 1 || all.Referrers[0].Key != "google.com" || all.Referrers[0].N != 5 { t.Fatalf("referrers (self referrals are not external): %+v", all.Referrers) } if all.Countries[0].Key != "BR" || all.Cities[0].Key != "Recife, BR" || all.Browsers[0].Key != "Firefox" || all.BotNames[0].Key != "Googlebot" { t.Fatalf("breakdowns %+v", all) } for _, p := range all.TopPages { if p.Key == "/style.css" { t.Fatal("assets are not pages") } } a := s.TrafficSummary("24h", "a.example") if a.Requests != 8 || a.Visitors != 2 { t.Fatalf("per domain %+v", a) } var tl uint32 for _, v := range a.Timeline.Req { tl += v } if tl != 8 { t.Fatalf("timeline %d", tl) } if w := s.TrafficSummary("7d", "a.example"); w.Requests != 8 || w.Visitors != 2 { t.Fatalf("7d %+v", w) } // privacy: the visitor IPs reach neither the snapshot nor any API payload p := filepath.Join(t.TempDir(), "state.gob") if err := s.Save(p, nil); err != nil { t.Fatal(err) } raw, _ := os.ReadFile(p) api, _ := json.Marshal([]any{all, a, s.Summary("24h"), s.AllIPs(ParseRange("7d"), true)}) for _, ip := range []string{"200.100.50.25", "200.100.50.26", "200.100.50.27", "66.249.66.1"} { if bytes.Contains(raw, []byte(ip)) || bytes.Contains(api, []byte(ip)) { t.Fatalf("visitor IP %s leaked", ip) } if _, ok := s.IP(ip); ok { t.Fatalf("visitor IP %s is in the threat table", ip) } } if bytes.Contains(raw, s.tr.salt[:]) { t.Fatal("the daily salt must never reach the disk") } if s.tr.saltDay == 0 { t.Fatal("test precondition: a salt was generated") } // the snapshot restores the aggregates s2 := newStore("oracle", 100) if _, err := s2.Load(p); err != nil { t.Fatal(err) } if r := s2.TrafficSummary("24h", "all"); r.Requests != 10 || r.Visitors != 2 { t.Fatalf("restored %+v", r) } } func TestMergeTrafficAndDomainCap(t *testing.T) { a, b := newStore("oracle", 10), newStore("hostinger", 10) a.Traffic(visit("1.1.1.1", "a.example", "/", "", 200, time.Minute)) b.Traffic(visit("2.2.2.2", "a.example", "/", "", 200, time.Minute)) b.Traffic(visit("2.2.2.3", "c.example", "/", "", 200, time.Minute)) m := MergeTraffic("all", []TrafficData{a.TrafficSummary("1h", "all"), b.TrafficSummary("1h", "all")}) if m.Requests != 3 || m.Visitors != 3 || len(m.Domains) != 2 || m.Domains[0].N != 2 || m.Countries[0].N != 3 { t.Fatalf("%+v", m) } c := newStore("x", 10) for i := 0; i < 60; i++ { c.Traffic(visit("1.1.1.1", "d"+string(rune('a'+i%26))+string(rune('a'+i/26))+".example", "/", "", 200, time.Minute)) } if len(c.tr.dom) > maxDomains+1 { t.Fatalf("domain cap: %d", len(c.tr.dom)) } } func TestToolBonusAndCountries(t *testing.T) { s := newStore("x", 100) e := ev("9.9.9.9", core.Scanner, time.Minute) e.E = core.Enrich{CC: "RU", Tool: true} s.Ingest(e) n := ev("9.9.9.8", core.NotFound, time.Minute) s.Ingest(n) if _, ok := s.IP("9.9.9.8"); ok { t.Fatal("404 without tool must not be tracked") } n.E.Tool = true n.IP = "9.9.9.7" s.Ingest(n) if r, ok := s.IP("9.9.9.9"); !ok || r.Score != 5 { t.Fatalf("tool bonus: %+v", r) } if r, ok := s.IP("9.9.9.7"); !ok || r.Score != 2.2 { t.Fatalf("tool 404: %+v", r) } if c := s.Summary("1h").Countries; len(c) != 1 || c[0].Key != "RU" || c[0].N != 1 { t.Fatalf("countries %+v", c) } } func browser(ip, dom, path string) core.Event { return visit(ip, dom, path, "", 200, time.Minute) } func TestVisitorsAreRealBrowsersCountedByAddress(t *testing.T) { s := newStore("oracle", 100) // a scraper rotating the User-Agent from one address is one visitor, not five for i := 0; i < 5; i++ { ev := browser("200.100.50.30", "a.example", "/p") ev.UA = "Mozilla/5.0 rotating " + string(rune('a'+i)) s.Traffic(ev) } // the same person on two sites counts once in the all-domains total s.Traffic(browser("200.100.50.31", "a.example", "/")) s.Traffic(browser("200.100.50.31", "b.example", "/")) // fetch/XHR, prefetch, HEAD: not pages, not visitors api := browser("200.100.50.32", "a.example", "/api/v1/summary") api.FetchDest = "empty" s.Traffic(api) pre := browser("200.100.50.33", "a.example", "/next") pre.Prefetch = true s.Traffic(pre) head := browser("200.100.50.34", "a.example", "/") head.Method = "HEAD" s.Traffic(head) doc := browser("200.100.50.35", "a.example", "/doc") doc.FetchDest = "document" s.Traffic(doc) // tools, unknown and empty User-Agents, and bots: non-human clients for i, e := range []core.Enrich{ {Device: "tool", Tool: true}, {Device: "unknown"}, {}, {Bot: true, BotName: "Googlebot", Device: "bot"}, } { ev := browser("66.249.66."+string(rune('1'+i)), "a.example", "/") ev.E = e s.Traffic(ev) } other := browser("66.249.66.1", "b.example", "/") // same bot on a second site other.E = core.Enrich{Bot: true, Device: "bot"} s.Traffic(other) all := s.TrafficSummary("24h", "all") if all.Visitors != 3 { // .30, .31, .35 t.Fatalf("all visitors = %d, want 3", all.Visitors) } if all.NonHuman != 4 { // four distinct addresses; the bot seen on two sites counts once t.Fatalf("all non-human = %d, want 4", all.NonHuman) } if a := s.TrafficSummary("24h", "a.example"); a.Visitors != 3 || a.NonHuman != 4 || a.Pages != 7 { t.Fatalf("a.example: visitors=%d nonhuman=%d pages=%d", a.Visitors, a.NonHuman, a.Pages) } if b := s.TrafficSummary("24h", "b.example"); b.Visitors != 1 || b.NonHuman != 1 { t.Fatalf("b.example: visitors=%d nonhuman=%d", b.Visitors, b.NonHuman) } } func TestNonHumanSurvivesSnapshotAndMerge(t *testing.T) { s := newStore("oracle", 100) bot := browser("66.249.66.9", "a.example", "/") bot.E = core.Enrich{Device: "tool", Tool: true} s.Traffic(bot) s.Traffic(browser("200.100.50.40", "a.example", "/")) a := s.TrafficSummary("24h", "all") m := MergeTraffic("all", []TrafficData{a, a}) if a.NonHuman != 1 || a.Visitors != 1 || m.NonHuman != 2 || m.Visitors != 2 { t.Fatalf("a=%+v m=%+v", a, m) } } type visGeo struct{} func (visGeo) Geo(ip string) core.GeoInfo { return core.GeoInfo{CC: "BR", City: "Recife", Lat: -8.0476, Lon: -34.877} } func (visGeo) UA(string) core.UAInfo { return core.UAInfo{} } func TestVisitEventsHaveNoAddressAndAreRateLimited(t *testing.T) { s := newStore("oracle", 100) s.SetEnricher(visGeo{}) // without subscribers nothing is built or kept s.Traffic(browser("200.100.50.60", "a.example", "/x")) ch, stop := s.SubscribeVisits() defer stop() ev := browser("200.100.50.61", "a.example", "/u/123e4567-e89b-12d3-a456-426614174000?token=secret") ev.Referer = "https://ref.example/?q=1" s.Traffic(ev) asset := browser("200.100.50.61", "a.example", "/s.css") s.Traffic(asset) // assets are not visits m := <-ch b, _ := json.Marshal(m) for _, bad := range []string{"200.100.50", `"ip"`, "Mozilla", "ref.example", "secret", "123e4567"} { if bytes.Contains(b, []byte(bad)) { t.Fatalf("visit leaks %q: %s", bad, b) } } if m.Kind != "visit" || m.Host != "oracle" || m.Domain != "a.example" || m.Device != "desktop" || m.Status != 200 || m.Path != "/u/:id" || m.Src == nil || m.Src.Lat != -8.0 || m.Src.Lon != -34.9 || m.Src.CC != "BR" { t.Fatalf("visit %s", b) } select { case x := <-ch: t.Fatalf("unexpected extra event %+v", x) default: } // 50 in one second: 20 pass (the first already used 1), the rest is dropped, then a batch for i := 0; i < 50; i++ { s.Traffic(browser("200.100.50.62", "a.example", "/p")) } s.now = func() time.Time { return t0.Add(time.Hour) } late := browser("200.100.50.63", "a.example", "/p") late.Time = t0.Add(time.Hour) s.Traffic(late) visits, batch := 0, 0 for len(ch) > 0 { x := <-ch bb, _ := json.Marshal(x) if bytes.Contains(bb, []byte(`"ip"`)) { t.Fatalf("ip in %s", bb) } switch x.Kind { case "visit": visits++ case "visit_batch": batch += x.N } } if visits != 20 || batch != 31 { // 19 left of the first second + 1 new second; 31 dropped t.Fatalf("visits=%d dropped=%d", visits, batch) } } func TestVisitSanitizeFromPeer(t *testing.T) { m := VisitMsg{Kind: "visit", T: 1, Domain: "d", Path: "/a\x01b", Device: "", Src: &GeoPoint{Lat: 500}} if !m.Sanitize(t0.Unix()) || m.Device != "unknown" || m.Src != nil || m.Path != "/ab" { t.Fatalf("%+v", m) } if (&VisitMsg{Kind: "ev"}).Sanitize(1) { t.Fatal("unknown kind accepted") } var raw map[string]any json.Unmarshal([]byte(`{"kind":"visit","ip":"1.2.3.4"}`), &raw) var v VisitMsg json.Unmarshal([]byte(`{"kind":"visit","ip":"1.2.3.4"}`), &v) b, _ := json.Marshal(v) if bytes.Contains(b, []byte("1.2.3.4")) { t.Fatal("ip survived a round trip") } }