internal/httpd/clientip_test.go
46 lines · 1582 bytes
1 symbol in this file
1package httpd
2
3import (
4 "net/http/httptest"
5 "testing"
6
7 "gitbay.org/gitbay/internal/config"
8)
9
10// With no trusted proxies the peer is the client and X-Forwarded-For is
11// ignored; behind a trusted proxy the client is the last hop that is not
12// itself a proxy, so a spoofed leading hop still cannot pick a bucket.
13func TestClientIPBehindProxy(t *testing.T) {
14 cases := []struct {
15 proxies []string
16 remote string
17 xff string
18 want string
19 }{
20 {nil, "203.0.113.9:4000", "198.51.100.1", "203.0.113.9"},
21 {[]string{"10.0.0.0/8"}, "10.1.2.3:4000", "198.51.100.1", "198.51.100.1"},
22 {[]string{"10.0.0.0/8"}, "10.1.2.3:4000", "198.51.100.1, 10.9.9.9", "198.51.100.1"},
23 {[]string{"10.0.0.0/8"}, "10.1.2.3:4000", "1.1.1.1, 198.51.100.1", "198.51.100.1"},
24 {[]string{"10.0.0.0/8"}, "10.1.2.3:4000", "", "10.1.2.3"},
25 {[]string{"10.0.0.0/8"}, "203.0.113.9:4000", "198.51.100.1", "203.0.113.9"},
26 {[]string{"127.0.0.1"}, "127.0.0.1:4000", "198.51.100.1", "198.51.100.1"},
27 }
28 for _, tc := range cases {
29 cfg := config.Default()
30 cfg.HTTP.TrustedProxies = tc.proxies
31 s := New(cfg, nil, nil)
32 r := httptest.NewRequest("GET", "/api/v1/read", nil)
33 r.RemoteAddr = tc.remote
34 if tc.xff != "" {
35 r.Header.Set("X-Forwarded-For", tc.xff)
36 }
37 if got := s.clientIP(r); got != tc.want {
38 t.Errorf("proxies=%v remote=%s xff=%q: got %s, want %s", tc.proxies, tc.remote, tc.xff, got, tc.want)
39 }
40 }
41 cfg := config.Default()
42 cfg.HTTP.TrustedProxies = []string{"not-an-address"}
43 if err := cfg.Validate(); err == nil {
44 t.Error("bad trusted_proxies entry accepted")
45 }
46}