package abuseipdb import ( "encoding/json" "net/http" "net/http/httptest" "strings" "testing" ) func TestCheckAndReport(t *testing.T) { var gotKey string server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotKey = r.Header.Get("Key") w.Header().Set("Content-Type", "application/json") if r.URL.Path == "/check" { if r.URL.Query().Get("ipAddress") != "8.8.8.8" || r.URL.Query().Get("maxAgeInDays") != "90" { t.Fatalf("unexpected check query: %s", r.URL.RawQuery) } _, _ = w.Write([]byte(`{"data":{"ipAddress":"8.8.8.8","abuseConfidenceScore":75,"totalReports":4}}`)) return } if r.URL.Path != "/report" || r.Method != http.MethodPost { t.Fatalf("unexpected report request: %s %s", r.Method, r.URL.Path) } if err := r.ParseForm(); err != nil || r.Form.Get("ip") != "8.8.8.8" || r.Form.Get("categories") != "14,18" { t.Fatalf("unexpected report form: %v", r.Form) } _, _ = w.Write([]byte(`{"data":{"ipAddress":"8.8.8.8","abuseConfidenceScore":80}}`)) })) defer server.Close() h := NewHandler(Config{Key: "test-key", BaseURL: server.URL}) check := httptest.NewRecorder() checkReq := httptest.NewRequest(http.MethodGet, "/api/source-ips/8.8.8.8/abuseipdb", nil).WithContext(t.Context()) checkReq.SetPathValue("ip", "8.8.8.8") h.Check(check, checkReq) if check.Code != http.StatusOK || !strings.Contains(check.Body.String(), `"abuseConfidenceScore":75`) { t.Fatalf("check response: %d %s", check.Code, check.Body.String()) } report := httptest.NewRecorder() body, _ := json.Marshal(reportRequest{Categories: []int{14, 18}, Comment: "scanner activity"}) reportReq := httptest.NewRequest(http.MethodPost, "/api/source-ips/8.8.8.8/abuseipdb/report", strings.NewReader(string(body))).WithContext(t.Context()) reportReq.SetPathValue("ip", "8.8.8.8") h.Report(report, reportReq) if report.Code != http.StatusOK || !strings.Contains(report.Body.String(), `"abuseConfidenceScore":80`) { t.Fatalf("report response: %d %s", report.Code, report.Body.String()) } if gotKey != "test-key" { t.Fatalf("key header = %q", gotKey) } } func TestRejectsPrivateAndUnconfigured(t *testing.T) { private := httptest.NewRecorder() privateReq := httptest.NewRequest(http.MethodGet, "/api/source-ips/192.168.1.2/abuseipdb", nil) privateReq.SetPathValue("ip", "192.168.1.2") NewHandler(Config{Key: "test-key", BaseURL: "http://invalid"}).Check(private, privateReq) if private.Code != http.StatusBadRequest { t.Fatalf("private status = %d", private.Code) } unconfigured := httptest.NewRecorder() unconfiguredReq := httptest.NewRequest(http.MethodGet, "/api/source-ips/8.8.8.8/abuseipdb", nil) unconfiguredReq.SetPathValue("ip", "8.8.8.8") NewHandler(Config{}).Check(unconfigured, unconfiguredReq) if unconfigured.Code != http.StatusNotImplemented { t.Fatalf("unconfigured status = %d", unconfigured.Code) } }