Skip to content

Commit

Permalink
fix(xff): Properly forward x-forwarded-for on proxy (#59)
Browse files Browse the repository at this point in the history
fix(xff): Properly forward x-forwarded-for on proxy

---------

Co-authored-by: ldebruijn <[email protected]>
  • Loading branch information
ldebruijn and ldebruijn authored Feb 9, 2024
1 parent dbd5f6f commit 8ba4da6
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
4 changes: 3 additions & 1 deletion internal/http/proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ func NewProxy(cfg Config, blockFieldSuggestions *block_field_suggestions.BlockFi
}
proxy := &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
r.Out.Header["X-Forwarded-For"] = r.In.Header["X-Forwarded-For"]
r.SetXForwarded()
r.SetURL(target)
r.Out.Host = r.In.Host
},
Expand All @@ -42,7 +44,7 @@ func NewProxy(cfg Config, blockFieldSuggestions *block_field_suggestions.BlockFi

func modifyResponse(blockFieldSuggestions *block_field_suggestions.BlockFieldSuggestionsHandler) func(res *http.Response) error {
return func(res *http.Response) error {
if !blockFieldSuggestions.Enabled() {
if blockFieldSuggestions == nil || !blockFieldSuggestions.Enabled() {
return nil
}

Expand Down
43 changes: 43 additions & 0 deletions internal/http/proxy/proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ import (
"github.com/stretchr/testify/assert"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)

func Test_modifyResponse(t *testing.T) {
Expand Down Expand Up @@ -142,3 +145,43 @@ func Test_modifyResponse(t *testing.T) {
})
}
}

func TestForwardsXff(t *testing.T) {
rr := &RequestRecorder{}
testServer := httptest.NewServer(rr)
upstreamURL, err := url.Parse(testServer.URL)
assert.NoError(t, err)

cfg := Config{
Timeout: 1 * time.Second,
KeepAlive: 180 * time.Second,
Host: "http://" + upstreamURL.Host,
Tracing: TracingConfig{},
}
proxy, err := NewProxy(cfg, nil)
assert.NoError(t, err)

req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("x-forwarded-for", "123.456.789.0")

w := httptest.NewRecorder()

proxy.ServeHTTP(w, req)

rr.Assert(func(r *http.Request) {
val := r.Header.Get("x-forwarded-for")
assert.True(t, strings.HasPrefix(val, "123.456.789.0,")) // trailing , to make sure IP of protect is appended to list
})
}

type RequestRecorder struct {
lastRequest *http.Request
}

func (r *RequestRecorder) ServeHTTP(_ http.ResponseWriter, request *http.Request) {
r.lastRequest = request
}

func (r *RequestRecorder) Assert(assert func(r *http.Request)) {
assert(r.lastRequest)
}

0 comments on commit 8ba4da6

Please sign in to comment.