package botfilter import ( "context" "net/http" "net/http/httptest" "testing" ) func TestRequiredHeaderCreatesTemporaryBan(t *testing.T) { cfg := CreateConfig() cfg.RequireUserAgent = true cfg.RequireAccept = true cfg.RequireHost = true nextCalls := 0 handler, err := New(context.Background(), http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { nextCalls++ rw.WriteHeader(http.StatusOK) }), cfg, "test") if err != nil { t.Fatalf("New() error = %v", err) } first := httptest.NewRequest(http.MethodGet, "http://wiki.example/content/article", nil) first.RemoteAddr = "203.0.113.11:54321" first.Header.Set("Accept", "text/html") first.Header.Del("User-Agent") firstResponse := httptest.NewRecorder() handler.ServeHTTP(firstResponse, first) if firstResponse.Code != http.StatusForbidden { t.Fatalf("first response status = %d, want %d", firstResponse.Code, http.StatusForbidden) } if firstResponse.Header().Get("Retry-After") == "" { t.Fatal("first response did not include Retry-After") } second := httptest.NewRequest(http.MethodGet, "http://wiki.example/", nil) second.RemoteAddr = "203.0.113.11:54321" second.Header.Set("Accept", "text/html") second.Header.Set("User-Agent", "Mozilla/5.0 Chrome/120.0 AppleWebKit/537.36 Safari/537.36") secondResponse := httptest.NewRecorder() handler.ServeHTTP(secondResponse, second) if secondResponse.Code != http.StatusForbidden { t.Fatalf("second response status = %d, want cached ban", secondResponse.Code) } if nextCalls != 0 { t.Fatalf("next handler calls = %d, want 0", nextCalls) } } func TestWhitelistBypassesFilter(t *testing.T) { cfg := CreateConfig() cfg.RequireUserAgent = true cfg.WhitelistCIDRs = []string{"192.168.0.0/16"} handler, err := New(context.Background(), http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusNoContent) }), cfg, "test") if err != nil { t.Fatalf("New() error = %v", err) }