Skip to content

Commit

Permalink
added parsing for extended X-Forwarded-For headers to allow proxy API…
Browse files Browse the repository at this point in the history
… registration in ipv4 (#80)
  • Loading branch information
jmwample committed Mar 25, 2021
1 parent 02daaf1 commit 709ec21
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
19 changes: 19 additions & 0 deletions registration-api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/golang/protobuf/proto"
zmq "github.com/pebbe/zmq4"
pb "github.com/refraction-networking/gotapdance/protobuf"
"github.com/stretchr/testify/require"
)

var (
Expand Down Expand Up @@ -333,3 +334,21 @@ func BenchmarkRegistration(b *testing.B) {
s.register(w, r)
}
}

func TestAPIGetClientAddr(t *testing.T) {

req, err := http.NewRequest("GET", "http://example.com", nil)
require.Nil(t, err)

req.RemoteAddr = "10.0.0.0"
require.Equal(t, "10.0.0.0", getRemoteAddr(req))

req.Header.Add("X-Forwarded-For", "192.168.1.1")
require.Equal(t, "192.168.1.1", getRemoteAddr(req))

req.Header.Set("X-Forwarded-For", "127.0.0.1, 192.168.0.0")
require.Equal(t, "127.0.0.1", getRemoteAddr(req))

req.Header.Set("X-Forwarded-For", "127.0.0.1,192.168.0.0")
require.Equal(t, "127.0.0.1", getRemoteAddr(req))
}
19 changes: 16 additions & 3 deletions registration-api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"os"
"strconv"
"strings"
"sync"

"github.com/BurntSushi/toml"
Expand Down Expand Up @@ -48,11 +49,23 @@ type server struct {
sock *zmq.Socket
}

func (s *server) register(w http.ResponseWriter, r *http.Request) {
requestIP := r.RemoteAddr
// Get the first element of the X-Forwarded-For header if it is available, this
// will be the clients address if intermediate proxies follow X-Forwarded-For
// specification (as seen here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For).
// Otherwise return the remote address specified in the request.
//
// In the future this may need to handle True-Client-IP headers.
func getRemoteAddr(r *http.Request) string {
if r.Header.Get("X-Forwarded-For") != "" {
requestIP = r.Header.Get("X-Forwarded-For")
addrList := r.Header.Get("X-Forwarded-For")
return strings.Trim(strings.Split(addrList, ",")[0], " \t")
}
return r.RemoteAddr
}

func (s *server) register(w http.ResponseWriter, r *http.Request) {
requestIP := getRemoteAddr(r)

if s.logClientIP {
s.logger.Printf("received %s request from IP %v with content-length %d\n", r.Method, requestIP, r.ContentLength)
} else {
Expand Down

0 comments on commit 709ec21

Please sign in to comment.