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} 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) } cfg, err := ParseFlags("serve", []string{"--trusted-proxy", "10.0.0.0/8"}) if err != nil || cfg.TrustedProxy != "10.0.0.0/8" { t.Fatalf("%+v %v", cfg, err) } bad := base bad.Name = "Not Valid" if err := bad.Validate(tok); err == nil { t.Fatal("the primary probe name must follow wire.ValidName") } } func TestRemovedEnvIsFatal(t *testing.T) { t.Setenv("URUTAU_PEERS", "hostinger=https://x.example.org") _, err := CheckRemovedEnv(os.LookupEnv) if err == nil || !strings.Contains(err.Error(), "URUTAU_PEERS") || !strings.Contains(err.Error(), "migration-2.0") { t.Fatalf("PEERS must stop the hub with a pointer to the guide: %v", err) } t.Setenv("URUTAU_PEERS", "") os.Unsetenv("URUTAU_PEERS") t.Setenv("URUTAU_PEER_TOKEN_HOSTINGER", "x") if _, err := CheckRemovedEnv(os.LookupEnv); err == nil { t.Fatal("per peer token must stop the hub") } os.Unsetenv("URUTAU_PEER_TOKEN_HOSTINGER") t.Setenv("URUTAU_TRAEFIK_LOG", "/x") warn, err := CheckRemovedEnv(os.LookupEnv) if err != nil || len(warn) != 1 { t.Fatalf("the 1.x image variables only warn: %v %v", warn, err) } t.Setenv("URUTAU_ENFORCE_LOG", "/x") if _, err := CheckRemovedEnv(os.LookupEnv); err == nil { t.Fatal("URUTAU_ENFORCE_LOG must be fatal") } } 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") } } // 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) } } }