Skip to content

Commit

Permalink
Merge pull request quay#410 from KeyboardNerd/xforward
Browse files Browse the repository at this point in the history
api: fix remote addr shows reverse proxy addr problem
  • Loading branch information
jzelinskie authored Jun 21, 2017
2 parents 5f5bf52 + 4019e06 commit 81b029e
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
24 changes: 24 additions & 0 deletions api/httputil/httputil.go
Original file line number Diff line number Diff line change
@@ -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
}
3 changes: 2 additions & 1 deletion api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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)
}

Expand Down
3 changes: 2 additions & 1 deletion api/v1/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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")
}
}

Expand Down

0 comments on commit 81b029e

Please sign in to comment.