package middleware import ( "net/http" "net/netip" p "git.whoswhip.dev/whoswhip/minibin/internal/pages" "github.com/oschwald/maxminddb-golang/v2" ) type ASNRecord struct { ASN uint32 `maxminddb:"autonomous_system_number"` } type ASNBlocker struct { DB *maxminddb.Reader Blocked map[uint32]struct{} Pages *p.Pages ResolveIP func(*http.Request) (string, error) } func (b *ASNBlocker) BlockASN(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { { ip, err := b.ResolveIP(r) if err != nil { b.Pages.HTTPError(w, r, "couldn't idenitify client address", http.StatusInternalServerError) return } parsed, err := netip.ParseAddr(ip) if err != nil { b.Pages.HTTPError(w, r, "couldn't idenitify client address", http.StatusInternalServerError) return } result := b.DB.Lookup(parsed) if !result.Found() { next.ServeHTTP(w, r) return } var record ASNRecord if err := result.Decode(&record); err != nil { b.Pages.HTTPError(w, r, "couldn't idenitify client address", http.StatusInternalServerError) return } if _, blocked := b.Blocked[record.ASN]; blocked { b.Pages.HTTPError(w, r, "traffic from your ASN is not allowed", http.StatusForbidden, "403, forbidden") return } next.ServeHTTP(w, r) } }) }