package app import ( "bytes" "context" "encoding/json" "os" "path/filepath" "strings" "testing" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" ) // fixture is a data directory as written by Urutau 1.6 on the Hostinger host. // Regenerate it (and expected.json) with: // // URUTAU_REGEN_FIXTURE=1 go test ./internal/app -run TestRegenFixture16 -count=1 const fixture = "testdata/hostinger-1.6" func TestRegenFixture16(t *testing.T) { if os.Getenv("URUTAU_REGEN_FIXTURE") != "1" { t.Skip("set URUTAU_REGEN_FIXTURE=1 to regenerate " + fixture) } dir, _ := filepath.Abs(fixture) if err := os.RemoveAll(dir); err != nil { t.Fatal(err) } if err := os.MkdirAll(dir, 0o700); err != nil { t.Fatal(err) } now := time.Now() // store + evlog: the same wiring as serve.go elog, err := evlog.Open(evlog.Options{Dir: filepath.Join(dir, "events"), Retention: 30 * 24 * time.Hour}) if err != nil { t.Fatal(err) } st := store.New(store.Config{Name: "hostinger", Version: "1.6.0", Retention: 7 * 24 * time.Hour}) st.SetEventLog(elog) type ev struct { ip string cat core.Category src string path string st int ago time.Duration n int } for _, e := range []ev{ {"203.0.114.7", core.Scanner, "traefik", "/.env", 404, 3 * time.Hour, 6}, {"203.0.114.8", core.Exploit, "traefik", "/cgi-bin/../../etc/passwd", 400, 2 * time.Hour, 4}, {"198.51.101.20", core.SSHFail, "ssh", "", 0, 50 * time.Hour, 5}, {"198.51.101.21", core.OK, "traefik", "/", 200, 26 * time.Hour, 3}, {"192.0.2.99", core.Scanner, "traefik", "/wp-login.php", 404, 90 * time.Hour, 2}, } { for i := 0; i < e.n; i++ { c := core.Event{Time: now.Add(-e.ago + time.Duration(i)*time.Second), IP: e.ip, Cat: e.cat, Source: e.src, Domain: "a.example", Method: "GET", Path: e.path, Status: e.st, UA: "fixture"} if e.src == "ssh" { c.User = "root" } st.Ingest(c) } } elog.Flush() elog.Close() if err := st.Save(SnapshotPath(dir), map[string]store.Offset{ "traefik": {Inode: 4242, Offset: 1048576}, "auth": {Inode: 4243, Offset: 22000}, "egress": {Inode: 4244, Offset: 90210}, }); err != nil { t.Fatal(err) } // incidents: INC-1 suppressed, INC-2 with comments, INC-3 manual is, err := incidents.Open(filepath.Join(dir, "incidents.json"), nil) if err != nil { t.Fatal(err) } is.Sync([]incidents.Finding{ {Host: "hostinger", Kind: "new-destination", Severity: "medium", Workload: "app-a", Dst: "198.51.100.5", Proto: "tcp", DPort: 443, First: now.Add(-48 * time.Hour).Unix(), Last: now.Add(-time.Hour).Unix(), Count: 12, Detail: "first contact"}, {Host: "hostinger", Kind: "exfil", Severity: "high", Workload: "app-b", Dst: "203.0.113.50", Proto: "tcp", DPort: 4444, First: now.Add(-24 * time.Hour).Unix(), Last: now.Add(-time.Hour).Unix(), Count: 40, Detail: "large upload"}, }) if _, err := is.Create(incidents.NewManual{Title: "Manual review of the proxy", Detail: "opened by the operator", Host: "hostinger", Severity: "low", Author: "lucas"}); err != nil { t.Fatal(err) } fp, yes := "false_positive", true if _, err := is.Update("INC-1", incidents.Patch{Status: &fp, Suppress: &yes, Author: "lucas"}); err != nil { t.Fatal(err) } for _, c := range []string{"Looks like the nightly backup.", "Confirmed with the app owner; keep watching."} { if _, err := is.AddComment("INC-2", c, "lucas", ""); err != nil { t.Fatal(err) } } is.Flush() // enforce.json: real bans through the real engine decisions := filepath.Join(t.TempDir(), "decisions.log") eng := enforce.New(enforce.Config{Mode: enforce.ModeOn, Path: decisions, StatePath: filepath.Join(dir, "enforce.json"), Host: "hostinger", Threshold: 5, MaxPerMin: 60}) ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { eng.Run(ctx); close(done) }() for _, ip := range []string{"203.0.114.7", "203.0.114.8"} { for i := 0; i < 6; i++ { eng.Observe(core.Event{Time: time.Now().Add(-time.Duration(i) * time.Second), IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x", Status: 404, UA: "x"}, "") } } for i := 0; i < 100; i++ { if b, _ := os.ReadFile(decisions); strings.Count(string(b), "\n") >= 2 { break } time.Sleep(100 * time.Millisecond) } cancel() <-done // files the contract does not name: tor cache, a note, and geo (skipped by default) must := func(p, s string) { p = filepath.Join(dir, p) if err := os.MkdirAll(filepath.Dir(p), 0o750); err != nil { t.Fatal(err) } if err := os.WriteFile(p, []byte(s), 0o640); err != nil { t.Fatal(err) } } must("tor/exit-addresses.txt", "198.51.100.200\n198.51.100.201\n") must("tor/relays.json", `{"relays":[]}`) must("operator-notes.txt", "unknown file kept verbatim\n") must("geo/GeoLite2-City.mmdb", "not a real database") // fixed mtimes, so the preservation check is meaningful old := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC) for _, p := range []string{"operator-notes.txt", "tor/relays.json", "tor/exit-addresses.txt"} { _ = os.Chtimes(filepath.Join(dir, p), old, old) } c, err := CountDir(dir) if err != nil { t.Fatal(err) } b, _ := json.MarshalIndent(c, "", " ") if err := os.WriteFile(filepath.Join(filepath.Dir(dir), "hostinger-1.6.expected.json"), append(b, '\n'), 0o644); err != nil { t.Fatal(err) } t.Logf("fixture regenerated: %+v", c) } func expectedCounts(t *testing.T) Counts { b, err := os.ReadFile("testdata/hostinger-1.6.expected.json") if err != nil { t.Fatal(err) } var c Counts if err := json.Unmarshal(b, &c); err != nil { t.Fatal(err) } return c } func TestFixtureCounts(t *testing.T) { c, err := CountDir(fixture) if err != nil { t.Fatal(err) } if want := expectedCounts(t); c != want { t.Fatalf("counts %+v want %+v", c, want) } if c.Events < 10 || c.IPs < 4 || c.Incidents != 3 || c.Comments < 2 || c.Suppressed < 1 || c.EnforceBans < 2 || c.Offsets != 3 { t.Fatalf("fixture is not realistic enough: %+v", c) } } func mustImport(t *testing.T, from, dd, host string, o ImportOptions) ImportReport { t.Helper() r, err := Import(from, dd, host, o) if err != nil { t.Fatal(err) } return r } func copyDir(t *testing.T, from string) string { t.Helper() to := filepath.Join(t.TempDir(), "src") tr, err := scanTree(from, true, false) if err != nil { t.Fatal(err) } if err := copyTree(from, to, tr.entries); err != nil { t.Fatal(err) } return to } func TestImportCountsAndHashes(t *testing.T) { dd := t.TempDir() fixture := copyDir(t, fixture) // git does not keep mtimes: pin one old := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC) os.Chtimes(filepath.Join(fixture, "operator-notes.txt"), old, old) rep := mustImport(t, fixture, dd, "hostinger", ImportOptions{}) dest := filepath.Join(dd, "probes", "hostinger") if rep.Dest != dest || rep.Skipped || rep.DryRun { t.Fatalf("report %+v", rep) } if want := expectedCounts(t); rep.Counts != want { t.Fatalf("counts %+v want %+v", rep.Counts, want) } got, err := CountDir(dest) if err != nil || got != rep.Counts { t.Fatalf("destination counts %+v %v", got, err) } // byte for byte: hashes, mode, mtime of every file; unknown files included; geo skipped srcT, _ := scanTree(fixture, false, false) hashTree(fixture, srcT) dstT, _ := scanTree(dest, true, true) hashTree(dest, dstT) if d := sameContent(srcT.entries, dropManifest(dstT.entries)); len(d) > 0 { t.Fatal(d) } if d := sameMeta(srcT.entries, dstT.entries); len(d) > 0 { t.Fatal(d) } for _, must := range []string{"urutau-state.gob", "incidents.json", "enforce.json", "operator-notes.txt", "tor/relays.json", ManifestName} { if _, err := os.Stat(filepath.Join(dest, must)); err != nil { t.Errorf("%s missing: %v", must, err) } } if _, err := os.Stat(filepath.Join(dest, "geo")); err == nil { t.Error("geo/ must be skipped by default") } found := false for _, w := range rep.Warnings { found = found || strings.Contains(w, "geo/") } if !found { t.Errorf("no geo warning: %v", rep.Warnings) } if fi, _ := os.Stat(filepath.Join(dest, "operator-notes.txt")); fi.ModTime().UTC().Year() != 2026 || fi.ModTime().UTC().Month() != 11 || fi.ModTime().UTC().Day() != 1 { t.Errorf("mtime not preserved: %v", fi.ModTime()) } if _, err := os.Stat(filepath.Join(dd, lockName)); err == nil { t.Error("the import lock was left behind") } if ents, _ := os.ReadDir(filepath.Join(dd, "probes")); len(ents) != 1 { t.Errorf("temporary directory left behind: %v", ents) } // the real loaders on the copy: the INC-2 comments, the suppression, the evlog lines is, err := incidents.Open(filepath.Join(dest, "incidents.json"), nil) if err != nil { t.Fatal(err) } tk, err := is.Get("INC-2") if err != nil || len(tk.Comments) != 2 { t.Fatalf("INC-2 %+v %v", tk, err) } if tk1, _ := is.Get("INC-1"); !tk1.Suppress { t.Error("INC-1 lost its suppression") } el, err := evlog.Open(evlog.Options{Dir: filepath.Join(dest, "events"), Retention: 30 * 24 * time.Hour}) if err != nil { t.Fatal(err) } n := 0 el.Scan(evlog.Filter{}, 0, false, func(evlog.Rec, []byte) bool { n++; return true }) el.Close() if n != rep.Events { t.Errorf("evlog scan sees %d events, count says %d", n, rep.Events) } st := store.New(store.Config{Name: "hostinger", MaxIPs: 1 << 20}) if offs, err := st.Load(SnapshotPath(dest)); err != nil || len(offs) != 3 || st.IPCount() != rep.IPs { t.Errorf("snapshot of the copy: %v %d %v", offs, st.IPCount(), err) } // verify passes if _, err := VerifyImport(fixture, dd, "hostinger"); err != nil { t.Fatal(err) } } func TestImportIdempotentAndDivergent(t *testing.T) { dd := t.TempDir() src := copyDir(t, fixture) mustImport(t, src, dd, "hostinger", ImportOptions{}) if r := mustImport(t, src, dd, "hostinger", ImportOptions{}); !r.Skipped { t.Fatalf("second run must be skipped: %+v", r) } // a hub that already ran changes the destination: still skipped, with a warning, nothing touched dest := filepath.Join(dd, "probes", "hostinger") if err := os.WriteFile(filepath.Join(dest, "incidents.json"), []byte(`{"next":9,"tickets":[]}`), 0o600); err != nil { t.Fatal(err) } r := mustImport(t, src, dd, "hostinger", ImportOptions{}) if !r.Skipped || len(r.Warnings) == 0 { t.Fatalf("drifted destination: %+v", r) } if b, _ := os.ReadFile(filepath.Join(dest, "incidents.json")); !strings.Contains(string(b), `"next":9`) { t.Fatal("skipped import touched the destination") } // the source changes: divergent, refuse without --force if err := os.WriteFile(filepath.Join(src, "operator-notes.txt"), []byte("changed\n"), 0o640); err != nil { t.Fatal(err) } if _, err := Import(src, dd, "hostinger", ImportOptions{}); err == nil || !strings.Contains(err.Error(), "--force") { t.Fatalf("divergent without --force must fail: %v", err) } if b, _ := os.ReadFile(filepath.Join(dest, "incidents.json")); !strings.Contains(string(b), `"next":9`) { t.Fatal("a refused import touched the destination") } // --force: old destination kept as .bak, new one in place r = mustImport(t, src, dd, "hostinger", ImportOptions{Force: true}) if r.Backup == "" || !strings.Contains(r.Backup, ".bak-") { t.Fatalf("backup %+v", r) } if b, _ := os.ReadFile(filepath.Join(r.Backup, "incidents.json")); !strings.Contains(string(b), `"next":9`) { t.Fatal("backup lost the old destination") } if _, err := os.Stat(filepath.Join(r.Backup, ManifestName)); err != nil { t.Fatal("backup lost the old manifest") } if b, _ := os.ReadFile(filepath.Join(dest, "operator-notes.txt")); string(b) != "changed\n" { t.Fatal("new content not installed") } // a second --force keeps the first backup too if err := os.WriteFile(filepath.Join(src, "operator-notes.txt"), []byte("changed again\n"), 0o640); err != nil { t.Fatal(err) } r2 := mustImport(t, src, dd, "hostinger", ImportOptions{Force: true}) if r2.Backup == r.Backup { t.Fatal("backups collided") } if _, err := os.Stat(r.Backup); err != nil { t.Fatal("first backup was deleted") } } func TestImportDestWithoutManifestIsDivergent(t *testing.T) { dd := t.TempDir() dest := filepath.Join(dd, "probes", "hostinger") os.MkdirAll(dest, 0o700) os.WriteFile(filepath.Join(dest, "urutau-state.gob"), []byte("something"), 0o600) if _, err := Import(fixture, dd, "hostinger", ImportOptions{}); err == nil { t.Fatal("must not import over an existing unknown directory") } if b, _ := os.ReadFile(filepath.Join(dest, "urutau-state.gob")); string(b) != "something" { t.Fatal("destination changed") } } func TestImportDryRunWritesNothing(t *testing.T) { dd := t.TempDir() rep := mustImport(t, fixture, dd, "hostinger", ImportOptions{DryRun: true}) if !rep.DryRun || len(rep.Files) == 0 || rep.Events == 0 { t.Fatalf("report %+v", rep) } if ents, _ := os.ReadDir(dd); len(ents) != 0 { t.Fatalf("dry run wrote %v", ents) } // also on top of an existing, divergent destination with --force mustImport(t, fixture, dd, "hostinger", ImportOptions{}) src := copyDir(t, fixture) os.WriteFile(filepath.Join(src, "operator-notes.txt"), []byte("x"), 0o640) before := treeSums(t, dd) if _, err := Import(src, dd, "hostinger", ImportOptions{DryRun: true, Force: true}); err != nil { t.Fatal(err) } if after := treeSums(t, dd); after != before { t.Fatal("dry run changed the data dir") } } func treeSums(t *testing.T, root string) string { tr, err := scanTree(root, true, true) if err != nil { t.Fatal(err) } if err := hashTree(root, tr); err != nil { t.Fatal(err) } b, _ := json.Marshal(tr.entries) return string(b) } func TestImportRefusesWithLock(t *testing.T) { dd := t.TempDir() if err := os.WriteFile(filepath.Join(dd, lockName), []byte("12345\n"), 0o600); err != nil { t.Fatal(err) } for _, o := range []ImportOptions{{}, {DryRun: true}, {Force: true}} { if _, err := Import(fixture, dd, "hostinger", o); err == nil || !strings.Contains(err.Error(), lockName) { t.Fatalf("lock must refuse (%+v): %v", o, err) } } if _, err := os.Stat(filepath.Join(dd, "probes")); err == nil { t.Fatal("wrote something despite the lock") } if _, err := os.Stat(filepath.Join(dd, lockName)); err != nil { t.Fatal("removed a lock that was not ours") } } func TestVerifyDetectsDamage(t *testing.T) { dd := t.TempDir() src := copyDir(t, fixture) if _, err := VerifyImport(src, dd, "hostinger"); err == nil { t.Fatal("verify before import must fail") } old := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC) os.Chtimes(filepath.Join(src, "operator-notes.txt"), old, old) mustImport(t, src, dd, "hostinger", ImportOptions{}) if _, err := VerifyImport(src, dd, "hostinger"); err != nil { t.Fatal(err) } dest := filepath.Join(dd, "probes", "hostinger") os.WriteFile(filepath.Join(dest, "operator-notes.txt"), []byte("unknown file kept verbatim\n"), 0o640) // same bytes, new mtime if _, err := VerifyImport(src, dd, "hostinger"); err == nil { t.Fatal("mtime damage not detected") } os.Chtimes(filepath.Join(dest, "operator-notes.txt"), old, old) if _, err := VerifyImport(src, dd, "hostinger"); err != nil { t.Fatal(err) } b, _ := os.ReadFile(filepath.Join(dest, "urutau-state.gob")) b[len(b)/2] ^= 0xff os.WriteFile(filepath.Join(dest, "urutau-state.gob"), b, 0o600) if _, err := VerifyImport(src, dd, "hostinger"); err == nil || !strings.Contains(err.Error(), "urutau-state.gob") { t.Fatalf("corruption not detected: %v", err) } } func TestCountDirDoesNotModify(t *testing.T) { src := copyDir(t, fixture) before := treeSums(t, src) if _, err := CountDir(src); err != nil { t.Fatal(err) } if treeSums(t, src) != before { t.Fatal("counting changed the directory") } // a corrupt incidents.json is an error and stays where it is (the real Open would rename it) os.WriteFile(filepath.Join(src, "incidents.json"), []byte("{broken"), 0o600) if _, err := CountDir(src); err == nil { t.Fatal("corrupt incidents.json must be an error") } if _, err := os.Stat(filepath.Join(src, "incidents.json")); err != nil { t.Fatal("corrupt file was moved") } } func TestImportArgs(t *testing.T) { dd := t.TempDir() if _, err := Import(fixture, dd, "Bad_Name", ImportOptions{}); err == nil { t.Fatal("invalid host accepted") } if _, err := Import(filepath.Join(dd, "missing"), dd, "hostinger", ImportOptions{}); err == nil { t.Fatal("missing source accepted") } src := filepath.Join(dd, "inside") os.MkdirAll(src, 0o700) if _, err := Import(src, dd, "hostinger", ImportOptions{}); err == nil { t.Fatal("source inside the data dir accepted") } if _, err := Import(fixture, fixture, "hostinger", ImportOptions{}); err == nil { t.Fatal("data dir equal to the source accepted") } // a source that is itself an import destination is not a 1.x directory mustImport(t, fixture, dd, "hostinger", ImportOptions{}) if _, err := Import(filepath.Join(dd, "probes", "hostinger"), t.TempDir(), "other", ImportOptions{}); err == nil { t.Fatal("manifest in the source must be refused") } } func TestImportGeoOptIn(t *testing.T) { dd := t.TempDir() mustImport(t, fixture, dd, "hostinger", ImportOptions{IncludeGeo: true}) if _, err := os.Stat(filepath.Join(dd, "probes", "hostinger", "geo", "GeoLite2-City.mmdb")); err != nil { t.Fatal(err) } if _, err := VerifyImport(fixture, dd, "hostinger"); err != nil { t.Fatal(err) } } func TestImportEmptyAndSymlink(t *testing.T) { src := t.TempDir() os.WriteFile(filepath.Join(src, "extra.bin"), []byte{0, 1, 2}, 0o600) os.MkdirAll(filepath.Join(src, "sub", "deep"), 0o750) os.WriteFile(filepath.Join(src, "sub", "deep", "x"), []byte("x"), 0o600) os.Symlink("extra.bin", filepath.Join(src, "link")) dd := t.TempDir() rep := mustImport(t, src, dd, "bare", ImportOptions{}) if rep.Events != 0 || rep.IPs != 0 { t.Fatalf("%+v", rep.Counts) } if tg, err := os.Readlink(filepath.Join(dd, "probes", "bare", "link")); err != nil || tg != "extra.bin" { t.Fatalf("symlink: %q %v", tg, err) } if _, err := VerifyImport(src, dd, "bare"); err != nil { t.Fatal(err) } } func TestImportCLI(t *testing.T) { var out, errb bytes.Buffer if code := ImportCLI([]string{"--count", fixture}, &out, &errb); code != 0 || !strings.Contains(out.String(), "incidents=3") { t.Fatalf("count: %d %q %q", code, out.String(), errb.String()) } dd := t.TempDir() out.Reset() if code := ImportCLI([]string{"--from", fixture, "--host", "hostinger", "--data-dir", dd, "--dry-run"}, &out, &errb); code != 0 || !strings.Contains(out.String(), "dry run") { t.Fatalf("dry: %d %q %q", code, out.String(), errb.String()) } out.Reset() if code := ImportCLI([]string{"--from", fixture, "--host", "hostinger", "--data-dir", dd}, &out, &errb); code != 0 || !strings.Contains(out.String(), "imported") { t.Fatalf("import: %d %q %q", code, out.String(), errb.String()) } out.Reset() if code := ImportCLI([]string{"--verify", "--from", fixture, "--host", "hostinger", "--data-dir", dd}, &out, &errb); code != 0 || !strings.Contains(out.String(), "verified") { t.Fatalf("verify: %d %q %q", code, out.String(), errb.String()) } out.Reset() if code := ImportCLI([]string{"--from", fixture, "--host", "hostinger", "--data-dir", dd}, &out, &errb); code != 0 || !strings.Contains(out.String(), "already imported") { t.Fatalf("again: %d %q", code, out.String()) } if code := ImportCLI([]string{"--host", "x"}, &out, &errb); code != 2 { t.Fatalf("usage code %d", code) } }