diff --git a/main.go b/main.go index b1ffd5b..6f765dc 100644 --- a/main.go +++ b/main.go @@ -7,6 +7,7 @@ import ( "net/http/httputil" "net/url" "os" + "strings" ) func main() { @@ -34,7 +35,7 @@ func main() { u, p, ok := r.BasicAuth() if !ok || subtle.ConstantTimeCompare([]byte(u), []byte(username)) != 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"`) http.Error(w, "unauthorized", http.StatusUnauthorized) return @@ -46,6 +47,18 @@ func main() { 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 { v := os.Getenv(key) if v == "" {