Files
urutau/internal/fed/live_test.go
T
Lucas RayanandClaude Opus 5.5 2ebda1e4d7
Release / Plan (reuse the published image?) (push) Successful in 3s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 28s
CI / Dependency audit (push) Successful in 20s
CI / Tests (Linux, race detector) (push) Successful in 1m10s
Release / ci (push) Successful in 1m10s
Release / Build image (arm64) (push) Successful in 55s
Release / Build image (amd64) (push) Successful in 1m16s
Release / Publish tags (push) Successful in 14s
Release / Gitea release (push) Skipped
feat: 1.3.0 thirteen new pages, charts, tooltips and error analysis
New pages grouped in the rail (Monitor, Investigate, Analyze, Operate,
Reports): Services (SLO, Apdex, latency app vs proxy), Sessions (stage
funnel), Campaigns, Event search, MITRE ATT&CK matrix, Evolution,
Concentration (Pareto, Gini), Survival (Kaplan-Meier per attack
episode, recidivists), Where errors come from (application vs failed
attack vs proxy vs client), Protocols and TLS, Defense (fail2ban, SSH,
blocklist), Integrity, and a printable executive report.

Chart library (donut, radar, stacked area, bars, heatmap, gauge),
glossary with accessible "?" tooltips, self-explanatory category names
(nonexistent page 404), page loader through pages.json.

Unique visitors fixed: real browsers opening a page, one per IP per day,
deduplicated across domains, with non-human clients counted apart.
Anonymous legitimate visits on the Live page (?visits=1, no IP).
Traefik origin, service, protocol and TLS fields parsed. Paths and
Referer paths drop e-mail and token segments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 22:39:33 -03:00

217 lines
7.6 KiB
Go

