Files
urutau/internal/app/app_test.go
T
Lucas RayanandClaude Opus 5.5 f4b295f582
Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 19s
CI / Tests (Linux, race detector) (push) Successful in 35s
CI / Dependency audit (push) Successful in 16s
Release / ci (push) Successful in 35s
Release / Build image (arm64) (push) Successful in 51s
Release / Build image (amd64) (push) Successful in 1m11s
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Skipped
feat: 1.1.0 interface, geography drill-down and live attack map
A new console interface (side rail, seven pages, opening sentence and
active slice on every page, IP drawer, light and dark design tokens);
a Geography page that drills from the world to a country's regions and
cities; a Live page drawing attacks as arcs on a flat map or a globe.

Backend: GET /api/v1/geo, GET /api/v1/live/recent, host/src/dst on live
events, --location, a strict static file pattern, and live federation
through GET /api/v1/peer/stream (peer token only, bounded and sanitized
relay on the hub).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:47:28 -03:00

431 lines
16 KiB
Go

package app
import (
"encoding/json"
"fmt"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func runner(t *testing.T, extra func(*Config)) (*Runner, *store.Store) {
c := Config{Ignore: DefaultIgnore, MonitorUA: DefaultMonitorUA, Name: "t", Retention: 168 * time.Hour, Trusted: "136.248.78.83,2001:db8:1::/48", TrustedProxy: DefaultTrustedProxy}
if extra != nil {
extra(&c)
}
st := store.New(store.Config{Name: "t", Version: "t"})
r, err := NewRunner(c, st, slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatal(err)
}
return r, st
}
func line(ip, method, path, ua string, status int) []byte {
return []byte(fmt.Sprintf(`{"ClientHost":%q,"DownstreamStatus":%d,"RequestHost":"a.example","RequestMethod":%q,"RequestPath":%q,"StartUTC":%q,"request_User-Agent":%q}`,
ip, status, method, path, time.Now().UTC().Format(time.RFC3339Nano), ua))
}
func TestMonitoringTrustedAndForged(t *testing.T) {
r, st := runner(t, nil)
h := r.handle(&source{name: "traefik", parse: traefikParse})
h(line("203.0.113.7", "GET", "/", "Uptime-Kuma/1.23", 200))
h(line("203.0.113.7", "GET", "/missing", "Uptime-Kuma/1.23", 404))
if _, ok := st.IP("203.0.113.7"); ok {
t.Fatal("monitor traffic must not create or score an IP")
}
sum := st.Summary("1h")
// without --monitor-from only the successful hit is filtered; the 404 is plain traffic
if sum.Totals.Monitoring != 1 || sum.Totals.Requests != 1 || sum.Totals.Malicious != 0 {
t.Fatalf("monitoring accounting: %+v", sum.Totals)
}
h(line("203.0.113.7", "GET", "/.env", "Uptime-Kuma/1.23", 404))
ip, ok := st.IP("203.0.113.7")
if !ok || ip.Score != 3 || ip.Counts["scanner"] != 1 {
t.Fatalf("forged monitor UA must be scored as an attack: %+v", ip)
}
if len(ip.Samples) != 1 || ip.Samples[0] != "GET /.env [forged monitor UA]" {
t.Fatalf("samples %v", ip.Samples)
}
if rec := st.Recent(5); len(rec) != 1 || !rec[0].Forged {
t.Fatalf("feed %+v", rec)
}
// trusted origins are dropped entirely, even for exploits and with other UAs
h(line("136.248.78.83", "GET", "/?x=../../etc/passwd", "curl/8", 200))
h(line("2001:db8:1::5", "GET", "/.env", "curl/8", 404))
h(line("127.0.0.1", "GET", "/.env", "curl/8", 404))
for _, a := range []string{"136.248.78.83", "2001:db8:1::5", "127.0.0.1"} {
if _, ok := st.IP(a); ok {
t.Fatalf("%s must be dropped", a)
}
}
// a non-matching UA from an external IP is a normal request
h(line("198.51.100.4", "GET", "/.env", "Mozilla/5.0", 404))
if _, ok := st.IP("198.51.100.4"); !ok {
t.Fatal("regular traffic is recorded")
}
}
const tok = "user-token-0123456789-abcdefghijklmnop"
func TestFlagsTrustedAndIgnoreAlias(t *testing.T) {
c, err := ParseFlags("serve", []string{"--trusted", "1.1.1.1", "--trusted", "2.2.2.0/24,3.3.3.3", "--ignore", "9.9.9.9", "--monitor-ua", "^kuma"})
if err != nil {
t.Fatal(err)
}
if c.Trusted != "1.1.1.1,2.2.2.0/24,3.3.3.3" || c.Ignore != "9.9.9.9" || c.MonitorUA != "^kuma" {
t.Fatalf("%+v", c)
}
c.Bind = "0.0.0.0:1"
if _, err := c.Validate(tok); err != nil {
t.Fatal(err)
}
c.MonitorUA = "("
if _, err := c.Validate(tok); err == nil {
t.Fatal("bad regex must be rejected")
}
if _, err := (Config{Ignore: "nonsense", MonitorUA: "", Retention: 168 * time.Hour}).Validate(tok); err == nil {
t.Fatal("bad cidr must be rejected")
}
if _, err := (Config{NoAuth: true, Bind: "0.0.0.0:1", Retention: 168 * time.Hour}).Validate(""); err == nil {
t.Fatal("no-auth must require loopback")
}
}
type fakeEnr struct{}
func (fakeEnr) Geo(ip string) core.GeoInfo {
return core.GeoInfo{CC: "NL", City: "Amsterdam", Country: "Netherlands"}
}
func (fakeEnr) UA(raw string) core.UAInfo {
switch {
case strings.HasPrefix(raw, "sqlmap"):
return core.UAInfo{Device: "tool", Tool: "sqlmap"}
case strings.HasPrefix(raw, "Googlebot"):
return core.UAInfo{Device: "bot", Bot: true, BotName: "Googlebot"}
}
return core.UAInfo{Browser: "Firefox", OS: "Linux", Device: "desktop"}
}
func TestEnrichmentFeedsThreatAndTraffic(t *testing.T) {
r, st := runner(t, nil)
r.Enr = fakeEnr{}
st.SetEnricher(fakeEnr{})
h := r.handle(&source{name: "traefik", parse: traefikParse})
h(line("203.0.113.9", "GET", "/", "Mozilla/5.0 Firefox", 200))
h(line("203.0.113.9", "GET", "/blog", "Mozilla/5.0 Firefox", 200))
h(line("66.249.1.1", "GET", "/", "Googlebot/2.1", 200))
h(line("198.51.100.66", "GET", "/.env", "sqlmap/1.7", 404))
tr := st.TrafficSummary("1h", "all")
if tr.Pages != 2 || tr.Visitors != 1 || tr.Bots != 1 || tr.Countries[0].Key != "NL" || tr.Browsers[0].Key != "Firefox" {
t.Fatalf("traffic %+v", tr)
}
ip, ok := st.IP("198.51.100.66")
if !ok || ip.Score != 5 || ip.CC != "NL" || ip.City != "Amsterdam" || len(ip.UALabels) != 1 || ip.UALabels[0] != "sqlmap (tool)" {
t.Fatalf("tool IP %+v", ip)
}
if _, ok := st.IP("203.0.113.9"); ok {
t.Fatal("legitimate visitor must not be tracked")
}
}
func TestTokenAndFederationValidation(t *testing.T) {
base := Config{Bind: "0.0.0.0:1", Retention: 168 * time.Hour, MonitorUA: "", Ignore: DefaultIgnore, TrustedProxy: DefaultTrustedProxy}
peerTok := "peer-token-0123456789-abcdefghijklmnopq"
if _, err := base.Validate("short-token-1234567890"); err == nil {
t.Fatal("URUTAU_TOKEN under 32 characters must be refused")
}
if _, err := base.Validate(tok); err != nil {
t.Fatal(err)
}
c := base
c.PeerToken = "short-peer"
if _, err := c.Validate(tok); err == nil {
t.Fatal("peer token under 32 characters must be refused")
}
c.PeerToken = tok
if _, err := c.Validate(tok); err == nil {
t.Fatal("peer token equal to URUTAU_TOKEN must be refused")
}
c.PeerToken = peerTok
if _, err := c.Validate(tok); err != nil {
t.Fatal(err)
}
c.Peers = []string{"hostinger=https://urutau.example.org"}
c.PeerToken = ""
if _, err := c.Validate(tok); err == nil {
t.Fatal("peers without a peer token must be refused")
}
c.PeerToken = peerTok
c.Peers = []string{"hostinger=http://urutau.example.org"}
if _, err := c.Validate(tok); err == nil {
t.Fatal("plain http to a non-loopback peer must be refused")
}
c.Peers = []string{"h=http://127.0.0.1:8791"}
if _, err := c.Validate(tok); err != nil {
t.Fatalf("http is fine on loopback: %v", err)
}
c.PeerAllow, c.Peers = "not-a-cidr", nil
if _, err := c.Validate(tok); err == nil {
t.Fatal("bad --peer-allow must be refused")
}
cfg, err := ParseFlags("serve", []string{"--peer-allow", "203.0.113.0/24", "--peer-allow", "198.51.100.7", "--trusted-proxy", "10.0.0.0/8"})
if err != nil || cfg.PeerAllow != "203.0.113.0/24,198.51.100.7" || cfg.TrustedProxy != "10.0.0.0/8" {
t.Fatalf("%+v %v", cfg, err)
}
}
func TestCorruptSnapshotDoesNotStopStartup(t *testing.T) {
log := slog.New(slog.NewTextHandler(io.Discard, nil))
dir := t.TempDir()
good := store.New(store.Config{Name: "t", Version: "t"})
good.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/x"})
if err := good.Save(SnapshotPath(dir), map[string]store.Offset{"traefik": {Inode: 1, Offset: 10}}); err != nil {
t.Fatal(err)
}
raw, _ := os.ReadFile(SnapshotPath(dir))
for name, data := range map[string][]byte{"truncated": raw[:len(raw)/2], "garbage": []byte("not a gob at all \x00\x01\x02"), "empty": {}} {
if err := os.WriteFile(SnapshotPath(dir), data, 0o600); err != nil {
t.Fatal(err)
}
st := store.New(store.Config{Name: "t", Version: "t"})
offs := LoadState(st, dir, log)
if len(offs) != 0 || st.IPCount() != 0 {
t.Fatalf("%s: must start empty, got %v / %d IPs", name, offs, st.IPCount())
}
if _, err := os.Stat(SnapshotPath(dir) + ".corrupt"); err != nil {
t.Fatalf("%s: the bad snapshot must be set aside: %v", name, err)
}
st.Ingest(core.Event{Time: time.Now(), IP: "6.6.6.6", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/x"})
if st.IPCount() != 1 {
t.Fatal("the store must be usable after a bad snapshot")
}
}
// the intact snapshot restores
if err := good.Save(SnapshotPath(dir), map[string]store.Offset{"traefik": {Inode: 1, Offset: 10}}); err != nil {
t.Fatal(err)
}
st := store.New(store.Config{Name: "t", Version: "t"})
if offs := LoadState(st, dir, log); offs["traefik"].Offset != 10 || st.IPCount() != 1 {
t.Fatal("a good snapshot must restore")
}
}
func TestDoctorJSONReportsGeoAndTraffic(t *testing.T) {
dir := t.TempDir()
st := store.New(store.Config{Name: "t", Version: "t"})
st.Traffic(core.Event{Time: time.Now(), IP: "9.9.9.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200})
if err := st.Save(SnapshotPath(dir), nil); err != nil {
t.Fatal(err)
}
t.Setenv("URUTAU_TOKEN", tok)
c := Config{Bind: "0.0.0.0:1", Name: "t", DataDir: dir, GeoDir: filepath.Join(dir, "geo"), GeoUpdate: time.Hour, Ignore: DefaultIgnore,
TrustedProxy: DefaultTrustedProxy, Retention: 168 * time.Hour}
var out strings.Builder
if !Doctor(c, &out, true) {
t.Fatalf("doctor failed: %s", out.String())
}
var doc struct {
Version string
Geo map[string]any
State map[string]any
Checks []Check
}
if err := json.Unmarshal([]byte(out.String()), &doc); err != nil {
t.Fatal(err)
}
if doc.Version == "" || doc.Geo["dir"] == nil || doc.Geo["attribution"] == nil || doc.Geo["city"] == nil {
t.Fatalf("geo section: %+v", doc.Geo)
}
if doc.State["traffic_domains"].(float64) != 1 || doc.State["ips"] == nil {
t.Fatalf("state section: %+v", doc.State)
}
if strings.Contains(out.String(), "9.9.9.9") {
t.Fatal("doctor must not print visitor IPs")
}
}
func TestMonitorFromBindsTheUserAgentToItsNetwork(t *testing.T) {
r, st := runner(t, func(c *Config) { c.MonitorFrom = "203.0.113.0/24" })
h := r.handle(&source{name: "traefik", parse: traefikParse})
h(line("203.0.113.7", "GET", "/", "Uptime-Kuma/1.23", 200))
h(line("203.0.113.7", "GET", "/gone", "Uptime-Kuma/1.23", 404))
if sum := st.Summary("1h"); sum.Totals.Monitoring != 2 || sum.Totals.Requests != 0 {
t.Fatalf("monitor from its network: %+v", sum.Totals)
}
h(line("198.51.100.9", "GET", "/", "Uptime-Kuma/1.23", 200))
if sum := st.Summary("24h"); sum.Totals.Monitoring != 2 || sum.Totals.Requests != 1 {
t.Fatalf("a monitor User-Agent from a stranger is ordinary traffic: %+v", sum.Totals)
}
}
func TestWeakMarkersNeedAnAttackTool(t *testing.T) {
r, st := runner(t, nil)
r.Enr = fakeEnr{}
h := r.handle(&source{name: "traefik", parse: traefikParse})
h(line("45.1.1.1", "GET", "/app?cmd=build", "Mozilla/5.0", 200))
if _, ok := st.IP("45.1.1.1"); ok {
t.Fatal("cmd= alone must not be an attack")
}
h(line("45.1.1.2", "GET", "/app?cmd=id", "sqlmap/1.7", 404))
d, ok := st.IP("45.1.1.2")
if !ok || d.Counts["exploit"] != 1 || !d.Strong {
t.Fatalf("cmd= with an attack tool: %+v", d)
}
}
func TestAPanicInOneLineDoesNotKillTheSource(t *testing.T) {
r, st := runner(t, nil)
r.Enr = panicEnr{}
src := &source{name: "traefik", parse: traefikParse}
h := r.handle(src)
h(line("45.1.1.3", "GET", "/.env", "x", 404)) // enrich panics
r.Enr = nil
h(line("45.1.1.4", "GET", "/.env", "x", 404))
if _, ok := st.IP("45.1.1.4"); !ok || src.malformed.Load() != 1 {
t.Fatal("the source must keep working after a panic and count it")
}
}
type panicEnr struct{}
func (panicEnr) Geo(string) core.GeoInfo { panic("corrupt database") }
func (panicEnr) UA(string) core.UAInfo { return core.UAInfo{} }
func TestTokenQualityAndFiles(t *testing.T) {
base := Config{Bind: "0.0.0.0:1", Retention: 168 * time.Hour, Ignore: DefaultIgnore, TrustedProxy: DefaultTrustedProxy}
if _, err := base.Validate(strings.Repeat("a", 40)); err == nil {
t.Fatal("aaaa... must be refused: too few distinct characters")
}
if _, err := base.Validate("abababababababababababababababab"); err == nil {
t.Fatal("two distinct characters must be refused")
}
if _, err := base.Validate(tok); err != nil {
t.Fatal(err)
}
dir := t.TempDir()
f := filepath.Join(dir, "token")
os.WriteFile(f, []byte(tok+"\n"), 0o600)
t.Setenv("URUTAU_TOKEN", "")
t.Setenv("URUTAU_TOKEN_FILE", f)
if got, err := Secret("URUTAU_TOKEN"); err != nil || got != tok {
t.Fatalf("%q %v", got, err)
}
t.Setenv("URUTAU_TOKEN_FILE", filepath.Join(dir, "missing"))
if _, err := Secret("URUTAU_TOKEN"); err == nil {
t.Fatal("a missing token file is an error")
}
}
func TestPerPeerTokens(t *testing.T) {
t.Setenv("URUTAU_PEER_TOKEN", "")
t.Setenv("URUTAU_PEER_TOKEN_HOSTINGER", "hostinger-token-0123456789-abcdefghijklmn")
f := filepath.Join(t.TempDir(), "o")
os.WriteFile(f, []byte("oracle-token-0123456789-abcdefghijklmnopq\n"), 0o600)
t.Setenv("URUTAU_PEER_TOKEN_MY_ORACLE_FILE", f)
c, err := ParseFlags("serve", []string{"--peer", "hostinger=https://h.example.org", "--peer", "my-oracle=https://o.example.org"})
if err != nil {
t.Fatal(err)
}
peers, err := c.Validate(tok)
if err != nil {
t.Fatal(err)
}
if peers[0].Token != "hostinger-token-0123456789-abcdefghijklmn" || peers[1].Token != "oracle-token-0123456789-abcdefghijklmnopq" {
t.Fatalf("per peer tokens: %+v", peers)
}
// Client tokens sent to peers never open the local export: a compromised
// peer knows its own token and must not read this instance with it.
if len(c.PeerTokens) != 0 {
t.Fatalf("per peer client tokens must not open the local export: %v", c.PeerTokens)
}
c.Peers = append(c.Peers, "nobody=https://n.example.org")
if _, err := c.Validate(tok); err == nil {
t.Fatal("a peer without any token must be refused")
}
}
func TestPeerServerTokenOnlyOpensExport(t *testing.T) {
t.Setenv("URUTAU_PEER_TOKEN", "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD")
t.Setenv("URUTAU_PEER_TOKEN_HOSTINGER", "client-side-token-Hj4kL9mN2pQ7rS1tV6wX3yZ")
c, err := ParseFlags("serve", []string{"--peer", "hostinger=https://h.example.org"})
if err != nil {
t.Fatal(err)
}
if len(c.PeerTokens) != 1 || c.PeerTokens[0] != "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD" {
t.Fatalf("export tokens: %v", c.PeerTokens)
}
}
func TestPeerNameTokenCollision(t *testing.T) {
t.Setenv("URUTAU_PEER_TOKEN", "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD")
c, err := ParseFlags("serve", []string{"--peer", "my-peer=https://a.example.org", "--peer", "my_peer=https://b.example.org"})
if err != nil {
t.Fatal(err)
}
if _, err := c.Validate(tok); err == nil || !strings.Contains(err.Error(), "share the token variable") {
t.Fatalf("colliding peer names must be refused, got %v", err)
}
}
// Without explicit configuration, X-Forwarded-For is only believed from loopback.
func TestTrustedProxyDefaultIsLoopback(t *testing.T) {
os.Unsetenv("URUTAU_TRUSTED_PROXY")
c, err := ParseFlags("serve", nil)
if err != nil {
t.Fatal(err)
}
if c.TrustedProxy != "127.0.0.0/8,::1" {
t.Fatalf("default trusted proxy: %q", c.TrustedProxy)
}
}
func TestHealthcheckCommand(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"status":"ok"}`)) }))
defer srv.Close()
if err := Healthcheck(Config{Bind: strings.TrimPrefix(srv.URL, "http://")}); err != nil {
t.Fatal(err)
}
bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "x", 500) }))
defer bad.Close()
if err := Healthcheck(Config{Bind: strings.TrimPrefix(bad.URL, "http://")}); err == nil {
t.Fatal("a failing daemon is unhealthy")
}
}
func TestDefaultIgnoreCoversPrivateRanges(t *testing.T) {
p, _ := core.ParseCIDRs(DefaultIgnore)
for _, ip := range []string{"192.168.1.5", "fd12::1", "fe80::2", "100.64.1.1", "169.254.3.3", "10.1.1.1", "127.0.0.1", "::1"} {
if !core.Ignored(p, ip) {
t.Errorf("%s must be ignored by default", ip)
}
}
}
func TestLocationFlagIsValidated(t *testing.T) {
for _, tc := range []struct {
v string
ok bool
}{{"", true}, {"-8.05,-34.9", true}, {"-8.05,-34.9,Recife", true}, {"95,0", false}, {"x", false}} {
c, err := ParseFlags("t", []string{"--location", tc.v})
if err != nil {
t.Fatal(err)
}
if _, err := c.Validate("zK3vQ9xT2mLp7WdR4nYb8HsJ6cFg1UaE5oXi0VtN"); (err == nil) != tc.ok {
t.Errorf("%q: %v", tc.v, err)
}
}
}