package server import ( "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" "net/http/httptest" "testing" ) func TestUserStudySlotsAnd503(t *testing.T) { s := &Server{user: make(chan struct{}, 2)} for i := 0; i < 2; i++ { if !s.userSlot(httptest.NewRecorder()) { t.Fatal("slot refused too early") } } w := httptest.NewRecorder() if s.userSlot(w) || w.Code != 503 || w.Header().Get("Retry-After") == "" { t.Fatalf("third study: %d %v", w.Code, w.Header()) } <-s.user if !s.userSlot(httptest.NewRecorder()) { t.Fatal("a slot must free up") } } func TestSortTargetsReturnsTheCutList(t *testing.T) { var l []map[string]any for i := 0; i < 30; i++ { l = append(l, map[string]any{"n": i}) } out := sortTargets(l) if len(out) != 20 || out[0]["n"].(int) != 29 || out[19]["n"].(int) != 10 { t.Fatalf("%d %v", len(out), out[0]) } } func TestActiveBansPairing(t *testing.T) { b := func(t int64, jail string, un bool) store.BanEvent { return store.BanEvent{T: t, Jail: jail, Unban: un} } reg := []store.BanEvent{b(1, "botsearch", false), b(2, "botsearch", true), b(3, "sshd", false), b(4, "sshd", true), b(5, "sshd", false), b(6, "sshd", false), b(7, "recidive", false)} got := activeBans(reg, store.IPInfo{Jails: []string{"sshd", "recidive"}}, "h") active := map[int64]bool{} for _, x := range got { if x.Active { active[x.T] = true } } // only the latest ban of each jail in force is active; an unbanned jail is not if len(got) != 7 || len(active) != 2 || !active[6] || !active[7] { t.Fatalf("%+v", got) } // both unbanned: nothing is active for _, x := range activeBans(reg[:4], store.IPInfo{}, "h") { if x.Active { t.Fatal("unbanned jails are never active") } } // an active ban that began before the window (or before the registry) is still listed got = activeBans(nil, store.IPInfo{Jails: []string{"recidive"}, BanSince: 99}, "h") if len(got) != 1 || !got[0].Active || got[0].T != 99 || got[0].Jail != "recidive" { t.Fatalf("%+v", got) } // the registry says the jail was released but the record still holds the ban: the record wins got = activeBans(reg[:4], store.IPInfo{Jails: []string{"sshd"}, BanSince: 50}, "h") n := 0 for _, x := range got { if x.Active { n++ } } if n != 1 || got[len(got)-1].T != 50 { t.Fatalf("%+v", got) } }