53 lines
1.3 KiB
Go
53 lines
1.3 KiB
Go
package serverimp
|
|
|
|
import (
|
|
"net"
|
|
"net/http"
|
|
"testing"
|
|
)
|
|
|
|
func TestClientIPFromRequest(t *testing.T) {
|
|
req := &http.Request{
|
|
Header: http.Header{"X-Forwarded-For": []string{"1.2.3.4, 5.6.7.8"}},
|
|
RemoteAddr: "9.8.7.6:1234",
|
|
}
|
|
ip := clientIPFromRequest(req)
|
|
if ip == nil || ip.String() != "1.2.3.4" {
|
|
t.Fatalf("expected forwarded ip, got %v", ip)
|
|
}
|
|
|
|
req = &http.Request{RemoteAddr: "9.8.7.6:1234"}
|
|
ip = clientIPFromRequest(req)
|
|
if ip == nil || ip.String() != "9.8.7.6" {
|
|
t.Fatalf("expected remote addr ip, got %v", ip)
|
|
}
|
|
|
|
req = &http.Request{RemoteAddr: "invalid"}
|
|
ip = clientIPFromRequest(req)
|
|
if ip != nil {
|
|
t.Fatalf("expected nil ip, got %v", ip)
|
|
}
|
|
}
|
|
|
|
func TestClientAllowed(t *testing.T) {
|
|
_, cidr, err := net.ParseCIDR("10.0.0.0/8")
|
|
if err != nil {
|
|
t.Fatalf("failed to parse cidr: %v", err)
|
|
}
|
|
|
|
allowedReq := &http.Request{RemoteAddr: "10.1.2.3:1234"}
|
|
if !clientAllowed(allowedReq, []*net.IPNet{cidr}) {
|
|
t.Fatalf("expected allowed request")
|
|
}
|
|
|
|
deniedReq := &http.Request{RemoteAddr: "8.8.8.8:1234"}
|
|
if clientAllowed(deniedReq, []*net.IPNet{cidr}) {
|
|
t.Fatalf("expected denied request")
|
|
}
|
|
|
|
openReq := &http.Request{RemoteAddr: "8.8.8.8:1234"}
|
|
if !clientAllowed(openReq, nil) {
|
|
t.Fatalf("expected allow when no cidrs are configured")
|
|
}
|
|
}
|