Files
uptimesebi/internal/platform/router.go
T
Sebastian UnterschützandClaude Opus 5.5 789ef077eb feat(platform): trust X-Forwarded-For only from configured proxies
gin trusted every proxy by default, so any client could choose the
address used for rate limits and the audit log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 09:59:52 +01:00

72 lines
1.9 KiB
Go

package platform
import (
"io"
"log/slog"
"net/http"
"runtime/debug"
"time"
"github.com/gin-gonic/gin"
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
)
var quietPaths = map[string]bool{"/healthz": true, "/readyz": true}
// NewRouter returns a gin engine that assigns request IDs, logs requests and
// panics through log as JSON and writes nothing to stdout itself.
func NewRouter(log *slog.Logger) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
gin.DefaultWriter = io.Discard
gin.DefaultErrorWriter = io.Discard
r := gin.New()
_ = r.SetTrustedProxies(nil)
r.Use(requestid.Middleware(), accessLog(log), recovery(log))
return r
}
// TrustProxies makes r take client addresses from X-Forwarded-For only when
// the request comes from one of proxies.
func TrustProxies(r *gin.Engine, proxies []string) error {
return r.SetTrustedProxies(proxies)
}
func accessLog(log *slog.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
if quietPaths[c.Request.URL.Path] && c.Writer.Status() < 500 {
return
}
attrs := []any{
"method", c.Request.Method,
"path", c.Request.URL.Path,
"route", c.FullPath(),
"status", c.Writer.Status(),
"duration_ms", time.Since(start).Milliseconds(),
"bytes", c.Writer.Size(),
"client_ip", c.ClientIP(),
}
if len(c.Errors) > 0 {
attrs = append(attrs, "errors", c.Errors.Errors())
}
level := slog.LevelInfo
switch {
case c.Writer.Status() >= 500:
level = slog.LevelError
case c.Writer.Status() >= 400:
level = slog.LevelWarn
}
log.Log(c.Request.Context(), level, "http request", attrs...)
}
}
func recovery(log *slog.Logger) gin.HandlerFunc {
return gin.CustomRecoveryWithWriter(io.Discard, func(c *gin.Context, err any) {
log.ErrorContext(c.Request.Context(), "panic",
"error", err, "path", c.Request.URL.Path, "stack", string(debug.Stack()))
c.AbortWithStatus(http.StatusInternalServerError)
})
}