1
0
forked from baron/baron-sso
Files
baron-sso/backend/internal/utils/client_ip_test.go

70 lines
2.2 KiB
Go

package utils
import "testing"
func TestResolveClientIP_PrefersPublicForwardedIP(t *testing.T) {
got := ResolveClientIP("100.100.100.1, 203.0.113.25, 10.0.0.2", "", "172.18.0.5")
if got != "203.0.113.25" {
t.Fatalf("expected public forwarded IP, got %q", got)
}
}
func TestResolveClientIP_FallsBackToFirstForwardedWhenAllPrivate(t *testing.T) {
got := ResolveClientIP("100.100.100.1, 10.0.0.2", "192.168.0.10", "172.18.0.5")
if got != "100.100.100.1" {
t.Fatalf("expected first forwarded private IP, got %q", got)
}
}
func TestResolveClientIP_PrefersPublicRealIPOverPrivateForwarded(t *testing.T) {
got := ResolveClientIP("100.100.100.1, 10.0.0.2", "198.51.100.7", "172.18.0.5")
if got != "198.51.100.7" {
t.Fatalf("expected public real IP, got %q", got)
}
}
func TestResolveClientIP_PrefersPublicRemoteIPWhenHeadersArePrivate(t *testing.T) {
got := ResolveClientIP("10.0.0.2", "192.168.0.10", "203.0.113.8:12345")
if got != "203.0.113.8" {
t.Fatalf("expected public remote IP, got %q", got)
}
}
func TestResolveClientIP_FallsBackToRealIPWhenNoForwardedCandidates(t *testing.T) {
got := ResolveClientIP("invalid", "192.168.0.10", "bad-remote")
if got != "192.168.0.10" {
t.Fatalf("expected normalized real IP, got %q", got)
}
}
func TestResolveClientIP_ReturnsEmptyForInvalidInputs(t *testing.T) {
got := ResolveClientIP("", "bad-real", "bad-remote")
if got != "" {
t.Fatalf("expected empty IP, got %q", got)
}
}
func TestIsPrivateOrReservedIP(t *testing.T) {
tests := []struct {
name string
ip string
expected bool
}{
{name: "invalid", ip: "not-an-ip", expected: false},
{name: "public", ip: "203.0.113.8", expected: false},
{name: "private ipv4", ip: "10.0.0.1", expected: true},
{name: "loopback", ip: "127.0.0.1", expected: true},
{name: "link local", ip: "169.254.1.1", expected: true},
{name: "carrier grade nat", ip: "100.64.0.1", expected: true},
{name: "unique local ipv6", ip: "fc00::1", expected: true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := IsPrivateOrReservedIP(tc.ip); got != tc.expected {
t.Fatalf("unexpected private state for %s: got=%v expected=%v", tc.ip, got, tc.expected)
}
})
}
}