cmd/anubis: set X-Real-Ip based on X-Forwarded-For (#63)

This triggers a SHAME release[0].

[0]: https://pridever.org/
This commit is contained in:
Xe Iaso 2025-03-21 16:45:33 -04:00 committed by GitHub
parent a9777a3126
commit 07e6695430
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 27 additions and 1 deletions

View file

@ -1 +1 @@
1.14.0
1.14.1

View file

@ -214,6 +214,7 @@ func main() {
var h http.Handler
h = mux
h = internal.DefaultXRealIP(*debugXRealIPDefault, h)
h = internal.XForwardedForToXRealIP(h)
srv := http.Server{Handler: h}
listener, url := setupListener(*bindNetwork, *bind)

View file

@ -11,6 +11,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## v1.14.1
Livia sas Junius: Echo 1
- Set the `X-Real-Ip` header based on the contents of `X-Forwarded-For`
[#62](https://github.com/TecharoHQ/anubis/issues/62)
## v1.14.0
Livia sas Junius

1
go.mod
View file

@ -34,6 +34,7 @@ require (
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.62.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/sebest/xff v0.0.0-20210106013422-671bd2870b3a // indirect
golang.org/x/mod v0.24.0 // indirect
golang.org/x/net v0.37.0 // indirect
golang.org/x/sync v0.12.0 // indirect

2
go.sum
View file

@ -59,6 +59,8 @@ github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ
github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I=
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
github.com/sebest/xff v0.0.0-20210106013422-671bd2870b3a h1:iLcLb5Fwwz7g/DLK89F+uQBDeAhHhwdzB5fSlVdhGcM=
github.com/sebest/xff v0.0.0-20210106013422-671bd2870b3a/go.mod h1:wozgYq9WEBQBaIJe4YZ0qTSFAMxmcwBhQH0fO0R34Z0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=

View file

@ -5,6 +5,7 @@ import (
"net/http"
"github.com/TecharoHQ/anubis"
"github.com/sebest/xff"
)
// UnchangingCache sets the Cache-Control header to cache a response for 1 year if
@ -33,3 +34,17 @@ func DefaultXRealIP(defaultIP string, next http.Handler) http.Handler {
next.ServeHTTP(w, r)
})
}
// XForwardedForToXRealIP sets the X-Real-Ip header based on the contents
// of the X-Forwarded-For header.
func XForwardedForToXRealIP(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if xffHeader := r.Header.Get("X-Forwarded-For"); r.Header.Get("X-Real-Ip") == "" && xffHeader != "" {
ip := xff.Parse(xffHeader)
slog.Debug("setting x-real-ip", "val", ip)
r.Header.Set("X-Real-Ip", ip)
}
next.ServeHTTP(w, r)
})
}