Files

75 lines
2.1 KiB
Go

package httpx_test
import (
"net/http"
"net/http/httptest"
"testing"
"git.asio.asia/nixevol/NixMsg/internal/httpx"
)
func TestClientIPWithoutProxy(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = "203.0.113.9:1234"
r.Header.Set("X-Forwarded-For", "198.51.100.1")
ip := httpx.ClientIP(r, nil)
if ip != "203.0.113.9" {
t.Fatalf("got %q", ip)
}
}
func TestParseCIDRsAndTrustedXFF(t *testing.T) {
trusted := httpx.ParseCIDRs([]string{"127.0.0.1/32"})
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = "127.0.0.1:9999"
r.Header.Set("X-Forwarded-For", "198.51.100.7, 127.0.0.1")
ip := httpx.ClientIP(r, trusted)
if ip != "198.51.100.7" {
t.Fatalf("got %q", ip)
}
r.Header.Set("X-Forwarded-Proto", "https")
if !httpx.IsHTTPS(r, trusted) {
t.Fatal("expected https via proxy")
}
}
func TestClientIPMultiLinePortAndIPv6(t *testing.T) {
trusted := httpx.ParseCIDRs([]string{"10.0.0.0/8", "127.0.0.1/32"})
t.Run("two header lines", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = "10.1.2.3:9"
r.Header["X-Forwarded-For"] = []string{"198.51.100.1", "203.0.113.8, 10.9.9.9"}
if got := httpx.ClientIP(r, trusted); got != "203.0.113.8" {
t.Fatalf("got %q", got)
}
})
t.Run("port on rightmost client", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = "10.1.2.3:9"
r.Header.Set("X-Forwarded-For", "198.51.100.9, 203.0.113.10:1234, 10.9.9.9")
if got := httpx.ClientIP(r, trusted); got != "203.0.113.10" {
t.Fatalf("got %q", got)
}
})
t.Run("unparseable stops", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = "10.1.2.3:9"
r.Header.Set("X-Forwarded-For", "198.51.100.1, not-an-ip, 10.9.9.9")
if got := httpx.ClientIP(r, trusted); got != "10.1.2.3" {
t.Fatalf("got %q", got)
}
})
t.Run("ipv6 brackets", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = "10.1.2.3:9"
r.Header.Set("X-Forwarded-For", "[2001:db8::1], 10.9.9.9")
if got := httpx.ClientIP(r, trusted); got != "2001:db8::1" {
t.Fatalf("got %q", got)
}
})
}