Skip to content

Commit

Permalink
fix ip parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
irshadaj committed Jan 30, 2024
1 parent 602d04b commit c83abdf
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 26 deletions.
9 changes: 1 addition & 8 deletions cmd/api/src/api/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,14 +156,7 @@ func parseUserIP(r *http.Request) string {
log.Errorf("No data found in X-Forwarded-For")
}

if parsedUrl, err := url.Parse(r.RemoteAddr); err != nil {
log.Errorf("Error parsing IP address from RemoteAddr: %s", err)
} else if hostName := parsedUrl.Hostname(); hostName == "" {
log.Errorf("Hostname not found in URL: %s", parsedUrl.String())
} else {
res += "Remote Address: " + parsedUrl.Hostname()
}

res += "Remote Address: " + r.RemoteAddr
return res
}

Expand Down
19 changes: 1 addition & 18 deletions cmd/api/src/api/middleware/middleware_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,23 +91,6 @@ func TestParseUserIP_XForwardedForMissing(t *testing.T) {
require.Contains(t, res, "Remote Address")
}

func TestParseUserIP_RemoteAddrError(t *testing.T) {
req, err := http.NewRequest("GET", "/teapot", nil)
require.Nil(t, err)

ip1 := "192.168.1.1:8080"
ip2 := "192.168.1.2"
ip3 := "192.168.1.3"
req.Header.Set("X-Forwarded-For", strings.Join([]string{ip1, ip2, ip3}, ","))
req.RemoteAddr = "0.0.0.0:3000"

res := parseUserIP(req)
require.Contains(t, res, "X-Forwarded-For")
require.Contains(t, res, ip1)
require.Contains(t, res, ip2)
require.NotContains(t, res, "Remote Address")
}

func TestParseUserIP_Success(t *testing.T) {
req, err := http.NewRequest("GET", "/teapot", nil)
require.Nil(t, err)
Expand All @@ -117,7 +100,7 @@ func TestParseUserIP_Success(t *testing.T) {
ip3 := "192.168.1.3"
req.Header.Set("X-Forwarded-For", strings.Join([]string{ip1, ip2, ip3}, ","))

req.RemoteAddr = "http://www.google.com/0.0.0.0:3000"
req.RemoteAddr = "0.0.0.0:3000"

res := parseUserIP(req)
require.Contains(t, res, "X-Forwarded-For")
Expand Down

0 comments on commit c83abdf

Please sign in to comment.