fix(api): 仅信任配置的反向代理转发客户端 IP (#39)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
|
||||
"github.com/baicai2026-baicai/goods/api/internal/clientip"
|
||||
"github.com/baicai2026-baicai/goods/api/internal/ratelimit"
|
||||
"github.com/baicai2026-baicai/goods/api/internal/store"
|
||||
)
|
||||
@@ -57,6 +58,7 @@ type Handler struct {
|
||||
store *store.Store
|
||||
spa fs.FS
|
||||
limiter *ratelimit.Limiter
|
||||
clientIP *clientip.Resolver
|
||||
anonLimit int
|
||||
anonTotalQuota int64
|
||||
regRatePerMin int
|
||||
@@ -69,6 +71,7 @@ func New(s *store.Store, spa fs.FS) *Handler {
|
||||
return &Handler{
|
||||
store: s,
|
||||
spa: spa,
|
||||
clientIP: clientip.Default(),
|
||||
anonLimit: defaultAnonLimit,
|
||||
anonTotalQuota: defaultAnonTotalQuota,
|
||||
regRatePerMin: defaultRegRatePerMin,
|
||||
@@ -87,6 +90,15 @@ func (h *Handler) WithRateLimit(l *ratelimit.Limiter, anonPerMin int) *Handler {
|
||||
return h
|
||||
}
|
||||
|
||||
// WithClientIP sets the trusted-proxy resolver used to normalize request IPs.
|
||||
func (h *Handler) WithClientIP(resolver *clientip.Resolver) *Handler {
|
||||
if resolver == nil {
|
||||
resolver = clientip.Default()
|
||||
}
|
||||
h.clientIP = resolver
|
||||
return h
|
||||
}
|
||||
|
||||
// WithQuotas configures the cumulative free quota for anonymous callers and the
|
||||
// per-minute rate + cumulative quota self-registered keys receive. Non-positive
|
||||
// values keep the defaults.
|
||||
@@ -107,7 +119,7 @@ func (h *Handler) WithQuotas(anonTotal, regPerMin, regTotal int) *Handler {
|
||||
func (h *Handler) Router() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(h.clientIP.Middleware)
|
||||
r.Use(middleware.Recoverer)
|
||||
|
||||
r.Get("/healthz", h.Healthz)
|
||||
|
||||
@@ -133,7 +133,7 @@ func presentedKey(r *http.Request) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// clientIP returns the caller IP, preferring chi's RealIP-normalized RemoteAddr.
|
||||
// clientIP returns the caller IP from the trusted-proxy-normalized RemoteAddr.
|
||||
func clientIP(r *http.Request) string {
|
||||
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||
return host
|
||||
|
||||
Reference in New Issue
Block a user