Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(httpx): use cf-connecting-ip header for client IP #786

Merged
merged 1 commit into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions httpx/client_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ func GetClientIPAddressesWithoutInternalIPs(ipAddresses []string) (string, error
func ClientIP(r *http.Request) string {
if trueClientIP := r.Header.Get("True-Client-IP"); trueClientIP != "" {
return trueClientIP
} else if cfConnectingIP := r.Header.Get("Cf-Connecting-IP"); cfConnectingIP != "" {
return cfConnectingIP
} else if realClientIP := r.Header.Get("X-Real-IP"); realClientIP != "" {
return realClientIP
} else if forwardedIP := r.Header.Get("X-Forwarded-For"); forwardedIP != "" {
Expand Down
13 changes: 11 additions & 2 deletions httpx/client_info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,26 +33,35 @@ func TestClientIP(t *testing.T) {
Header: http.Header{},
}
req.Header.Add("true-client-ip", "1.0.0.1")
req.Header.Add("x-real-ip", "1.0.0.2")
req.Header.Add("cf-connecting-ip", "1.0.0.2")
req.Header.Add("x-real-ip", "1.0.0.3")
req.Header.Add("x-forwarded-for", "192.168.1.1,1.0.0.3,10.0.0.1")
t.Run("true-client-ip", func(t *testing.T) {
req := req.Clone(context.Background())
assert.Equal(t, "1.0.0.1", ClientIP(req))
})
t.Run("x-real-ip", func(t *testing.T) {
t.Run("cf-connecting-ip", func(t *testing.T) {
req := req.Clone(context.Background())
req.Header.Del("true-client-ip")
assert.Equal(t, "1.0.0.2", ClientIP(req))
})
t.Run("x-real-ip", func(t *testing.T) {
req := req.Clone(context.Background())
req.Header.Del("true-client-ip")
req.Header.Del("cf-connecting-ip")
assert.Equal(t, "1.0.0.3", ClientIP(req))
})
t.Run("x-forwarded-for", func(t *testing.T) {
req := req.Clone(context.Background())
req.Header.Del("true-client-ip")
req.Header.Del("cf-connecting-ip")
req.Header.Del("x-real-ip")
assert.Equal(t, "1.0.0.3", ClientIP(req))
})
t.Run("remote-addr", func(t *testing.T) {
req := req.Clone(context.Background())
req.Header.Del("true-client-ip")
req.Header.Del("cf-connecting-ip")
req.Header.Del("x-real-ip")
req.Header.Del("x-forwarded-for")
assert.Equal(t, "1.0.0.4", ClientIP(req))
Expand Down
Loading