| 1 | package realip |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "net/http/httptest" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | |
| 9 | "github.com/stretchr/testify/assert" |
| 10 | "github.com/stretchr/testify/require" |
| 11 | ) |
| 12 | |
| 13 | func TestTrusted(t *testing.T) { |
| 14 | nets, err := parseTrusted([]string{"10.0.0.0/8"}) |
| 15 | require.NoError(t, err) |
| 16 | cases := []struct { |
| 17 | Case, IP, XFF, Expected string |
| 18 | Trusted bool |
| 19 | }{ |
| 20 | // direct from an untrusted IP |
| 21 | {"Direct", "172.16.0.1", "", "172.16.0.1", false}, |
| 22 | // direct from a trusted IP |
| 23 | {"DirectInternal", "10.0.0.1", "", "10.0.0.1", false}, |
| 24 | // direct from an untrusted IP with an untrusted hop |
| 25 | {"DirectUntrusted", "10.0.0.1", "", "10.0.0.1", false}, |
| 26 | // connected via trusted proxy |
| 27 | {"OneHop", "10.0.0.1", "192.168.100.1", "192.168.100.1", true}, |
| 28 | // connected via trusted proxy and the client is also a trusted IP |
| 29 | {"OneHopInternal", "10.0.0.1", "10.0.0.2", "10.0.0.2", true}, |
| 30 | // connected via trusted proxy with an untrusted hop |
| 31 | {"OneHopUntrusted", "10.0.0.1", "172.16.0.1, 192.168.100.1", "192.168.100.1", true}, |
| 32 | // connected via two trusted proxies |
| 33 | {"TwoHops", "10.0.0.1", "192.168.100.1, 10.0.0.2", "192.168.100.1", true}, |
| 34 | } |
| 35 | for _, c := range cases { |
| 36 | t.Run(c.Case, func(t *testing.T) { |
| 37 | req := httptest.NewRequest(http.MethodGet, "/", nil) |
| 38 | req.RemoteAddr = c.IP + ":12345" |
| 39 | if c.XFF != "" { |
| 40 | req.Header.Set("X-Forwarded-For", c.XFF) |
| 41 | } |
| 42 | actual, trusted := trustedClient(nets, req) |
| 43 | assert.Equal(t, c.Expected, actual) |
| 44 | assert.Equal(t, c.Trusted, trusted) |
| 45 | req.Header.Del("X-Forwarded-For") |
| 46 | |
| 47 | }) |
| 48 | if !strings.ContainsRune(c.XFF, ',') { |
| 49 | continue |
| 50 | } |
| 51 | // do it again with separate XFF headers |
| 52 | t.Run(c.Case+"Multi", func(t *testing.T) { |
| 53 | req := httptest.NewRequest(http.MethodGet, "/", nil) |
| 54 | req.RemoteAddr = c.IP + ":12345" |
| 55 | for _, v := range strings.Split(c.XFF, ",") { |
| 56 | req.Header.Add("X-Forwarded-For", v) |
| 57 | } |
| 58 | actual, trusted := trustedClient(nets, req) |
| 59 | assert.Equal(t, c.Expected, actual) |
| 60 | assert.Equal(t, c.Trusted, trusted) |
| 61 | }) |
| 62 | } |
| 63 | } |