api: fix remote addr shows reverse proxy addr problem

Uses the first ip addr in X-forwarded-for as the client's remote addr if it exists
otherwise, fall back to use default http.Request.RemoteAddr
This commit is contained in:
Sida Chen 2017-06-05 18:02:56 -04:00
parent 044425ec07
commit c6f0eaa3c8
3 changed files with 28 additions and 2 deletions

24
api/httputil/httputil.go Normal file
View File

@ -0,0 +1,24 @@
package httputil
import (
"net"
"net/http"
"strings"
)
// GetClientAddr returns the first value in X-Forwarded-For if it exists
// otherwise fall back to use RemoteAddr
func GetClientAddr(r *http.Request) string {
addr := r.RemoteAddr
if s := r.Header.Get("X-Forwarded-For"); s != "" {
ips := strings.Split(s, ",")
// assume the first one is the client address
if len(ips) != 0 {
// validate the ip
if realIP := net.ParseIP(ips[0]); realIP != nil {
addr = strings.TrimSpace(ips[0])
}
}
}
return addr
}

View File

@ -21,6 +21,7 @@ import (
"github.com/julienschmidt/httprouter"
log "github.com/sirupsen/logrus"
"github.com/coreos/clair/api/httputil"
"github.com/coreos/clair/api/v1"
"github.com/coreos/clair/database"
)
@ -53,7 +54,7 @@ func (rtr router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
log.WithFields(log.Fields{"status": http.StatusNotFound, "method": r.Method, "request uri": r.RequestURI, "remote addr": r.RemoteAddr}).Info("Served HTTP request")
log.WithFields(log.Fields{"status": http.StatusNotFound, "method": r.Method, "request uri": r.RequestURI, "remote addr": httputil.GetClientAddr(r)}).Info("Served HTTP request")
http.NotFound(w, r)
}

View File

@ -24,6 +24,7 @@ import (
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"github.com/coreos/clair/api/httputil"
"github.com/coreos/clair/database"
)
@ -54,7 +55,7 @@ func httpHandler(h handler, ctx *context) httprouter.Handle {
WithLabelValues(route, statusStr).
Observe(float64(time.Since(start).Nanoseconds()) / float64(time.Millisecond))
log.WithFields(log.Fields{"remote addr": r.RemoteAddr, "method": r.Method, "request uri": r.RequestURI, "status": statusStr, "elapsed time": time.Since(start)}).Info("Handled HTTP request")
log.WithFields(log.Fields{"remote addr": httputil.GetClientAddr(r), "method": r.Method, "request uri": r.RequestURI, "status": statusStr, "elapsed time": time.Since(start)}).Info("Handled HTTP request")
}
}