package fed_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func fakeStream(t *testing.T, conns *atomic.Int32, body func(w http.ResponseWriter)) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v1/peer/stream" {
http.NotFound(w, r)
return
}
if r.Header.Get("Authorization") != "Bearer tok" {
http.Error(w, "no", 401)
return
}
conns.Add(1)
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(200)
body(w)
w.(http.Flusher).Flush()
<-r.Context().Done()
}))
}
func ev(data string) string { return "event: ev\ndata: " + data + "\n\n" }
func TestLiveRelaySanitizesAndDrops(t *testing.T) {
var conns atomic.Int32
big := ev(`{"ip":"1.2.3.4","cat":"scanner","path":"` + strings.Repeat("a", 20000) + `"}`)
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
fmt.Fprint(w, ": connected\n\n")
fmt.Fprint(w, ev(`{"ip":"not-an-ip","cat":"scanner"}`))
fmt.Fprint(w, ev(`{"ip":"5.5.5.5","cat":"ok"}`)) // not malicious
fmt.Fprint(w, ev(`{"ip":"5.5.5.5","cat":"<script>"}`)) // unknown category
fmt.Fprint(w, ev(`{"ip":"6.6.6.6","cat":"exploit","host":"evil","path":"/a\u0001b`+strings.Repeat("x", 500)+`","cc":"brasil","status":99999,"src":{"lat":500,"lon":1},"dst":{"lat":10,"lon":20,"label":"`+strings.Repeat("L", 200)+`"},"extra":"x"}`))
fmt.Fprint(w, "event: other\ndata: {\"ip\":\"7.7.7.7\",\"cat\":\"exploit\"}\n\n")
fmt.Fprint(w, ev(`{"ip":"8.8.8.8","cat":"scanner","src":{"lat":-8,"lon":-34,"cc":"BR","city":"Recife"}}`))
fmt.Fprint(w, big) // over 16 KB: the stream is cut
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ch, stop := h.Subscribe()
defer stop()
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
var got []store.LiveEvent
for len(got) < 2 {
select {
case e := <-ch:
got = append(got, e)
case <-time.After(5 * time.Second):
t.Fatalf("only %d events: %+v", len(got), got)
}
}
a, b := got[0], got[1]
if a.IP != "6.6.6.6" || a.Host != "edge" || a.Cat != "exploit" || a.CC != "" || a.Status != 0 || a.Src != nil {
t.Fatalf("sanitized event %+v", a)
}
if strings.ContainsRune(a.Path, 1) || len(a.Path) > 240 || a.Dst == nil || len(a.Dst.Label) != 64 {
t.Fatalf("strings %q dst %+v", a.Path, a.Dst)
}
if b.IP != "8.8.8.8" || b.Src == nil || b.Src.City != "Recife" || b.Host != "edge" {
t.Fatalf("second %+v", b)
}
if r := h.Recent(10); len(r) != 2 || r[0].IP != "8.8.8.8" {
t.Fatalf("recent %+v", r)
}
// the oversize line ended the stream: no event from it, and the hub reconnects
deadline := time.After(5 * time.Second)
for conns.Load() < 2 {
select {
case <-deadline:
t.Fatalf("no reconnection (%d)", conns.Load())
case <-time.After(50 * time.Millisecond):
}
}
select {
case e := <-ch:
if e.IP == "1.2.3.4" {
t.Fatal("oversize line must not become an event")
}
default:
}
}
func TestLiveRateLimitAndFlag(t *testing.T) {
var conns atomic.Int32
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
for i := 0; i < 400; i++ {
fmt.Fprint(w, ev(fmt.Sprintf(`{"ip":"9.9.%d.%d","cat":"scanner"}`, i/250, i%250+1)))
}
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
deadline := time.Now().Add(5 * time.Second)
for len(h.Recent(500)) == 0 && time.Now().Before(deadline) {
time.Sleep(20 * time.Millisecond)
}
time.Sleep(300 * time.Millisecond)
if n := len(h.Recent(500)); n < 40 || n > 120 {
t.Fatalf("a burst of 400 must be cut to about 50 (got %d)", n)
}
if hs := h.Hosts(); len(hs) != 1 || hs[0].Live {
// Live also needs the peer to be online (polled); here it never was
t.Fatalf("hosts %+v", hs)
}
}
func TestLiveWithRealPeerServer(t *testing.T) {
ps := store.New(store.Config{Name: "remote", Version: "t", Location: &store.Location{Lat: -8, Lon: -35, Label: "Recife"}})
srv := httptest.NewServer(server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{"peer-secret-0123456789-abcdefghijklmnopqr"}, Version: "t", Store: ps}))
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "peer-secret-0123456789-abcdefghijklmnopqr")
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Refresh(ctx)
h.Stream(ctx)
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
ps.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/x"})
if len(h.Recent(5)) > 0 {
break
}
time.Sleep(50 * time.Millisecond)
}
r := h.Recent(5)
if len(r) == 0 || r[0].Host != "edge" || r[0].IP != "5.5.5.5" || r[0].Dst == nil || r[0].Dst.Label != "Recife" {
t.Fatalf("relayed %+v", r)
}
hs := h.Hosts()
if !hs[0].Live || !hs[0].Online || hs[0].Location == nil || hs[0].Location.Label != "Recife" {
t.Fatalf("hosts %+v", hs)
}
}
func TestLiveByteFloodDropsConnection(t *testing.T) {
defer fed.SetLiveLimits(200*time.Millisecond, 10_000, 100*time.Millisecond)()
start := time.Now()
var conns atomic.Int32
pad := strings.Repeat("a", 1000)
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
for i := 0; i < 200; i++ { // ~200 KB at once: far above 10 KB/s
fmt.Fprintf(w, ": %s\n", pad)
}
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
// the flood ends the connection (window check), then the hub reconnects after the backoff
for conns.Load() < 2 {
if time.Since(start) > 2500*time.Millisecond {
t.Fatalf("no drop and reconnection (%d connections)", conns.Load())
}
time.Sleep(20 * time.Millisecond)
}
}
func TestVisitRelayHasNoAddressAndNoRecent(t *testing.T) {
var conns atomic.Int32
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit","t":`+fmt.Sprint(time.Now().Unix())+`,"host":"evil","ip":"9.9.9.9","ua":"Mozilla","domain":"a.example","path":"/x","status":200,"device":"mobile","src":{"lat":-8,"lon":-34.9,"cc":"BR","city":"Recife"}}`+"\n\n")
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit_batch","t":`+fmt.Sprint(time.Now().Unix())+`,"n":7}`+"\n\n")
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"nope"}`+"\n\n")
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ch, stop := h.SubscribeVisits()
defer stop()
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
var got []store.VisitMsg
for len(got) < 2 {
select {
case m := <-ch:
got = append(got, m)
case <-time.After(5 * time.Second):
t.Fatalf("timeout, got %+v", got)
}
}
for _, m := range got {
b, _ := json.Marshal(m)
if strings.Contains(string(b), "9.9.9.9") || strings.Contains(string(b), `"ip"`) || strings.Contains(string(b), "Mozilla") || m.Host != "edge" {
t.Fatalf("relayed %s", b)
}
}
if got[0].Device != "mobile" || got[1].Kind != "visit_batch" || got[1].N != 7 || len(h.Recent(10)) != 0 {
t.Fatalf("%+v recent=%d", got, len(h.Recent(10)))
}
}