package admin import ( "net/http" "net/http/httptest" "testing" ) func okHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte("ok")) }) } func TestIPAllow(t *testing.T) { allow, err := ParseCIDRs([]string{"127.0.0.0/8", "10.0.0.0/8"}) if err != nil { t.Fatal(err) } store := newFakeStore() sec := NewSecurityLog(store, nil) mw := NewIPAllow(allow, sec, okHandler()) cases := []struct { remote string want int }{ {"127.0.0.1:5555", http.StatusOK}, {"10.4.5.6:5555", http.StatusOK}, {"8.8.8.8:5555", http.StatusForbidden}, {"192.168.1.1:5555", http.StatusForbidden}, } for _, c := range cases { req := httptest.NewRequest("GET", "/", nil) req.RemoteAddr = c.remote rec := httptest.NewRecorder() mw.ServeHTTP(rec, req) if rec.Code != c.want { t.Errorf("remote %s: status %d; want %d", c.remote, rec.Code, c.want) } } // A blocked request must produce a security-event audit row. if len(store.auditFor("admin_ip_blocked")) == 0 { t.Error("expected admin_ip_blocked security event in audit log") } }