forked from nzlov/forwardingproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy_test.go
114 lines (90 loc) · 2.42 KB
/
proxy_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// Copyright (C) 2018 Betalo AB - All Rights Reserved
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParseBasicProxyAuth(t *testing.T) {
// Arrange
cases := []struct {
name string
givenAuth string
expectedUser string
expectedPass string
expectedAuth bool
}{
{
name: "ValidAuth",
givenAuth: "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
expectedUser: "Aladdin",
expectedPass: "open sesame",
expectedAuth: true,
},
{
name: "InvalidAuth",
givenAuth: "Basic ####",
expectedUser: "",
expectedPass: "",
expectedAuth: false,
},
{
name: "InvalidPrefix",
givenAuth: "Foo QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
expectedUser: "",
expectedPass: "",
expectedAuth: false,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Act
observedUser, observedPass, observedAuth := parseBasicProxyAuth(tc.givenAuth)
// Assert
assert.Equal(t, tc.expectedUser, observedUser)
assert.Equal(t, tc.expectedPass, observedPass)
assert.Equal(t, tc.expectedAuth, observedAuth)
})
}
}
func TestNewForwardingHTTPProxy(t *testing.T) {
// Arrange
// Proxy server
forwardingHTTPProxy := NewForwardingHTTPProxy(nil)
proxyServer := httptest.NewServer(forwardingHTTPProxy)
defer proxyServer.Close()
proxyServerURL, err := url.Parse(proxyServer.URL)
require.NoError(t, err)
// Destination server
destServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Hop-by-hop headers are removed when sent to the backend.
// See: https://golang.org/src/net/http/httputil/reverseproxy.go#L129
_, found := r.Header["Proxy-Authorization"]
assert.False(t, found)
assert.Equal(t, "bar", r.Header.Get("Content-type"))
fmt.Fprintln(w, "dummy-response")
}))
defer destServer.Close()
// Act
client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyServerURL),
},
}
req, err := http.NewRequest("GET", destServer.URL, nil)
require.NoError(t, err)
req.Header.Set("Proxy-Authorization", "Basic foo")
req.Header.Set("Content-type", "bar")
resp, err := client.Do(req)
require.NoError(t, err)
// Assert
b, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, "dummy-response", strings.TrimSpace(string(b)))
}