-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip.go
More file actions
75 lines (65 loc) · 2.2 KB
/
ip.go
File metadata and controls
75 lines (65 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package keratin
import (
"context"
"net"
"net/http"
"net/netip"
"strings"
)
type IPExtractor func(r *http.Request) string
// RemoteIP returns the IP address of the client that sent the request.
//
// IPv6 addresses are returned expanded.
// For example, "2001:db8::1" becomes "2001:0db8:0000:0000:0000:0000:0000:0001".
//
// Note that if you are behind reverse proxy(ies), this method returns
// the IP of the last connecting proxy.
func RemoteIP(r *http.Request) string {
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
parsed, _ := netip.ParseAddr(ip)
return parsed.StringExpanded()
}
// TrustedProxy defines the trusted proxy settings.
// https://developers.cloudflare.com/fundamentals/reference/http-headers/#x-forwarded-for
type TrustedProxy struct {
// Headers is a list of explicit trusted header(s) to check.
Headers []string `env:"HEADERS" json:"headers,omitempty" yaml:"headers,omitempty"`
// UseLeftmostIP specifies to use the left-mostish IP from the trusted headers.
//
// Note that this could be insecure when used with X-Forwarded-For header
// because some proxies like AWS ELB allow users to prepend their own header value
// before appending the trusted ones.
UseLeftmostIP bool `env:"USE_LEFTMOST_IP" json:"useLeftmostIP,omitempty" yaml:"useLeftmostIP,omitempty"`
}
func RealIP(fn func(ctx context.Context) (*TrustedProxy, error)) IPExtractor {
return func(r *http.Request) string {
if trusted, err := fn(r.Context()); err == nil {
for _, h := range trusted.Headers {
headerValues := r.Header.Values(h)
if len(headerValues) == 0 {
continue
}
// extract the last header value as it is expected to be the one controlled by the proxy
ipsList := headerValues[len(headerValues)-1]
if ipsList == "" {
continue
}
ips := strings.Split(ipsList, ",")
if trusted.UseLeftmostIP {
for _, ip := range ips {
if parsed, err := netip.ParseAddr(strings.TrimSpace(ip)); err == nil {
return parsed.StringExpanded()
}
}
} else {
for i := len(ips) - 1; i >= 0; i-- {
if parsed, err := netip.ParseAddr(strings.TrimSpace(ips[i])); err == nil {
return parsed.StringExpanded()
}
}
}
}
}
return RemoteIP(r)
}
}