Repository Public
1package httpx23import (4 "net/http/httptest"5 "testing"6 "time"7)89func TestResolveIPTrustsOnlyConfiguredProxies(t *testing.T) {10 trusted := parsePrefixes([]string{"10.67.0.1", "127.0.0.1"})11 cases := []struct{ remote, xff, want string }{12 {"203.0.113.9:4000", "1.2.3.4", "203.0.113.9"}, // direct client: header ignored (spoofing)13 {"10.67.0.1:5000", "198.51.100.7", "198.51.100.7"}, // via the gateway14 {"10.67.0.1:5000", "6.6.6.6, 198.51.100.7", "198.51.100.7"}, // client-injected prefix ignored15 {"10.67.0.1:5000", "", "10.67.0.1"},16 {"10.67.0.1:5000", "garbage", "10.67.0.1"},17 {"[::ffff:10.67.0.1]:5000", "198.51.100.7", "198.51.100.7"},18 }19 for _, c := range cases {20 r := httptest.NewRequest("GET", "/", nil)21 r.RemoteAddr = c.remote22 if c.xff != "" {23 r.Header.Set("X-Forwarded-For", c.xff)24 }25 got, _ := resolveIP(r, trusted)26 if got.String() != c.want {27 t.Errorf("remote=%s xff=%q: got %s, want %s", c.remote, c.xff, got, c.want)28 }29 }30}3132func TestLimiter(t *testing.T) {33 l := NewLimiter(60, 3)34 now := time.Unix(1000, 0)35 l.now = func() time.Time { return now }36 for i := 0; i < 3; i++ {37 if ok, _ := l.Allow("a"); !ok {38 t.Fatalf("burst event %d refused", i)39 }40 }41 if ok, wait := l.Allow("a"); ok || wait < 1 {42 t.Fatalf("4th event must be refused with a wait, got ok=%v wait=%d", ok, wait)43 }44 if ok, _ := l.Allow("b"); !ok {45 t.Fatal("keys are independent")46 }47 now = now.Add(time.Second)48 if ok, _ := l.Allow("a"); !ok {49 t.Fatal("one token per second should have refilled")50 }51}52