feat: parse remote address from X-Forwarded-For header

This commit is contained in:
2026-05-06 01:40:28 +02:00
parent f51d2cc471
commit 0a88292f0a
+14 -1
View File
@@ -7,6 +7,7 @@ import (
"net/http/httputil" "net/http/httputil"
"net/url" "net/url"
"os" "os"
"strings"
) )
func main() { func main() {
@@ -34,7 +35,7 @@ func main() {
u, p, ok := r.BasicAuth() u, p, ok := r.BasicAuth()
if !ok || subtle.ConstantTimeCompare([]byte(u), []byte(username)) != 1 || if !ok || subtle.ConstantTimeCompare([]byte(u), []byte(username)) != 1 ||
subtle.ConstantTimeCompare([]byte(p), []byte(password)) != 1 { subtle.ConstantTimeCompare([]byte(p), []byte(password)) != 1 {
log.Printf("unauthorized request from %s", r.RemoteAddr) log.Printf("unauthorized request from %s", clientIP(r))
w.Header().Set("WWW-Authenticate", `Basic realm="pz8-relay"`) w.Header().Set("WWW-Authenticate", `Basic realm="pz8-relay"`)
http.Error(w, "unauthorized", http.StatusUnauthorized) http.Error(w, "unauthorized", http.StatusUnauthorized)
return return
@@ -46,6 +47,18 @@ func main() {
log.Fatal(http.ListenAndServe(addr, nil)) log.Fatal(http.ListenAndServe(addr, nil))
} }
// clientIP returns the original client address, trusting X-Forwarded-For
// because this service runs behind Traefik. Do not expose directly.
func clientIP(r *http.Request) string {
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
if i := strings.IndexByte(xff, ','); i >= 0 {
return strings.TrimSpace(xff[:i])
}
return strings.TrimSpace(xff)
}
return r.RemoteAddr
}
func mustEnv(key string) string { func mustEnv(key string) string {
v := os.Getenv(key) v := os.Getenv(key)
if v == "" { if v == "" {