Skip to content

Commit

Permalink
contrib/internal/httptrace: handle DD_CLIENT_IP_HEADER env var
Browse files Browse the repository at this point in the history
  • Loading branch information
Hellzy committed Jun 8, 2022
1 parent 9d83401 commit 7a889bf
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 8 deletions.
22 changes: 19 additions & 3 deletions contrib/internal/httptrace/httptrace.go
Expand Up @@ -36,7 +36,7 @@ func StartRequestSpan(r *http.Request, opts ...ddtrace.StartSpanOption) (tracer.
tracer.Tag("http.host", r.Host),
}, opts...)
}
if ip := getClientIP(r.RemoteAddr, r.Header); ip.IsValid() {
if ip := getClientIP(r.RemoteAddr, r.Header, cfg.ipHeader); ip.IsValid() {
opts = append(opts, tracer.Tag(ext.HTTPClientIP, ip.String()))
}
if spanctx, err := tracer.Extract(tracer.HTTPHeadersCarrier(r.Header)); err == nil {
Expand Down Expand Up @@ -73,10 +73,26 @@ var (
ipv6SpecialNetworks = []*netaddr.IPPrefix{
ippref("fec0::/10"), // site local
}
ipHeaders = []string{"x-forwarded-for", "x-real-ip", "x-client-ip", "x-forwarded", "x-cluster-client-ip", "forwarded-for", "forwarded", "via", "true-client-ip"}
ipHeaders = []string{
"x-forwarded-for",
"x-real-ip",
"x-client-ip",
"x-forwarded",
"x-cluster-client-ip",
"forwarded-for",
"forwarded",
"via",
"true-client-ip",
}
)

func getClientIP(remoteAddr string, headers http.Header) netaddr.IP {
// getClientIP uses the request headers to resolve the client IP. If a specific header to check is provided through
// DD_CLIENT_IP_HEADER, then only this header is checked.
func getClientIP(remoteAddr string, headers http.Header, clientIPHeader string) netaddr.IP {
ipHeaders := ipHeaders
if len(clientIPHeader) > 0 {
ipHeaders = []string{clientIPHeader}
}
check := func(value string) netaddr.IP {
for _, ip := range strings.Split(value, ",") {
ipStr := strings.Trim(ip, " ")
Expand Down
11 changes: 6 additions & 5 deletions contrib/internal/httptrace/httptrace_test.go
Expand Up @@ -31,10 +31,11 @@ func TestStartRequestSpan(t *testing.T) {
}

type IPTestCase struct {
name string
remoteAddr string
headers map[string]string
expectedIP netaddr.IP
name string
remoteAddr string
headers map[string]string
expectedIP netaddr.IP
userIPHeader string
}

func genIPTestCases() []IPTestCase {
Expand Down Expand Up @@ -151,7 +152,7 @@ func TestIPHeaders(t *testing.T) {
for k, v := range tc.headers {
header.Add(k, v)
}
require.Equal(t, tc.expectedIP.String(), getClientIP(tc.remoteAddr, header).String())
require.Equal(t, tc.expectedIP.String(), getClientIP(tc.remoteAddr, header, tc.userIPHeader).String())
})
}

Expand Down
13 changes: 13 additions & 0 deletions contrib/internal/httptrace/options.go
@@ -0,0 +1,13 @@
package httptrace

import "os"

type config struct {
ipHeader string
}

var cfg = config{}

func init() {
cfg.ipHeader = os.Getenv("DD_CLIENT_IP_HEADER")
}

0 comments on commit 7a889bf

Please sign in to comment.