blob: d2379061fcb6c04563661f49884831bfcc226f86 [file] [log] [blame]
Serge Bazanski13c90f02021-05-22 19:10:13 +00001package mirko
2
3import (
4 "net"
5 "net/http"
6 "testing"
7
8 "k8s.io/client-go/kubernetes"
9)
10
11// TestHTTPRemoteClient exercises GetHTTPRemoteClient.
12func TestHTTPRemoteClient(t *testing.T) {
13 for i, te := range []struct {
14 // k8s is whether GetHTTPRemoteClient should see itself as running in
15 // production.
16 k8s bool
17 r *http.Request
18 wantIP net.IP
19 wantPort uint16
20 }{
21 // 0: No headers set, outside cluseter - should work as expected.
22 {false, &http.Request{RemoteAddr: "1.2.3.4:1234", Header: map[string][]string{}}, net.IPv4(1, 2, 3, 4), 1234},
23 // 1: No headers set, in cluseter - should fail.
24 {true, &http.Request{RemoteAddr: "1.2.3.4:1234", Header: map[string][]string{}}, nil, 0},
25 // 2: Headers set, outside cluster - should parse request, not headers.
26 {false, &http.Request{RemoteAddr: "1.2.3.4:1234", Header: map[string][]string{
27 "Hscloud-Nic-Source-Ip": []string{"2.3.4.5"},
28 "Hscloud-Nic-Source-Port": []string{"2345"},
29 }}, net.IPv4(1, 2, 3, 4), 1234},
30 // 3: Headers set, in cluster - should parse headers, not request.
31 {true, &http.Request{RemoteAddr: "1.2.3.4:1234", Header: map[string][]string{
32 "Hscloud-Nic-Source-Ip": []string{"2.3.4.5"},
33 "Hscloud-Nic-Source-Port": []string{"2345"},
34 }}, net.IPv4(2, 3, 4, 5), 2345},
35
36 // 4: Test IPv6 parsing.
37 {false, &http.Request{RemoteAddr: "[2a0d:eb00::42]:1234", Header: map[string][]string{}},
38 net.IP([]byte{0x2a, 0x0d, 0xeb, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x42}), 1234},
39
40 // 5: Test broken IPv6.
41 {false, &http.Request{RemoteAddr: "2a0d:eb00::42:1234", Header: map[string][]string{}}, nil, 0},
42 // 6: Test broken IPv6.
43 {false, &http.Request{RemoteAddr: "2a0d:eb00::42", Header: map[string][]string{}}, nil, 0},
44 // 7: Test broken IPv6.
45 {false, &http.Request{RemoteAddr: "2a0d:80", Header: map[string][]string{}}, nil, 0},
46
47 // 8: Test broken port.
48 {false, &http.Request{RemoteAddr: "1.2.3.4", Header: map[string][]string{}}, nil, 0},
49 // 9: Test broken port.
50 {false, &http.Request{RemoteAddr: "1.2.3.4:0", Header: map[string][]string{}}, nil, 0},
51 } {
52 kubernetesCSMu.Lock()
53 if te.k8s {
54 kubernetesCS = &kubernetes.Clientset{}
55 } else {
56 kubernetesCS = nil
57 }
58 kubernetesCSValid = true
59 kubernetesCSMu.Unlock()
60
61 gotIP, gotPort, err := GetHTTPRemoteClient(te.r)
62 if err == nil {
63 if want, got := te.wantIP, gotIP; !want.Equal(got) {
64 t.Errorf("%d: wanted IP %v, got %v", i, want, got)
65 }
66 if want, got := te.wantPort, gotPort; want != got {
67 t.Errorf("%d: wanted port %d, got %d", i, want, got)
68 }
69 } else {
70 if te.wantIP != nil || te.wantPort != 0 {
71 t.Errorf("%d: wanted %v %d, got failure", te.wantIP, te.wantPort)
72 }
73 }
74 }
75}