fix
This commit is contained in:
@@ -185,11 +185,13 @@ func Handler() http.Handler {
|
||||
}
|
||||
|
||||
// Gate restricts Prometheus scrapes in production: allow when metricsPublic is true
|
||||
// (METRICS_PUBLIC=1) or the peer is loopback. Non-production always allows (local scrapes).
|
||||
// (METRICS_PUBLIC=1) or the immediate TCP peer is loopback. Non-production always
|
||||
// allows (local scrapes). Loopback is ignored when client-IP proxy headers are
|
||||
// present so TrustedRealIP cannot mint 127.0.0.1 from X-Forwarded-For.
|
||||
func Gate(isProduction, metricsPublic bool) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !isProduction || metricsPublic || isLoopbackRemoteAddr(r.RemoteAddr) {
|
||||
if !isProduction || metricsPublic || allowLoopbackMetricsPeer(r) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
@@ -198,6 +200,19 @@ func Gate(isProduction, metricsPublic bool) func(http.Handler) http.Handler {
|
||||
}
|
||||
}
|
||||
|
||||
func allowLoopbackMetricsPeer(r *http.Request) bool {
|
||||
if forwardedClientIPPresent(r) {
|
||||
return false
|
||||
}
|
||||
return isLoopbackRemoteAddr(r.RemoteAddr)
|
||||
}
|
||||
|
||||
func forwardedClientIPPresent(r *http.Request) bool {
|
||||
return strings.TrimSpace(r.Header.Get("X-Forwarded-For")) != "" ||
|
||||
strings.TrimSpace(r.Header.Get("X-Real-IP")) != "" ||
|
||||
strings.TrimSpace(r.Header.Get("True-Client-IP")) != ""
|
||||
}
|
||||
|
||||
func isLoopbackRemoteAddr(remoteAddr string) bool {
|
||||
host := strings.TrimSpace(remoteAddr)
|
||||
if host == "" {
|
||||
|
||||
@@ -134,3 +134,17 @@ func TestGateAllowsPublicFlagInProduction(t *testing.T) {
|
||||
t.Fatalf("METRICS_PUBLIC status=%d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateBlocksSpoofedLoopbackXFFInProduction(t *testing.T) {
|
||||
t.Cleanup(Reset)
|
||||
Reset()
|
||||
h := Gate(true, false)(Handler())
|
||||
req := httptest.NewRequest(http.MethodGet, "/metrics", nil)
|
||||
req.RemoteAddr = "127.0.0.1:54321"
|
||||
req.Header.Set("X-Forwarded-For", "127.0.0.1")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("spoofed XFF loopback status=%d want 404", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user