Backend: Add logs and metric for when host is redirected (#112373)

This commit is contained in:
Josh Hunt
2025-11-04 13:28:33 +00:00
committed by GitHub
parent 0c016e210a
commit 69e4b4667b
+13
View File
@@ -3,11 +3,22 @@ package middleware
import (
"strings"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/web"
)
var (
hostRedirectCounter = promauto.NewCounter(prometheus.CounterOpts{
Name: "host_redirect_total",
Help: "Number of requests redirected due to host header mismatch",
Namespace: "grafana",
})
)
func ValidateHostHeader(cfg *setting.Cfg) web.Handler {
return func(c *contextmodel.ReqContext) {
// ignore local render calls
@@ -21,6 +32,8 @@ func ValidateHostHeader(cfg *setting.Cfg) web.Handler {
}
if !strings.EqualFold(h, cfg.Domain) {
hostRedirectCounter.Inc()
c.Logger.Info("Enforcing Host header", "hosted", c.Req.Host, "expected", cfg.Domain)
c.Redirect(strings.TrimSuffix(cfg.AppURL, "/")+c.Req.RequestURI, 301)
return
}