| package mirko |
| |
| import ( |
| "net" |
| "net/http" |
| "testing" |
| |
| "k8s.io/client-go/kubernetes" |
| ) |
| |
| // TestHTTPRemoteClient exercises GetHTTPRemoteClient. |
| func TestHTTPRemoteClient(t *testing.T) { |
| for i, te := range []struct { |
| // k8s is whether GetHTTPRemoteClient should see itself as running in |
| // production. |
| k8s bool |
| r *http.Request |
| wantIP net.IP |
| wantPort uint16 |
| }{ |
| // 0: No headers set, outside cluseter - should work as expected. |
| {false, &http.Request{RemoteAddr: "1.2.3.4:1234", Header: map[string][]string{}}, net.IPv4(1, 2, 3, 4), 1234}, |
| // 1: No headers set, in cluseter - should fail. |
| {true, &http.Request{RemoteAddr: "1.2.3.4:1234", Header: map[string][]string{}}, nil, 0}, |
| // 2: Headers set, outside cluster - should parse request, not headers. |
| {false, &http.Request{RemoteAddr: "1.2.3.4:1234", Header: map[string][]string{ |
| "Hscloud-Nic-Source-Ip": []string{"2.3.4.5"}, |
| "Hscloud-Nic-Source-Port": []string{"2345"}, |
| }}, net.IPv4(1, 2, 3, 4), 1234}, |
| // 3: Headers set, in cluster - should parse headers, not request. |
| {true, &http.Request{RemoteAddr: "1.2.3.4:1234", Header: map[string][]string{ |
| "Hscloud-Nic-Source-Ip": []string{"2.3.4.5"}, |
| "Hscloud-Nic-Source-Port": []string{"2345"}, |
| }}, net.IPv4(2, 3, 4, 5), 2345}, |
| |
| // 4: Test IPv6 parsing. |
| {false, &http.Request{RemoteAddr: "[2a0d:eb00::42]:1234", Header: map[string][]string{}}, |
| net.IP([]byte{0x2a, 0x0d, 0xeb, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x42}), 1234}, |
| |
| // 5: Test broken IPv6. |
| {false, &http.Request{RemoteAddr: "2a0d:eb00::42:1234", Header: map[string][]string{}}, nil, 0}, |
| // 6: Test broken IPv6. |
| {false, &http.Request{RemoteAddr: "2a0d:eb00::42", Header: map[string][]string{}}, nil, 0}, |
| // 7: Test broken IPv6. |
| {false, &http.Request{RemoteAddr: "2a0d:80", Header: map[string][]string{}}, nil, 0}, |
| |
| // 8: Test broken port. |
| {false, &http.Request{RemoteAddr: "1.2.3.4", Header: map[string][]string{}}, nil, 0}, |
| // 9: Test broken port. |
| {false, &http.Request{RemoteAddr: "1.2.3.4:0", Header: map[string][]string{}}, nil, 0}, |
| } { |
| kubernetesCSMu.Lock() |
| if te.k8s { |
| kubernetesCS = &kubernetes.Clientset{} |
| } else { |
| kubernetesCS = nil |
| } |
| kubernetesCSValid = true |
| kubernetesCSMu.Unlock() |
| |
| gotIP, gotPort, err := GetHTTPRemoteClient(te.r) |
| if err == nil { |
| if want, got := te.wantIP, gotIP; !want.Equal(got) { |
| t.Errorf("%d: wanted IP %v, got %v", i, want, got) |
| } |
| if want, got := te.wantPort, gotPort; want != got { |
| t.Errorf("%d: wanted port %d, got %d", i, want, got) |
| } |
| } else { |
| if te.wantIP != nil || te.wantPort != 0 { |
| t.Errorf("%d: wanted %v %d, got failure", te.wantIP, te.wantPort) |
| } |
| } |
| } |
| } |